1use std::path::Path;
14
15use rucc_base::Interner;
16use rucc_codegen::coverage::Fired;
17use rucc_codegen::pipeline::{self, Machine};
18use rucc_diag::{Diagnostic, Severity, Span};
19use rucc_lex::{Convert, Keywords, PpToken, convert};
20use rucc_sema::{Checker, Context as CheckContext};
21use rucc_session::{EmitKind, FileSystem, Options, Session};
22use rucc_target::TargetInfo;
23
24use crate::preprocess::render;
25
26#[derive(Debug, Clone, PartialEq, Eq, Default)]
33pub enum Artifact {
34 #[default]
37 Nothing,
38 Text(String),
40 Object(Vec<u8>),
42}
43
44impl Artifact {
45 #[must_use]
47 pub fn bytes(&self) -> &[u8] {
48 match self {
49 Artifact::Nothing => &[],
50 Artifact::Text(text) => text.as_bytes(),
51 Artifact::Object(bytes) => bytes,
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Compiled {
59 pub artifact: Artifact,
61 pub messages: Vec<String>,
63 pub errors: u32,
65 pub fired: Fired,
71 pub dumps: Vec<rucc_opt::Dump>,
77}
78
79impl Compiled {
80 #[must_use]
82 pub fn failed(&self) -> bool {
83 self.errors > 0
84 }
85
86 #[must_use]
91 pub fn text(&self) -> &str {
92 match &self.artifact {
93 Artifact::Text(text) => text,
94 _ => "",
95 }
96 }
97}
98
99#[must_use]
112pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
113 let mut sess = Session::new(opts.clone());
114 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
118 let mut diagnostics: Vec<Diagnostic> = Vec::new();
119 let mut fired = Fired::new();
121 let mut dumps = Vec::new();
123
124 let bytes = match fs.read(Path::new(name)) {
125 Ok(bytes) => bytes,
126 Err(e) => return failure(format!("{name}: {e}")),
127 };
128 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
129 return failure(format!("{name}: the source map has no room left for this file"));
130 };
131
132 let mut pp = rucc_pp::Preprocessor::new();
136 let predef = rucc_pp::Predef::for_options(opts);
137 let expanded: Vec<PpToken> = {
138 let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
139 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
140 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
141 return failure(format!("{name}: the source map has no room for the built in macros"));
142 }
143 pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
144 };
145 diagnostics.extend(pp.take_diagnostics());
146
147 let cx = Convert {
150 keywords: &keywords,
151 interner: &sess.interner,
152 target: &sess.target,
153 std: opts.std,
154 gnu: opts.gnu_extensions,
155 pedantic: opts.pedantic,
156 };
157 let (tokens, complaints) = convert(&expanded, &cx);
158 diagnostics.extend(complaints);
159
160 let parsed = rucc_parse::parse(
161 &tokens,
162 rucc_parse::Context {
163 interner: &sess.interner,
164 std: opts.std,
165 gnu: opts.gnu_extensions,
166 pedantic: opts.pedantic,
167 error_limit: opts.error_limit as usize,
168 },
169 );
170 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
171 diagnostics.extend(parsed.diagnostics);
172
173 let mut artifact = Artifact::Nothing;
174 if !parse_failed {
175 let mut checker = Checker::new(
176 &parsed.ast,
177 CheckContext {
178 names: &sess.interner,
179 target: &sess.target,
180 std: opts.std,
181 gnu: opts.gnu_extensions,
182 pedantic: opts.pedantic,
183 error_limit: opts.error_limit as usize,
184 },
185 );
186 checker.check_unit();
187 let checked = checker.finish();
188 if !checked.failed() {
189 match opts.emit {
190 EmitKind::Tast => {
191 artifact = Artifact::Text(rucc_sema::print(
192 &checked.tast,
193 &checked.types,
194 &sess.interner,
195 ));
196 }
197 EmitKind::Ir
198 | EmitKind::MirFinal
199 | EmitKind::Asm
200 | EmitKind::Object
201 | EmitKind::Executable => {
202 let mut lowered = rucc_lower::lower(
203 name,
204 rucc_lower::Context {
205 tast: &checked.tast,
206 types: &checked.types,
207 target: &sess.target,
208 names: &mut sess.interner,
209 },
210 );
211 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
215 if !failed {
216 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
221 for error in errors {
222 diagnostics.push(internal(&format!("invalid IR, {error}")));
223 }
224 } else if let Err(complaints) =
225 optimize(&mut lowered.module, &sess.interner, opts, &mut dumps)
226 {
227 diagnostics.extend(complaints);
228 } else if opts.emit == EmitKind::Ir {
229 artifact =
234 Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
235 } else {
236 match generate(
239 &mut lowered.module,
240 &mut sess.interner,
241 &sess.target,
242 opts,
243 &mut fired,
244 ) {
245 Ok(made) => artifact = made,
246 Err(complaints) => diagnostics.extend(complaints),
247 }
248 }
249 }
250 diagnostics.extend(lowered.diagnostics);
251 }
252 _ => {}
253 }
254 }
255 diagnostics.extend(checked.diagnostics);
256 }
257
258 let mut messages = Vec::with_capacity(diagnostics.len());
259 let mut errors = 0;
260 for diag in &diagnostics {
261 if diag.severity.is_fatal()
262 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
263 {
264 errors += 1;
265 }
266 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
267 }
268 if errors > 0 {
269 artifact = Artifact::Nothing;
271 }
272 Compiled { artifact, messages, errors, fired, dumps }
275}
276
277#[must_use]
287pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
288 let mut sess = Session::new(opts.clone());
289 if opts.emit != EmitKind::Ir {
290 return failure(format!(
291 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
292 the C in front of it became",
293 opts.emit.as_str()
294 ));
295 }
296 let bytes = match fs.read(Path::new(name)) {
297 Ok(bytes) => bytes,
298 Err(e) => return failure(format!("{name}: {e}")),
299 };
300 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
301 return failure(format!("{name}: this is not text, so it is not IR"));
302 };
303
304 let module = match rucc_ir::parse(text, &mut sess.interner) {
305 Ok(module) => module,
306 Err(error) => {
307 return failure(format!("{name}:{}: {}", error.line, error.message));
308 }
309 };
310 let mut diagnostics: Vec<Diagnostic> = Vec::new();
311 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
312 for error in errors {
313 diagnostics.push(invalid(&format!("invalid IR, {error}")));
314 }
315 }
316 let mut messages = Vec::with_capacity(diagnostics.len());
317 for diag in &diagnostics {
318 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
319 }
320 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
321 let artifact = if errors > 0 {
322 Artifact::Nothing
323 } else {
324 Artifact::Text(rucc_ir::print(&module, &sess.interner))
325 };
326 Compiled { artifact, messages, errors, fired: Fired::new(), dumps: Vec::new() }
328}
329
330fn optimize(
342 module: &mut rucc_ir::Module,
343 names: &Interner,
344 opts: &Options,
345 dumps: &mut Vec<rucc_opt::Dump>,
346) -> Result<(), Vec<Diagnostic>> {
347 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
348 settings.toggles.clone_from(&opts.passes);
349 settings.fuel = opts.pass_fuel.iter().cloned().collect();
350 settings.verify |= opts.verify_each;
351 for spec in &opts.dump_ir {
352 if let Err(why) = settings.dumps.add(spec) {
355 return Err(vec![internal(&why)]);
356 }
357 }
358 let report = rucc_opt::run(module, names, &settings);
359 dumps.extend(report.dumps);
360 match report.broke.is_empty() {
361 true => Ok(()),
362 false => Err(report.broke.iter().map(|why| internal(why)).collect()),
363 }
364}
365
366fn generate(
385 module: &mut rucc_ir::Module,
386 names: &mut Interner,
387 target: &TargetInfo,
388 opts: &Options,
389 fired: &mut Fired,
390) -> Result<Artifact, Vec<Diagnostic>> {
391 let Some(machine) = Machine::for_target(target) else {
392 return Err(vec![unsupported(&format!(
393 "there is no back end for {} in this compiler yet, so there is nothing to generate",
394 target.triple
395 ))]);
396 };
397 let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
398
399 let mut funcs = Vec::new();
400 let mut complaints = Vec::new();
401 for id in module.funcs() {
402 if module[id].is_declaration() {
403 continue;
404 }
405 match pipeline::compile_recording(&mut module[id], names, &machine, flags, fired) {
406 Ok(func) => funcs.push(func),
407 Err(why) => {
408 let name = names.resolve(module[id].name).to_owned();
409 let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
412 let said = format!("cannot generate code for '{name}': {why}");
413 complaints.push(unsupported_at(&said, span));
414 }
415 }
416 }
417 if !complaints.is_empty() {
418 return Err(complaints);
419 }
420 let globals = match opts.emit {
424 EmitKind::Asm | EmitKind::Object | EmitKind::Executable => {
425 rucc_asm::globals(module, names).map_err(refused)?
426 }
427 _ => rucc_asm::Globals::default(),
428 };
429 match opts.emit {
433 EmitKind::Asm => {
434 rucc_asm::print(&funcs, &globals, names, target).map(Artifact::Text).map_err(refused)
435 }
436 EmitKind::Object | EmitKind::Executable => {
439 let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
440 let data = globals.image();
441 rucc_object::write(&text, &data, target).map(Artifact::Object).map_err(
444 |why| match why {
445 rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
446 rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
447 },
448 )
449 }
450 _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
451 }
452}
453
454fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
460 match why {
461 rucc_asm::Error::Thread { .. } => vec![unsupported(&why.to_string())],
462 _ => vec![internal(&why.to_string())],
463 }
464}
465
466fn unsupported(message: &str) -> Diagnostic {
472 unsupported_at(message, Span::DUMMY)
473}
474
475fn unsupported_at(message: &str, span: Span) -> Diagnostic {
481 Diagnostic::error(message.to_owned(), span)
482 .with_code("E0653")
483 .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
484}
485
486fn invalid(message: &str) -> Diagnostic {
488 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
489}
490
491fn internal(message: &str) -> Diagnostic {
493 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
494 .with_code("E0652")
495 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
496}
497
498fn failure(message: String) -> Compiled {
501 Compiled {
502 artifact: Artifact::Nothing,
503 messages: vec![format!("rucc: error: {message}")],
504 errors: 1,
505 fired: Fired::new(),
506 dumps: Vec::new(),
507 }
508}
509
510#[cfg(test)]
511mod tests {
512 use rucc_session::{MemoryFileSystem, Std};
513 use rucc_target::Triple;
514
515 use super::*;
516
517 fn options() -> Options {
518 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
519 opts.emit = EmitKind::Tast;
520 opts
521 }
522
523 fn run(opts: &Options, source: &str) -> Compiled {
524 let mut fs = MemoryFileSystem::new();
525 fs.insert("/main.c", source.to_owned().into_bytes());
526 compile(opts, "/main.c", &fs)
527 }
528
529 fn freestanding() -> Options {
533 let mut opts = options();
534 opts.hosted = false;
535 opts.search.push_system(rucc_session::runtime::DIR);
536 opts
537 }
538
539 fn shipped(source: &str) -> String {
541 let result = run(&freestanding(), source);
542 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
543 result.text().to_owned()
544 }
545
546 fn tast(source: &str) -> String {
548 let result = run(&options(), source);
549 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
550 result.text().to_owned()
551 }
552
553 #[test]
554 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
555 let text = shipped(concat!(
556 "#include <stdarg.h>\n",
557 "int sum(int n, ...) {\n",
558 " va_list ap, copy;\n",
559 " va_start(ap, n);\n",
560 " va_copy(copy, ap);\n",
561 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
562 " va_end(ap);\n",
563 " va_end(copy);\n",
564 " return total;\n",
565 "}\n",
566 ));
567 assert!(text.contains("va-start"), "{text}");
568 assert!(text.contains("va-copy"), "{text}");
569 assert!(text.contains("va-arg"), "{text}");
570 assert!(text.contains("va-end"), "{text}");
571 }
572
573 #[test]
577 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
578 let text = shipped(concat!(
579 "#define __need___va_list\n",
580 "#include <stdarg.h>\n",
581 "int vprint(const char *f, __gnuc_va_list ap);\n",
582 "#ifdef va_start\n",
583 "#error va_start should not be defined\n",
584 "#endif\n",
585 "#ifdef _VA_LIST_DEFINED\n",
586 "#error va_list should not have been made\n",
587 "#endif\n",
588 ));
589 assert!(text.contains("vprint"), "{text}");
590 }
591
592 #[test]
595 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
596 let text = shipped(concat!(
597 "#define __need_size_t\n",
598 "#include <stddef.h>\n",
599 "#ifdef offsetof\n",
600 "#error offsetof should not be defined yet\n",
601 "#endif\n",
602 "#define __need_ptrdiff_t\n",
603 "#include <stddef.h>\n",
604 "#include <stddef.h>\n",
605 "size_t a;\n",
606 "ptrdiff_t b;\n",
607 "wchar_t c;\n",
608 "max_align_t d;\n",
609 "void *e = NULL;\n",
610 "struct P { int x; long y; };\n",
611 "size_t f = offsetof(struct P, y);\n",
612 ));
613 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
614 assert!(text.contains("decl #1 b : long"), "{text}");
615 }
616
617 #[test]
618 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
619 let text = shipped(concat!(
620 "#include <limits.h>\n",
621 "#include <float.h>\n",
622 "int bits = CHAR_BIT;\n",
623 "long big = LONG_MAX;\n",
624 "int low = INT_MIN;\n",
625 "int radix = FLT_RADIX;\n",
626 "int digits = DBL_MANT_DIG;\n",
627 ));
628 assert!(text.contains("const 8 : int"), "{text}");
629 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
630 assert!(text.contains("const 2 : int"), "{text}");
631 assert!(text.contains("const 53 : int"), "{text}");
632 }
633
634 #[test]
638 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
639 let text = shipped(concat!(
640 "#include <stdint.h>\n",
641 "int64_t a = INT64_C(1);\n",
642 "uint_least16_t b;\n",
643 "intptr_t c;\n",
644 "uintmax_t d = UINTMAX_MAX;\n",
645 "int wide = sizeof(int_fast64_t);\n",
646 ));
647 assert!(text.contains("decl #0 a : long"), "{text}");
648 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
649 assert!(text.contains("decl #2 c : long"), "{text}");
650 }
651
652 #[test]
653 fn the_three_formality_headers_still_have_to_work() {
654 let text = shipped(concat!(
655 "#include <stdbool.h>\n",
656 "#include <stdalign.h>\n",
657 "#include <iso646.h>\n",
658 "#include <stdnoreturn.h>\n",
659 "int t = true and not false;\n",
660 "_Alignas(16) char buf[16];\n",
661 "int a = alignof(long);\n",
662 ));
663 assert!(text.contains("decl #0 t : int"), "{text}");
664 assert!(text.contains("const 8 : unsigned long"), "{text}");
665 }
666
667 #[test]
670 fn every_shipped_header_can_be_included_twice() {
671 let mut source = String::new();
672 for _ in 0..2 {
673 for name in rucc_session::runtime::names() {
674 source.push_str(&format!("#include <{name}>\n"));
675 }
676 }
677 source.push_str("int x;\n");
678 let text = shipped(&source);
679 assert!(text.starts_with("decl #0 x : int"), "{text}");
680 }
681
682 #[test]
683 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
684 let fs = MemoryFileSystem::new();
685 let result = compile(&options(), "/nope.c", &fs);
686 assert!(result.failed());
687 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
688 assert!(result.text().is_empty());
689 }
690
691 #[test]
692 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
693 let text = tast("int x = 1;\n");
694 let expected = "\
695decl #0 x : int object external static defined
696 init
697 +0
698 const 1 : int
699";
700 assert_eq!(text, expected);
701 }
702
703 #[test]
704 fn the_macros_are_expanded_before_anything_is_parsed() {
705 let text = tast("#define N 2\nint a[N];\n");
709 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
710 }
711
712 #[test]
718 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
719 let text = tast(concat!(
720 "#pragma pack(4)\n",
721 "struct s { int a; };\n",
722 "#pragma pack()\n",
723 "int b;\n",
724 "_Pragma(\"GCC visibility push(default)\") int c;\n",
725 ));
726 assert!(text.contains("decl #0 b : int"), "{text}");
727 assert!(text.contains("decl #1 c : int"), "{text}");
728 }
729
730 #[test]
738 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
739 tast(concat!(
740 "struct A { char c; int i; } __attribute__((packed));\n",
741 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
742 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
743 "struct B { char c; int i; } __attribute__((aligned));\n",
746 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
747 "struct C { char c; int i __attribute__((packed)); };\n",
748 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
749 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
750 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
751 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
752 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
753 "struct E { char c; _Alignas(8) int i; };\n",
754 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
755 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
756 "struct F { char c; int i __attribute__((aligned(8))); };\n",
757 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
758 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
761 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
762 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
763 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
764 "struct I { [[gnu::packed]] char c; int i; };\n",
767 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
768 "struct J { char c; [[gnu::packed]] int i; };\n",
769 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
770 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
771 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
772 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
773 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
774 "union L { char c; int i; } __attribute__((packed));\n",
775 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
776 "struct O { char c; int i; } __attribute__((__packed__));\n",
780 "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
781 "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
782 "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
783 ));
784 }
785
786 #[test]
796 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
797 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
799 assert_eq!(
800 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
801 1
802 );
803 assert_eq!(
804 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
805 1
806 );
807 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
808 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
810 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
811 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
813 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
814 }
815
816 fn bit_field_byte(record: &str) -> u64 {
818 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
819 let body = body(&source);
820 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
821 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
822 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
823 }
824
825 #[test]
831 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
832 tast(concat!(
833 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
834 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
835 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
836 "struct b { char c; __attribute__((packed)) int i; };\n",
837 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
838 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
839 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
840 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
841 ));
842 }
843
844 #[test]
850 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
851 tast(concat!(
852 "#pragma pack(1)\n",
853 "struct A { char c; int i; };\n",
854 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
855 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
856 "#pragma pack()\n",
857 "struct B { char c; int i; };\n",
858 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
859 "#pragma pack(2)\n",
860 "struct C { char c; int i; double d; };\n",
861 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
862 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
863 "struct K { char c; int i __attribute__((aligned(8))); };\n",
865 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
866 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
867 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
869 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
870 "#pragma pack()\n",
871 "#pragma pack(push, 1)\n",
872 "struct D { char c; short s; };\n",
873 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
874 "#pragma pack(pop)\n",
875 "struct E { char c; short s; };\n",
876 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
877 "struct H { char c;\n",
879 "#pragma pack(1)\n",
880 " int i; };\n",
881 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
882 "#pragma pack(1)\n",
883 "struct I { char c;\n",
884 "#pragma pack()\n",
885 " int i; };\n",
886 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
887 "#pragma pack()\n",
888 "#pragma pack(push, 8)\n",
890 "#pragma pack(push, 1)\n",
891 "struct P { char c; int i; };\n",
892 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
893 "#pragma pack(pop)\n",
894 "struct Q { char c; int i; };\n",
895 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
896 "#pragma pack(pop)\n",
897 "#pragma pack(16)\n",
899 "struct R { char c; int i; };\n",
900 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
901 "#pragma pack()\n",
902 "#pragma pack(1)\n",
903 "struct S { char c; int i : 5; int j : 20; };\n",
904 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
905 "union T { char c; int i; };\n",
906 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
907 "#pragma pack()\n",
908 ));
909 }
910
911 #[test]
915 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
916 let result = run(
917 &options(),
918 concat!(
919 "#pragma pack 4\n",
920 "#pragma pack(pop)\n",
921 "#pragma pack(3)\n",
922 "#pragma pack(1) junk\n",
923 "#pragma pack(push, 1\n",
924 "#pragma pack(x)\n",
925 "#pragma pack(0)\n",
928 "#pragma pack(push)\n",
929 "struct s { char c; int i; };\n",
930 "#pragma pack(pop)\n",
931 "#pragma pack(pop, foo)\n",
932 ),
933 );
934 let expected = [
935 "missing `(` after `#pragma pack` - ignored",
936 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
937 "alignment must be a small power of two, not 3",
938 "junk at end of `#pragma pack`",
939 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
940 "unknown action `x` for `#pragma pack` - ignored",
941 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
942 ];
943 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
944 for (message, want) in result.messages.iter().zip(expected) {
945 assert!(message.contains(want), "expected {want:?} in {message:?}");
946 }
947 }
948
949 #[test]
953 fn the_wide_integer_answers_to_all_three_of_its_names() {
954 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
955 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
956 assert!(text.contains("decl #1 b : __int128"), "{text}");
957 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
958 }
959
960 #[test]
961 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
962 let text = tast("long f(int a, long b) { return a + b; }\n");
966 assert!(text.contains("convert arithmetic"), "{text}");
967 }
968
969 #[test]
970 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
971 for source in [
972 "#error stop\n",
973 "int f(void) { return 1 + ; }\n",
974 "int f(void) { return undeclared; }\n",
975 ] {
976 let result = run(&options(), source);
977 assert!(result.failed(), "expected this to fail:\n{source}");
978 assert!(
979 result.text().is_empty(),
980 "a file that did not compile wrote a tree:\n{source}"
981 );
982 }
983 }
984
985 #[test]
986 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
987 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
991 assert_eq!(result.errors, 1, "{:?}", result.messages);
992 }
993
994 #[test]
995 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
996 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
1000 assert_eq!(result.errors, 1, "{:?}", result.messages);
1001 }
1002
1003 #[test]
1004 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
1005 let source = "int f(void) { char c = 300; return c; }\n";
1006 let plain = run(&options(), source);
1007 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
1008 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
1009 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
1010
1011 let mut opts = options();
1012 opts.warnings_are_errors = true;
1013 let strict = run(&opts, source);
1014 assert!(strict.failed());
1015 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
1016 for message in &strict.messages {
1017 assert!(!message.contains("warning:"), "{message}");
1018 }
1019 }
1020
1021 #[test]
1022 fn the_dialect_reaches_the_keywords_and_the_checking() {
1023 let source = "typeof(1) x;\n";
1026 let mut opts = options();
1027 opts.std = Std::C23;
1028 opts.gnu_extensions = false;
1029 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
1030
1031 opts.std = Std::C17;
1032 assert!(run(&opts, source).failed());
1033 }
1034
1035 #[test]
1036 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
1037 let mut opts = options();
1038 opts.emit = EmitKind::Object;
1039 let result = run(&opts, "int x = 1;\n");
1040 assert!(!result.failed(), "{:?}", result.messages);
1041 assert!(result.text().is_empty());
1042 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
1045 }
1046
1047 fn mir(source: &str) -> String {
1049 let mut opts = options();
1050 opts.emit = EmitKind::MirFinal;
1051 let result = run(&opts, source);
1052 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1053 result.text().to_owned()
1054 }
1055
1056 #[test]
1062 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
1063 let text = mir("int add(int a, int b) { return a + b; }\n");
1064 assert!(text.starts_with("mfunc @add {"), "{text}");
1065 assert!(text.contains("x64.add_rr_32"), "{text}");
1066 assert!(text.contains("x64.ret"), "{text}");
1067 assert!(!text.contains('%'), "{text}");
1070 }
1071
1072 #[test]
1074 fn a_function_with_no_body_produces_no_machine_function() {
1075 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1076 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1077 assert!(text.contains("mfunc @f {"), "{text}");
1078 assert!(text.contains("x64.call"), "{text}");
1079 }
1080
1081 #[test]
1083 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1084 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1085 let first = text.find("mfunc @a").expect("the first function");
1086 let second = text.find("mfunc @b").expect("the second function");
1087 assert!(first < second, "{text}");
1088 }
1089
1090 #[test]
1092 fn the_target_decides_which_convention_the_generated_code_follows() {
1093 let mut opts = options();
1094 opts.emit = EmitKind::MirFinal;
1095 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1096 assert!(linux.contains("$rdi"), "{linux}");
1097
1098 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1099 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1100 assert!(windows.contains("$rcx"), "{windows}");
1101 assert!(!windows.contains("$rdi"), "{windows}");
1102 }
1103
1104 #[test]
1106 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1107 let mut opts = options();
1108 opts.emit = EmitKind::MirFinal;
1109 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1110 let result = run(&opts, "int f(int a) { return a; }\n");
1111 assert!(result.failed());
1112 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1113 assert!(result.text().is_empty());
1114 }
1115
1116 #[test]
1123 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1124 let mut opts = options();
1125 opts.emit = EmitKind::MirFinal;
1126 let source = "long double a(long double x) { return x; }\n\
1127 long double b(long double x) { return x; }\n";
1128 let result = run(&opts, source);
1129 assert!(result.failed());
1130 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1131 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1132 assert!(result.messages[0].contains("x87 stack"), "{:?}", result);
1133 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1134 assert!(result.text().is_empty());
1135 }
1136
1137 #[test]
1144 fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1145 let mut opts = options();
1146 opts.emit = EmitKind::MirFinal;
1147 let result = run(&opts, "int f(int a) {\n __int128 wide = a;\n return (int) wide;\n}\n");
1148 assert!(result.failed());
1149 assert!(
1150 result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1151 "{result:?}"
1152 );
1153 assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1154 assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1155 }
1156
1157 #[test]
1159 fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1160 let mut opts = options();
1161 opts.emit = EmitKind::MirFinal;
1162 let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1163 assert!(result.failed());
1164 let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1165 assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1166 assert!(!note.contains("spec/17-milestones.md"), "{note}");
1167 }
1168
1169 #[test]
1171 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1172 let source = "int f(int a) { return a; }\n";
1173 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1174
1175 let mut opts = options();
1176 opts.emit = EmitKind::MirFinal;
1177 opts.frame_pointer = true;
1178 let kept = run(&opts, source).text().to_owned();
1179 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1180 }
1181
1182 fn asm(source: &str) -> String {
1184 let mut opts = options();
1185 opts.emit = EmitKind::Asm;
1186 let result = run(&opts, source);
1187 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1188 result.text().to_owned()
1189 }
1190
1191 #[test]
1198 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1199 let text = asm("int add(int a, int b) { return a + b; }\n");
1200 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1201 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1202 assert!(text.contains("\nadd:\n"), "{text}");
1203 assert!(text.contains("\taddl\t"), "{text}");
1204 assert!(text.contains("\tret\n"), "{text}");
1205 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1206 assert!(text.contains(".note.GNU-stack"), "{text}");
1209 }
1210
1211 #[test]
1217 fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1218 let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1219 assert!(text.contains("\tcall\t*%"), "{text}");
1220 assert!(text.contains("\tcall\tg\n"), "{text}");
1221 assert!(text.contains("%rdi"), "{text}");
1225 }
1226
1227 #[test]
1229 fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1230 let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1231 assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1232 }
1233
1234 #[test]
1236 fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1237 let text = asm("long f(void *p) { return (long)p; }\n");
1238 for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1243 let mnemonic = line.split_whitespace().next().unwrap_or("");
1244 assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1245 }
1246 }
1247
1248 #[test]
1252 fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1253 let six = "long a, long b, long c, long d, long e, long f";
1254 let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1255
1256 assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1260 assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1261
1262 let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1266 assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1267 let eight =
1268 "double a, double b, double c, double d, double e, double f, double g, double h";
1269 let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1270 assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1271 }
1272
1273 #[test]
1276 fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1277 let six = "1, 2, 3, 4, 5, 6";
1278 let decl = "long g(long, long, long, long, long, long, long, long);\n";
1279 let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1280
1281 assert!(text.contains("\tmovq\t%"), "{text}");
1282 assert!(text.contains(", (%rsp)\n"), "{text}");
1283 assert!(text.contains(", 8(%rsp)\n"), "{text}");
1284 assert!(text.contains("\tsubq\t$"), "{text}");
1286
1287 let narrow = "int g(int, int, int, int, int, int, int);\n";
1289 let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1290 assert!(text.contains("\tmovl\t%"), "{text}");
1291 assert!(text.contains(", (%rsp)\n"), "{text}");
1292 }
1293
1294 #[test]
1297 fn a_variadic_call_counts_registers_and_not_arguments() {
1298 let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1299 let decl = "int g(int, ...);\n";
1300 let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1301
1302 assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1303 assert!(text.contains("\tmovsd\t%"), "{text}");
1304 assert!(text.contains(", (%rsp)\n"), "{text}");
1305 }
1306
1307 #[test]
1312 fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1313 let body =
1314 "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1315 let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1316
1317 let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1320 assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1321 assert!(!text.contains(", 0(%r"), "{text}");
1322 assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1323
1324 assert!(text.contains("\tsubq\t$"), "{text}");
1326 }
1327
1328 #[test]
1331 fn va_start_writes_the_four_fields_the_psabi_describes() {
1332 let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1333 let params = "int a, int b, int c, double d";
1334 let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1335
1336 assert!(text.contains(" movl $24, "), "{text}");
1340 assert!(text.contains(" movl $64, "), "{text}");
1341 assert!(text.contains(", 8(%r"), "{text}");
1345 assert!(text.contains(", 16(%r"), "{text}");
1346 let frame: u32 = text
1347 .lines()
1348 .find_map(|line| line.trim().strip_prefix("subq $")?.split(',').next()?.parse().ok())
1349 .expect("a variadic function takes a frame for the save area");
1350 let above = |line: &str| {
1351 let at: u32 = line.trim().strip_prefix("leaq ")?.split('(').next()?.parse().ok()?;
1352 Some(at > frame)
1353 };
1354 assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1355 }
1356
1357 #[test]
1360 fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1361 let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1362 let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1363 let text = asm(&ints);
1364
1365 assert!(text.contains("$40, "), "{text}");
1368 assert!(text.contains(" cmpl "), "{text}");
1369 assert!(text.contains(" setbe "), "unsigned, since an offset is a count of bytes: {text}");
1370
1371 let arg = "__builtin_va_arg(ap, double)";
1372 let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1373 assert!(text.contains("$160, "), "the last vector slot: {text}");
1374 }
1375
1376 #[test]
1379 fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1380 let decl = "struct pair { long a, b; };\n";
1381 let body = "struct pair p = *q; return p.a + p.b;";
1382 let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
1383
1384 assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
1385 assert!(!text.contains("\tcall"), "{text}");
1386 assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
1388 }
1389
1390 #[test]
1393 fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
1394 let decl = "struct bytes { char a[8]; };\n";
1395 let body = "struct bytes p = *q; return p.a[0];";
1396 let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
1397
1398 assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
1400 }
1401
1402 #[test]
1405 fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
1406 let decl = "struct wide { long a, b, c; };\n";
1407 let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
1408
1409 assert!(!text.contains("memset"), "nothing calls the library: {text}");
1410 assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
1411 }
1412
1413 #[test]
1416 fn a_copy_too_large_to_unroll_calls_the_runtime() {
1417 let decl = "struct huge { char a[4096]; };\n";
1418 let mut opts = options();
1419 opts.emit = EmitKind::Asm;
1420 let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
1421 let result = run(&opts, &source);
1422 assert!(!result.failed(), "{:?}", result.messages);
1423 let text = result.text();
1424 assert!(text.contains("call") && text.contains("memcpy"), "{text}");
1425 assert!(text.contains("4096"), "the size travels: {text}");
1428 }
1429
1430 #[test]
1433 fn a_realigned_frame_reads_them_through_the_frame_pointer() {
1434 let six = "long a, long b, long c, long d, long e, long f";
1435 let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
1436 let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
1437
1438 assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
1442 assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
1443 assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
1444 }
1445
1446 #[test]
1448 fn the_target_decides_how_the_assembly_is_spelled() {
1449 let mut opts = options();
1450 opts.emit = EmitKind::Asm;
1451 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1452 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1453 assert!(text.contains("__TEXT,__text"), "{text}");
1454 assert!(text.contains("\n_f:\n"), "{text}");
1455 assert!(!text.contains(".note.GNU-stack"), "{text}");
1456 }
1457
1458 fn obj(source: &str) -> Vec<u8> {
1460 let mut opts = options();
1461 opts.emit = EmitKind::Object;
1462 let result = run(&opts, source);
1463 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1464 match result.artifact {
1465 Artifact::Object(bytes) => bytes,
1466 other => panic!("expected an object, got {other:?}"),
1467 }
1468 }
1469
1470 #[test]
1476 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1477 let bytes = obj("int add(int a, int b) { return a + b; }\n");
1478 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1479 let text = asm("int add(int a, int b) { return a + b; }\n");
1480 assert!(
1481 text.contains("\taddl\t"),
1482 "and the listing of it is the same instructions:\n{text}"
1483 );
1484 }
1485
1486 #[test]
1488 fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1489 let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1490 assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1491 assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1492 assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1493 assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1496 assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1497 assert!(!text.contains(".globl\thidden"), "{text}");
1498 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1501 }
1502
1503 #[test]
1505 fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1506 let text = asm("const char *f(void) { return \"hi\"; }\n");
1507 assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1508 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1509 let label = text
1510 .lines()
1511 .find(|line| line.starts_with(".Lstr"))
1512 .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1513 assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1514 }
1515
1516 #[test]
1518 fn an_address_in_an_initializer_is_left_to_the_linker() {
1519 let source = "int counter;\nint *p = &counter;\n";
1520 let text = asm(source);
1521 assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1522 let bytes = obj(source);
1525 assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1526 }
1527
1528 #[test]
1530 fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
1531 let mut opts = options();
1532 opts.emit = EmitKind::Asm;
1533 let result = run(&opts, "_Thread_local int x = 1;\n");
1534 assert!(result.failed(), "every thread sharing one variable is worse than a message");
1535 assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
1536 assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
1538 }
1539
1540 #[test]
1542 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1543 let source = "int callee(void); int g(void) { return callee(); }\n";
1547 let bytes = obj(source);
1548 assert!(
1549 bytes.windows(7).any(|w| w == b"callee\0"),
1550 "the object has to name the callee for the linker to find it"
1551 );
1552 let text = asm(source);
1553 assert!(text.contains("\tcall\tcallee\n"), "{text}");
1554 }
1555
1556 #[test]
1562 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1563 let mut opts = options();
1564 opts.emit = EmitKind::Executable;
1566 let result = run(&opts, "int main(void) { return 0; }\n");
1567 assert_eq!(result.messages, Vec::<String>::new());
1568 match result.artifact {
1569 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1570 other => panic!("expected an object, got {other:?}"),
1571 }
1572 }
1573
1574 #[test]
1576 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1577 let mut opts = options();
1578 opts.emit = EmitKind::Object;
1579 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1580 let result = run(&opts, "int f(void) { return 0; }\n");
1581 assert!(result.failed(), "an object nobody can read is worse than a message");
1582 assert!(
1583 result.messages.iter().any(|m| m.contains("no object writer")),
1584 "{:?}",
1585 result.messages
1586 );
1587 }
1588
1589 fn ir(source: &str) -> String {
1591 let mut opts = options();
1592 opts.emit = EmitKind::Ir;
1593 let result = run(&opts, source);
1594 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1595 result.text().to_owned()
1596 }
1597
1598 fn body(source: &str) -> String {
1600 let text = ir(source);
1601 let (_, rest) = text.split_once("{\n").expect("a function definition");
1602 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1603 body.to_owned()
1604 }
1605
1606 #[test]
1614 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1615 let text = ir(concat!(
1616 "int g;\n",
1617 "int a = __builtin_constant_p(1);\n",
1618 "int b = __builtin_constant_p(g);\n",
1619 "int c = __builtin_constant_p(\"abc\");\n",
1620 "int d = __builtin_constant_p(&g);\n",
1621 "int e = __builtin_constant_p(1.5);\n",
1622 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1623 ));
1624 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1625 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1626 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1627 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1628 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1629 assert!(text.contains("global @h : i32 = 11,"), "{text}");
1630 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1631
1632 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1636 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
1637 }
1638
1639 #[test]
1648 fn a_call_to_a_library_builtin_reaches_the_library_function() {
1649 let text = body("void f(void) { __builtin_abort(); }\n");
1650 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
1651
1652 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1655 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1656 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1657 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1658 }
1659
1660 #[test]
1672 fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
1673 let text = ir(concat!(
1674 "long a = __builtin_expect(7, 1);\n",
1675 "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
1676 "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
1677 ));
1678 assert!(text.contains("global @a : i64 = 7,"), "{text}");
1679 assert!(text.contains("global @b : i64 = 9,"), "{text}");
1680 assert!(text.contains("global @c : i64 = 8,"), "{text}");
1681 assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
1682
1683 let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
1686 assert!(text.contains("sext"), "{text}");
1687
1688 let one = "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 1\n %2 = sext.i64 %1\n return %0\n";
1692 assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
1693 let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
1694 assert_eq!(body(source), one);
1695 }
1696
1697 #[test]
1709 fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
1710 let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
1711 let text = ir(promised);
1712 assert!(text.contains(" unreachable_hint\n"), "{text}");
1713 assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
1714
1715 let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
1719 assert!(after.contains("return"), "{after}");
1720
1721 let text = asm(promised);
1724 let mine = text.split_once("\nf:\n").expect("a definition").1;
1725 let mine = mine.split_once("\t.size").expect("a definition").0;
1726 let plain = asm("int f(int x) { if (x) return 1; }\n");
1727 let plain = plain.split_once("\nf:\n").expect("a definition").1;
1728 let plain = plain.split_once("\t.size").expect("a definition").0;
1729 assert_eq!(mine, plain);
1730 assert!(mine.trim_end().ends_with("ret"), "{mine}");
1731 assert!(!mine.contains("ud2"), "{mine}");
1732 }
1733
1734 #[test]
1741 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1742 let mut opts = options();
1743 opts.emit = EmitKind::Ir;
1744 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1745 assert!(
1746 messages.iter().any(|m| m.contains("__builtin_abort")),
1747 "expected the written name in {messages:?}"
1748 );
1749 }
1750
1751 #[test]
1759 fn a_builtin_nothing_lowers_is_refused_by_name() {
1760 let mut opts = options();
1761 opts.emit = EmitKind::Ir;
1762 for (builtin, call) in [
1763 ("__builtin_clz", "__builtin_clz(1u)"),
1764 ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
1765 ("__atomic_load_n", "__atomic_load_n(&counter, 0)"),
1766 ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
1767 ] {
1768 let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
1769 let messages = run(&opts, &source).messages;
1770 let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
1771 assert!(named, "expected {builtin} to be refused by name in {messages:?}");
1772 }
1773 }
1774
1775 #[test]
1783 fn what_is_refused_is_the_call_and_not_the_name() {
1784 let text = ir("unsigned long n = sizeof(__builtin_clz(1u));\n");
1785 assert!(text.contains("global @n : i64 = 4,"), "{text}");
1786
1787 let text = ir(
1788 "int __builtin_clz(unsigned x) { return 1; }\nint f(void) { return __builtin_clz(2u); }\n",
1789 );
1790 assert!(text.contains("call @__builtin_clz"), "{text}");
1791 }
1792
1793 #[test]
1798 fn a_static_function_nothing_refers_to_is_not_emitted() {
1799 let text = ir("static int dropped(void) { return 1; }\n\
1800 static int kept(void) { return 2; }\n\
1801 int main(void) { return kept(); }\n");
1802 assert!(text.contains("func @kept"), "{text}");
1803 assert!(!text.contains("dropped"), "{text}");
1804 }
1805
1806 #[test]
1812 fn two_static_functions_that_only_call_each_other_are_both_dropped() {
1813 let text = ir("static int ping(void);\n\
1814 static int pong(void) { return ping(); }\n\
1815 static int ping(void) { return pong(); }\n\
1816 int main(void) { return 0; }\n");
1817 assert!(!text.contains("ping"), "{text}");
1818 assert!(!text.contains("pong"), "{text}");
1819 }
1820
1821 #[test]
1827 fn naming_a_static_function_anywhere_keeps_it() {
1828 let text = ir("static int by_address(void) { return 1; }\n\
1829 static int in_an_image(void) { return 2; }\n\
1830 static int deeper(void) { return 3; }\n\
1831 static int reaches_deeper(void) { return deeper(); }\n\
1832 static int (*table[1])(void) = {in_an_image};\n\
1833 int main(void) {\n\
1834 int (*p)(void) = by_address;\n\
1835 return p() + table[0]() + reaches_deeper();\n\
1836 }\n");
1837 for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
1838 assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
1839 }
1840 }
1841
1842 #[test]
1848 fn an_attribute_keeps_a_static_function_nothing_refers_to() {
1849 for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
1850 let source = format!(
1851 "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
1852 int main(void) {{ return 0; }}\n"
1853 );
1854 let text = ir(&source);
1855 assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
1856 }
1857 }
1858
1859 #[test]
1862 fn a_function_anything_could_call_is_emitted_without_being_called() {
1863 let text =
1864 ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
1865 assert!(text.contains("func @nobody_here_calls_it"), "{text}");
1866 }
1867
1868 #[test]
1875 fn a_classification_c_has_an_operator_for_is_that_operator() {
1876 for (builtin, operator) in [
1877 ("__builtin_isgreater", "binary >"),
1878 ("__builtin_isgreaterequal", "binary >="),
1879 ("__builtin_isless", "binary <"),
1880 ("__builtin_islessequal", "binary <="),
1881 ] {
1882 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1883 let text = tast(&source);
1884 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1885 }
1886 }
1887
1888 #[test]
1897 fn the_classification_builtins_are_comparisons_and_not_calls() {
1898 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1899 assert_eq!(
1900 text,
1901 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
1902 %2\n return %3\n"
1903 );
1904
1905 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1907 assert!(text.contains("fcmp one %0, %1"), "{text}");
1908
1909 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1910 assert!(text.contains("fcmp uno %0, %0"), "{text}");
1911
1912 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1913 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1914 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1915 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1916 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1917 assert!(text.contains("%5 = or %3, %4"), "{text}");
1918
1919 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1922 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1923 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1924 assert!(text.contains("%5 = and %3, %4"), "{text}");
1925
1926 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1927 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1928 assert!(text.contains("icmp slt %1, %2"), "{text}");
1929
1930 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1933 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1934
1935 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1938 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1939 }
1940
1941 #[test]
1948 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1949 let text = ir(concat!(
1950 "int a = __builtin_isinff(1e300);\n",
1951 "int b = __builtin_isinf(1e300);\n",
1952 "int c = __builtin_isnan(0.0);\n",
1956 "int d = __builtin_signbit(-0.0);\n",
1957 "int e = __builtin_islessgreater(1.0, 2.0);\n",
1958 ));
1959 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1960 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1961 assert!(text.contains("global @c : i32 = 0,"), "{text}");
1962 assert!(text.contains("global @d : i32 = 1,"), "{text}");
1963 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1964 }
1965
1966 #[test]
1968 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1969 let mut opts = options();
1970 opts.emit = EmitKind::Ir;
1971 let source = concat!(
1972 "int a(int x) { return __builtin_isnan(x); }\n",
1973 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1974 "int c(double x) { return __builtin_isnan(x, x); }\n",
1975 );
1976 let messages = run(&opts, source).messages;
1977 assert_eq!(
1978 messages,
1979 [
1980 "/main.c:1:23: error: non-floating-point argument in call to function \
1981 '__builtin_isnan' [E0685]",
1982 "/main.c:2:30: error: non-floating-point arguments in call to function \
1983 '__builtin_isunordered' [E0685]",
1984 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1985 ]
1986 );
1987 }
1988
1989 #[test]
1998 fn the_last_three_classification_builtins_are_comparisons_and_not_calls() {
1999 let text = body("int f(double x) { return __builtin_isnormal(x); }\n");
2000 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
2004 assert!(text.contains("%2 = iconst.i64 9223372036854775807"), "{text}");
2005 assert!(text.contains("%3 = and %1, %2"), "{text}");
2006 assert!(text.contains("%4 = iconst.i64 4503599627370496"), "{text}");
2007 assert!(text.contains("%5 = iconst.i64 9218868437227405312"), "{text}");
2008 assert!(text.contains("%6 = icmp uge %3, %4"), "{text}");
2009 assert!(text.contains("%7 = icmp ult %3, %5"), "{text}");
2010 assert!(text.contains("%8 = and %6, %7"), "{text}");
2011
2012 let text = body("int f(long double x) { return __builtin_isnormal(x); }\n");
2016 assert!(text.contains("%4 = iconst.i80 27670116110564327424"), "{text}");
2017 assert!(text.contains("%5 = iconst.i80 604453686435277732577280"), "{text}");
2018
2019 let text = body("int f(double x) { return __builtin_isinf_sign(x); }\n");
2020 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
2021 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
2022 assert!(text.contains("%7 = sub %5, %6"), "{text}");
2023
2024 let text = body("int f(double x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n");
2025 assert!(text.contains("fcmp uno %0, %0"), "{text}");
2026 assert!(text.contains("fcmp oeq %0, %6"), "{text}");
2027 assert_eq!(text.matches(" = zext.i32 ").count(), 4, "{text}");
2031 assert_eq!(text.matches(" = xor ").count(), 4, "{text}");
2032 assert!(!text.contains("call"), "{text}");
2033
2034 let text = body(concat!(
2037 "double g(void);\n",
2038 "int f(void) { return __builtin_fpclassify(0, 1, 2, 3, 4, g()); }\n",
2039 ));
2040 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
2041 }
2042
2043 #[test]
2050 fn the_last_three_classification_builtins_fold_where_their_operand_is_a_constant() {
2051 let text = ir(concat!(
2052 "int a = __builtin_isnormal(1.0);\n",
2053 "int b = __builtin_isnormal(0.0);\n",
2054 "int c = __builtin_isnormal(1.0 / 0.0);\n",
2055 "int d = __builtin_isinf_sign(-1.0 / 0.0);\n",
2056 "int e = __builtin_isinf_sign(1.0);\n",
2057 "int g = __builtin_fpclassify(0, 1, 2, 3, 4, 0.0);\n",
2058 "int h = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0);\n",
2059 "int i = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0 / 0.0);\n",
2060 ));
2061 assert!(text.contains("global @a : i32 = 1,"), "{text}");
2062 assert!(text.contains("global @b : i32 = 0,"), "{text}");
2063 assert!(text.contains("global @c : i32 = 0,"), "{text}");
2064 assert!(text.contains("global @d : i32 = -1,"), "{text}");
2065 assert!(text.contains("global @e : i32 = 0,"), "{text}");
2066 assert!(text.contains("global @g : i32 = 4,"), "{text}");
2067 assert!(text.contains("global @h : i32 = 2,"), "{text}");
2068 assert!(text.contains("global @i : i32 = 1,"), "{text}");
2069 }
2070
2071 #[test]
2077 fn fpclassify_refuses_an_answer_that_is_not_an_integer_constant() {
2078 let mut opts = options();
2079 opts.emit = EmitKind::Ir;
2080 let source = concat!(
2081 "int a(double x, int n) { return __builtin_fpclassify(0, 1, n, 3, 4, x); }\n",
2082 "int b(double x) { return __builtin_fpclassify(0, 1, 2, 3, x); }\n",
2083 "int c(int x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n",
2084 );
2085 let messages = run(&opts, source).messages;
2086 assert_eq!(
2087 messages,
2088 [
2089 "/main.c:1:60: error: non-const integer argument 3 in call to function \
2090 '__builtin_fpclassify' [E0687]",
2091 "/main.c:2:26: error: too few arguments to function '__builtin_fpclassify' \
2092 [E0511]",
2093 "/main.c:3:23: error: non-floating-point argument in call to function \
2094 '__builtin_fpclassify' [E0685]",
2095 ]
2096 );
2097 }
2098
2099 #[test]
2107 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
2108 let text = ir(concat!(
2109 "double a = __builtin_inf();\n",
2110 "float b = __builtin_huge_valf();\n",
2111 "long double c = __builtin_infl();\n",
2112 "double d = __builtin_huge_val();\n",
2113 ));
2114 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
2115 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
2116 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
2117 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
2118 assert!(!text.contains("call"), "{text}");
2119 }
2120
2121 #[test]
2130 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
2131 let text = ir(concat!(
2132 "double a = __builtin_nan(\"\");\n",
2133 "double b = __builtin_nan(\"0x1\");\n",
2134 "double c = __builtin_nan(\"010\");\n",
2136 "double d = __builtin_nans(\"\");\n",
2137 "double e = __builtin_nans(\"0x1\");\n",
2138 "float f = __builtin_nanf(\"0x1\");\n",
2139 "float g = __builtin_nansf(\"\");\n",
2140 "long double h = __builtin_nansl(\"\");\n",
2141 ));
2142 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
2143 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
2144 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
2145 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
2146 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
2147 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
2148 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
2149 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
2150
2151 let text = ir(concat!(
2154 "double f(const char *p) { return __builtin_nan(p); }\n",
2155 "double g(void) { return __builtin_nans(\"1x\"); }\n",
2156 ));
2157 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
2158 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
2159 }
2160
2161 #[test]
2169 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
2170 let text = ir(concat!(
2171 "unsigned long a = __builtin_strlen(\"hello\");\n",
2172 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
2173 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
2174 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
2175 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
2176 ));
2177 assert!(text.contains("global @a : i64 = 5,"), "{text}");
2178 assert!(text.contains("global @b : i64 = 1,"), "{text}");
2179 assert!(text.contains("global @c : i32 = 1,"), "{text}");
2180 assert!(text.contains("global @d : i32 = 0,"), "{text}");
2181 assert!(text.contains("global @e : i32 = 1,"), "{text}");
2182 assert!(!text.contains("call"), "{text}");
2183
2184 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
2186 assert!(text.contains("call @strlen("), "{text}");
2187 }
2188
2189 #[test]
2196 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
2197 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
2198 assert!(text.contains("bitcast.i64 %0"), "{text}");
2199 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
2200 assert!(text.contains("and %1, %2"), "{text}");
2201 assert!(text.contains("bitcast.f64 %3"), "{text}");
2202 assert!(!text.contains("call"), "{text}");
2203
2204 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
2205 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
2206 assert!(text.contains("%8 = or %4, %7"), "{text}");
2207 assert!(!text.contains("call"), "{text}");
2208
2209 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
2212 assert!(text.contains("bitcast.i80 %0"), "{text}");
2213 assert!(text.contains("bitcast.f80"), "{text}");
2214
2215 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
2218 assert!(text.contains("fpext.f64 %0"), "{text}");
2219 assert!(text.contains("bitcast.i64 %1"), "{text}");
2220 }
2221
2222 #[test]
2231 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
2232 let text = ir(concat!(
2233 "double a = __builtin_fabs(-3.5);\n",
2234 "double b = __builtin_copysign(1.0, -0.0);\n",
2235 "double c = __builtin_copysign(0.0, -2.0);\n",
2236 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
2238 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
2239 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
2240 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
2241 "long double i = __builtin_fabsl(-__builtin_infl());\n",
2242 ));
2243 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
2244 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
2245 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
2246 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
2247 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
2248 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
2249 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
2250 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
2251 }
2252
2253 #[test]
2260 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
2261 let text = ir(concat!(
2262 "constexpr int side = 4;\n",
2263 "constexpr int wider = side + 1;\n",
2264 "constexpr double half = 1.5;\n",
2265 "struct point { int x; int y; };\n",
2266 "constexpr struct point origin = { 5, 6 };\n",
2267 "int square[side * side];\n",
2268 "int rectangle[wider];\n",
2269 "int rounded[(int)half * 2];\n",
2270 "int across[origin.y];\n",
2271 "enum named { four = side };\n",
2272 "int e = four;\n",
2273 ));
2274 assert!(text.contains("global @square : bytes 64 ="), "{text}");
2275 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
2276 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
2277 assert!(text.contains("global @across : bytes 24 ="), "{text}");
2278 assert!(text.contains("global @e : i32 = 4,"), "{text}");
2279
2280 let mut opts = options();
2283 opts.emit = EmitKind::Ir;
2284 let konst = "const int n = 1;\nint a[n];\n";
2285 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
2286 assert_eq!(run(&opts, konst).messages, [message]);
2287
2288 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
2290 assert_eq!(run(&opts, subscript).messages, [message]);
2291
2292 let address = "constexpr int c = 3;\nint *p = &c;\n";
2294 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
2295 pointer target type [E0514]";
2296 assert_eq!(run(&opts, address).messages, [warning]);
2297 }
2298
2299 #[test]
2308 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
2309 let mut opts = options();
2312 opts.std = Std::C17;
2313 let source = concat!(
2314 "int add(a, b)\n",
2315 "int a;\n",
2316 "int b;\n",
2317 "{ return a + b; }\n",
2318 "int promoted(c)\n",
2319 "char c;\n",
2320 "{ return c; }\n",
2321 "int narrow(char);\n",
2322 "int narrow(c)\n",
2323 "char c;\n",
2324 "{ return c; }\n",
2325 "int first(a)\n",
2326 "int a[4];\n",
2327 "{ return a[0]; }\n",
2328 );
2329 let result = run(&opts, source);
2330 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2331 let text = result.text();
2332 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
2333 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
2334 assert!(text.contains("c : char object automatic defined"), "{text}");
2336 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
2337 assert!(text.contains("first : int(int *) function external defined"), "{text}");
2339 }
2340
2341 #[test]
2348 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
2349 let mut opts = options();
2350 opts.std = Std::C17;
2351 for (source, message) in [
2352 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
2353 (
2354 "int f(a)\nint a;\nint b;\n{ return a; }\n",
2355 "3:5: error: declaration for parameter 'b' but no such parameter",
2356 ),
2357 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
2358 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
2359 (
2360 "int f(a)\nstatic int a;\n{ return a; }\n",
2361 "2:12: error: storage class specified for parameter 'a'",
2362 ),
2363 (
2364 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
2365 "2:7: error: argument 'a' doesn't match prototype",
2366 ),
2367 ] {
2368 let result = run(&opts, source);
2369 assert!(result.failed(), "expected this to fail:\n{source}");
2370 assert!(result.messages[0].contains(message), "{:?}", result.messages);
2371 }
2372
2373 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
2376 let mut older = options();
2377 older.std = Std::C89;
2378 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
2379 let result = run(&opts, implicit);
2380 assert!(
2381 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
2382 "{:?}",
2383 result.messages
2384 );
2385
2386 let mut newer = options();
2390 newer.std = Std::C23;
2391 let plain = "int f(a)\nint a;\n{ return a; }\n";
2392 let result = run(&newer, plain);
2393 assert!(!result.failed(), "{:?}", result.messages);
2394 assert_eq!(
2395 result.messages,
2396 ["/main.c:1:5: warning: old-style function definition [E0412]"]
2397 );
2398 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
2399 }
2400
2401 #[test]
2408 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
2409 let text = ir(concat!(
2410 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
2411 "struct brim { char buf[9223372036854775807L]; };\n",
2412 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
2413 "unsigned long h = sizeof(struct huge_struct);\n",
2414 "unsigned long b = sizeof(struct brim);\n",
2415 "unsigned long y = sizeof(struct bitty);\n",
2416 ));
2417 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
2418 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
2419 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
2420
2421 let mut opts = options();
2422 opts.emit = EmitKind::Ir;
2423 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
2424 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
2425 assert_eq!(run(&opts, over).messages, [message]);
2426 let array = "struct wide { short buf[1L << 62]; };\n";
2427 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
2428 maximum object size '9223372036854775807' [E0537]";
2429 assert_eq!(run(&opts, array).messages[0], message);
2430 }
2431
2432 fn compile_bytes(source: &[u8]) -> Compiled {
2437 let mut opts = options();
2438 opts.emit = EmitKind::Ir;
2439 let mut fs = MemoryFileSystem::new();
2440 fs.insert("/main.c", source.to_vec());
2441 compile(&opts, "/main.c", &fs)
2442 }
2443
2444 #[test]
2451 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
2452 let mut source = b"char s[] = \"a".to_vec();
2453 source.push(0xff);
2454 source.extend_from_slice(b"b\";\nchar c = '");
2455 source.push(0xff);
2456 source.extend_from_slice(b"';\n");
2457 let result = compile_bytes(&source);
2458 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
2459 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
2460 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
2462
2463 let mut stray = b"int a".to_vec();
2464 stray.push(0xff);
2465 stray.extend_from_slice(b" = 1;\n");
2466 let result = compile_bytes(&stray);
2467 assert!(
2468 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
2469 "{:?}",
2470 result.messages
2471 );
2472 }
2473
2474 #[test]
2475 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
2476 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
2477 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
2478 let expected = "\
2479func @add(i32, i32) -> i32, linkage(external) {
2480block0(%0: i32, %1: i32):
2481 %2 = add.nsw %0, %1
2482 return %2
2483}
2484";
2485 assert!(text.contains(expected), "{text}");
2486 }
2487
2488 #[test]
2489 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
2490 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
2491 assert!(!text.contains("alloca"), "{text}");
2492 assert!(!text.contains("load"), "{text}");
2493 assert!(!text.contains("store"), "{text}");
2494 }
2495
2496 #[test]
2497 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
2498 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
2499 let expected = "\
2500block0:
2501 %0 = alloca, size 4, align 4
2502 %1 = iconst.i32 1
2503 store %1 -> %0, align 4
2504 %2 = call @g(%0) : (ptr) -> i32
2505 return %2
2506";
2507 assert_eq!(text, expected);
2508 }
2509
2510 #[test]
2511 fn a_loop_carries_what_it_changes_as_block_parameters() {
2512 let text = body(
2515 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
2516 return total;\n}\n",
2517 );
2518 assert!(!text.contains("alloca"), "{text}");
2519 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
2520 assert!(text.contains("jump block1("), "{text}");
2521 }
2522
2523 #[test]
2524 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
2525 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
2526 assert!(text.contains("icmp slt %0, %1"), "{text}");
2527 assert!(!text.contains("zext"), "{text}");
2528 }
2529
2530 #[test]
2531 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
2532 let text = body("int f(int a, int b) { return a && b; }\n");
2533 let expected = "\
2534block0(%0: i32, %1: i32):
2535 %2 = iconst.i32 0
2536 %3 = icmp ne %0, %2
2537 %4 = iconst.i1 0
2538 br_if %3, block1, block2(%4)
2539
2540block1:
2541 %5 = iconst.i32 0
2542 %6 = icmp ne %1, %5
2543 jump block2(%6)
2544
2545block2(%7: i1):
2546 %8 = zext.i32 %7
2547 return %8
2548";
2549 assert_eq!(text, expected);
2550 }
2551
2552 #[test]
2553 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
2554 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
2555 assert!(!text.contains("block3"), "{text}");
2558 assert!(!text.contains("iconst.i32 3"), "{text}");
2559 }
2560
2561 #[test]
2562 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
2563 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
2564 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
2565 assert!(body("int f(void) { }\n").contains("unreachable"));
2566 }
2567
2568 #[test]
2569 fn a_structure_is_copied_rather_than_held_in_a_value() {
2570 let text = body(
2571 "struct point { int x, y; };\n\
2572 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
2573 );
2574 assert!(text.contains("memcpy"), "{text}");
2575 }
2576
2577 #[test]
2578 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
2579 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
2580 assert!(text.contains("memset"), "{text}");
2581 }
2582
2583 #[test]
2584 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
2585 let text = body(
2586 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
2587 default: r = 4; } return r; }\n",
2588 );
2589 let expected = "\
2590block0(%0: i32):
2591 %1 = iconst.i32 0
2592 switch %0, block1, [1 => block2, 2 => block3(%1)]
2593
2594block1:
2595 %2 = iconst.i32 4
2596 jump block4(%2)
2597
2598block2:
2599 %3 = iconst.i32 1
2600 jump block3(%3)
2601
2602block3(%4: i32):
2603 %5 = iconst.i32 2
2604 %6 = add.nsw %4, %5
2605 jump block4(%6)
2606
2607block4(%7: i32):
2608 return %7
2609";
2610 assert_eq!(text, expected);
2611 }
2612
2613 #[test]
2614 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
2615 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
2618 assert!(text.contains("%2 = sub %0, %1"), "{text}");
2619 assert!(text.contains("icmp ule"), "{text}");
2620 assert!(!text.contains("switch"), "{text}");
2621 }
2622
2623 #[test]
2624 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
2625 let text = body(
2626 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
2627 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
2628 );
2629 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
2632 assert!(text.contains("block5:\n jump block7("), "{text}");
2633 assert!(text.contains("block6:\n jump block8("), "{text}");
2634 }
2635
2636 #[test]
2637 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
2638 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
2639 }
2640
2641 #[test]
2642 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
2643 let text = body(
2648 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
2649 return n; }\n",
2650 );
2651 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
2654 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
2655 assert!(text.contains("block5:\n jump block3("), "{text}");
2656 }
2657
2658 #[test]
2659 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
2660 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
2663 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
2664 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
2665 assert!(text.contains("br_if %7, block3, block4"), "{text}");
2666 }
2667
2668 #[test]
2669 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
2670 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
2671 assert!(!text.contains("alloca"), "{text}");
2673 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
2674 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
2675 }
2676
2677 #[test]
2678 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
2679 let text =
2680 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
2681 assert!(!text.contains("alloca"), "{text}");
2682 assert!(text.contains("block1(%2: i32):"), "{text}");
2683 assert!(text.contains("jump block1(%5)"), "{text}");
2684 }
2685
2686 #[test]
2687 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
2688 assert_eq!(
2691 body("int f(int x) { return x; spare: return 0; }\n"),
2692 "block0(%0: i32):\n return %0\n"
2693 );
2694 }
2695
2696 #[test]
2697 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
2698 let text = body(
2699 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
2700 );
2701 assert_eq!(
2704 text,
2705 "\
2706block0(%0: ptr):
2707 %1 = load.i8 %0, align 1
2708 %2 = iconst.i8 3
2709 %3 = ashr %1, %2
2710 %4 = sext.i32 %3
2711 return %4
2712"
2713 );
2714 }
2715
2716 #[test]
2717 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
2718 let text =
2722 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
2723 assert_eq!(
2724 text,
2725 "\
2726block0(%0: ptr, %1: i32):
2727 %2 = iconst.i32 16777215
2728 %3 = and %1, %2
2729 %4 = trunc.i16 %3
2730 store %4 -> %0, align 2
2731 %5 = iconst.i32 16
2732 %6 = lshr %3, %5
2733 %7 = trunc.i8 %6
2734 %8 = iconst.i64 2
2735 %9 = ptr_add %0, %8
2736 store %7 -> %9, align 1
2737 return
2738"
2739 );
2740 }
2741
2742 #[test]
2743 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2744 let text =
2745 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2746 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
2749 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
2750 }
2751
2752 #[test]
2753 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2754 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2757 assert_eq!(text.matches("ashr").count(), 0, "{text}");
2758 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
2759 }
2760
2761 #[test]
2762 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2763 let text = body(
2767 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2768 );
2769 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2770 }
2771
2772 #[test]
2773 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2774 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2777 assert!(
2778 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2779 "{text}"
2780 );
2781 }
2782
2783 #[test]
2784 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2785 let text = ir(concat!(
2790 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2791 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2792 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2793 "char s[2] = \"hi\";\n",
2794 ));
2795 assert!(
2796 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2797 "{text}"
2798 );
2799 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2800 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2801 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2804 }
2805
2806 #[test]
2807 fn a_definition_takes_a_parameter_it_left_unnamed() {
2808 let text = ir("int f(int a, int) { return a; }\n");
2812 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2813 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2814
2815 let text = ir("int g(int, int n) { return n; }\n");
2818 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
2819 }
2820
2821 #[test]
2822 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2823 let text = body(concat!(
2828 "struct s { int f; int g; };\n",
2829 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2830 "{ *d = *e = a[0] = *c; }\n",
2831 ));
2832 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2833 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2834 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2835 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2836 }
2837
2838 #[test]
2839 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2840 let mut opts = options();
2845 opts.emit = EmitKind::Ir;
2846 let result = run(
2847 &opts,
2848 concat!(
2849 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2850 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2851 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2852 "const union u c = { { \"1234\", \"567\" } };\n",
2853 ),
2854 );
2855 let text = result.text();
2856 assert_eq!(
2857 result.messages,
2858 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2859 (5 chars into 3 available) [E0637]"]
2860 );
2861 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2862 assert!(
2863 text.contains(
2864 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2865 bytes \"9\\00\", zero 3 }"
2866 ),
2867 "{text}"
2868 );
2869 assert!(
2872 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2873 "{text}"
2874 );
2875 }
2876
2877 #[test]
2878 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2879 let text = body(concat!(
2883 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2884 "void g(struct v *);\n",
2885 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2886 ));
2887 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2888 }
2889
2890 #[test]
2891 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2892 let text = ir(concat!(
2897 "struct s { int x; };\n",
2898 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2899 "int n = (int){ 7 };\n",
2900 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2901 ));
2902 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2903 assert!(text.contains("global @n : i32 = 7,"), "{text}");
2904 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2907 }
2908
2909 #[test]
2910 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2911 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2915 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2916 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2917 }
2918
2919 #[test]
2920 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2921 let text = ir("unsigned char foo[1][0];\n");
2925 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2926 }
2927
2928 #[test]
2929 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2930 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2933 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2934 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2935 }
2936
2937 #[test]
2938 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2939 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2943 assert!(
2944 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2945 "{text}"
2946 );
2947 }
2948
2949 #[test]
2950 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2951 let text = body(
2956 "\
2957struct s { int a, b; };
2958struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2959",
2960 );
2961 assert!(text.contains("block3(%7: ptr)"), "{text}");
2963 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2964 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2965 }
2966
2967 #[test]
2968 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2969 let text = ir("\
2973struct pair { int a, b; };
2974struct pair make(int a, int b);
2975struct pair twice(struct pair p) { return make(p.a, p.b); }
2976");
2977 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2978 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2979 }
2980
2981 #[test]
2982 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2983 let text = ir("\
2987struct big { double v[8]; };
2988struct big grow(struct big b);
2989struct big twice(struct big b) { return grow(grow(b)); }
2990");
2991 assert!(
2992 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2993 "{text}"
2994 );
2995 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2996 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2999 }
3000
3001 #[test]
3002 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
3003 let text = ir("\
3008struct big { double v[8]; };
3009struct pair { int a, b; };
3010int p(const char *, ...);
3011int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
3012");
3013 assert!(
3014 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
3015 "{text}"
3016 );
3017 }
3018
3019 #[test]
3020 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
3021 let body = body(
3024 "\
3025struct pair { int a, b; };
3026struct pair make(int a, int b);
3027int second(void) { return make(1, 2).b; }
3028",
3029 );
3030 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
3031 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
3032 }
3033
3034 #[test]
3035 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
3036 let source = "\
3040struct hfa { float x, y, z; };
3041int take(struct hfa h);
3042int give(struct hfa h) { return take(h); }
3043";
3044 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
3045 let mut opts = options();
3046 opts.emit = EmitKind::Ir;
3047 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
3048 let result = run(&opts, source);
3049 assert_eq!(result.messages, Vec::<String>::new());
3050 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
3051 }
3052
3053 #[test]
3054 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
3055 let source = "\
3058int use(int *);
3059void f(int n) {
3060 {
3061 int a[n];
3062 use(a);
3063 }
3064 use(0);
3065}
3066";
3067 let body = body(source);
3068 assert!(body.contains("mul.nsw"), "{body}");
3069 assert!(body.contains("stacksave"), "{body}");
3070 assert!(body.contains("alloca %"), "{body}");
3071 assert!(body.contains("stackrestore"), "{body}");
3072 }
3073
3074 #[test]
3075 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
3076 let source = "\
3081int use(int *);
3082int f(int n) {
3083 {
3084 int a[n];
3085 if (use(a)) goto out;
3086 use(0);
3087 }
3088out:
3089 return 0;
3090}
3091";
3092 let body = body(source);
3093 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
3095 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
3096 assert!(after.starts_with(" %4\n jump block"), "{body}");
3097 }
3098
3099 #[test]
3100 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
3101 let source = "\
3105int use(int *);
3106int f(int n) {
3107 int a[n];
3108again:
3109 if (use(a)) goto again;
3110 return 0;
3111}
3112";
3113 let body = body(source);
3114 assert!(body.contains("stacksave"), "{body}");
3115 assert!(!body.contains("stackrestore"), "{body}");
3116 }
3117
3118 #[test]
3119 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
3120 let source = "\
3125int use(int *);
3126int f(int n) {
3127again:
3128 {
3129 int a[n];
3130 if (use(a)) goto again;
3131 }
3132 return 0;
3133}
3134";
3135 let body = body(source);
3136 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
3137 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
3138 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
3139 }
3140
3141 #[test]
3142 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
3143 let source = "\
3149int f(void);
3150void t(void) {
3151 int count = 10;
3152 for (; count--;) {
3153 int b[f()];
3154 int i;
3155 for (i = 0; i < f(); i++) {
3156 b[i] = count;
3157 }
3158 }
3159}
3160";
3161 let body = body(source);
3162 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
3166 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
3167 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
3168 assert!(next.contains("jump block1("), "{body}");
3169 }
3170
3171 #[test]
3172 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
3173 let source = "\
3176unsigned long f(int n) {
3177 int a[n];
3178 n = 0;
3179 return sizeof a;
3180}
3181";
3182 let body = body(source);
3183 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
3185 }
3186
3187 #[test]
3188 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
3189 let source = "\
3192int use(int);
3193int f(int x) {
3194 return ({
3195 int t = use(x);
3196 t * t;
3197 });
3198}
3199";
3200 let expected = "\
3201block0(%0: i32):
3202 %1 = call @use(%0) : (i32) -> i32
3203 %2 = mul.nsw %1, %1
3204 return %2
3205";
3206 assert_eq!(body(source), expected);
3207 }
3208
3209 #[test]
3210 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
3211 let source = "int f(int x) { return ({ return x; 0; }); }\n";
3215 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
3216 }
3217
3218 #[test]
3219 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
3220 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
3224 let expected = "\
3225block0(%0: ptr):
3226 %1 = va_arg.f64 %0
3227 %2 = va_arg.f64 %0
3228 %3 = fadd %1, %2
3229 return %3
3230";
3231 assert_eq!(body(source), expected);
3232 }
3233
3234 #[test]
3235 fn one_that_reads_a_structure_answers_where_the_object_is() {
3236 let source = "\
3245struct s { int a; long b; };
3246long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
3247";
3248 let expected = "\
3249block0(%0: ptr):
3250 %1 = alloca, size 16, align 8
3251 %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
3252 memcpy %1, %2, size 16, align 8
3253 %3 = iconst.i64 8
3254 %4 = ptr_add %1, %3
3255 %5 = load.i64 %4, align 8
3256 return %5
3257";
3258 assert_eq!(body(source), expected);
3259 }
3260
3261 #[test]
3265 fn the_classification_says_which_registers_the_object_arrived_in() {
3266 let source = "\
3267struct s { double a; double b; };
3268double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
3269";
3270 assert!(
3271 body(source)
3272 .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
3273 "{}",
3274 body(source)
3275 );
3276
3277 let big = "\
3278struct s { long a[4]; };
3279long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
3280";
3281 assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
3282 }
3283
3284 #[test]
3285 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
3286 let source = "\
3290int f(int c) {
3291 void *p = c ? &&one : &&two;
3292 goto *p;
3293one:
3294 return 1;
3295two:
3296 return 2;
3297}
3298";
3299 let expected = "\
3300block0(%0: i32):
3301 %1 = iconst.i32 0
3302 %2 = icmp ne %0, %1
3303 br_if %2, block1, block2
3304
3305block1:
3306 %3 = block_addr block3
3307 jump block4(%3)
3308
3309block2:
3310 %4 = block_addr block5
3311 jump block4(%4)
3312
3313block3:
3314 %5 = iconst.i32 1
3315 return %5
3316
3317block4(%6: ptr):
3318 indirect_br %6, block3, block5
3319
3320block5:
3321 %7 = iconst.i32 2
3322 return %7
3323";
3324 assert_eq!(body(source), expected);
3325 }
3326
3327 #[test]
3328 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
3329 let source = "void **next(void);
3332void f(void) { goto *next(); }
3333";
3334 let expected = "\
3335block0:
3336 %0 = call @next() : () -> ptr
3337 unreachable
3338";
3339 assert_eq!(body(source), expected);
3340 }
3341
3342 #[test]
3343 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
3344 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
3347 let expected = "\
3348block0:
3349 inline_asm.volatile \"mfence\", \"\", \"memory\"()
3350 return
3351";
3352 assert_eq!(body(source), expected);
3353 }
3354
3355 #[test]
3356 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
3357 let source = "\
3360int f(int x, int y) {
3361 int r;
3362 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
3363 return r + y;
3364}
3365";
3366 let expected = "\
3367block0(%0: i32, %1: i32):
3368 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
3369 %4 = add.nsw %2, %3
3370 return %4
3371";
3372 assert_eq!(body(source), expected);
3373 }
3374
3375 #[test]
3376 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
3377 let source = "\
3382struct pair { int a, b; };
3383int f(int x) {
3384 int slot = x;
3385 struct pair p = { x, x };
3386 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
3387 return slot + p.a;
3388}
3389";
3390 let text = body(source);
3391 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
3392 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
3393 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
3394 }
3395
3396 #[test]
3397 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
3398 let source = "\
3403int f(int x) {
3404 int r = 7;
3405 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
3406 return r;
3407away:
3408 return r;
3409}
3410";
3411 let expected = "\
3412block0(%0: i32):
3413 %1 = iconst.i32 7
3414 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
3415
3416block1:
3417 return %2
3418
3419block2:
3420 return %1
3421";
3422 assert_eq!(body(source), expected);
3423 }
3424
3425 #[test]
3426 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
3427 let mut opts = options();
3431 opts.emit = EmitKind::Ir;
3432 for (source, expected) in [
3433 (
3434 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
3435 "output operand constraint lacks '='",
3436 ),
3437 (
3438 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
3439 "lvalue required in 'asm' statement",
3440 ),
3441 (
3442 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
3443 "read-only variable 'g' used as 'asm' output",
3444 ),
3445 (
3446 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
3447 "input operand constraint contains '='",
3448 ),
3449 (
3450 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
3451 "memory input 0 is not directly addressable",
3452 ),
3453 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
3454 (
3455 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
3456 "duplicate asm operand name 'a'",
3457 ),
3458 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
3459 ] {
3460 let result = run(&opts, source);
3461 assert!(result.failed(), "expected this to be reported:\n{source}");
3462 assert!(
3463 result.messages.iter().any(|m| m.contains(expected)),
3464 "{expected}\n{:?}",
3465 result.messages
3466 );
3467 }
3468 }
3469
3470 #[test]
3471 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
3472 let mut opts = options();
3473 opts.emit = EmitKind::Ir;
3474 for source in [
3475 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
3476 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
3477 ] {
3478 let result = run(&opts, source);
3479 assert!(result.failed(), "expected this to be reported:\n{source}");
3480 assert!(
3481 result.messages.iter().any(|m| m.contains("not supported yet")),
3482 "{:?}",
3483 result.messages
3484 );
3485 }
3486 }
3487
3488 fn round_trip(source: &str) -> (String, String) {
3490 let printed = ir(source);
3491 let mut opts = options();
3492 opts.emit = EmitKind::Ir;
3493 let mut fs = MemoryFileSystem::new();
3494 fs.insert("/main.ir", printed.clone().into_bytes());
3495 let result = compile_ir(&opts, "/main.ir", &fs);
3496 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
3497 (printed, result.text().to_owned())
3498 }
3499
3500 #[test]
3501 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
3502 let (printed, again) = round_trip(
3506 "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",
3507 );
3508 assert_eq!(printed, again);
3509 }
3510
3511 #[test]
3512 fn ir_that_is_not_ir_says_which_line_stopped_it() {
3513 let mut opts = options();
3514 opts.emit = EmitKind::Ir;
3515 let mut fs = MemoryFileSystem::new();
3516 let text = "\
3517; ModuleID = 'a.c'
3518; format 0
3519target triple = \"x86_64-unknown-linux-gnu\"
3520target datalayout = \"e-p:64:64-i64:64-S128\"
3521
3522func @f(), linkage(external) {
3523block0:
3524 frobnicate
3525}
3526";
3527 fs.insert("/main.ir", text.as_bytes().to_vec());
3528 let result = compile_ir(&opts, "/main.ir", &fs);
3529 assert!(result.failed());
3530 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
3531 }
3532
3533 #[test]
3534 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
3535 let mut opts = options();
3538 opts.emit = EmitKind::Ir;
3539 let mut fs = MemoryFileSystem::new();
3540 let text = "\
3541; ModuleID = 'a.c'
3542; format 0
3543target triple = \"x86_64-unknown-linux-gnu\"
3544target datalayout = \"e-p:64:64-i64:64-S128\"
3545
3546func @f(), linkage(external) {
3547block0:
3548 %0 = iconst.i32 1
3549 return %0
3550}
3551";
3552 fs.insert("/main.ir", text.as_bytes().to_vec());
3553 let result = compile_ir(&opts, "/main.ir", &fs);
3554 assert!(result.failed());
3555 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
3556 }
3557
3558 #[test]
3559 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
3560 let mut fs = MemoryFileSystem::new();
3562 fs.insert("/main.ir", Vec::new());
3563 let result = compile_ir(&options(), "/main.ir", &fs);
3564 assert!(result.failed());
3565 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
3566 }
3567
3568 #[test]
3569 fn the_printed_ir_reads_back_as_the_same_module() {
3570 let text = ir("\
3573struct point { int x, y; };
3574static const char greeting[] = \"hi\";
3575int table[4] = { 1, 2, 3 };
3576int puts(const char *);
3577double half(double x) { return x / 2.0; }
3578int f(int n) {
3579 int total = 0;
3580 for (int i = 0; i < n; i++) {
3581 if (i == 3) continue;
3582 total += table[i];
3583 }
3584 switch (n) {
3585 case 0: total = 1;
3586 case 1: total++; break;
3587 default: total = -total;
3588 }
3589 struct point p = { total, 1 };
3590 int *q = &p.y;
3591 puts(greeting);
3592 return p.x + *q;
3593}
3594int dispatch(int c) {
3595 void *p = c ? &&one : &&two;
3596 goto *p;
3597one:
3598 return 1;
3599two:
3600 return 2;
3601}
3602int assembly(int x, int *p) {
3603 int r;
3604 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
3605 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
3606 return r;
3607away:
3608 return 0;
3609}
3610");
3611 let mut names = Interner::new();
3612 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
3613 assert_eq!(rucc_ir::print(&module, &names), text);
3614 }
3615}