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 "struct O { char c; int i; } __attribute__((__packed__));\n",
712 "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
713 "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
714 "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
715 ));
716 }
717
718 #[test]
728 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
729 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
731 assert_eq!(
732 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
733 1
734 );
735 assert_eq!(
736 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
737 1
738 );
739 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
740 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
742 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
743 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
745 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
746 }
747
748 fn bit_field_byte(record: &str) -> u64 {
750 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
751 let body = body(&source);
752 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
753 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
754 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
755 }
756
757 #[test]
763 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
764 tast(concat!(
765 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
766 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
767 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
768 "struct b { char c; __attribute__((packed)) int i; };\n",
769 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
770 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
771 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
772 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
773 ));
774 }
775
776 #[test]
782 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
783 tast(concat!(
784 "#pragma pack(1)\n",
785 "struct A { char c; int i; };\n",
786 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
787 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
788 "#pragma pack()\n",
789 "struct B { char c; int i; };\n",
790 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
791 "#pragma pack(2)\n",
792 "struct C { char c; int i; double d; };\n",
793 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
794 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
795 "struct K { char c; int i __attribute__((aligned(8))); };\n",
797 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
798 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
799 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
801 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
802 "#pragma pack()\n",
803 "#pragma pack(push, 1)\n",
804 "struct D { char c; short s; };\n",
805 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
806 "#pragma pack(pop)\n",
807 "struct E { char c; short s; };\n",
808 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
809 "struct H { char c;\n",
811 "#pragma pack(1)\n",
812 " int i; };\n",
813 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
814 "#pragma pack(1)\n",
815 "struct I { char c;\n",
816 "#pragma pack()\n",
817 " int i; };\n",
818 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
819 "#pragma pack()\n",
820 "#pragma pack(push, 8)\n",
822 "#pragma pack(push, 1)\n",
823 "struct P { char c; int i; };\n",
824 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
825 "#pragma pack(pop)\n",
826 "struct Q { char c; int i; };\n",
827 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
828 "#pragma pack(pop)\n",
829 "#pragma pack(16)\n",
831 "struct R { char c; int i; };\n",
832 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
833 "#pragma pack()\n",
834 "#pragma pack(1)\n",
835 "struct S { char c; int i : 5; int j : 20; };\n",
836 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
837 "union T { char c; int i; };\n",
838 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
839 "#pragma pack()\n",
840 ));
841 }
842
843 #[test]
847 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
848 let result = run(
849 &options(),
850 concat!(
851 "#pragma pack 4\n",
852 "#pragma pack(pop)\n",
853 "#pragma pack(3)\n",
854 "#pragma pack(1) junk\n",
855 "#pragma pack(push, 1\n",
856 "#pragma pack(x)\n",
857 "#pragma pack(0)\n",
860 "#pragma pack(push)\n",
861 "struct s { char c; int i; };\n",
862 "#pragma pack(pop)\n",
863 "#pragma pack(pop, foo)\n",
864 ),
865 );
866 let expected = [
867 "missing `(` after `#pragma pack` - ignored",
868 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
869 "alignment must be a small power of two, not 3",
870 "junk at end of `#pragma pack`",
871 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
872 "unknown action `x` for `#pragma pack` - ignored",
873 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
874 ];
875 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
876 for (message, want) in result.messages.iter().zip(expected) {
877 assert!(message.contains(want), "expected {want:?} in {message:?}");
878 }
879 }
880
881 #[test]
885 fn the_wide_integer_answers_to_all_three_of_its_names() {
886 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
887 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
888 assert!(text.contains("decl #1 b : __int128"), "{text}");
889 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
890 }
891
892 #[test]
893 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
894 let text = tast("long f(int a, long b) { return a + b; }\n");
898 assert!(text.contains("convert arithmetic"), "{text}");
899 }
900
901 #[test]
902 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
903 for source in [
904 "#error stop\n",
905 "int f(void) { return 1 + ; }\n",
906 "int f(void) { return undeclared; }\n",
907 ] {
908 let result = run(&options(), source);
909 assert!(result.failed(), "expected this to fail:\n{source}");
910 assert!(
911 result.text().is_empty(),
912 "a file that did not compile wrote a tree:\n{source}"
913 );
914 }
915 }
916
917 #[test]
918 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
919 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
923 assert_eq!(result.errors, 1, "{:?}", result.messages);
924 }
925
926 #[test]
927 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
928 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
932 assert_eq!(result.errors, 1, "{:?}", result.messages);
933 }
934
935 #[test]
936 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
937 let source = "int f(void) { char c = 300; return c; }\n";
938 let plain = run(&options(), source);
939 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
940 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
941 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
942
943 let mut opts = options();
944 opts.warnings_are_errors = true;
945 let strict = run(&opts, source);
946 assert!(strict.failed());
947 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
948 for message in &strict.messages {
949 assert!(!message.contains("warning:"), "{message}");
950 }
951 }
952
953 #[test]
954 fn the_dialect_reaches_the_keywords_and_the_checking() {
955 let source = "typeof(1) x;\n";
958 let mut opts = options();
959 opts.std = Std::C23;
960 opts.gnu_extensions = false;
961 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
962
963 opts.std = Std::C17;
964 assert!(run(&opts, source).failed());
965 }
966
967 #[test]
968 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
969 let mut opts = options();
970 opts.emit = EmitKind::Object;
971 let result = run(&opts, "int x = 1;\n");
972 assert!(!result.failed(), "{:?}", result.messages);
973 assert!(result.text().is_empty());
974 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
977 }
978
979 fn mir(source: &str) -> String {
981 let mut opts = options();
982 opts.emit = EmitKind::MirFinal;
983 let result = run(&opts, source);
984 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
985 result.text().to_owned()
986 }
987
988 #[test]
994 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
995 let text = mir("int add(int a, int b) { return a + b; }\n");
996 assert!(text.starts_with("mfunc @add {"), "{text}");
997 assert!(text.contains("x64.add_rr_32"), "{text}");
998 assert!(text.contains("x64.ret"), "{text}");
999 assert!(!text.contains('%'), "{text}");
1002 }
1003
1004 #[test]
1006 fn a_function_with_no_body_produces_no_machine_function() {
1007 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1008 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1009 assert!(text.contains("mfunc @f {"), "{text}");
1010 assert!(text.contains("x64.call"), "{text}");
1011 }
1012
1013 #[test]
1015 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1016 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1017 let first = text.find("mfunc @a").expect("the first function");
1018 let second = text.find("mfunc @b").expect("the second function");
1019 assert!(first < second, "{text}");
1020 }
1021
1022 #[test]
1024 fn the_target_decides_which_convention_the_generated_code_follows() {
1025 let mut opts = options();
1026 opts.emit = EmitKind::MirFinal;
1027 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1028 assert!(linux.contains("$rdi"), "{linux}");
1029
1030 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1031 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1032 assert!(windows.contains("$rcx"), "{windows}");
1033 assert!(!windows.contains("$rdi"), "{windows}");
1034 }
1035
1036 #[test]
1038 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1039 let mut opts = options();
1040 opts.emit = EmitKind::MirFinal;
1041 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1042 let result = run(&opts, "int f(int a) { return a; }\n");
1043 assert!(result.failed());
1044 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1045 assert!(result.text().is_empty());
1046 }
1047
1048 #[test]
1055 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1056 let mut opts = options();
1057 opts.emit = EmitKind::MirFinal;
1058 let source = "long double a(long double x) { return x; }\n\
1059 long double b(long double x) { return x; }\n";
1060 let result = run(&opts, source);
1061 assert!(result.failed());
1062 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1063 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1064 assert!(result.messages[0].contains("x87 stack"), "{:?}", result);
1065 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1066 assert!(result.text().is_empty());
1067 }
1068
1069 #[test]
1076 fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1077 let mut opts = options();
1078 opts.emit = EmitKind::MirFinal;
1079 let result = run(&opts, "int f(int a) {\n __int128 wide = a;\n return (int) wide;\n}\n");
1080 assert!(result.failed());
1081 assert!(
1082 result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1083 "{result:?}"
1084 );
1085 assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1086 assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1087 }
1088
1089 #[test]
1091 fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1092 let mut opts = options();
1093 opts.emit = EmitKind::MirFinal;
1094 let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1095 assert!(result.failed());
1096 let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1097 assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1098 assert!(!note.contains("spec/17-milestones.md"), "{note}");
1099 }
1100
1101 #[test]
1103 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1104 let source = "int f(int a) { return a; }\n";
1105 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1106
1107 let mut opts = options();
1108 opts.emit = EmitKind::MirFinal;
1109 opts.frame_pointer = true;
1110 let kept = run(&opts, source).text().to_owned();
1111 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1112 }
1113
1114 fn asm(source: &str) -> String {
1116 let mut opts = options();
1117 opts.emit = EmitKind::Asm;
1118 let result = run(&opts, source);
1119 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1120 result.text().to_owned()
1121 }
1122
1123 #[test]
1130 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1131 let text = asm("int add(int a, int b) { return a + b; }\n");
1132 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1133 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1134 assert!(text.contains("\nadd:\n"), "{text}");
1135 assert!(text.contains("\taddl\t"), "{text}");
1136 assert!(text.contains("\tret\n"), "{text}");
1137 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1138 assert!(text.contains(".note.GNU-stack"), "{text}");
1141 }
1142
1143 #[test]
1149 fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1150 let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1151 assert!(text.contains("\tcall\t*%"), "{text}");
1152 assert!(text.contains("\tcall\tg\n"), "{text}");
1153 assert!(text.contains("%rdi"), "{text}");
1157 }
1158
1159 #[test]
1161 fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1162 let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1163 assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1164 }
1165
1166 #[test]
1168 fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1169 let text = asm("long f(void *p) { return (long)p; }\n");
1170 for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1175 let mnemonic = line.split_whitespace().next().unwrap_or("");
1176 assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1177 }
1178 }
1179
1180 #[test]
1184 fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1185 let six = "long a, long b, long c, long d, long e, long f";
1186 let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1187
1188 assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1192 assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1193
1194 let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1198 assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1199 let eight =
1200 "double a, double b, double c, double d, double e, double f, double g, double h";
1201 let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1202 assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1203 }
1204
1205 #[test]
1208 fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1209 let six = "1, 2, 3, 4, 5, 6";
1210 let decl = "long g(long, long, long, long, long, long, long, long);\n";
1211 let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1212
1213 assert!(text.contains("\tmovq\t%"), "{text}");
1214 assert!(text.contains(", (%rsp)\n"), "{text}");
1215 assert!(text.contains(", 8(%rsp)\n"), "{text}");
1216 assert!(text.contains("\tsubq\t$"), "{text}");
1218
1219 let narrow = "int g(int, int, int, int, int, int, int);\n";
1221 let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1222 assert!(text.contains("\tmovl\t%"), "{text}");
1223 assert!(text.contains(", (%rsp)\n"), "{text}");
1224 }
1225
1226 #[test]
1229 fn a_variadic_call_counts_registers_and_not_arguments() {
1230 let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1231 let decl = "int g(int, ...);\n";
1232 let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1233
1234 assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1235 assert!(text.contains("\tmovsd\t%"), "{text}");
1236 assert!(text.contains(", (%rsp)\n"), "{text}");
1237 }
1238
1239 #[test]
1244 fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1245 let body =
1246 "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1247 let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1248
1249 let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1252 assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1253 assert!(!text.contains(", 0(%r"), "{text}");
1254 assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1255
1256 assert!(text.contains("\tsubq\t$"), "{text}");
1258 }
1259
1260 #[test]
1263 fn va_start_writes_the_four_fields_the_psabi_describes() {
1264 let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1265 let params = "int a, int b, int c, double d";
1266 let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1267
1268 assert!(text.contains(" movl $24, "), "{text}");
1272 assert!(text.contains(" movl $64, "), "{text}");
1273 assert!(text.contains(", 8(%r"), "{text}");
1277 assert!(text.contains(", 16(%r"), "{text}");
1278 let frame: u32 = text
1279 .lines()
1280 .find_map(|line| line.trim().strip_prefix("subq $")?.split(',').next()?.parse().ok())
1281 .expect("a variadic function takes a frame for the save area");
1282 let above = |line: &str| {
1283 let at: u32 = line.trim().strip_prefix("leaq ")?.split('(').next()?.parse().ok()?;
1284 Some(at > frame)
1285 };
1286 assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1287 }
1288
1289 #[test]
1292 fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1293 let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1294 let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1295 let text = asm(&ints);
1296
1297 assert!(text.contains("$40, "), "{text}");
1300 assert!(text.contains(" cmpl "), "{text}");
1301 assert!(text.contains(" setbe "), "unsigned, since an offset is a count of bytes: {text}");
1302
1303 let arg = "__builtin_va_arg(ap, double)";
1304 let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1305 assert!(text.contains("$160, "), "the last vector slot: {text}");
1306 }
1307
1308 #[test]
1311 fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1312 let decl = "struct pair { long a, b; };\n";
1313 let body = "struct pair p = *q; return p.a + p.b;";
1314 let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
1315
1316 assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
1317 assert!(!text.contains("\tcall"), "{text}");
1318 assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
1320 }
1321
1322 #[test]
1325 fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
1326 let decl = "struct bytes { char a[8]; };\n";
1327 let body = "struct bytes p = *q; return p.a[0];";
1328 let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
1329
1330 assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
1332 }
1333
1334 #[test]
1337 fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
1338 let decl = "struct wide { long a, b, c; };\n";
1339 let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
1340
1341 assert!(!text.contains("memset"), "nothing calls the library: {text}");
1342 assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
1343 }
1344
1345 #[test]
1348 fn a_copy_too_large_to_unroll_calls_the_runtime() {
1349 let decl = "struct huge { char a[4096]; };\n";
1350 let mut opts = options();
1351 opts.emit = EmitKind::Asm;
1352 let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
1353 let result = run(&opts, &source);
1354 assert!(!result.failed(), "{:?}", result.messages);
1355 let text = result.text();
1356 assert!(text.contains("call") && text.contains("memcpy"), "{text}");
1357 assert!(text.contains("4096"), "the size travels: {text}");
1360 }
1361
1362 #[test]
1365 fn a_realigned_frame_reads_them_through_the_frame_pointer() {
1366 let six = "long a, long b, long c, long d, long e, long f";
1367 let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
1368 let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
1369
1370 assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
1374 assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
1375 assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
1376 }
1377
1378 #[test]
1380 fn the_target_decides_how_the_assembly_is_spelled() {
1381 let mut opts = options();
1382 opts.emit = EmitKind::Asm;
1383 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1384 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1385 assert!(text.contains("__TEXT,__text"), "{text}");
1386 assert!(text.contains("\n_f:\n"), "{text}");
1387 assert!(!text.contains(".note.GNU-stack"), "{text}");
1388 }
1389
1390 fn obj(source: &str) -> Vec<u8> {
1392 let mut opts = options();
1393 opts.emit = EmitKind::Object;
1394 let result = run(&opts, source);
1395 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1396 match result.artifact {
1397 Artifact::Object(bytes) => bytes,
1398 other => panic!("expected an object, got {other:?}"),
1399 }
1400 }
1401
1402 #[test]
1408 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1409 let bytes = obj("int add(int a, int b) { return a + b; }\n");
1410 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1411 let text = asm("int add(int a, int b) { return a + b; }\n");
1412 assert!(
1413 text.contains("\taddl\t"),
1414 "and the listing of it is the same instructions:\n{text}"
1415 );
1416 }
1417
1418 #[test]
1420 fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1421 let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1422 assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1423 assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1424 assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1425 assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1428 assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1429 assert!(!text.contains(".globl\thidden"), "{text}");
1430 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1433 }
1434
1435 #[test]
1437 fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1438 let text = asm("const char *f(void) { return \"hi\"; }\n");
1439 assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1440 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1441 let label = text
1442 .lines()
1443 .find(|line| line.starts_with(".Lstr"))
1444 .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1445 assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1446 }
1447
1448 #[test]
1450 fn an_address_in_an_initializer_is_left_to_the_linker() {
1451 let source = "int counter;\nint *p = &counter;\n";
1452 let text = asm(source);
1453 assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1454 let bytes = obj(source);
1457 assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1458 }
1459
1460 #[test]
1462 fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
1463 let mut opts = options();
1464 opts.emit = EmitKind::Asm;
1465 let result = run(&opts, "_Thread_local int x = 1;\n");
1466 assert!(result.failed(), "every thread sharing one variable is worse than a message");
1467 assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
1468 assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
1470 }
1471
1472 #[test]
1474 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1475 let source = "int callee(void); int g(void) { return callee(); }\n";
1479 let bytes = obj(source);
1480 assert!(
1481 bytes.windows(7).any(|w| w == b"callee\0"),
1482 "the object has to name the callee for the linker to find it"
1483 );
1484 let text = asm(source);
1485 assert!(text.contains("\tcall\tcallee\n"), "{text}");
1486 }
1487
1488 #[test]
1494 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1495 let mut opts = options();
1496 opts.emit = EmitKind::Executable;
1498 let result = run(&opts, "int main(void) { return 0; }\n");
1499 assert_eq!(result.messages, Vec::<String>::new());
1500 match result.artifact {
1501 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1502 other => panic!("expected an object, got {other:?}"),
1503 }
1504 }
1505
1506 #[test]
1508 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1509 let mut opts = options();
1510 opts.emit = EmitKind::Object;
1511 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1512 let result = run(&opts, "int f(void) { return 0; }\n");
1513 assert!(result.failed(), "an object nobody can read is worse than a message");
1514 assert!(
1515 result.messages.iter().any(|m| m.contains("no object writer")),
1516 "{:?}",
1517 result.messages
1518 );
1519 }
1520
1521 fn ir(source: &str) -> String {
1523 let mut opts = options();
1524 opts.emit = EmitKind::Ir;
1525 let result = run(&opts, source);
1526 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1527 result.text().to_owned()
1528 }
1529
1530 fn body(source: &str) -> String {
1532 let text = ir(source);
1533 let (_, rest) = text.split_once("{\n").expect("a function definition");
1534 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1535 body.to_owned()
1536 }
1537
1538 #[test]
1546 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1547 let text = ir(concat!(
1548 "int g;\n",
1549 "int a = __builtin_constant_p(1);\n",
1550 "int b = __builtin_constant_p(g);\n",
1551 "int c = __builtin_constant_p(\"abc\");\n",
1552 "int d = __builtin_constant_p(&g);\n",
1553 "int e = __builtin_constant_p(1.5);\n",
1554 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1555 ));
1556 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1557 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1558 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1559 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1560 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1561 assert!(text.contains("global @h : i32 = 11,"), "{text}");
1562 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1563
1564 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1568 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
1569 }
1570
1571 #[test]
1580 fn a_call_to_a_library_builtin_reaches_the_library_function() {
1581 let text = body("void f(void) { __builtin_abort(); }\n");
1582 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
1583
1584 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1587 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1588 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1589 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1590 }
1591
1592 #[test]
1604 fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
1605 let text = ir(concat!(
1606 "long a = __builtin_expect(7, 1);\n",
1607 "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
1608 "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
1609 ));
1610 assert!(text.contains("global @a : i64 = 7,"), "{text}");
1611 assert!(text.contains("global @b : i64 = 9,"), "{text}");
1612 assert!(text.contains("global @c : i64 = 8,"), "{text}");
1613 assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
1614
1615 let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
1618 assert!(text.contains("sext"), "{text}");
1619
1620 let one = "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 1\n %2 = sext.i64 %1\n return %0\n";
1624 assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
1625 let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
1626 assert_eq!(body(source), one);
1627 }
1628
1629 #[test]
1641 fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
1642 let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
1643 let text = ir(promised);
1644 assert!(text.contains(" unreachable_hint\n"), "{text}");
1645 assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
1646
1647 let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
1651 assert!(after.contains("return"), "{after}");
1652
1653 let text = asm(promised);
1656 let mine = text.split_once("\nf:\n").expect("a definition").1;
1657 let mine = mine.split_once("\t.size").expect("a definition").0;
1658 let plain = asm("int f(int x) { if (x) return 1; }\n");
1659 let plain = plain.split_once("\nf:\n").expect("a definition").1;
1660 let plain = plain.split_once("\t.size").expect("a definition").0;
1661 assert_eq!(mine, plain);
1662 assert!(mine.trim_end().ends_with("ret"), "{mine}");
1663 assert!(!mine.contains("ud2"), "{mine}");
1664 }
1665
1666 #[test]
1673 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1674 let mut opts = options();
1675 opts.emit = EmitKind::Ir;
1676 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1677 assert!(
1678 messages.iter().any(|m| m.contains("__builtin_abort")),
1679 "expected the written name in {messages:?}"
1680 );
1681 }
1682
1683 #[test]
1691 fn a_builtin_nothing_lowers_is_refused_by_name() {
1692 let mut opts = options();
1693 opts.emit = EmitKind::Ir;
1694 for (builtin, call) in [
1695 ("__builtin_clz", "__builtin_clz(1u)"),
1696 ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
1697 ("__atomic_load_n", "__atomic_load_n(&counter, 0)"),
1698 ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
1699 ] {
1700 let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
1701 let messages = run(&opts, &source).messages;
1702 let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
1703 assert!(named, "expected {builtin} to be refused by name in {messages:?}");
1704 }
1705 }
1706
1707 #[test]
1715 fn what_is_refused_is_the_call_and_not_the_name() {
1716 let text = ir("unsigned long n = sizeof(__builtin_clz(1u));\n");
1717 assert!(text.contains("global @n : i64 = 4,"), "{text}");
1718
1719 let text = ir(
1720 "int __builtin_clz(unsigned x) { return 1; }\nint f(void) { return __builtin_clz(2u); }\n",
1721 );
1722 assert!(text.contains("call @__builtin_clz"), "{text}");
1723 }
1724
1725 #[test]
1730 fn a_static_function_nothing_refers_to_is_not_emitted() {
1731 let text = ir("static int dropped(void) { return 1; }\n\
1732 static int kept(void) { return 2; }\n\
1733 int main(void) { return kept(); }\n");
1734 assert!(text.contains("func @kept"), "{text}");
1735 assert!(!text.contains("dropped"), "{text}");
1736 }
1737
1738 #[test]
1744 fn two_static_functions_that_only_call_each_other_are_both_dropped() {
1745 let text = ir("static int ping(void);\n\
1746 static int pong(void) { return ping(); }\n\
1747 static int ping(void) { return pong(); }\n\
1748 int main(void) { return 0; }\n");
1749 assert!(!text.contains("ping"), "{text}");
1750 assert!(!text.contains("pong"), "{text}");
1751 }
1752
1753 #[test]
1759 fn naming_a_static_function_anywhere_keeps_it() {
1760 let text = ir("static int by_address(void) { return 1; }\n\
1761 static int in_an_image(void) { return 2; }\n\
1762 static int deeper(void) { return 3; }\n\
1763 static int reaches_deeper(void) { return deeper(); }\n\
1764 static int (*table[1])(void) = {in_an_image};\n\
1765 int main(void) {\n\
1766 int (*p)(void) = by_address;\n\
1767 return p() + table[0]() + reaches_deeper();\n\
1768 }\n");
1769 for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
1770 assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
1771 }
1772 }
1773
1774 #[test]
1780 fn an_attribute_keeps_a_static_function_nothing_refers_to() {
1781 for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
1782 let source = format!(
1783 "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
1784 int main(void) {{ return 0; }}\n"
1785 );
1786 let text = ir(&source);
1787 assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
1788 }
1789 }
1790
1791 #[test]
1794 fn a_function_anything_could_call_is_emitted_without_being_called() {
1795 let text =
1796 ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
1797 assert!(text.contains("func @nobody_here_calls_it"), "{text}");
1798 }
1799
1800 #[test]
1807 fn a_classification_c_has_an_operator_for_is_that_operator() {
1808 for (builtin, operator) in [
1809 ("__builtin_isgreater", "binary >"),
1810 ("__builtin_isgreaterequal", "binary >="),
1811 ("__builtin_isless", "binary <"),
1812 ("__builtin_islessequal", "binary <="),
1813 ] {
1814 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1815 let text = tast(&source);
1816 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1817 }
1818 }
1819
1820 #[test]
1829 fn the_classification_builtins_are_comparisons_and_not_calls() {
1830 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1831 assert_eq!(
1832 text,
1833 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
1834 %2\n return %3\n"
1835 );
1836
1837 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1839 assert!(text.contains("fcmp one %0, %1"), "{text}");
1840
1841 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1842 assert!(text.contains("fcmp uno %0, %0"), "{text}");
1843
1844 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1845 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1846 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1847 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1848 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1849 assert!(text.contains("%5 = or %3, %4"), "{text}");
1850
1851 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1854 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1855 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1856 assert!(text.contains("%5 = and %3, %4"), "{text}");
1857
1858 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1859 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1860 assert!(text.contains("icmp slt %1, %2"), "{text}");
1861
1862 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1865 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1866
1867 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1870 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1871 }
1872
1873 #[test]
1880 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1881 let text = ir(concat!(
1882 "int a = __builtin_isinff(1e300);\n",
1883 "int b = __builtin_isinf(1e300);\n",
1884 "int c = __builtin_isnan(0.0);\n",
1888 "int d = __builtin_signbit(-0.0);\n",
1889 "int e = __builtin_islessgreater(1.0, 2.0);\n",
1890 ));
1891 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1892 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1893 assert!(text.contains("global @c : i32 = 0,"), "{text}");
1894 assert!(text.contains("global @d : i32 = 1,"), "{text}");
1895 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1896 }
1897
1898 #[test]
1900 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1901 let mut opts = options();
1902 opts.emit = EmitKind::Ir;
1903 let source = concat!(
1904 "int a(int x) { return __builtin_isnan(x); }\n",
1905 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1906 "int c(double x) { return __builtin_isnan(x, x); }\n",
1907 );
1908 let messages = run(&opts, source).messages;
1909 assert_eq!(
1910 messages,
1911 [
1912 "/main.c:1:23: error: non-floating-point argument in call to function \
1913 '__builtin_isnan' [E0685]",
1914 "/main.c:2:30: error: non-floating-point arguments in call to function \
1915 '__builtin_isunordered' [E0685]",
1916 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1917 ]
1918 );
1919 }
1920
1921 #[test]
1929 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
1930 let text = ir(concat!(
1931 "double a = __builtin_inf();\n",
1932 "float b = __builtin_huge_valf();\n",
1933 "long double c = __builtin_infl();\n",
1934 "double d = __builtin_huge_val();\n",
1935 ));
1936 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1937 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1938 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1939 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1940 assert!(!text.contains("call"), "{text}");
1941 }
1942
1943 #[test]
1952 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1953 let text = ir(concat!(
1954 "double a = __builtin_nan(\"\");\n",
1955 "double b = __builtin_nan(\"0x1\");\n",
1956 "double c = __builtin_nan(\"010\");\n",
1958 "double d = __builtin_nans(\"\");\n",
1959 "double e = __builtin_nans(\"0x1\");\n",
1960 "float f = __builtin_nanf(\"0x1\");\n",
1961 "float g = __builtin_nansf(\"\");\n",
1962 "long double h = __builtin_nansl(\"\");\n",
1963 ));
1964 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1965 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1966 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1967 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1968 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1969 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1970 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1971 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1972
1973 let text = ir(concat!(
1976 "double f(const char *p) { return __builtin_nan(p); }\n",
1977 "double g(void) { return __builtin_nans(\"1x\"); }\n",
1978 ));
1979 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1980 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1981 }
1982
1983 #[test]
1991 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
1992 let text = ir(concat!(
1993 "unsigned long a = __builtin_strlen(\"hello\");\n",
1994 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
1995 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
1996 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
1997 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
1998 ));
1999 assert!(text.contains("global @a : i64 = 5,"), "{text}");
2000 assert!(text.contains("global @b : i64 = 1,"), "{text}");
2001 assert!(text.contains("global @c : i32 = 1,"), "{text}");
2002 assert!(text.contains("global @d : i32 = 0,"), "{text}");
2003 assert!(text.contains("global @e : i32 = 1,"), "{text}");
2004 assert!(!text.contains("call"), "{text}");
2005
2006 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
2008 assert!(text.contains("call @strlen("), "{text}");
2009 }
2010
2011 #[test]
2018 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
2019 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
2020 assert!(text.contains("bitcast.i64 %0"), "{text}");
2021 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
2022 assert!(text.contains("and %1, %2"), "{text}");
2023 assert!(text.contains("bitcast.f64 %3"), "{text}");
2024 assert!(!text.contains("call"), "{text}");
2025
2026 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
2027 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
2028 assert!(text.contains("%8 = or %4, %7"), "{text}");
2029 assert!(!text.contains("call"), "{text}");
2030
2031 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
2034 assert!(text.contains("bitcast.i80 %0"), "{text}");
2035 assert!(text.contains("bitcast.f80"), "{text}");
2036
2037 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
2040 assert!(text.contains("fpext.f64 %0"), "{text}");
2041 assert!(text.contains("bitcast.i64 %1"), "{text}");
2042 }
2043
2044 #[test]
2053 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
2054 let text = ir(concat!(
2055 "double a = __builtin_fabs(-3.5);\n",
2056 "double b = __builtin_copysign(1.0, -0.0);\n",
2057 "double c = __builtin_copysign(0.0, -2.0);\n",
2058 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
2060 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
2061 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
2062 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
2063 "long double i = __builtin_fabsl(-__builtin_infl());\n",
2064 ));
2065 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
2066 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
2067 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
2068 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
2069 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
2070 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
2071 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
2072 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
2073 }
2074
2075 #[test]
2082 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
2083 let text = ir(concat!(
2084 "constexpr int side = 4;\n",
2085 "constexpr int wider = side + 1;\n",
2086 "constexpr double half = 1.5;\n",
2087 "struct point { int x; int y; };\n",
2088 "constexpr struct point origin = { 5, 6 };\n",
2089 "int square[side * side];\n",
2090 "int rectangle[wider];\n",
2091 "int rounded[(int)half * 2];\n",
2092 "int across[origin.y];\n",
2093 "enum named { four = side };\n",
2094 "int e = four;\n",
2095 ));
2096 assert!(text.contains("global @square : bytes 64 ="), "{text}");
2097 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
2098 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
2099 assert!(text.contains("global @across : bytes 24 ="), "{text}");
2100 assert!(text.contains("global @e : i32 = 4,"), "{text}");
2101
2102 let mut opts = options();
2105 opts.emit = EmitKind::Ir;
2106 let konst = "const int n = 1;\nint a[n];\n";
2107 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
2108 assert_eq!(run(&opts, konst).messages, [message]);
2109
2110 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
2112 assert_eq!(run(&opts, subscript).messages, [message]);
2113
2114 let address = "constexpr int c = 3;\nint *p = &c;\n";
2116 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
2117 pointer target type [E0514]";
2118 assert_eq!(run(&opts, address).messages, [warning]);
2119 }
2120
2121 #[test]
2130 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
2131 let mut opts = options();
2134 opts.std = Std::C17;
2135 let source = concat!(
2136 "int add(a, b)\n",
2137 "int a;\n",
2138 "int b;\n",
2139 "{ return a + b; }\n",
2140 "int promoted(c)\n",
2141 "char c;\n",
2142 "{ return c; }\n",
2143 "int narrow(char);\n",
2144 "int narrow(c)\n",
2145 "char c;\n",
2146 "{ return c; }\n",
2147 "int first(a)\n",
2148 "int a[4];\n",
2149 "{ return a[0]; }\n",
2150 );
2151 let result = run(&opts, source);
2152 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2153 let text = result.text();
2154 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
2155 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
2156 assert!(text.contains("c : char object automatic defined"), "{text}");
2158 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
2159 assert!(text.contains("first : int(int *) function external defined"), "{text}");
2161 }
2162
2163 #[test]
2170 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
2171 let mut opts = options();
2172 opts.std = Std::C17;
2173 for (source, message) in [
2174 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
2175 (
2176 "int f(a)\nint a;\nint b;\n{ return a; }\n",
2177 "3:5: error: declaration for parameter 'b' but no such parameter",
2178 ),
2179 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
2180 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
2181 (
2182 "int f(a)\nstatic int a;\n{ return a; }\n",
2183 "2:12: error: storage class specified for parameter 'a'",
2184 ),
2185 (
2186 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
2187 "2:7: error: argument 'a' doesn't match prototype",
2188 ),
2189 ] {
2190 let result = run(&opts, source);
2191 assert!(result.failed(), "expected this to fail:\n{source}");
2192 assert!(result.messages[0].contains(message), "{:?}", result.messages);
2193 }
2194
2195 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
2198 let mut older = options();
2199 older.std = Std::C89;
2200 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
2201 let result = run(&opts, implicit);
2202 assert!(
2203 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
2204 "{:?}",
2205 result.messages
2206 );
2207
2208 let mut newer = options();
2212 newer.std = Std::C23;
2213 let plain = "int f(a)\nint a;\n{ return a; }\n";
2214 let result = run(&newer, plain);
2215 assert!(!result.failed(), "{:?}", result.messages);
2216 assert_eq!(
2217 result.messages,
2218 ["/main.c:1:5: warning: old-style function definition [E0412]"]
2219 );
2220 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
2221 }
2222
2223 #[test]
2230 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
2231 let text = ir(concat!(
2232 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
2233 "struct brim { char buf[9223372036854775807L]; };\n",
2234 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
2235 "unsigned long h = sizeof(struct huge_struct);\n",
2236 "unsigned long b = sizeof(struct brim);\n",
2237 "unsigned long y = sizeof(struct bitty);\n",
2238 ));
2239 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
2240 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
2241 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
2242
2243 let mut opts = options();
2244 opts.emit = EmitKind::Ir;
2245 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
2246 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
2247 assert_eq!(run(&opts, over).messages, [message]);
2248 let array = "struct wide { short buf[1L << 62]; };\n";
2249 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
2250 maximum object size '9223372036854775807' [E0537]";
2251 assert_eq!(run(&opts, array).messages[0], message);
2252 }
2253
2254 fn compile_bytes(source: &[u8]) -> Compiled {
2259 let mut opts = options();
2260 opts.emit = EmitKind::Ir;
2261 let mut fs = MemoryFileSystem::new();
2262 fs.insert("/main.c", source.to_vec());
2263 compile(&opts, "/main.c", &fs)
2264 }
2265
2266 #[test]
2273 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
2274 let mut source = b"char s[] = \"a".to_vec();
2275 source.push(0xff);
2276 source.extend_from_slice(b"b\";\nchar c = '");
2277 source.push(0xff);
2278 source.extend_from_slice(b"';\n");
2279 let result = compile_bytes(&source);
2280 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
2281 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
2282 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
2284
2285 let mut stray = b"int a".to_vec();
2286 stray.push(0xff);
2287 stray.extend_from_slice(b" = 1;\n");
2288 let result = compile_bytes(&stray);
2289 assert!(
2290 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
2291 "{:?}",
2292 result.messages
2293 );
2294 }
2295
2296 #[test]
2297 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
2298 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
2299 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
2300 let expected = "\
2301func @add(i32, i32) -> i32, linkage(external) {
2302block0(%0: i32, %1: i32):
2303 %2 = add.nsw %0, %1
2304 return %2
2305}
2306";
2307 assert!(text.contains(expected), "{text}");
2308 }
2309
2310 #[test]
2311 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
2312 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
2313 assert!(!text.contains("alloca"), "{text}");
2314 assert!(!text.contains("load"), "{text}");
2315 assert!(!text.contains("store"), "{text}");
2316 }
2317
2318 #[test]
2319 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
2320 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
2321 let expected = "\
2322block0:
2323 %0 = alloca, size 4, align 4
2324 %1 = iconst.i32 1
2325 store %1 -> %0, align 4
2326 %2 = call @g(%0) : (ptr) -> i32
2327 return %2
2328";
2329 assert_eq!(text, expected);
2330 }
2331
2332 #[test]
2333 fn a_loop_carries_what_it_changes_as_block_parameters() {
2334 let text = body(
2337 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
2338 return total;\n}\n",
2339 );
2340 assert!(!text.contains("alloca"), "{text}");
2341 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
2342 assert!(text.contains("jump block1("), "{text}");
2343 }
2344
2345 #[test]
2346 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
2347 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
2348 assert!(text.contains("icmp slt %0, %1"), "{text}");
2349 assert!(!text.contains("zext"), "{text}");
2350 }
2351
2352 #[test]
2353 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
2354 let text = body("int f(int a, int b) { return a && b; }\n");
2355 let expected = "\
2356block0(%0: i32, %1: i32):
2357 %2 = iconst.i32 0
2358 %3 = icmp ne %0, %2
2359 %4 = iconst.i1 0
2360 br_if %3, block1, block2(%4)
2361
2362block1:
2363 %5 = iconst.i32 0
2364 %6 = icmp ne %1, %5
2365 jump block2(%6)
2366
2367block2(%7: i1):
2368 %8 = zext.i32 %7
2369 return %8
2370";
2371 assert_eq!(text, expected);
2372 }
2373
2374 #[test]
2375 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
2376 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
2377 assert!(!text.contains("block3"), "{text}");
2380 assert!(!text.contains("iconst.i32 3"), "{text}");
2381 }
2382
2383 #[test]
2384 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
2385 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
2386 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
2387 assert!(body("int f(void) { }\n").contains("unreachable"));
2388 }
2389
2390 #[test]
2391 fn a_structure_is_copied_rather_than_held_in_a_value() {
2392 let text = body(
2393 "struct point { int x, y; };\n\
2394 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
2395 );
2396 assert!(text.contains("memcpy"), "{text}");
2397 }
2398
2399 #[test]
2400 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
2401 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
2402 assert!(text.contains("memset"), "{text}");
2403 }
2404
2405 #[test]
2406 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
2407 let text = body(
2408 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
2409 default: r = 4; } return r; }\n",
2410 );
2411 let expected = "\
2412block0(%0: i32):
2413 %1 = iconst.i32 0
2414 switch %0, block1, [1 => block2, 2 => block3(%1)]
2415
2416block1:
2417 %2 = iconst.i32 4
2418 jump block4(%2)
2419
2420block2:
2421 %3 = iconst.i32 1
2422 jump block3(%3)
2423
2424block3(%4: i32):
2425 %5 = iconst.i32 2
2426 %6 = add.nsw %4, %5
2427 jump block4(%6)
2428
2429block4(%7: i32):
2430 return %7
2431";
2432 assert_eq!(text, expected);
2433 }
2434
2435 #[test]
2436 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
2437 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
2440 assert!(text.contains("%2 = sub %0, %1"), "{text}");
2441 assert!(text.contains("icmp ule"), "{text}");
2442 assert!(!text.contains("switch"), "{text}");
2443 }
2444
2445 #[test]
2446 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
2447 let text = body(
2448 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
2449 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
2450 );
2451 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
2454 assert!(text.contains("block5:\n jump block7("), "{text}");
2455 assert!(text.contains("block6:\n jump block8("), "{text}");
2456 }
2457
2458 #[test]
2459 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
2460 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
2461 }
2462
2463 #[test]
2464 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
2465 let text = body(
2470 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
2471 return n; }\n",
2472 );
2473 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
2476 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
2477 assert!(text.contains("block5:\n jump block3("), "{text}");
2478 }
2479
2480 #[test]
2481 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
2482 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
2485 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
2486 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
2487 assert!(text.contains("br_if %7, block3, block4"), "{text}");
2488 }
2489
2490 #[test]
2491 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
2492 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
2493 assert!(!text.contains("alloca"), "{text}");
2495 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
2496 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
2497 }
2498
2499 #[test]
2500 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
2501 let text =
2502 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
2503 assert!(!text.contains("alloca"), "{text}");
2504 assert!(text.contains("block1(%2: i32):"), "{text}");
2505 assert!(text.contains("jump block1(%5)"), "{text}");
2506 }
2507
2508 #[test]
2509 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
2510 assert_eq!(
2513 body("int f(int x) { return x; spare: return 0; }\n"),
2514 "block0(%0: i32):\n return %0\n"
2515 );
2516 }
2517
2518 #[test]
2519 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
2520 let text = body(
2521 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
2522 );
2523 assert_eq!(
2526 text,
2527 "\
2528block0(%0: ptr):
2529 %1 = load.i8 %0, align 1
2530 %2 = iconst.i8 3
2531 %3 = ashr %1, %2
2532 %4 = sext.i32 %3
2533 return %4
2534"
2535 );
2536 }
2537
2538 #[test]
2539 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
2540 let text =
2544 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
2545 assert_eq!(
2546 text,
2547 "\
2548block0(%0: ptr, %1: i32):
2549 %2 = iconst.i32 16777215
2550 %3 = and %1, %2
2551 %4 = trunc.i16 %3
2552 store %4 -> %0, align 2
2553 %5 = iconst.i32 16
2554 %6 = lshr %3, %5
2555 %7 = trunc.i8 %6
2556 %8 = iconst.i64 2
2557 %9 = ptr_add %0, %8
2558 store %7 -> %9, align 1
2559 return
2560"
2561 );
2562 }
2563
2564 #[test]
2565 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2566 let text =
2567 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2568 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
2571 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
2572 }
2573
2574 #[test]
2575 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2576 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2579 assert_eq!(text.matches("ashr").count(), 0, "{text}");
2580 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
2581 }
2582
2583 #[test]
2584 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2585 let text = body(
2589 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2590 );
2591 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2592 }
2593
2594 #[test]
2595 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2596 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2599 assert!(
2600 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2601 "{text}"
2602 );
2603 }
2604
2605 #[test]
2606 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2607 let text = ir(concat!(
2612 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2613 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2614 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2615 "char s[2] = \"hi\";\n",
2616 ));
2617 assert!(
2618 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2619 "{text}"
2620 );
2621 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2622 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2623 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2626 }
2627
2628 #[test]
2629 fn a_definition_takes_a_parameter_it_left_unnamed() {
2630 let text = ir("int f(int a, int) { return a; }\n");
2634 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2635 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2636
2637 let text = ir("int g(int, int n) { return n; }\n");
2640 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
2641 }
2642
2643 #[test]
2644 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2645 let text = body(concat!(
2650 "struct s { int f; int g; };\n",
2651 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2652 "{ *d = *e = a[0] = *c; }\n",
2653 ));
2654 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2655 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2656 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2657 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2658 }
2659
2660 #[test]
2661 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2662 let mut opts = options();
2667 opts.emit = EmitKind::Ir;
2668 let result = run(
2669 &opts,
2670 concat!(
2671 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2672 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2673 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2674 "const union u c = { { \"1234\", \"567\" } };\n",
2675 ),
2676 );
2677 let text = result.text();
2678 assert_eq!(
2679 result.messages,
2680 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2681 (5 chars into 3 available) [E0637]"]
2682 );
2683 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2684 assert!(
2685 text.contains(
2686 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2687 bytes \"9\\00\", zero 3 }"
2688 ),
2689 "{text}"
2690 );
2691 assert!(
2694 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2695 "{text}"
2696 );
2697 }
2698
2699 #[test]
2700 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2701 let text = body(concat!(
2705 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2706 "void g(struct v *);\n",
2707 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2708 ));
2709 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2710 }
2711
2712 #[test]
2713 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2714 let text = ir(concat!(
2719 "struct s { int x; };\n",
2720 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2721 "int n = (int){ 7 };\n",
2722 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2723 ));
2724 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2725 assert!(text.contains("global @n : i32 = 7,"), "{text}");
2726 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2729 }
2730
2731 #[test]
2732 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2733 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2737 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2738 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2739 }
2740
2741 #[test]
2742 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2743 let text = ir("unsigned char foo[1][0];\n");
2747 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2748 }
2749
2750 #[test]
2751 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2752 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2755 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2756 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2757 }
2758
2759 #[test]
2760 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2761 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2765 assert!(
2766 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2767 "{text}"
2768 );
2769 }
2770
2771 #[test]
2772 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2773 let text = body(
2778 "\
2779struct s { int a, b; };
2780struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2781",
2782 );
2783 assert!(text.contains("block3(%7: ptr)"), "{text}");
2785 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2786 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2787 }
2788
2789 #[test]
2790 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2791 let text = ir("\
2795struct pair { int a, b; };
2796struct pair make(int a, int b);
2797struct pair twice(struct pair p) { return make(p.a, p.b); }
2798");
2799 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2800 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2801 }
2802
2803 #[test]
2804 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2805 let text = ir("\
2809struct big { double v[8]; };
2810struct big grow(struct big b);
2811struct big twice(struct big b) { return grow(grow(b)); }
2812");
2813 assert!(
2814 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2815 "{text}"
2816 );
2817 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2818 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2821 }
2822
2823 #[test]
2824 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2825 let text = ir("\
2830struct big { double v[8]; };
2831struct pair { int a, b; };
2832int p(const char *, ...);
2833int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2834");
2835 assert!(
2836 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2837 "{text}"
2838 );
2839 }
2840
2841 #[test]
2842 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2843 let body = body(
2846 "\
2847struct pair { int a, b; };
2848struct pair make(int a, int b);
2849int second(void) { return make(1, 2).b; }
2850",
2851 );
2852 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
2853 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2854 }
2855
2856 #[test]
2857 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2858 let source = "\
2862struct hfa { float x, y, z; };
2863int take(struct hfa h);
2864int give(struct hfa h) { return take(h); }
2865";
2866 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2867 let mut opts = options();
2868 opts.emit = EmitKind::Ir;
2869 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2870 let result = run(&opts, source);
2871 assert_eq!(result.messages, Vec::<String>::new());
2872 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
2873 }
2874
2875 #[test]
2876 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
2877 let source = "\
2880int use(int *);
2881void f(int n) {
2882 {
2883 int a[n];
2884 use(a);
2885 }
2886 use(0);
2887}
2888";
2889 let body = body(source);
2890 assert!(body.contains("mul.nsw"), "{body}");
2891 assert!(body.contains("stacksave"), "{body}");
2892 assert!(body.contains("alloca %"), "{body}");
2893 assert!(body.contains("stackrestore"), "{body}");
2894 }
2895
2896 #[test]
2897 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
2898 let source = "\
2903int use(int *);
2904int f(int n) {
2905 {
2906 int a[n];
2907 if (use(a)) goto out;
2908 use(0);
2909 }
2910out:
2911 return 0;
2912}
2913";
2914 let body = body(source);
2915 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
2917 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2918 assert!(after.starts_with(" %4\n jump block"), "{body}");
2919 }
2920
2921 #[test]
2922 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
2923 let source = "\
2927int use(int *);
2928int f(int n) {
2929 int a[n];
2930again:
2931 if (use(a)) goto again;
2932 return 0;
2933}
2934";
2935 let body = body(source);
2936 assert!(body.contains("stacksave"), "{body}");
2937 assert!(!body.contains("stackrestore"), "{body}");
2938 }
2939
2940 #[test]
2941 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2942 let source = "\
2947int use(int *);
2948int f(int n) {
2949again:
2950 {
2951 int a[n];
2952 if (use(a)) goto again;
2953 }
2954 return 0;
2955}
2956";
2957 let body = body(source);
2958 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2959 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2960 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
2961 }
2962
2963 #[test]
2964 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2965 let source = "\
2971int f(void);
2972void t(void) {
2973 int count = 10;
2974 for (; count--;) {
2975 int b[f()];
2976 int i;
2977 for (i = 0; i < f(); i++) {
2978 b[i] = count;
2979 }
2980 }
2981}
2982";
2983 let body = body(source);
2984 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2988 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2989 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
2990 assert!(next.contains("jump block1("), "{body}");
2991 }
2992
2993 #[test]
2994 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
2995 let source = "\
2998unsigned long f(int n) {
2999 int a[n];
3000 n = 0;
3001 return sizeof a;
3002}
3003";
3004 let body = body(source);
3005 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
3007 }
3008
3009 #[test]
3010 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
3011 let source = "\
3014int use(int);
3015int f(int x) {
3016 return ({
3017 int t = use(x);
3018 t * t;
3019 });
3020}
3021";
3022 let expected = "\
3023block0(%0: i32):
3024 %1 = call @use(%0) : (i32) -> i32
3025 %2 = mul.nsw %1, %1
3026 return %2
3027";
3028 assert_eq!(body(source), expected);
3029 }
3030
3031 #[test]
3032 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
3033 let source = "int f(int x) { return ({ return x; 0; }); }\n";
3037 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
3038 }
3039
3040 #[test]
3041 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
3042 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
3046 let expected = "\
3047block0(%0: ptr):
3048 %1 = va_arg.f64 %0
3049 %2 = va_arg.f64 %0
3050 %3 = fadd %1, %2
3051 return %3
3052";
3053 assert_eq!(body(source), expected);
3054 }
3055
3056 #[test]
3057 fn one_that_reads_a_structure_answers_where_the_object_is() {
3058 let source = "\
3067struct s { int a; long b; };
3068long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
3069";
3070 let expected = "\
3071block0(%0: ptr):
3072 %1 = alloca, size 16, align 8
3073 %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
3074 memcpy %1, %2, size 16, align 8
3075 %3 = iconst.i64 8
3076 %4 = ptr_add %1, %3
3077 %5 = load.i64 %4, align 8
3078 return %5
3079";
3080 assert_eq!(body(source), expected);
3081 }
3082
3083 #[test]
3087 fn the_classification_says_which_registers_the_object_arrived_in() {
3088 let source = "\
3089struct s { double a; double b; };
3090double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
3091";
3092 assert!(
3093 body(source)
3094 .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
3095 "{}",
3096 body(source)
3097 );
3098
3099 let big = "\
3100struct s { long a[4]; };
3101long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
3102";
3103 assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
3104 }
3105
3106 #[test]
3107 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
3108 let source = "\
3112int f(int c) {
3113 void *p = c ? &&one : &&two;
3114 goto *p;
3115one:
3116 return 1;
3117two:
3118 return 2;
3119}
3120";
3121 let expected = "\
3122block0(%0: i32):
3123 %1 = iconst.i32 0
3124 %2 = icmp ne %0, %1
3125 br_if %2, block1, block2
3126
3127block1:
3128 %3 = block_addr block3
3129 jump block4(%3)
3130
3131block2:
3132 %4 = block_addr block5
3133 jump block4(%4)
3134
3135block3:
3136 %5 = iconst.i32 1
3137 return %5
3138
3139block4(%6: ptr):
3140 indirect_br %6, block3, block5
3141
3142block5:
3143 %7 = iconst.i32 2
3144 return %7
3145";
3146 assert_eq!(body(source), expected);
3147 }
3148
3149 #[test]
3150 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
3151 let source = "void **next(void);
3154void f(void) { goto *next(); }
3155";
3156 let expected = "\
3157block0:
3158 %0 = call @next() : () -> ptr
3159 unreachable
3160";
3161 assert_eq!(body(source), expected);
3162 }
3163
3164 #[test]
3165 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
3166 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
3169 let expected = "\
3170block0:
3171 inline_asm.volatile \"mfence\", \"\", \"memory\"()
3172 return
3173";
3174 assert_eq!(body(source), expected);
3175 }
3176
3177 #[test]
3178 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
3179 let source = "\
3182int f(int x, int y) {
3183 int r;
3184 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
3185 return r + y;
3186}
3187";
3188 let expected = "\
3189block0(%0: i32, %1: i32):
3190 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
3191 %4 = add.nsw %2, %3
3192 return %4
3193";
3194 assert_eq!(body(source), expected);
3195 }
3196
3197 #[test]
3198 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
3199 let source = "\
3204struct pair { int a, b; };
3205int f(int x) {
3206 int slot = x;
3207 struct pair p = { x, x };
3208 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
3209 return slot + p.a;
3210}
3211";
3212 let text = body(source);
3213 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
3214 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
3215 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
3216 }
3217
3218 #[test]
3219 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
3220 let source = "\
3225int f(int x) {
3226 int r = 7;
3227 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
3228 return r;
3229away:
3230 return r;
3231}
3232";
3233 let expected = "\
3234block0(%0: i32):
3235 %1 = iconst.i32 7
3236 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
3237
3238block1:
3239 return %2
3240
3241block2:
3242 return %1
3243";
3244 assert_eq!(body(source), expected);
3245 }
3246
3247 #[test]
3248 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
3249 let mut opts = options();
3253 opts.emit = EmitKind::Ir;
3254 for (source, expected) in [
3255 (
3256 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
3257 "output operand constraint lacks '='",
3258 ),
3259 (
3260 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
3261 "lvalue required in 'asm' statement",
3262 ),
3263 (
3264 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
3265 "read-only variable 'g' used as 'asm' output",
3266 ),
3267 (
3268 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
3269 "input operand constraint contains '='",
3270 ),
3271 (
3272 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
3273 "memory input 0 is not directly addressable",
3274 ),
3275 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
3276 (
3277 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
3278 "duplicate asm operand name 'a'",
3279 ),
3280 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
3281 ] {
3282 let result = run(&opts, source);
3283 assert!(result.failed(), "expected this to be reported:\n{source}");
3284 assert!(
3285 result.messages.iter().any(|m| m.contains(expected)),
3286 "{expected}\n{:?}",
3287 result.messages
3288 );
3289 }
3290 }
3291
3292 #[test]
3293 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
3294 let mut opts = options();
3295 opts.emit = EmitKind::Ir;
3296 for source in [
3297 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
3298 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
3299 ] {
3300 let result = run(&opts, source);
3301 assert!(result.failed(), "expected this to be reported:\n{source}");
3302 assert!(
3303 result.messages.iter().any(|m| m.contains("not supported yet")),
3304 "{:?}",
3305 result.messages
3306 );
3307 }
3308 }
3309
3310 fn round_trip(source: &str) -> (String, String) {
3312 let printed = ir(source);
3313 let mut opts = options();
3314 opts.emit = EmitKind::Ir;
3315 let mut fs = MemoryFileSystem::new();
3316 fs.insert("/main.ir", printed.clone().into_bytes());
3317 let result = compile_ir(&opts, "/main.ir", &fs);
3318 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
3319 (printed, result.text().to_owned())
3320 }
3321
3322 #[test]
3323 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
3324 let (printed, again) = round_trip(
3328 "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",
3329 );
3330 assert_eq!(printed, again);
3331 }
3332
3333 #[test]
3334 fn ir_that_is_not_ir_says_which_line_stopped_it() {
3335 let mut opts = options();
3336 opts.emit = EmitKind::Ir;
3337 let mut fs = MemoryFileSystem::new();
3338 let text = "\
3339; ModuleID = 'a.c'
3340; format 0
3341target triple = \"x86_64-unknown-linux-gnu\"
3342target datalayout = \"e-p:64:64-i64:64-S128\"
3343
3344func @f(), linkage(external) {
3345block0:
3346 frobnicate
3347}
3348";
3349 fs.insert("/main.ir", text.as_bytes().to_vec());
3350 let result = compile_ir(&opts, "/main.ir", &fs);
3351 assert!(result.failed());
3352 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
3353 }
3354
3355 #[test]
3356 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
3357 let mut opts = options();
3360 opts.emit = EmitKind::Ir;
3361 let mut fs = MemoryFileSystem::new();
3362 let text = "\
3363; ModuleID = 'a.c'
3364; format 0
3365target triple = \"x86_64-unknown-linux-gnu\"
3366target datalayout = \"e-p:64:64-i64:64-S128\"
3367
3368func @f(), linkage(external) {
3369block0:
3370 %0 = iconst.i32 1
3371 return %0
3372}
3373";
3374 fs.insert("/main.ir", text.as_bytes().to_vec());
3375 let result = compile_ir(&opts, "/main.ir", &fs);
3376 assert!(result.failed());
3377 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
3378 }
3379
3380 #[test]
3381 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
3382 let mut fs = MemoryFileSystem::new();
3384 fs.insert("/main.ir", Vec::new());
3385 let result = compile_ir(&options(), "/main.ir", &fs);
3386 assert!(result.failed());
3387 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
3388 }
3389
3390 #[test]
3391 fn the_printed_ir_reads_back_as_the_same_module() {
3392 let text = ir("\
3395struct point { int x, y; };
3396static const char greeting[] = \"hi\";
3397int table[4] = { 1, 2, 3 };
3398int puts(const char *);
3399double half(double x) { return x / 2.0; }
3400int f(int n) {
3401 int total = 0;
3402 for (int i = 0; i < n; i++) {
3403 if (i == 3) continue;
3404 total += table[i];
3405 }
3406 switch (n) {
3407 case 0: total = 1;
3408 case 1: total++; break;
3409 default: total = -total;
3410 }
3411 struct point p = { total, 1 };
3412 int *q = &p.y;
3413 puts(greeting);
3414 return p.x + *q;
3415}
3416int dispatch(int c) {
3417 void *p = c ? &&one : &&two;
3418 goto *p;
3419one:
3420 return 1;
3421two:
3422 return 2;
3423}
3424int assembly(int x, int *p) {
3425 int r;
3426 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
3427 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
3428 return r;
3429away:
3430 return 0;
3431}
3432");
3433 let mut names = Interner::new();
3434 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
3435 assert_eq!(rucc_ir::print(&module, &names), text);
3436 }
3437}