1use std::path::Path;
14
15use rucc_base::Interner;
16use rucc_codegen::pipeline::{self, Machine};
17use rucc_diag::{Diagnostic, Severity, Span};
18use rucc_lex::{Convert, Keywords, PpToken, convert};
19use rucc_sema::{Checker, Context as CheckContext};
20use rucc_session::{EmitKind, FileSystem, Options, Session};
21use rucc_target::TargetInfo;
22
23use crate::preprocess::render;
24
25#[derive(Debug, Clone, PartialEq, Eq, Default)]
32pub enum Artifact {
33 #[default]
36 Nothing,
37 Text(String),
39 Object(Vec<u8>),
41}
42
43impl Artifact {
44 #[must_use]
46 pub fn bytes(&self) -> &[u8] {
47 match self {
48 Artifact::Nothing => &[],
49 Artifact::Text(text) => text.as_bytes(),
50 Artifact::Object(bytes) => bytes,
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Compiled {
58 pub artifact: Artifact,
60 pub messages: Vec<String>,
62 pub errors: u32,
64}
65
66impl Compiled {
67 #[must_use]
69 pub fn failed(&self) -> bool {
70 self.errors > 0
71 }
72
73 #[must_use]
78 pub fn text(&self) -> &str {
79 match &self.artifact {
80 Artifact::Text(text) => text,
81 _ => "",
82 }
83 }
84}
85
86#[must_use]
99pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
100 let mut sess = Session::new(opts.clone());
101 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
105 let mut diagnostics: Vec<Diagnostic> = Vec::new();
106
107 let bytes = match fs.read(Path::new(name)) {
108 Ok(bytes) => bytes,
109 Err(e) => return failure(format!("{name}: {e}")),
110 };
111 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
112 return failure(format!("{name}: the source map has no room left for this file"));
113 };
114
115 let mut pp = rucc_pp::Preprocessor::new();
119 let predef = rucc_pp::Predef::for_options(opts);
120 let expanded: Vec<PpToken> = {
121 let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
122 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
123 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
124 return failure(format!("{name}: the source map has no room for the built in macros"));
125 }
126 pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
127 };
128 diagnostics.extend(pp.take_diagnostics());
129
130 let cx = Convert {
133 keywords: &keywords,
134 interner: &sess.interner,
135 target: &sess.target,
136 std: opts.std,
137 gnu: opts.gnu_extensions,
138 pedantic: opts.pedantic,
139 };
140 let (tokens, complaints) = convert(&expanded, &cx);
141 diagnostics.extend(complaints);
142
143 let parsed = rucc_parse::parse(
144 &tokens,
145 rucc_parse::Context {
146 interner: &sess.interner,
147 std: opts.std,
148 gnu: opts.gnu_extensions,
149 pedantic: opts.pedantic,
150 error_limit: opts.error_limit as usize,
151 },
152 );
153 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
154 diagnostics.extend(parsed.diagnostics);
155
156 let mut artifact = Artifact::Nothing;
157 if !parse_failed {
158 let mut checker = Checker::new(
159 &parsed.ast,
160 CheckContext {
161 names: &sess.interner,
162 target: &sess.target,
163 std: opts.std,
164 gnu: opts.gnu_extensions,
165 pedantic: opts.pedantic,
166 error_limit: opts.error_limit as usize,
167 },
168 );
169 checker.check_unit();
170 let checked = checker.finish();
171 if !checked.failed() {
172 match opts.emit {
173 EmitKind::Tast => {
174 artifact = Artifact::Text(rucc_sema::print(
175 &checked.tast,
176 &checked.types,
177 &sess.interner,
178 ));
179 }
180 EmitKind::Ir
181 | EmitKind::MirFinal
182 | EmitKind::Asm
183 | EmitKind::Object
184 | EmitKind::Executable => {
185 let mut lowered = rucc_lower::lower(
186 name,
187 rucc_lower::Context {
188 tast: &checked.tast,
189 types: &checked.types,
190 target: &sess.target,
191 names: &mut sess.interner,
192 },
193 );
194 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
198 if !failed {
199 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
204 for error in errors {
205 diagnostics.push(internal(&format!("invalid IR, {error}")));
206 }
207 } else if opts.emit == EmitKind::Ir {
208 artifact =
209 Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
210 } else {
211 match generate(
214 &mut lowered.module,
215 &mut sess.interner,
216 &sess.target,
217 opts,
218 ) {
219 Ok(made) => artifact = made,
220 Err(complaints) => diagnostics.extend(complaints),
221 }
222 }
223 }
224 diagnostics.extend(lowered.diagnostics);
225 }
226 _ => {}
227 }
228 }
229 diagnostics.extend(checked.diagnostics);
230 }
231
232 let mut messages = Vec::with_capacity(diagnostics.len());
233 let mut errors = 0;
234 for diag in &diagnostics {
235 if diag.severity.is_fatal()
236 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
237 {
238 errors += 1;
239 }
240 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
241 }
242 if errors > 0 {
243 artifact = Artifact::Nothing;
245 }
246 Compiled { artifact, messages, errors }
247}
248
249#[must_use]
259pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
260 let mut sess = Session::new(opts.clone());
261 if opts.emit != EmitKind::Ir {
262 return failure(format!(
263 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
264 the C in front of it became",
265 opts.emit.as_str()
266 ));
267 }
268 let bytes = match fs.read(Path::new(name)) {
269 Ok(bytes) => bytes,
270 Err(e) => return failure(format!("{name}: {e}")),
271 };
272 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
273 return failure(format!("{name}: this is not text, so it is not IR"));
274 };
275
276 let module = match rucc_ir::parse(text, &mut sess.interner) {
277 Ok(module) => module,
278 Err(error) => {
279 return failure(format!("{name}:{}: {}", error.line, error.message));
280 }
281 };
282 let mut diagnostics: Vec<Diagnostic> = Vec::new();
283 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
284 for error in errors {
285 diagnostics.push(invalid(&format!("invalid IR, {error}")));
286 }
287 }
288 let mut messages = Vec::with_capacity(diagnostics.len());
289 for diag in &diagnostics {
290 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
291 }
292 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
293 let artifact = if errors > 0 {
294 Artifact::Nothing
295 } else {
296 Artifact::Text(rucc_ir::print(&module, &sess.interner))
297 };
298 Compiled { artifact, messages, errors }
299}
300
301fn generate(
320 module: &mut rucc_ir::Module,
321 names: &mut Interner,
322 target: &TargetInfo,
323 opts: &Options,
324) -> Result<Artifact, Vec<Diagnostic>> {
325 let Some(machine) = Machine::for_target(target) else {
326 return Err(vec![unsupported(&format!(
327 "there is no back end for {} in this compiler yet, so there is nothing to generate",
328 target.triple
329 ))]);
330 };
331 let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
332
333 let mut funcs = Vec::new();
334 let mut complaints = Vec::new();
335 for id in module.funcs() {
336 if module[id].is_declaration() {
337 continue;
338 }
339 match pipeline::compile(&mut module[id], names, &machine, flags) {
340 Ok(func) => funcs.push(func),
341 Err(why) => {
342 let name = names.resolve(module[id].name).to_owned();
343 let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
346 let said = format!("cannot generate code for '{name}': {why}");
347 complaints.push(unsupported_at(&said, span));
348 }
349 }
350 }
351 if !complaints.is_empty() {
352 return Err(complaints);
353 }
354 let globals = match opts.emit {
358 EmitKind::Asm | EmitKind::Object | EmitKind::Executable => {
359 rucc_asm::globals(module, names).map_err(refused)?
360 }
361 _ => rucc_asm::Globals::default(),
362 };
363 match opts.emit {
367 EmitKind::Asm => {
368 rucc_asm::print(&funcs, &globals, names, target).map(Artifact::Text).map_err(refused)
369 }
370 EmitKind::Object | EmitKind::Executable => {
373 let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
374 let data = globals.image();
375 rucc_object::write(&text, &data, target).map(Artifact::Object).map_err(
378 |why| match why {
379 rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
380 rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
381 },
382 )
383 }
384 _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
385 }
386}
387
388fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
394 match why {
395 rucc_asm::Error::Thread { .. } => vec![unsupported(&why.to_string())],
396 _ => vec![internal(&why.to_string())],
397 }
398}
399
400fn unsupported(message: &str) -> Diagnostic {
406 unsupported_at(message, Span::DUMMY)
407}
408
409fn unsupported_at(message: &str, span: Span) -> Diagnostic {
415 Diagnostic::error(message.to_owned(), span)
416 .with_code("E0653")
417 .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
418}
419
420fn invalid(message: &str) -> Diagnostic {
422 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
423}
424
425fn internal(message: &str) -> Diagnostic {
427 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
428 .with_code("E0652")
429 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
430}
431
432fn failure(message: String) -> Compiled {
435 Compiled {
436 artifact: Artifact::Nothing,
437 messages: vec![format!("rucc: error: {message}")],
438 errors: 1,
439 }
440}
441
442#[cfg(test)]
443mod tests {
444 use rucc_session::{MemoryFileSystem, Std};
445 use rucc_target::Triple;
446
447 use super::*;
448
449 fn options() -> Options {
450 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
451 opts.emit = EmitKind::Tast;
452 opts
453 }
454
455 fn run(opts: &Options, source: &str) -> Compiled {
456 let mut fs = MemoryFileSystem::new();
457 fs.insert("/main.c", source.to_owned().into_bytes());
458 compile(opts, "/main.c", &fs)
459 }
460
461 fn freestanding() -> Options {
465 let mut opts = options();
466 opts.hosted = false;
467 opts.search.push_system(rucc_session::runtime::DIR);
468 opts
469 }
470
471 fn shipped(source: &str) -> String {
473 let result = run(&freestanding(), source);
474 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
475 result.text().to_owned()
476 }
477
478 fn tast(source: &str) -> String {
480 let result = run(&options(), source);
481 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
482 result.text().to_owned()
483 }
484
485 #[test]
486 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
487 let text = shipped(concat!(
488 "#include <stdarg.h>\n",
489 "int sum(int n, ...) {\n",
490 " va_list ap, copy;\n",
491 " va_start(ap, n);\n",
492 " va_copy(copy, ap);\n",
493 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
494 " va_end(ap);\n",
495 " va_end(copy);\n",
496 " return total;\n",
497 "}\n",
498 ));
499 assert!(text.contains("va-start"), "{text}");
500 assert!(text.contains("va-copy"), "{text}");
501 assert!(text.contains("va-arg"), "{text}");
502 assert!(text.contains("va-end"), "{text}");
503 }
504
505 #[test]
509 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
510 let text = shipped(concat!(
511 "#define __need___va_list\n",
512 "#include <stdarg.h>\n",
513 "int vprint(const char *f, __gnuc_va_list ap);\n",
514 "#ifdef va_start\n",
515 "#error va_start should not be defined\n",
516 "#endif\n",
517 "#ifdef _VA_LIST_DEFINED\n",
518 "#error va_list should not have been made\n",
519 "#endif\n",
520 ));
521 assert!(text.contains("vprint"), "{text}");
522 }
523
524 #[test]
527 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
528 let text = shipped(concat!(
529 "#define __need_size_t\n",
530 "#include <stddef.h>\n",
531 "#ifdef offsetof\n",
532 "#error offsetof should not be defined yet\n",
533 "#endif\n",
534 "#define __need_ptrdiff_t\n",
535 "#include <stddef.h>\n",
536 "#include <stddef.h>\n",
537 "size_t a;\n",
538 "ptrdiff_t b;\n",
539 "wchar_t c;\n",
540 "max_align_t d;\n",
541 "void *e = NULL;\n",
542 "struct P { int x; long y; };\n",
543 "size_t f = offsetof(struct P, y);\n",
544 ));
545 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
546 assert!(text.contains("decl #1 b : long"), "{text}");
547 }
548
549 #[test]
550 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
551 let text = shipped(concat!(
552 "#include <limits.h>\n",
553 "#include <float.h>\n",
554 "int bits = CHAR_BIT;\n",
555 "long big = LONG_MAX;\n",
556 "int low = INT_MIN;\n",
557 "int radix = FLT_RADIX;\n",
558 "int digits = DBL_MANT_DIG;\n",
559 ));
560 assert!(text.contains("const 8 : int"), "{text}");
561 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
562 assert!(text.contains("const 2 : int"), "{text}");
563 assert!(text.contains("const 53 : int"), "{text}");
564 }
565
566 #[test]
570 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
571 let text = shipped(concat!(
572 "#include <stdint.h>\n",
573 "int64_t a = INT64_C(1);\n",
574 "uint_least16_t b;\n",
575 "intptr_t c;\n",
576 "uintmax_t d = UINTMAX_MAX;\n",
577 "int wide = sizeof(int_fast64_t);\n",
578 ));
579 assert!(text.contains("decl #0 a : long"), "{text}");
580 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
581 assert!(text.contains("decl #2 c : long"), "{text}");
582 }
583
584 #[test]
585 fn the_three_formality_headers_still_have_to_work() {
586 let text = shipped(concat!(
587 "#include <stdbool.h>\n",
588 "#include <stdalign.h>\n",
589 "#include <iso646.h>\n",
590 "#include <stdnoreturn.h>\n",
591 "int t = true and not false;\n",
592 "_Alignas(16) char buf[16];\n",
593 "int a = alignof(long);\n",
594 ));
595 assert!(text.contains("decl #0 t : int"), "{text}");
596 assert!(text.contains("const 8 : unsigned long"), "{text}");
597 }
598
599 #[test]
602 fn every_shipped_header_can_be_included_twice() {
603 let mut source = String::new();
604 for _ in 0..2 {
605 for name in rucc_session::runtime::names() {
606 source.push_str(&format!("#include <{name}>\n"));
607 }
608 }
609 source.push_str("int x;\n");
610 let text = shipped(&source);
611 assert!(text.starts_with("decl #0 x : int"), "{text}");
612 }
613
614 #[test]
615 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
616 let fs = MemoryFileSystem::new();
617 let result = compile(&options(), "/nope.c", &fs);
618 assert!(result.failed());
619 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
620 assert!(result.text().is_empty());
621 }
622
623 #[test]
624 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
625 let text = tast("int x = 1;\n");
626 let expected = "\
627decl #0 x : int object external static defined
628 init
629 +0
630 const 1 : int
631";
632 assert_eq!(text, expected);
633 }
634
635 #[test]
636 fn the_macros_are_expanded_before_anything_is_parsed() {
637 let text = tast("#define N 2\nint a[N];\n");
641 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
642 }
643
644 #[test]
650 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
651 let text = tast(concat!(
652 "#pragma pack(4)\n",
653 "struct s { int a; };\n",
654 "#pragma pack()\n",
655 "int b;\n",
656 "_Pragma(\"GCC visibility push(default)\") int c;\n",
657 ));
658 assert!(text.contains("decl #0 b : int"), "{text}");
659 assert!(text.contains("decl #1 c : int"), "{text}");
660 }
661
662 #[test]
670 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
671 tast(concat!(
672 "struct A { char c; int i; } __attribute__((packed));\n",
673 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
674 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
675 "struct B { char c; int i; } __attribute__((aligned));\n",
678 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
679 "struct C { char c; int i __attribute__((packed)); };\n",
680 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
681 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
682 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
683 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
684 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
685 "struct E { char c; _Alignas(8) int i; };\n",
686 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
687 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
688 "struct F { char c; int i __attribute__((aligned(8))); };\n",
689 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
690 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
693 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
694 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
695 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
696 "struct I { [[gnu::packed]] char c; int i; };\n",
699 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
700 "struct J { char c; [[gnu::packed]] int i; };\n",
701 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
702 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
703 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
704 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
705 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
706 "union L { char c; int i; } __attribute__((packed));\n",
707 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
708 ));
709 }
710
711 #[test]
721 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
722 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
724 assert_eq!(
725 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
726 1
727 );
728 assert_eq!(
729 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
730 1
731 );
732 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
733 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
735 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
736 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
738 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
739 }
740
741 fn bit_field_byte(record: &str) -> u64 {
743 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
744 let body = body(&source);
745 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
746 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
747 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
748 }
749
750 #[test]
756 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
757 tast(concat!(
758 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
759 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
760 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
761 "struct b { char c; __attribute__((packed)) int i; };\n",
762 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
763 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
764 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
765 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
766 ));
767 }
768
769 #[test]
775 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
776 tast(concat!(
777 "#pragma pack(1)\n",
778 "struct A { char c; int i; };\n",
779 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
780 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
781 "#pragma pack()\n",
782 "struct B { char c; int i; };\n",
783 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
784 "#pragma pack(2)\n",
785 "struct C { char c; int i; double d; };\n",
786 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
787 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
788 "struct K { char c; int i __attribute__((aligned(8))); };\n",
790 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
791 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
792 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
794 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
795 "#pragma pack()\n",
796 "#pragma pack(push, 1)\n",
797 "struct D { char c; short s; };\n",
798 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
799 "#pragma pack(pop)\n",
800 "struct E { char c; short s; };\n",
801 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
802 "struct H { char c;\n",
804 "#pragma pack(1)\n",
805 " int i; };\n",
806 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
807 "#pragma pack(1)\n",
808 "struct I { char c;\n",
809 "#pragma pack()\n",
810 " int i; };\n",
811 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
812 "#pragma pack()\n",
813 "#pragma pack(push, 8)\n",
815 "#pragma pack(push, 1)\n",
816 "struct P { char c; int i; };\n",
817 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
818 "#pragma pack(pop)\n",
819 "struct Q { char c; int i; };\n",
820 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
821 "#pragma pack(pop)\n",
822 "#pragma pack(16)\n",
824 "struct R { char c; int i; };\n",
825 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
826 "#pragma pack()\n",
827 "#pragma pack(1)\n",
828 "struct S { char c; int i : 5; int j : 20; };\n",
829 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
830 "union T { char c; int i; };\n",
831 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
832 "#pragma pack()\n",
833 ));
834 }
835
836 #[test]
840 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
841 let result = run(
842 &options(),
843 concat!(
844 "#pragma pack 4\n",
845 "#pragma pack(pop)\n",
846 "#pragma pack(3)\n",
847 "#pragma pack(1) junk\n",
848 "#pragma pack(push, 1\n",
849 "#pragma pack(x)\n",
850 "#pragma pack(0)\n",
853 "#pragma pack(push)\n",
854 "struct s { char c; int i; };\n",
855 "#pragma pack(pop)\n",
856 "#pragma pack(pop, foo)\n",
857 ),
858 );
859 let expected = [
860 "missing `(` after `#pragma pack` - ignored",
861 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
862 "alignment must be a small power of two, not 3",
863 "junk at end of `#pragma pack`",
864 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
865 "unknown action `x` for `#pragma pack` - ignored",
866 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
867 ];
868 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
869 for (message, want) in result.messages.iter().zip(expected) {
870 assert!(message.contains(want), "expected {want:?} in {message:?}");
871 }
872 }
873
874 #[test]
878 fn the_wide_integer_answers_to_all_three_of_its_names() {
879 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
880 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
881 assert!(text.contains("decl #1 b : __int128"), "{text}");
882 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
883 }
884
885 #[test]
886 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
887 let text = tast("long f(int a, long b) { return a + b; }\n");
891 assert!(text.contains("convert arithmetic"), "{text}");
892 }
893
894 #[test]
895 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
896 for source in [
897 "#error stop\n",
898 "int f(void) { return 1 + ; }\n",
899 "int f(void) { return undeclared; }\n",
900 ] {
901 let result = run(&options(), source);
902 assert!(result.failed(), "expected this to fail:\n{source}");
903 assert!(
904 result.text().is_empty(),
905 "a file that did not compile wrote a tree:\n{source}"
906 );
907 }
908 }
909
910 #[test]
911 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
912 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
916 assert_eq!(result.errors, 1, "{:?}", result.messages);
917 }
918
919 #[test]
920 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
921 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
925 assert_eq!(result.errors, 1, "{:?}", result.messages);
926 }
927
928 #[test]
929 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
930 let source = "int f(void) { char c = 300; return c; }\n";
931 let plain = run(&options(), source);
932 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
933 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
934 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
935
936 let mut opts = options();
937 opts.warnings_are_errors = true;
938 let strict = run(&opts, source);
939 assert!(strict.failed());
940 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
941 for message in &strict.messages {
942 assert!(!message.contains("warning:"), "{message}");
943 }
944 }
945
946 #[test]
947 fn the_dialect_reaches_the_keywords_and_the_checking() {
948 let source = "typeof(1) x;\n";
951 let mut opts = options();
952 opts.std = Std::C23;
953 opts.gnu_extensions = false;
954 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
955
956 opts.std = Std::C17;
957 assert!(run(&opts, source).failed());
958 }
959
960 #[test]
961 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
962 let mut opts = options();
963 opts.emit = EmitKind::Object;
964 let result = run(&opts, "int x = 1;\n");
965 assert!(!result.failed(), "{:?}", result.messages);
966 assert!(result.text().is_empty());
967 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
970 }
971
972 fn mir(source: &str) -> String {
974 let mut opts = options();
975 opts.emit = EmitKind::MirFinal;
976 let result = run(&opts, source);
977 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
978 result.text().to_owned()
979 }
980
981 #[test]
987 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
988 let text = mir("int add(int a, int b) { return a + b; }\n");
989 assert!(text.starts_with("mfunc @add {"), "{text}");
990 assert!(text.contains("x64.add_rr_32"), "{text}");
991 assert!(text.contains("x64.ret"), "{text}");
992 assert!(!text.contains('%'), "{text}");
995 }
996
997 #[test]
999 fn a_function_with_no_body_produces_no_machine_function() {
1000 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1001 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1002 assert!(text.contains("mfunc @f {"), "{text}");
1003 assert!(text.contains("x64.call"), "{text}");
1004 }
1005
1006 #[test]
1008 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1009 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1010 let first = text.find("mfunc @a").expect("the first function");
1011 let second = text.find("mfunc @b").expect("the second function");
1012 assert!(first < second, "{text}");
1013 }
1014
1015 #[test]
1017 fn the_target_decides_which_convention_the_generated_code_follows() {
1018 let mut opts = options();
1019 opts.emit = EmitKind::MirFinal;
1020 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1021 assert!(linux.contains("$rdi"), "{linux}");
1022
1023 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1024 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1025 assert!(windows.contains("$rcx"), "{windows}");
1026 assert!(!windows.contains("$rdi"), "{windows}");
1027 }
1028
1029 #[test]
1031 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1032 let mut opts = options();
1033 opts.emit = EmitKind::MirFinal;
1034 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1035 let result = run(&opts, "int f(int a) { return a; }\n");
1036 assert!(result.failed());
1037 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1038 assert!(result.text().is_empty());
1039 }
1040
1041 #[test]
1048 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1049 let mut opts = options();
1050 opts.emit = EmitKind::MirFinal;
1051 let result =
1052 run(&opts, "double a(double x) { return x; }\ndouble b(double x) { return x; }\n");
1053 assert!(result.failed());
1054 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1055 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1056 assert!(result.messages[0].contains("vector register"), "{:?}", result);
1057 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1058 assert!(result.text().is_empty());
1059 }
1060
1061 #[test]
1068 fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1069 let mut opts = options();
1070 opts.emit = EmitKind::MirFinal;
1071 let result = run(&opts, "int f(int a) {\n return a == 1;\n}\n");
1072 assert!(result.failed());
1073 assert!(
1074 result.messages[0].contains("no rule lowers a `zext` producing a `i32`"),
1075 "{result:?}"
1076 );
1077 assert!(result.messages[0].contains(":2:"), "the line the comparison is on: {result:?}");
1078 assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1079 }
1080
1081 #[test]
1083 fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1084 let mut opts = options();
1085 opts.emit = EmitKind::MirFinal;
1086 let result = run(&opts, "int f(int a) { return a == 1; }\n");
1087 assert!(result.failed());
1088 let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1089 assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1090 assert!(!note.contains("spec/17-milestones.md"), "{note}");
1091 }
1092
1093 #[test]
1095 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1096 let source = "int f(int a) { return a; }\n";
1097 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1098
1099 let mut opts = options();
1100 opts.emit = EmitKind::MirFinal;
1101 opts.frame_pointer = true;
1102 let kept = run(&opts, source).text().to_owned();
1103 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1104 }
1105
1106 fn asm(source: &str) -> String {
1108 let mut opts = options();
1109 opts.emit = EmitKind::Asm;
1110 let result = run(&opts, source);
1111 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1112 result.text().to_owned()
1113 }
1114
1115 #[test]
1122 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1123 let text = asm("int add(int a, int b) { return a + b; }\n");
1124 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1125 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1126 assert!(text.contains("\nadd:\n"), "{text}");
1127 assert!(text.contains("\taddl\t"), "{text}");
1128 assert!(text.contains("\tret\n"), "{text}");
1129 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1130 assert!(text.contains(".note.GNU-stack"), "{text}");
1133 }
1134
1135 #[test]
1137 fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1138 let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1139 assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1140 }
1141
1142 #[test]
1144 fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1145 let text = asm("long f(void *p) { return (long)p; }\n");
1146 for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1151 let mnemonic = line.split_whitespace().next().unwrap_or("");
1152 assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1153 }
1154 }
1155
1156 #[test]
1158 fn the_target_decides_how_the_assembly_is_spelled() {
1159 let mut opts = options();
1160 opts.emit = EmitKind::Asm;
1161 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1162 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1163 assert!(text.contains("__TEXT,__text"), "{text}");
1164 assert!(text.contains("\n_f:\n"), "{text}");
1165 assert!(!text.contains(".note.GNU-stack"), "{text}");
1166 }
1167
1168 fn obj(source: &str) -> Vec<u8> {
1170 let mut opts = options();
1171 opts.emit = EmitKind::Object;
1172 let result = run(&opts, source);
1173 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1174 match result.artifact {
1175 Artifact::Object(bytes) => bytes,
1176 other => panic!("expected an object, got {other:?}"),
1177 }
1178 }
1179
1180 #[test]
1186 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1187 let bytes = obj("int add(int a, int b) { return a + b; }\n");
1188 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1189 let text = asm("int add(int a, int b) { return a + b; }\n");
1190 assert!(
1191 text.contains("\taddl\t"),
1192 "and the listing of it is the same instructions:\n{text}"
1193 );
1194 }
1195
1196 #[test]
1198 fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1199 let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1200 assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1201 assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1202 assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1203 assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1206 assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1207 assert!(!text.contains(".globl\thidden"), "{text}");
1208 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1211 }
1212
1213 #[test]
1215 fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1216 let text = asm("const char *f(void) { return \"hi\"; }\n");
1217 assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1218 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1219 let label = text
1220 .lines()
1221 .find(|line| line.starts_with(".Lstr"))
1222 .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1223 assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1224 }
1225
1226 #[test]
1228 fn an_address_in_an_initializer_is_left_to_the_linker() {
1229 let source = "int counter;\nint *p = &counter;\n";
1230 let text = asm(source);
1231 assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1232 let bytes = obj(source);
1235 assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1236 }
1237
1238 #[test]
1240 fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
1241 let mut opts = options();
1242 opts.emit = EmitKind::Asm;
1243 let result = run(&opts, "_Thread_local int x = 1;\n");
1244 assert!(result.failed(), "every thread sharing one variable is worse than a message");
1245 assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
1246 assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
1248 }
1249
1250 #[test]
1252 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1253 let source = "int callee(void); int g(void) { return callee(); }\n";
1257 let bytes = obj(source);
1258 assert!(
1259 bytes.windows(7).any(|w| w == b"callee\0"),
1260 "the object has to name the callee for the linker to find it"
1261 );
1262 let text = asm(source);
1263 assert!(text.contains("\tcall\tcallee\n"), "{text}");
1264 }
1265
1266 #[test]
1272 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1273 let mut opts = options();
1274 opts.emit = EmitKind::Executable;
1276 let result = run(&opts, "int main(void) { return 0; }\n");
1277 assert_eq!(result.messages, Vec::<String>::new());
1278 match result.artifact {
1279 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1280 other => panic!("expected an object, got {other:?}"),
1281 }
1282 }
1283
1284 #[test]
1286 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1287 let mut opts = options();
1288 opts.emit = EmitKind::Object;
1289 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1290 let result = run(&opts, "int f(void) { return 0; }\n");
1291 assert!(result.failed(), "an object nobody can read is worse than a message");
1292 assert!(
1293 result.messages.iter().any(|m| m.contains("no object writer")),
1294 "{:?}",
1295 result.messages
1296 );
1297 }
1298
1299 fn ir(source: &str) -> String {
1301 let mut opts = options();
1302 opts.emit = EmitKind::Ir;
1303 let result = run(&opts, source);
1304 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1305 result.text().to_owned()
1306 }
1307
1308 fn body(source: &str) -> String {
1310 let text = ir(source);
1311 let (_, rest) = text.split_once("{\n").expect("a function definition");
1312 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1313 body.to_owned()
1314 }
1315
1316 #[test]
1324 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1325 let text = ir(concat!(
1326 "int g;\n",
1327 "int a = __builtin_constant_p(1);\n",
1328 "int b = __builtin_constant_p(g);\n",
1329 "int c = __builtin_constant_p(\"abc\");\n",
1330 "int d = __builtin_constant_p(&g);\n",
1331 "int e = __builtin_constant_p(1.5);\n",
1332 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1333 ));
1334 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1335 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1336 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1337 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1338 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1339 assert!(text.contains("global @h : i32 = 11,"), "{text}");
1340 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1341
1342 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1346 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
1347 }
1348
1349 #[test]
1358 fn a_call_to_a_library_builtin_reaches_the_library_function() {
1359 let text = body("void f(void) { __builtin_abort(); }\n");
1360 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
1361
1362 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1365 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1366 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1367 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1368 }
1369
1370 #[test]
1377 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1378 let mut opts = options();
1379 opts.emit = EmitKind::Ir;
1380 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1381 assert!(
1382 messages.iter().any(|m| m.contains("__builtin_abort")),
1383 "expected the written name in {messages:?}"
1384 );
1385 }
1386
1387 #[test]
1394 fn a_classification_c_has_an_operator_for_is_that_operator() {
1395 for (builtin, operator) in [
1396 ("__builtin_isgreater", "binary >"),
1397 ("__builtin_isgreaterequal", "binary >="),
1398 ("__builtin_isless", "binary <"),
1399 ("__builtin_islessequal", "binary <="),
1400 ] {
1401 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1402 let text = tast(&source);
1403 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1404 }
1405 }
1406
1407 #[test]
1416 fn the_classification_builtins_are_comparisons_and_not_calls() {
1417 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1418 assert_eq!(
1419 text,
1420 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
1421 %2\n return %3\n"
1422 );
1423
1424 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1426 assert!(text.contains("fcmp one %0, %1"), "{text}");
1427
1428 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1429 assert!(text.contains("fcmp uno %0, %0"), "{text}");
1430
1431 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1432 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1433 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1434 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1435 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1436 assert!(text.contains("%5 = or %3, %4"), "{text}");
1437
1438 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1441 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1442 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1443 assert!(text.contains("%5 = and %3, %4"), "{text}");
1444
1445 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1446 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1447 assert!(text.contains("icmp slt %1, %2"), "{text}");
1448
1449 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1452 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1453
1454 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1457 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1458 }
1459
1460 #[test]
1467 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1468 let text = ir(concat!(
1469 "int a = __builtin_isinff(1e300);\n",
1470 "int b = __builtin_isinf(1e300);\n",
1471 "int c = __builtin_isnan(0.0);\n",
1475 "int d = __builtin_signbit(-0.0);\n",
1476 "int e = __builtin_islessgreater(1.0, 2.0);\n",
1477 ));
1478 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1479 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1480 assert!(text.contains("global @c : i32 = 0,"), "{text}");
1481 assert!(text.contains("global @d : i32 = 1,"), "{text}");
1482 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1483 }
1484
1485 #[test]
1487 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1488 let mut opts = options();
1489 opts.emit = EmitKind::Ir;
1490 let source = concat!(
1491 "int a(int x) { return __builtin_isnan(x); }\n",
1492 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1493 "int c(double x) { return __builtin_isnan(x, x); }\n",
1494 );
1495 let messages = run(&opts, source).messages;
1496 assert_eq!(
1497 messages,
1498 [
1499 "/main.c:1:23: error: non-floating-point argument in call to function \
1500 '__builtin_isnan' [E0685]",
1501 "/main.c:2:30: error: non-floating-point arguments in call to function \
1502 '__builtin_isunordered' [E0685]",
1503 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1504 ]
1505 );
1506 }
1507
1508 #[test]
1516 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
1517 let text = ir(concat!(
1518 "double a = __builtin_inf();\n",
1519 "float b = __builtin_huge_valf();\n",
1520 "long double c = __builtin_infl();\n",
1521 "double d = __builtin_huge_val();\n",
1522 ));
1523 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1524 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1525 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1526 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1527 assert!(!text.contains("call"), "{text}");
1528 }
1529
1530 #[test]
1539 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1540 let text = ir(concat!(
1541 "double a = __builtin_nan(\"\");\n",
1542 "double b = __builtin_nan(\"0x1\");\n",
1543 "double c = __builtin_nan(\"010\");\n",
1545 "double d = __builtin_nans(\"\");\n",
1546 "double e = __builtin_nans(\"0x1\");\n",
1547 "float f = __builtin_nanf(\"0x1\");\n",
1548 "float g = __builtin_nansf(\"\");\n",
1549 "long double h = __builtin_nansl(\"\");\n",
1550 ));
1551 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1552 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1553 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1554 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1555 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1556 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1557 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1558 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1559
1560 let text = ir(concat!(
1563 "double f(const char *p) { return __builtin_nan(p); }\n",
1564 "double g(void) { return __builtin_nans(\"1x\"); }\n",
1565 ));
1566 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1567 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1568 }
1569
1570 #[test]
1578 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
1579 let text = ir(concat!(
1580 "unsigned long a = __builtin_strlen(\"hello\");\n",
1581 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
1582 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
1583 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
1584 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
1585 ));
1586 assert!(text.contains("global @a : i64 = 5,"), "{text}");
1587 assert!(text.contains("global @b : i64 = 1,"), "{text}");
1588 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1589 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1590 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1591 assert!(!text.contains("call"), "{text}");
1592
1593 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
1595 assert!(text.contains("call @strlen("), "{text}");
1596 }
1597
1598 #[test]
1605 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
1606 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
1607 assert!(text.contains("bitcast.i64 %0"), "{text}");
1608 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
1609 assert!(text.contains("and %1, %2"), "{text}");
1610 assert!(text.contains("bitcast.f64 %3"), "{text}");
1611 assert!(!text.contains("call"), "{text}");
1612
1613 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
1614 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
1615 assert!(text.contains("%8 = or %4, %7"), "{text}");
1616 assert!(!text.contains("call"), "{text}");
1617
1618 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
1621 assert!(text.contains("bitcast.i80 %0"), "{text}");
1622 assert!(text.contains("bitcast.f80"), "{text}");
1623
1624 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
1627 assert!(text.contains("fpext.f64 %0"), "{text}");
1628 assert!(text.contains("bitcast.i64 %1"), "{text}");
1629 }
1630
1631 #[test]
1640 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
1641 let text = ir(concat!(
1642 "double a = __builtin_fabs(-3.5);\n",
1643 "double b = __builtin_copysign(1.0, -0.0);\n",
1644 "double c = __builtin_copysign(0.0, -2.0);\n",
1645 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
1647 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
1648 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
1649 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
1650 "long double i = __builtin_fabsl(-__builtin_infl());\n",
1651 ));
1652 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
1653 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
1654 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
1655 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
1656 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
1657 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
1658 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
1659 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1660 }
1661
1662 #[test]
1669 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
1670 let text = ir(concat!(
1671 "constexpr int side = 4;\n",
1672 "constexpr int wider = side + 1;\n",
1673 "constexpr double half = 1.5;\n",
1674 "struct point { int x; int y; };\n",
1675 "constexpr struct point origin = { 5, 6 };\n",
1676 "int square[side * side];\n",
1677 "int rectangle[wider];\n",
1678 "int rounded[(int)half * 2];\n",
1679 "int across[origin.y];\n",
1680 "enum named { four = side };\n",
1681 "int e = four;\n",
1682 ));
1683 assert!(text.contains("global @square : bytes 64 ="), "{text}");
1684 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
1685 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
1686 assert!(text.contains("global @across : bytes 24 ="), "{text}");
1687 assert!(text.contains("global @e : i32 = 4,"), "{text}");
1688
1689 let mut opts = options();
1692 opts.emit = EmitKind::Ir;
1693 let konst = "const int n = 1;\nint a[n];\n";
1694 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
1695 assert_eq!(run(&opts, konst).messages, [message]);
1696
1697 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
1699 assert_eq!(run(&opts, subscript).messages, [message]);
1700
1701 let address = "constexpr int c = 3;\nint *p = &c;\n";
1703 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
1704 pointer target type [E0514]";
1705 assert_eq!(run(&opts, address).messages, [warning]);
1706 }
1707
1708 #[test]
1717 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
1718 let mut opts = options();
1721 opts.std = Std::C17;
1722 let source = concat!(
1723 "int add(a, b)\n",
1724 "int a;\n",
1725 "int b;\n",
1726 "{ return a + b; }\n",
1727 "int promoted(c)\n",
1728 "char c;\n",
1729 "{ return c; }\n",
1730 "int narrow(char);\n",
1731 "int narrow(c)\n",
1732 "char c;\n",
1733 "{ return c; }\n",
1734 "int first(a)\n",
1735 "int a[4];\n",
1736 "{ return a[0]; }\n",
1737 );
1738 let result = run(&opts, source);
1739 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1740 let text = result.text();
1741 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
1742 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
1743 assert!(text.contains("c : char object automatic defined"), "{text}");
1745 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
1746 assert!(text.contains("first : int(int *) function external defined"), "{text}");
1748 }
1749
1750 #[test]
1757 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
1758 let mut opts = options();
1759 opts.std = Std::C17;
1760 for (source, message) in [
1761 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
1762 (
1763 "int f(a)\nint a;\nint b;\n{ return a; }\n",
1764 "3:5: error: declaration for parameter 'b' but no such parameter",
1765 ),
1766 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
1767 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
1768 (
1769 "int f(a)\nstatic int a;\n{ return a; }\n",
1770 "2:12: error: storage class specified for parameter 'a'",
1771 ),
1772 (
1773 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
1774 "2:7: error: argument 'a' doesn't match prototype",
1775 ),
1776 ] {
1777 let result = run(&opts, source);
1778 assert!(result.failed(), "expected this to fail:\n{source}");
1779 assert!(result.messages[0].contains(message), "{:?}", result.messages);
1780 }
1781
1782 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
1785 let mut older = options();
1786 older.std = Std::C89;
1787 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
1788 let result = run(&opts, implicit);
1789 assert!(
1790 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
1791 "{:?}",
1792 result.messages
1793 );
1794
1795 let mut newer = options();
1799 newer.std = Std::C23;
1800 let plain = "int f(a)\nint a;\n{ return a; }\n";
1801 let result = run(&newer, plain);
1802 assert!(!result.failed(), "{:?}", result.messages);
1803 assert_eq!(
1804 result.messages,
1805 ["/main.c:1:5: warning: old-style function definition [E0412]"]
1806 );
1807 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
1808 }
1809
1810 #[test]
1817 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
1818 let text = ir(concat!(
1819 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
1820 "struct brim { char buf[9223372036854775807L]; };\n",
1821 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
1822 "unsigned long h = sizeof(struct huge_struct);\n",
1823 "unsigned long b = sizeof(struct brim);\n",
1824 "unsigned long y = sizeof(struct bitty);\n",
1825 ));
1826 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
1827 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
1828 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
1829
1830 let mut opts = options();
1831 opts.emit = EmitKind::Ir;
1832 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
1833 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
1834 assert_eq!(run(&opts, over).messages, [message]);
1835 let array = "struct wide { short buf[1L << 62]; };\n";
1836 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
1837 maximum object size '9223372036854775807' [E0537]";
1838 assert_eq!(run(&opts, array).messages[0], message);
1839 }
1840
1841 fn compile_bytes(source: &[u8]) -> Compiled {
1846 let mut opts = options();
1847 opts.emit = EmitKind::Ir;
1848 let mut fs = MemoryFileSystem::new();
1849 fs.insert("/main.c", source.to_vec());
1850 compile(&opts, "/main.c", &fs)
1851 }
1852
1853 #[test]
1860 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
1861 let mut source = b"char s[] = \"a".to_vec();
1862 source.push(0xff);
1863 source.extend_from_slice(b"b\";\nchar c = '");
1864 source.push(0xff);
1865 source.extend_from_slice(b"';\n");
1866 let result = compile_bytes(&source);
1867 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
1868 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
1869 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
1871
1872 let mut stray = b"int a".to_vec();
1873 stray.push(0xff);
1874 stray.extend_from_slice(b" = 1;\n");
1875 let result = compile_bytes(&stray);
1876 assert!(
1877 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
1878 "{:?}",
1879 result.messages
1880 );
1881 }
1882
1883 #[test]
1884 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
1885 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
1886 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
1887 let expected = "\
1888func @add(i32, i32) -> i32, linkage(external) {
1889block0(%0: i32, %1: i32):
1890 %2 = add.nsw %0, %1
1891 return %2
1892}
1893";
1894 assert!(text.contains(expected), "{text}");
1895 }
1896
1897 #[test]
1898 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
1899 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
1900 assert!(!text.contains("alloca"), "{text}");
1901 assert!(!text.contains("load"), "{text}");
1902 assert!(!text.contains("store"), "{text}");
1903 }
1904
1905 #[test]
1906 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
1907 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
1908 let expected = "\
1909block0:
1910 %0 = alloca, size 4, align 4
1911 %1 = iconst.i32 1
1912 store %1 -> %0, align 4
1913 %2 = call @g(%0) : (ptr) -> i32
1914 return %2
1915";
1916 assert_eq!(text, expected);
1917 }
1918
1919 #[test]
1920 fn a_loop_carries_what_it_changes_as_block_parameters() {
1921 let text = body(
1924 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
1925 return total;\n}\n",
1926 );
1927 assert!(!text.contains("alloca"), "{text}");
1928 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
1929 assert!(text.contains("jump block1("), "{text}");
1930 }
1931
1932 #[test]
1933 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
1934 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
1935 assert!(text.contains("icmp slt %0, %1"), "{text}");
1936 assert!(!text.contains("zext"), "{text}");
1937 }
1938
1939 #[test]
1940 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
1941 let text = body("int f(int a, int b) { return a && b; }\n");
1942 let expected = "\
1943block0(%0: i32, %1: i32):
1944 %2 = iconst.i32 0
1945 %3 = icmp ne %0, %2
1946 %4 = iconst.i1 0
1947 br_if %3, block1, block2(%4)
1948
1949block1:
1950 %5 = iconst.i32 0
1951 %6 = icmp ne %1, %5
1952 jump block2(%6)
1953
1954block2(%7: i1):
1955 %8 = zext.i32 %7
1956 return %8
1957";
1958 assert_eq!(text, expected);
1959 }
1960
1961 #[test]
1962 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
1963 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
1964 assert!(!text.contains("block3"), "{text}");
1967 assert!(!text.contains("iconst.i32 3"), "{text}");
1968 }
1969
1970 #[test]
1971 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
1972 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
1973 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
1974 assert!(body("int f(void) { }\n").contains("unreachable"));
1975 }
1976
1977 #[test]
1978 fn a_structure_is_copied_rather_than_held_in_a_value() {
1979 let text = body(
1980 "struct point { int x, y; };\n\
1981 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
1982 );
1983 assert!(text.contains("memcpy"), "{text}");
1984 }
1985
1986 #[test]
1987 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
1988 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
1989 assert!(text.contains("memset"), "{text}");
1990 }
1991
1992 #[test]
1993 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
1994 let text = body(
1995 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
1996 default: r = 4; } return r; }\n",
1997 );
1998 let expected = "\
1999block0(%0: i32):
2000 %1 = iconst.i32 0
2001 switch %0, block1, [1 => block2, 2 => block3(%1)]
2002
2003block1:
2004 %2 = iconst.i32 4
2005 jump block4(%2)
2006
2007block2:
2008 %3 = iconst.i32 1
2009 jump block3(%3)
2010
2011block3(%4: i32):
2012 %5 = iconst.i32 2
2013 %6 = add.nsw %4, %5
2014 jump block4(%6)
2015
2016block4(%7: i32):
2017 return %7
2018";
2019 assert_eq!(text, expected);
2020 }
2021
2022 #[test]
2023 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
2024 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
2027 assert!(text.contains("%2 = sub %0, %1"), "{text}");
2028 assert!(text.contains("icmp ule"), "{text}");
2029 assert!(!text.contains("switch"), "{text}");
2030 }
2031
2032 #[test]
2033 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
2034 let text = body(
2035 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
2036 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
2037 );
2038 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
2041 assert!(text.contains("block5:\n jump block7("), "{text}");
2042 assert!(text.contains("block6:\n jump block8("), "{text}");
2043 }
2044
2045 #[test]
2046 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
2047 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
2048 }
2049
2050 #[test]
2051 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
2052 let text = body(
2057 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
2058 return n; }\n",
2059 );
2060 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
2063 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
2064 assert!(text.contains("block5:\n jump block3("), "{text}");
2065 }
2066
2067 #[test]
2068 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
2069 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
2072 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
2073 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
2074 assert!(text.contains("br_if %7, block3, block4"), "{text}");
2075 }
2076
2077 #[test]
2078 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
2079 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
2080 assert!(!text.contains("alloca"), "{text}");
2082 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
2083 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
2084 }
2085
2086 #[test]
2087 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
2088 let text =
2089 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
2090 assert!(!text.contains("alloca"), "{text}");
2091 assert!(text.contains("block1(%2: i32):"), "{text}");
2092 assert!(text.contains("jump block1(%5)"), "{text}");
2093 }
2094
2095 #[test]
2096 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
2097 assert_eq!(
2100 body("int f(int x) { return x; spare: return 0; }\n"),
2101 "block0(%0: i32):\n return %0\n"
2102 );
2103 }
2104
2105 #[test]
2106 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
2107 let text = body(
2108 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
2109 );
2110 assert_eq!(
2113 text,
2114 "\
2115block0(%0: ptr):
2116 %1 = load.i8 %0, align 1
2117 %2 = iconst.i8 3
2118 %3 = ashr %1, %2
2119 %4 = sext.i32 %3
2120 return %4
2121"
2122 );
2123 }
2124
2125 #[test]
2126 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
2127 let text =
2131 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
2132 assert_eq!(
2133 text,
2134 "\
2135block0(%0: ptr, %1: i32):
2136 %2 = iconst.i32 16777215
2137 %3 = and %1, %2
2138 %4 = trunc.i16 %3
2139 store %4 -> %0, align 2
2140 %5 = iconst.i32 16
2141 %6 = lshr %3, %5
2142 %7 = trunc.i8 %6
2143 %8 = iconst.i64 2
2144 %9 = ptr_add %0, %8
2145 store %7 -> %9, align 1
2146 return
2147"
2148 );
2149 }
2150
2151 #[test]
2152 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2153 let text =
2154 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2155 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
2158 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
2159 }
2160
2161 #[test]
2162 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2163 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2166 assert_eq!(text.matches("ashr").count(), 0, "{text}");
2167 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
2168 }
2169
2170 #[test]
2171 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2172 let text = body(
2176 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2177 );
2178 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2179 }
2180
2181 #[test]
2182 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2183 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2186 assert!(
2187 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2188 "{text}"
2189 );
2190 }
2191
2192 #[test]
2193 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2194 let text = ir(concat!(
2199 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2200 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2201 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2202 "char s[2] = \"hi\";\n",
2203 ));
2204 assert!(
2205 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2206 "{text}"
2207 );
2208 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2209 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2210 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2213 }
2214
2215 #[test]
2216 fn a_definition_takes_a_parameter_it_left_unnamed() {
2217 let text = ir("int f(int a, int) { return a; }\n");
2221 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2222 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2223
2224 let text = ir("int g(int, int n) { return n; }\n");
2227 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
2228 }
2229
2230 #[test]
2231 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2232 let text = body(concat!(
2237 "struct s { int f; int g; };\n",
2238 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2239 "{ *d = *e = a[0] = *c; }\n",
2240 ));
2241 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2242 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2243 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2244 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2245 }
2246
2247 #[test]
2248 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2249 let mut opts = options();
2254 opts.emit = EmitKind::Ir;
2255 let result = run(
2256 &opts,
2257 concat!(
2258 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2259 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2260 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2261 "const union u c = { { \"1234\", \"567\" } };\n",
2262 ),
2263 );
2264 let text = result.text();
2265 assert_eq!(
2266 result.messages,
2267 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2268 (5 chars into 3 available) [E0637]"]
2269 );
2270 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2271 assert!(
2272 text.contains(
2273 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2274 bytes \"9\\00\", zero 3 }"
2275 ),
2276 "{text}"
2277 );
2278 assert!(
2281 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2282 "{text}"
2283 );
2284 }
2285
2286 #[test]
2287 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2288 let text = body(concat!(
2292 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2293 "void g(struct v *);\n",
2294 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2295 ));
2296 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2297 }
2298
2299 #[test]
2300 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2301 let text = ir(concat!(
2306 "struct s { int x; };\n",
2307 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2308 "int n = (int){ 7 };\n",
2309 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2310 ));
2311 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2312 assert!(text.contains("global @n : i32 = 7,"), "{text}");
2313 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2316 }
2317
2318 #[test]
2319 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2320 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2324 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2325 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2326 }
2327
2328 #[test]
2329 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2330 let text = ir("unsigned char foo[1][0];\n");
2334 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2335 }
2336
2337 #[test]
2338 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2339 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2342 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2343 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2344 }
2345
2346 #[test]
2347 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2348 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2352 assert!(
2353 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2354 "{text}"
2355 );
2356 }
2357
2358 #[test]
2359 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2360 let text = body(
2365 "\
2366struct s { int a, b; };
2367struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2368",
2369 );
2370 assert!(text.contains("block3(%7: ptr)"), "{text}");
2372 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2373 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2374 }
2375
2376 #[test]
2377 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2378 let text = ir("\
2382struct pair { int a, b; };
2383struct pair make(int a, int b);
2384struct pair twice(struct pair p) { return make(p.a, p.b); }
2385");
2386 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2387 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2388 }
2389
2390 #[test]
2391 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2392 let text = ir("\
2396struct big { double v[8]; };
2397struct big grow(struct big b);
2398struct big twice(struct big b) { return grow(grow(b)); }
2399");
2400 assert!(
2401 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2402 "{text}"
2403 );
2404 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2405 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2408 }
2409
2410 #[test]
2411 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2412 let text = ir("\
2417struct big { double v[8]; };
2418struct pair { int a, b; };
2419int p(const char *, ...);
2420int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2421");
2422 assert!(
2423 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2424 "{text}"
2425 );
2426 }
2427
2428 #[test]
2429 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2430 let body = body(
2433 "\
2434struct pair { int a, b; };
2435struct pair make(int a, int b);
2436int second(void) { return make(1, 2).b; }
2437",
2438 );
2439 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
2440 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2441 }
2442
2443 #[test]
2444 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2445 let source = "\
2449struct hfa { float x, y, z; };
2450int take(struct hfa h);
2451int give(struct hfa h) { return take(h); }
2452";
2453 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2454 let mut opts = options();
2455 opts.emit = EmitKind::Ir;
2456 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2457 let result = run(&opts, source);
2458 assert_eq!(result.messages, Vec::<String>::new());
2459 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
2460 }
2461
2462 #[test]
2463 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
2464 let source = "\
2467int use(int *);
2468void f(int n) {
2469 {
2470 int a[n];
2471 use(a);
2472 }
2473 use(0);
2474}
2475";
2476 let body = body(source);
2477 assert!(body.contains("mul.nsw"), "{body}");
2478 assert!(body.contains("stacksave"), "{body}");
2479 assert!(body.contains("alloca %"), "{body}");
2480 assert!(body.contains("stackrestore"), "{body}");
2481 }
2482
2483 #[test]
2484 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
2485 let source = "\
2490int use(int *);
2491int f(int n) {
2492 {
2493 int a[n];
2494 if (use(a)) goto out;
2495 use(0);
2496 }
2497out:
2498 return 0;
2499}
2500";
2501 let body = body(source);
2502 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
2504 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2505 assert!(after.starts_with(" %4\n jump block"), "{body}");
2506 }
2507
2508 #[test]
2509 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
2510 let source = "\
2514int use(int *);
2515int f(int n) {
2516 int a[n];
2517again:
2518 if (use(a)) goto again;
2519 return 0;
2520}
2521";
2522 let body = body(source);
2523 assert!(body.contains("stacksave"), "{body}");
2524 assert!(!body.contains("stackrestore"), "{body}");
2525 }
2526
2527 #[test]
2528 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2529 let source = "\
2534int use(int *);
2535int f(int n) {
2536again:
2537 {
2538 int a[n];
2539 if (use(a)) goto again;
2540 }
2541 return 0;
2542}
2543";
2544 let body = body(source);
2545 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2546 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2547 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
2548 }
2549
2550 #[test]
2551 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2552 let source = "\
2558int f(void);
2559void t(void) {
2560 int count = 10;
2561 for (; count--;) {
2562 int b[f()];
2563 int i;
2564 for (i = 0; i < f(); i++) {
2565 b[i] = count;
2566 }
2567 }
2568}
2569";
2570 let body = body(source);
2571 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2575 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2576 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
2577 assert!(next.contains("jump block1("), "{body}");
2578 }
2579
2580 #[test]
2581 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
2582 let source = "\
2585unsigned long f(int n) {
2586 int a[n];
2587 n = 0;
2588 return sizeof a;
2589}
2590";
2591 let body = body(source);
2592 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
2594 }
2595
2596 #[test]
2597 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
2598 let source = "\
2601int use(int);
2602int f(int x) {
2603 return ({
2604 int t = use(x);
2605 t * t;
2606 });
2607}
2608";
2609 let expected = "\
2610block0(%0: i32):
2611 %1 = call @use(%0) : (i32) -> i32
2612 %2 = mul.nsw %1, %1
2613 return %2
2614";
2615 assert_eq!(body(source), expected);
2616 }
2617
2618 #[test]
2619 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
2620 let source = "int f(int x) { return ({ return x; 0; }); }\n";
2624 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
2625 }
2626
2627 #[test]
2628 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
2629 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
2633 let expected = "\
2634block0(%0: ptr):
2635 %1 = va_arg.f64 %0
2636 %2 = va_arg.f64 %0
2637 %3 = fadd %1, %2
2638 return %3
2639";
2640 assert_eq!(body(source), expected);
2641 }
2642
2643 #[test]
2644 fn one_that_reads_a_structure_answers_where_the_object_is() {
2645 let source = "\
2652struct s { int a; long b; };
2653long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
2654";
2655 let expected = "\
2656block0(%0: ptr):
2657 %1 = alloca, size 16, align 8
2658 %2 = va_object %0, size 16, align 8
2659 memcpy %1, %2, size 16, align 8
2660 %3 = iconst.i64 8
2661 %4 = ptr_add %1, %3
2662 %5 = load.i64 %4, align 8
2663 return %5
2664";
2665 assert_eq!(body(source), expected);
2666 }
2667
2668 #[test]
2669 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
2670 let source = "\
2674int f(int c) {
2675 void *p = c ? &&one : &&two;
2676 goto *p;
2677one:
2678 return 1;
2679two:
2680 return 2;
2681}
2682";
2683 let expected = "\
2684block0(%0: i32):
2685 %1 = iconst.i32 0
2686 %2 = icmp ne %0, %1
2687 br_if %2, block1, block2
2688
2689block1:
2690 %3 = block_addr block3
2691 jump block4(%3)
2692
2693block2:
2694 %4 = block_addr block5
2695 jump block4(%4)
2696
2697block3:
2698 %5 = iconst.i32 1
2699 return %5
2700
2701block4(%6: ptr):
2702 indirect_br %6, block3, block5
2703
2704block5:
2705 %7 = iconst.i32 2
2706 return %7
2707";
2708 assert_eq!(body(source), expected);
2709 }
2710
2711 #[test]
2712 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
2713 let source = "void **next(void);
2716void f(void) { goto *next(); }
2717";
2718 let expected = "\
2719block0:
2720 %0 = call @next() : () -> ptr
2721 unreachable
2722";
2723 assert_eq!(body(source), expected);
2724 }
2725
2726 #[test]
2727 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
2728 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
2731 let expected = "\
2732block0:
2733 inline_asm.volatile \"mfence\", \"\", \"memory\"()
2734 return
2735";
2736 assert_eq!(body(source), expected);
2737 }
2738
2739 #[test]
2740 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
2741 let source = "\
2744int f(int x, int y) {
2745 int r;
2746 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
2747 return r + y;
2748}
2749";
2750 let expected = "\
2751block0(%0: i32, %1: i32):
2752 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
2753 %4 = add.nsw %2, %3
2754 return %4
2755";
2756 assert_eq!(body(source), expected);
2757 }
2758
2759 #[test]
2760 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
2761 let source = "\
2766struct pair { int a, b; };
2767int f(int x) {
2768 int slot = x;
2769 struct pair p = { x, x };
2770 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
2771 return slot + p.a;
2772}
2773";
2774 let text = body(source);
2775 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
2776 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
2777 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
2778 }
2779
2780 #[test]
2781 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
2782 let source = "\
2787int f(int x) {
2788 int r = 7;
2789 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
2790 return r;
2791away:
2792 return r;
2793}
2794";
2795 let expected = "\
2796block0(%0: i32):
2797 %1 = iconst.i32 7
2798 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
2799
2800block1:
2801 return %2
2802
2803block2:
2804 return %1
2805";
2806 assert_eq!(body(source), expected);
2807 }
2808
2809 #[test]
2810 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
2811 let mut opts = options();
2815 opts.emit = EmitKind::Ir;
2816 for (source, expected) in [
2817 (
2818 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
2819 "output operand constraint lacks '='",
2820 ),
2821 (
2822 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
2823 "lvalue required in 'asm' statement",
2824 ),
2825 (
2826 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
2827 "read-only variable 'g' used as 'asm' output",
2828 ),
2829 (
2830 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
2831 "input operand constraint contains '='",
2832 ),
2833 (
2834 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
2835 "memory input 0 is not directly addressable",
2836 ),
2837 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
2838 (
2839 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
2840 "duplicate asm operand name 'a'",
2841 ),
2842 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
2843 ] {
2844 let result = run(&opts, source);
2845 assert!(result.failed(), "expected this to be reported:\n{source}");
2846 assert!(
2847 result.messages.iter().any(|m| m.contains(expected)),
2848 "{expected}\n{:?}",
2849 result.messages
2850 );
2851 }
2852 }
2853
2854 #[test]
2855 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
2856 let mut opts = options();
2857 opts.emit = EmitKind::Ir;
2858 for source in [
2859 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
2860 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
2861 ] {
2862 let result = run(&opts, source);
2863 assert!(result.failed(), "expected this to be reported:\n{source}");
2864 assert!(
2865 result.messages.iter().any(|m| m.contains("not supported yet")),
2866 "{:?}",
2867 result.messages
2868 );
2869 }
2870 }
2871
2872 fn round_trip(source: &str) -> (String, String) {
2874 let printed = ir(source);
2875 let mut opts = options();
2876 opts.emit = EmitKind::Ir;
2877 let mut fs = MemoryFileSystem::new();
2878 fs.insert("/main.ir", printed.clone().into_bytes());
2879 let result = compile_ir(&opts, "/main.ir", &fs);
2880 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
2881 (printed, result.text().to_owned())
2882 }
2883
2884 #[test]
2885 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
2886 let (printed, again) = round_trip(
2890 "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",
2891 );
2892 assert_eq!(printed, again);
2893 }
2894
2895 #[test]
2896 fn ir_that_is_not_ir_says_which_line_stopped_it() {
2897 let mut opts = options();
2898 opts.emit = EmitKind::Ir;
2899 let mut fs = MemoryFileSystem::new();
2900 let text = "\
2901; ModuleID = 'a.c'
2902; format 0
2903target triple = \"x86_64-unknown-linux-gnu\"
2904target datalayout = \"e-p:64:64-i64:64-S128\"
2905
2906func @f(), linkage(external) {
2907block0:
2908 frobnicate
2909}
2910";
2911 fs.insert("/main.ir", text.as_bytes().to_vec());
2912 let result = compile_ir(&opts, "/main.ir", &fs);
2913 assert!(result.failed());
2914 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
2915 }
2916
2917 #[test]
2918 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
2919 let mut opts = options();
2922 opts.emit = EmitKind::Ir;
2923 let mut fs = MemoryFileSystem::new();
2924 let text = "\
2925; ModuleID = 'a.c'
2926; format 0
2927target triple = \"x86_64-unknown-linux-gnu\"
2928target datalayout = \"e-p:64:64-i64:64-S128\"
2929
2930func @f(), linkage(external) {
2931block0:
2932 %0 = iconst.i32 1
2933 return %0
2934}
2935";
2936 fs.insert("/main.ir", text.as_bytes().to_vec());
2937 let result = compile_ir(&opts, "/main.ir", &fs);
2938 assert!(result.failed());
2939 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
2940 }
2941
2942 #[test]
2943 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
2944 let mut fs = MemoryFileSystem::new();
2946 fs.insert("/main.ir", Vec::new());
2947 let result = compile_ir(&options(), "/main.ir", &fs);
2948 assert!(result.failed());
2949 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
2950 }
2951
2952 #[test]
2953 fn the_printed_ir_reads_back_as_the_same_module() {
2954 let text = ir("\
2957struct point { int x, y; };
2958static const char greeting[] = \"hi\";
2959int table[4] = { 1, 2, 3 };
2960int puts(const char *);
2961double half(double x) { return x / 2.0; }
2962int f(int n) {
2963 int total = 0;
2964 for (int i = 0; i < n; i++) {
2965 if (i == 3) continue;
2966 total += table[i];
2967 }
2968 switch (n) {
2969 case 0: total = 1;
2970 case 1: total++; break;
2971 default: total = -total;
2972 }
2973 struct point p = { total, 1 };
2974 int *q = &p.y;
2975 puts(greeting);
2976 return p.x + *q;
2977}
2978int dispatch(int c) {
2979 void *p = c ? &&one : &&two;
2980 goto *p;
2981one:
2982 return 1;
2983two:
2984 return 2;
2985}
2986int assembly(int x, int *p) {
2987 int r;
2988 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
2989 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
2990 return r;
2991away:
2992 return 0;
2993}
2994");
2995 let mut names = Interner::new();
2996 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
2997 assert_eq!(rucc_ir::print(&module, &names), text);
2998 }
2999}