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)]
27pub struct Compiled {
28 pub text: String,
30 pub messages: Vec<String>,
32 pub errors: u32,
34}
35
36impl Compiled {
37 #[must_use]
39 pub fn failed(&self) -> bool {
40 self.errors > 0
41 }
42}
43
44#[must_use]
57pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
58 let mut sess = Session::new(opts.clone());
59 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
63 let mut diagnostics: Vec<Diagnostic> = Vec::new();
64
65 let bytes = match fs.read(Path::new(name)) {
66 Ok(bytes) => bytes,
67 Err(e) => return failure(format!("{name}: {e}")),
68 };
69 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
70 return failure(format!("{name}: the source map has no room left for this file"));
71 };
72
73 let mut pp = rucc_pp::Preprocessor::new();
77 let predef = rucc_pp::Predef::for_options(opts);
78 let expanded: Vec<PpToken> = {
79 let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
80 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
81 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
82 return failure(format!("{name}: the source map has no room for the built in macros"));
83 }
84 pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
85 };
86 diagnostics.extend(pp.take_diagnostics());
87
88 let cx = Convert {
91 keywords: &keywords,
92 interner: &sess.interner,
93 target: &sess.target,
94 std: opts.std,
95 gnu: opts.gnu_extensions,
96 pedantic: opts.pedantic,
97 };
98 let (tokens, complaints) = convert(&expanded, &cx);
99 diagnostics.extend(complaints);
100
101 let parsed = rucc_parse::parse(
102 &tokens,
103 rucc_parse::Context {
104 interner: &sess.interner,
105 std: opts.std,
106 gnu: opts.gnu_extensions,
107 pedantic: opts.pedantic,
108 error_limit: opts.error_limit as usize,
109 },
110 );
111 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
112 diagnostics.extend(parsed.diagnostics);
113
114 let mut text = String::new();
115 if !parse_failed {
116 let mut checker = Checker::new(
117 &parsed.ast,
118 CheckContext {
119 names: &sess.interner,
120 target: &sess.target,
121 std: opts.std,
122 gnu: opts.gnu_extensions,
123 pedantic: opts.pedantic,
124 error_limit: opts.error_limit as usize,
125 },
126 );
127 checker.check_unit();
128 let checked = checker.finish();
129 if !checked.failed() {
130 match opts.emit {
131 EmitKind::Tast => {
132 text = rucc_sema::print(&checked.tast, &checked.types, &sess.interner);
133 }
134 EmitKind::Ir | EmitKind::MirFinal | EmitKind::Asm => {
135 let lowered = rucc_lower::lower(
136 name,
137 rucc_lower::Context {
138 tast: &checked.tast,
139 types: &checked.types,
140 target: &sess.target,
141 names: &mut sess.interner,
142 },
143 );
144 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
148 if !failed {
149 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
154 for error in errors {
155 diagnostics.push(internal(&format!("invalid IR, {error}")));
156 }
157 } else if opts.emit == EmitKind::Ir {
158 text = rucc_ir::print(&lowered.module, &sess.interner);
159 } else {
160 match generate(&lowered.module, &mut sess.interner, &sess.target, opts)
163 {
164 Ok(printed) => text = printed,
165 Err(complaints) => diagnostics.extend(complaints),
166 }
167 }
168 }
169 diagnostics.extend(lowered.diagnostics);
170 }
171 _ => {}
172 }
173 }
174 diagnostics.extend(checked.diagnostics);
175 }
176
177 let mut messages = Vec::with_capacity(diagnostics.len());
178 let mut errors = 0;
179 for diag in &diagnostics {
180 if diag.severity.is_fatal()
181 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
182 {
183 errors += 1;
184 }
185 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
186 }
187 if errors > 0 {
188 text.clear();
190 }
191 Compiled { text, messages, errors }
192}
193
194#[must_use]
204pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
205 let mut sess = Session::new(opts.clone());
206 if opts.emit != EmitKind::Ir {
207 return failure(format!(
208 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
209 the C in front of it became",
210 opts.emit.as_str()
211 ));
212 }
213 let bytes = match fs.read(Path::new(name)) {
214 Ok(bytes) => bytes,
215 Err(e) => return failure(format!("{name}: {e}")),
216 };
217 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
218 return failure(format!("{name}: this is not text, so it is not IR"));
219 };
220
221 let module = match rucc_ir::parse(text, &mut sess.interner) {
222 Ok(module) => module,
223 Err(error) => {
224 return failure(format!("{name}:{}: {}", error.line, error.message));
225 }
226 };
227 let mut diagnostics: Vec<Diagnostic> = Vec::new();
228 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
229 for error in errors {
230 diagnostics.push(invalid(&format!("invalid IR, {error}")));
231 }
232 }
233 let mut messages = Vec::with_capacity(diagnostics.len());
234 for diag in &diagnostics {
235 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
236 }
237 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
238 let text = if errors > 0 { String::new() } else { rucc_ir::print(&module, &sess.interner) };
239 Compiled { text, messages, errors }
240}
241
242fn generate(
254 module: &rucc_ir::Module,
255 names: &mut Interner,
256 target: &TargetInfo,
257 opts: &Options,
258) -> Result<String, Vec<Diagnostic>> {
259 let Some(machine) = Machine::for_target(target) else {
260 return Err(vec![unsupported(&format!(
261 "there is no back end for {} in this compiler yet, so there is nothing to generate",
262 target.triple
263 ))]);
264 };
265 let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
266
267 let mut funcs = Vec::new();
268 let mut complaints = Vec::new();
269 for id in module.funcs() {
270 if module[id].is_declaration() {
271 continue;
272 }
273 match pipeline::compile(&module[id], names, &machine, flags) {
274 Ok(func) => funcs.push(func),
275 Err(why) => {
276 let name = names.resolve(module[id].name).to_owned();
277 complaints.push(unsupported(&format!("cannot generate code for '{name}': {why}")));
278 }
279 }
280 }
281 if !complaints.is_empty() {
282 return Err(complaints);
283 }
284 if opts.emit == EmitKind::Asm {
285 rucc_asm::print(&funcs, names, target).map_err(|why| vec![internal(&why.to_string())])
289 } else {
290 Ok(rucc_mir::print(&funcs, names, target.regs))
291 }
292}
293
294fn unsupported(message: &str) -> Diagnostic {
300 Diagnostic::error(message.to_owned(), Span::DUMMY)
301 .with_code("E0653")
302 .note("this construct is not lowered yet, see spec/17-milestones.md", Span::DUMMY)
303}
304
305fn invalid(message: &str) -> Diagnostic {
307 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
308}
309
310fn internal(message: &str) -> Diagnostic {
312 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
313 .with_code("E0652")
314 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
315}
316
317fn failure(message: String) -> Compiled {
320 Compiled { text: String::new(), messages: vec![format!("rucc: error: {message}")], errors: 1 }
321}
322
323#[cfg(test)]
324mod tests {
325 use rucc_session::{MemoryFileSystem, Std};
326 use rucc_target::Triple;
327
328 use super::*;
329
330 fn options() -> Options {
331 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
332 opts.emit = EmitKind::Tast;
333 opts
334 }
335
336 fn run(opts: &Options, source: &str) -> Compiled {
337 let mut fs = MemoryFileSystem::new();
338 fs.insert("/main.c", source.to_owned().into_bytes());
339 compile(opts, "/main.c", &fs)
340 }
341
342 fn freestanding() -> Options {
346 let mut opts = options();
347 opts.hosted = false;
348 opts.search.push_system(rucc_session::runtime::DIR);
349 opts
350 }
351
352 fn shipped(source: &str) -> String {
354 let result = run(&freestanding(), source);
355 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
356 result.text
357 }
358
359 fn tast(source: &str) -> String {
361 let result = run(&options(), source);
362 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
363 result.text
364 }
365
366 #[test]
367 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
368 let text = shipped(concat!(
369 "#include <stdarg.h>\n",
370 "int sum(int n, ...) {\n",
371 " va_list ap, copy;\n",
372 " va_start(ap, n);\n",
373 " va_copy(copy, ap);\n",
374 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
375 " va_end(ap);\n",
376 " va_end(copy);\n",
377 " return total;\n",
378 "}\n",
379 ));
380 assert!(text.contains("va-start"), "{text}");
381 assert!(text.contains("va-copy"), "{text}");
382 assert!(text.contains("va-arg"), "{text}");
383 assert!(text.contains("va-end"), "{text}");
384 }
385
386 #[test]
390 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
391 let text = shipped(concat!(
392 "#define __need___va_list\n",
393 "#include <stdarg.h>\n",
394 "int vprint(const char *f, __gnuc_va_list ap);\n",
395 "#ifdef va_start\n",
396 "#error va_start should not be defined\n",
397 "#endif\n",
398 "#ifdef _VA_LIST_DEFINED\n",
399 "#error va_list should not have been made\n",
400 "#endif\n",
401 ));
402 assert!(text.contains("vprint"), "{text}");
403 }
404
405 #[test]
408 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
409 let text = shipped(concat!(
410 "#define __need_size_t\n",
411 "#include <stddef.h>\n",
412 "#ifdef offsetof\n",
413 "#error offsetof should not be defined yet\n",
414 "#endif\n",
415 "#define __need_ptrdiff_t\n",
416 "#include <stddef.h>\n",
417 "#include <stddef.h>\n",
418 "size_t a;\n",
419 "ptrdiff_t b;\n",
420 "wchar_t c;\n",
421 "max_align_t d;\n",
422 "void *e = NULL;\n",
423 "struct P { int x; long y; };\n",
424 "size_t f = offsetof(struct P, y);\n",
425 ));
426 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
427 assert!(text.contains("decl #1 b : long"), "{text}");
428 }
429
430 #[test]
431 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
432 let text = shipped(concat!(
433 "#include <limits.h>\n",
434 "#include <float.h>\n",
435 "int bits = CHAR_BIT;\n",
436 "long big = LONG_MAX;\n",
437 "int low = INT_MIN;\n",
438 "int radix = FLT_RADIX;\n",
439 "int digits = DBL_MANT_DIG;\n",
440 ));
441 assert!(text.contains("const 8 : int"), "{text}");
442 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
443 assert!(text.contains("const 2 : int"), "{text}");
444 assert!(text.contains("const 53 : int"), "{text}");
445 }
446
447 #[test]
451 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
452 let text = shipped(concat!(
453 "#include <stdint.h>\n",
454 "int64_t a = INT64_C(1);\n",
455 "uint_least16_t b;\n",
456 "intptr_t c;\n",
457 "uintmax_t d = UINTMAX_MAX;\n",
458 "int wide = sizeof(int_fast64_t);\n",
459 ));
460 assert!(text.contains("decl #0 a : long"), "{text}");
461 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
462 assert!(text.contains("decl #2 c : long"), "{text}");
463 }
464
465 #[test]
466 fn the_three_formality_headers_still_have_to_work() {
467 let text = shipped(concat!(
468 "#include <stdbool.h>\n",
469 "#include <stdalign.h>\n",
470 "#include <iso646.h>\n",
471 "#include <stdnoreturn.h>\n",
472 "int t = true and not false;\n",
473 "_Alignas(16) char buf[16];\n",
474 "int a = alignof(long);\n",
475 ));
476 assert!(text.contains("decl #0 t : int"), "{text}");
477 assert!(text.contains("const 8 : unsigned long"), "{text}");
478 }
479
480 #[test]
483 fn every_shipped_header_can_be_included_twice() {
484 let mut source = String::new();
485 for _ in 0..2 {
486 for name in rucc_session::runtime::names() {
487 source.push_str(&format!("#include <{name}>\n"));
488 }
489 }
490 source.push_str("int x;\n");
491 let text = shipped(&source);
492 assert!(text.starts_with("decl #0 x : int"), "{text}");
493 }
494
495 #[test]
496 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
497 let fs = MemoryFileSystem::new();
498 let result = compile(&options(), "/nope.c", &fs);
499 assert!(result.failed());
500 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
501 assert!(result.text.is_empty());
502 }
503
504 #[test]
505 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
506 let text = tast("int x = 1;\n");
507 let expected = "\
508decl #0 x : int object external static defined
509 init
510 +0
511 const 1 : int
512";
513 assert_eq!(text, expected);
514 }
515
516 #[test]
517 fn the_macros_are_expanded_before_anything_is_parsed() {
518 let text = tast("#define N 2\nint a[N];\n");
522 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
523 }
524
525 #[test]
531 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
532 let text = tast(concat!(
533 "#pragma pack(4)\n",
534 "struct s { int a; };\n",
535 "#pragma pack()\n",
536 "int b;\n",
537 "_Pragma(\"GCC visibility push(default)\") int c;\n",
538 ));
539 assert!(text.contains("decl #0 b : int"), "{text}");
540 assert!(text.contains("decl #1 c : int"), "{text}");
541 }
542
543 #[test]
551 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
552 tast(concat!(
553 "struct A { char c; int i; } __attribute__((packed));\n",
554 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
555 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
556 "struct B { char c; int i; } __attribute__((aligned));\n",
559 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
560 "struct C { char c; int i __attribute__((packed)); };\n",
561 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
562 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
563 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
564 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
565 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
566 "struct E { char c; _Alignas(8) int i; };\n",
567 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
568 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
569 "struct F { char c; int i __attribute__((aligned(8))); };\n",
570 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
571 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
574 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
575 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
576 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
577 "struct I { [[gnu::packed]] char c; int i; };\n",
580 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
581 "struct J { char c; [[gnu::packed]] int i; };\n",
582 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
583 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
584 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
585 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
586 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
587 "union L { char c; int i; } __attribute__((packed));\n",
588 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
589 ));
590 }
591
592 #[test]
602 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
603 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
605 assert_eq!(
606 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
607 1
608 );
609 assert_eq!(
610 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
611 1
612 );
613 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
614 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
616 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
617 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
619 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
620 }
621
622 fn bit_field_byte(record: &str) -> u64 {
624 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
625 let body = body(&source);
626 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
627 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
628 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
629 }
630
631 #[test]
637 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
638 tast(concat!(
639 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
640 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
641 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
642 "struct b { char c; __attribute__((packed)) int i; };\n",
643 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
644 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
645 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
646 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
647 ));
648 }
649
650 #[test]
656 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
657 tast(concat!(
658 "#pragma pack(1)\n",
659 "struct A { char c; int i; };\n",
660 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
661 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
662 "#pragma pack()\n",
663 "struct B { char c; int i; };\n",
664 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
665 "#pragma pack(2)\n",
666 "struct C { char c; int i; double d; };\n",
667 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
668 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
669 "struct K { char c; int i __attribute__((aligned(8))); };\n",
671 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
672 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
673 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
675 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
676 "#pragma pack()\n",
677 "#pragma pack(push, 1)\n",
678 "struct D { char c; short s; };\n",
679 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
680 "#pragma pack(pop)\n",
681 "struct E { char c; short s; };\n",
682 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
683 "struct H { char c;\n",
685 "#pragma pack(1)\n",
686 " int i; };\n",
687 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
688 "#pragma pack(1)\n",
689 "struct I { char c;\n",
690 "#pragma pack()\n",
691 " int i; };\n",
692 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
693 "#pragma pack()\n",
694 "#pragma pack(push, 8)\n",
696 "#pragma pack(push, 1)\n",
697 "struct P { char c; int i; };\n",
698 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
699 "#pragma pack(pop)\n",
700 "struct Q { char c; int i; };\n",
701 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
702 "#pragma pack(pop)\n",
703 "#pragma pack(16)\n",
705 "struct R { char c; int i; };\n",
706 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
707 "#pragma pack()\n",
708 "#pragma pack(1)\n",
709 "struct S { char c; int i : 5; int j : 20; };\n",
710 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
711 "union T { char c; int i; };\n",
712 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
713 "#pragma pack()\n",
714 ));
715 }
716
717 #[test]
721 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
722 let result = run(
723 &options(),
724 concat!(
725 "#pragma pack 4\n",
726 "#pragma pack(pop)\n",
727 "#pragma pack(3)\n",
728 "#pragma pack(1) junk\n",
729 "#pragma pack(push, 1\n",
730 "#pragma pack(x)\n",
731 "#pragma pack(0)\n",
734 "#pragma pack(push)\n",
735 "struct s { char c; int i; };\n",
736 "#pragma pack(pop)\n",
737 "#pragma pack(pop, foo)\n",
738 ),
739 );
740 let expected = [
741 "missing `(` after `#pragma pack` - ignored",
742 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
743 "alignment must be a small power of two, not 3",
744 "junk at end of `#pragma pack`",
745 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
746 "unknown action `x` for `#pragma pack` - ignored",
747 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
748 ];
749 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
750 for (message, want) in result.messages.iter().zip(expected) {
751 assert!(message.contains(want), "expected {want:?} in {message:?}");
752 }
753 }
754
755 #[test]
759 fn the_wide_integer_answers_to_all_three_of_its_names() {
760 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
761 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
762 assert!(text.contains("decl #1 b : __int128"), "{text}");
763 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
764 }
765
766 #[test]
767 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
768 let text = tast("long f(int a, long b) { return a + b; }\n");
772 assert!(text.contains("convert arithmetic"), "{text}");
773 }
774
775 #[test]
776 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
777 for source in [
778 "#error stop\n",
779 "int f(void) { return 1 + ; }\n",
780 "int f(void) { return undeclared; }\n",
781 ] {
782 let result = run(&options(), source);
783 assert!(result.failed(), "expected this to fail:\n{source}");
784 assert!(result.text.is_empty(), "a file that did not compile wrote a tree:\n{source}");
785 }
786 }
787
788 #[test]
789 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
790 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
794 assert_eq!(result.errors, 1, "{:?}", result.messages);
795 }
796
797 #[test]
798 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
799 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
803 assert_eq!(result.errors, 1, "{:?}", result.messages);
804 }
805
806 #[test]
807 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
808 let source = "int f(void) { char c = 300; return c; }\n";
809 let plain = run(&options(), source);
810 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
811 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
812 assert!(!plain.text.is_empty(), "a warning is not a reason to write nothing");
813
814 let mut opts = options();
815 opts.warnings_are_errors = true;
816 let strict = run(&opts, source);
817 assert!(strict.failed());
818 assert!(strict.text.is_empty(), "and under -Werror it is a reason to write nothing");
819 for message in &strict.messages {
820 assert!(!message.contains("warning:"), "{message}");
821 }
822 }
823
824 #[test]
825 fn the_dialect_reaches_the_keywords_and_the_checking() {
826 let source = "typeof(1) x;\n";
829 let mut opts = options();
830 opts.std = Std::C23;
831 opts.gnu_extensions = false;
832 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
833
834 opts.std = Std::C17;
835 assert!(run(&opts, source).failed());
836 }
837
838 #[test]
839 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
840 let mut opts = options();
841 opts.emit = EmitKind::Object;
842 let result = run(&opts, "int x = 1;\n");
843 assert!(!result.failed(), "{:?}", result.messages);
844 assert!(result.text.is_empty());
845 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
848 }
849
850 fn mir(source: &str) -> String {
852 let mut opts = options();
853 opts.emit = EmitKind::MirFinal;
854 let result = run(&opts, source);
855 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
856 result.text
857 }
858
859 #[test]
865 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
866 let text = mir("int add(int a, int b) { return a + b; }\n");
867 assert!(text.starts_with("mfunc @add {"), "{text}");
868 assert!(text.contains("x64.add_rr_32"), "{text}");
869 assert!(text.contains("x64.ret"), "{text}");
870 assert!(!text.contains('%'), "{text}");
873 }
874
875 #[test]
877 fn a_function_with_no_body_produces_no_machine_function() {
878 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
879 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
880 assert!(text.contains("mfunc @f {"), "{text}");
881 assert!(text.contains("x64.call"), "{text}");
882 }
883
884 #[test]
886 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
887 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
888 let first = text.find("mfunc @a").expect("the first function");
889 let second = text.find("mfunc @b").expect("the second function");
890 assert!(first < second, "{text}");
891 }
892
893 #[test]
895 fn the_target_decides_which_convention_the_generated_code_follows() {
896 let mut opts = options();
897 opts.emit = EmitKind::MirFinal;
898 let linux = run(&opts, "int f(int a) { return a; }\n").text;
899 assert!(linux.contains("$rdi"), "{linux}");
900
901 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
902 let windows = run(&opts, "int f(int a) { return a; }\n").text;
903 assert!(windows.contains("$rcx"), "{windows}");
904 assert!(!windows.contains("$rdi"), "{windows}");
905 }
906
907 #[test]
909 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
910 let mut opts = options();
911 opts.emit = EmitKind::MirFinal;
912 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
913 let result = run(&opts, "int f(int a) { return a; }\n");
914 assert!(result.failed());
915 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
916 assert!(result.text.is_empty());
917 }
918
919 #[test]
926 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
927 let mut opts = options();
928 opts.emit = EmitKind::MirFinal;
929 let result =
930 run(&opts, "double a(double x) { return x; }\ndouble b(double x) { return x; }\n");
931 assert!(result.failed());
932 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
933 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
934 assert!(result.messages[0].contains("vector register"), "{:?}", result);
935 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
936 assert!(result.text.is_empty());
937 }
938
939 #[test]
941 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
942 let source = "int f(int a) { return a; }\n";
943 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
944
945 let mut opts = options();
946 opts.emit = EmitKind::MirFinal;
947 opts.frame_pointer = true;
948 let kept = run(&opts, source).text;
949 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
950 }
951
952 fn asm(source: &str) -> String {
954 let mut opts = options();
955 opts.emit = EmitKind::Asm;
956 let result = run(&opts, source);
957 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
958 result.text
959 }
960
961 #[test]
968 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
969 let text = asm("int add(int a, int b) { return a + b; }\n");
970 assert!(text.contains("\t.globl\tadd\n"), "{text}");
971 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
972 assert!(text.contains("\nadd:\n"), "{text}");
973 assert!(text.contains("\taddl\t"), "{text}");
974 assert!(text.contains("\tret\n"), "{text}");
975 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
976 assert!(text.contains(".note.GNU-stack"), "{text}");
979 }
980
981 #[test]
983 fn the_target_decides_how_the_assembly_is_spelled() {
984 let mut opts = options();
985 opts.emit = EmitKind::Asm;
986 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
987 let text = run(&opts, "int f(void) { return 0; }\n").text;
988 assert!(text.contains("__TEXT,__text"), "{text}");
989 assert!(text.contains("\n_f:\n"), "{text}");
990 assert!(!text.contains(".note.GNU-stack"), "{text}");
991 }
992
993 fn ir(source: &str) -> String {
995 let mut opts = options();
996 opts.emit = EmitKind::Ir;
997 let result = run(&opts, source);
998 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
999 result.text
1000 }
1001
1002 fn body(source: &str) -> String {
1004 let text = ir(source);
1005 let (_, rest) = text.split_once("{\n").expect("a function definition");
1006 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1007 body.to_owned()
1008 }
1009
1010 #[test]
1018 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1019 let text = ir(concat!(
1020 "int g;\n",
1021 "int a = __builtin_constant_p(1);\n",
1022 "int b = __builtin_constant_p(g);\n",
1023 "int c = __builtin_constant_p(\"abc\");\n",
1024 "int d = __builtin_constant_p(&g);\n",
1025 "int e = __builtin_constant_p(1.5);\n",
1026 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1027 ));
1028 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1029 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1030 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1031 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1032 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1033 assert!(text.contains("global @h : i32 = 11,"), "{text}");
1034 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1035
1036 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1040 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
1041 }
1042
1043 #[test]
1052 fn a_call_to_a_library_builtin_reaches_the_library_function() {
1053 let text = body("void f(void) { __builtin_abort(); }\n");
1054 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
1055
1056 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1059 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1060 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1061 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1062 }
1063
1064 #[test]
1071 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1072 let mut opts = options();
1073 opts.emit = EmitKind::Ir;
1074 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1075 assert!(
1076 messages.iter().any(|m| m.contains("__builtin_abort")),
1077 "expected the written name in {messages:?}"
1078 );
1079 }
1080
1081 #[test]
1088 fn a_classification_c_has_an_operator_for_is_that_operator() {
1089 for (builtin, operator) in [
1090 ("__builtin_isgreater", "binary >"),
1091 ("__builtin_isgreaterequal", "binary >="),
1092 ("__builtin_isless", "binary <"),
1093 ("__builtin_islessequal", "binary <="),
1094 ] {
1095 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1096 let text = tast(&source);
1097 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1098 }
1099 }
1100
1101 #[test]
1110 fn the_classification_builtins_are_comparisons_and_not_calls() {
1111 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1112 assert_eq!(
1113 text,
1114 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
1115 %2\n return %3\n"
1116 );
1117
1118 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1120 assert!(text.contains("fcmp one %0, %1"), "{text}");
1121
1122 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1123 assert!(text.contains("fcmp uno %0, %0"), "{text}");
1124
1125 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1126 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1127 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1128 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1129 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1130 assert!(text.contains("%5 = or %3, %4"), "{text}");
1131
1132 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1135 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1136 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1137 assert!(text.contains("%5 = and %3, %4"), "{text}");
1138
1139 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1140 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1141 assert!(text.contains("icmp slt %1, %2"), "{text}");
1142
1143 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1146 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1147
1148 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1151 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1152 }
1153
1154 #[test]
1161 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1162 let text = ir(concat!(
1163 "int a = __builtin_isinff(1e300);\n",
1164 "int b = __builtin_isinf(1e300);\n",
1165 "int c = __builtin_isnan(0.0);\n",
1169 "int d = __builtin_signbit(-0.0);\n",
1170 "int e = __builtin_islessgreater(1.0, 2.0);\n",
1171 ));
1172 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1173 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1174 assert!(text.contains("global @c : i32 = 0,"), "{text}");
1175 assert!(text.contains("global @d : i32 = 1,"), "{text}");
1176 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1177 }
1178
1179 #[test]
1181 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1182 let mut opts = options();
1183 opts.emit = EmitKind::Ir;
1184 let source = concat!(
1185 "int a(int x) { return __builtin_isnan(x); }\n",
1186 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1187 "int c(double x) { return __builtin_isnan(x, x); }\n",
1188 );
1189 let messages = run(&opts, source).messages;
1190 assert_eq!(
1191 messages,
1192 [
1193 "/main.c:1:23: error: non-floating-point argument in call to function \
1194 '__builtin_isnan' [E0685]",
1195 "/main.c:2:30: error: non-floating-point arguments in call to function \
1196 '__builtin_isunordered' [E0685]",
1197 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1198 ]
1199 );
1200 }
1201
1202 #[test]
1210 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
1211 let text = ir(concat!(
1212 "double a = __builtin_inf();\n",
1213 "float b = __builtin_huge_valf();\n",
1214 "long double c = __builtin_infl();\n",
1215 "double d = __builtin_huge_val();\n",
1216 ));
1217 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1218 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1219 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1220 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1221 assert!(!text.contains("call"), "{text}");
1222 }
1223
1224 #[test]
1233 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1234 let text = ir(concat!(
1235 "double a = __builtin_nan(\"\");\n",
1236 "double b = __builtin_nan(\"0x1\");\n",
1237 "double c = __builtin_nan(\"010\");\n",
1239 "double d = __builtin_nans(\"\");\n",
1240 "double e = __builtin_nans(\"0x1\");\n",
1241 "float f = __builtin_nanf(\"0x1\");\n",
1242 "float g = __builtin_nansf(\"\");\n",
1243 "long double h = __builtin_nansl(\"\");\n",
1244 ));
1245 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1246 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1247 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1248 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1249 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1250 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1251 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1252 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1253
1254 let text = ir(concat!(
1257 "double f(const char *p) { return __builtin_nan(p); }\n",
1258 "double g(void) { return __builtin_nans(\"1x\"); }\n",
1259 ));
1260 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1261 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1262 }
1263
1264 #[test]
1272 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
1273 let text = ir(concat!(
1274 "unsigned long a = __builtin_strlen(\"hello\");\n",
1275 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
1276 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
1277 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
1278 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
1279 ));
1280 assert!(text.contains("global @a : i64 = 5,"), "{text}");
1281 assert!(text.contains("global @b : i64 = 1,"), "{text}");
1282 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1283 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1284 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1285 assert!(!text.contains("call"), "{text}");
1286
1287 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
1289 assert!(text.contains("call @strlen("), "{text}");
1290 }
1291
1292 #[test]
1299 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
1300 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
1301 assert!(text.contains("bitcast.i64 %0"), "{text}");
1302 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
1303 assert!(text.contains("and %1, %2"), "{text}");
1304 assert!(text.contains("bitcast.f64 %3"), "{text}");
1305 assert!(!text.contains("call"), "{text}");
1306
1307 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
1308 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
1309 assert!(text.contains("%8 = or %4, %7"), "{text}");
1310 assert!(!text.contains("call"), "{text}");
1311
1312 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
1315 assert!(text.contains("bitcast.i80 %0"), "{text}");
1316 assert!(text.contains("bitcast.f80"), "{text}");
1317
1318 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
1321 assert!(text.contains("fpext.f64 %0"), "{text}");
1322 assert!(text.contains("bitcast.i64 %1"), "{text}");
1323 }
1324
1325 #[test]
1334 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
1335 let text = ir(concat!(
1336 "double a = __builtin_fabs(-3.5);\n",
1337 "double b = __builtin_copysign(1.0, -0.0);\n",
1338 "double c = __builtin_copysign(0.0, -2.0);\n",
1339 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
1341 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
1342 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
1343 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
1344 "long double i = __builtin_fabsl(-__builtin_infl());\n",
1345 ));
1346 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
1347 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
1348 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
1349 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
1350 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
1351 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
1352 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
1353 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1354 }
1355
1356 #[test]
1363 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
1364 let text = ir(concat!(
1365 "constexpr int side = 4;\n",
1366 "constexpr int wider = side + 1;\n",
1367 "constexpr double half = 1.5;\n",
1368 "struct point { int x; int y; };\n",
1369 "constexpr struct point origin = { 5, 6 };\n",
1370 "int square[side * side];\n",
1371 "int rectangle[wider];\n",
1372 "int rounded[(int)half * 2];\n",
1373 "int across[origin.y];\n",
1374 "enum named { four = side };\n",
1375 "int e = four;\n",
1376 ));
1377 assert!(text.contains("global @square : bytes 64 ="), "{text}");
1378 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
1379 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
1380 assert!(text.contains("global @across : bytes 24 ="), "{text}");
1381 assert!(text.contains("global @e : i32 = 4,"), "{text}");
1382
1383 let mut opts = options();
1386 opts.emit = EmitKind::Ir;
1387 let konst = "const int n = 1;\nint a[n];\n";
1388 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
1389 assert_eq!(run(&opts, konst).messages, [message]);
1390
1391 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
1393 assert_eq!(run(&opts, subscript).messages, [message]);
1394
1395 let address = "constexpr int c = 3;\nint *p = &c;\n";
1397 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
1398 pointer target type [E0514]";
1399 assert_eq!(run(&opts, address).messages, [warning]);
1400 }
1401
1402 #[test]
1411 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
1412 let mut opts = options();
1415 opts.std = Std::C17;
1416 let source = concat!(
1417 "int add(a, b)\n",
1418 "int a;\n",
1419 "int b;\n",
1420 "{ return a + b; }\n",
1421 "int promoted(c)\n",
1422 "char c;\n",
1423 "{ return c; }\n",
1424 "int narrow(char);\n",
1425 "int narrow(c)\n",
1426 "char c;\n",
1427 "{ return c; }\n",
1428 "int first(a)\n",
1429 "int a[4];\n",
1430 "{ return a[0]; }\n",
1431 );
1432 let result = run(&opts, source);
1433 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1434 let text = result.text;
1435 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
1436 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
1437 assert!(text.contains("c : char object automatic defined"), "{text}");
1439 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
1440 assert!(text.contains("first : int(int *) function external defined"), "{text}");
1442 }
1443
1444 #[test]
1451 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
1452 let mut opts = options();
1453 opts.std = Std::C17;
1454 for (source, message) in [
1455 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
1456 (
1457 "int f(a)\nint a;\nint b;\n{ return a; }\n",
1458 "3:5: error: declaration for parameter 'b' but no such parameter",
1459 ),
1460 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
1461 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
1462 (
1463 "int f(a)\nstatic int a;\n{ return a; }\n",
1464 "2:12: error: storage class specified for parameter 'a'",
1465 ),
1466 (
1467 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
1468 "2:7: error: argument 'a' doesn't match prototype",
1469 ),
1470 ] {
1471 let result = run(&opts, source);
1472 assert!(result.failed(), "expected this to fail:\n{source}");
1473 assert!(result.messages[0].contains(message), "{:?}", result.messages);
1474 }
1475
1476 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
1479 let mut older = options();
1480 older.std = Std::C89;
1481 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
1482 let result = run(&opts, implicit);
1483 assert!(
1484 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
1485 "{:?}",
1486 result.messages
1487 );
1488
1489 let mut newer = options();
1493 newer.std = Std::C23;
1494 let plain = "int f(a)\nint a;\n{ return a; }\n";
1495 let result = run(&newer, plain);
1496 assert!(!result.failed(), "{:?}", result.messages);
1497 assert_eq!(
1498 result.messages,
1499 ["/main.c:1:5: warning: old-style function definition [E0412]"]
1500 );
1501 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
1502 }
1503
1504 #[test]
1511 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
1512 let text = ir(concat!(
1513 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
1514 "struct brim { char buf[9223372036854775807L]; };\n",
1515 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
1516 "unsigned long h = sizeof(struct huge_struct);\n",
1517 "unsigned long b = sizeof(struct brim);\n",
1518 "unsigned long y = sizeof(struct bitty);\n",
1519 ));
1520 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
1521 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
1522 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
1523
1524 let mut opts = options();
1525 opts.emit = EmitKind::Ir;
1526 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
1527 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
1528 assert_eq!(run(&opts, over).messages, [message]);
1529 let array = "struct wide { short buf[1L << 62]; };\n";
1530 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
1531 maximum object size '9223372036854775807' [E0537]";
1532 assert_eq!(run(&opts, array).messages[0], message);
1533 }
1534
1535 fn compile_bytes(source: &[u8]) -> Compiled {
1540 let mut opts = options();
1541 opts.emit = EmitKind::Ir;
1542 let mut fs = MemoryFileSystem::new();
1543 fs.insert("/main.c", source.to_vec());
1544 compile(&opts, "/main.c", &fs)
1545 }
1546
1547 #[test]
1554 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
1555 let mut source = b"char s[] = \"a".to_vec();
1556 source.push(0xff);
1557 source.extend_from_slice(b"b\";\nchar c = '");
1558 source.push(0xff);
1559 source.extend_from_slice(b"';\n");
1560 let result = compile_bytes(&source);
1561 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
1562 assert!(result.text.contains(r#"bytes "a\ffb\00""#), "{}", result.text);
1563 assert!(result.text.contains("global @c : i8 = -1,"), "{}", result.text);
1565
1566 let mut stray = b"int a".to_vec();
1567 stray.push(0xff);
1568 stray.extend_from_slice(b" = 1;\n");
1569 let result = compile_bytes(&stray);
1570 assert!(
1571 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
1572 "{:?}",
1573 result.messages
1574 );
1575 }
1576
1577 #[test]
1578 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
1579 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
1580 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
1581 let expected = "\
1582func @add(i32, i32) -> i32, linkage(external) {
1583block0(%0: i32, %1: i32):
1584 %2 = add.nsw %0, %1
1585 return %2
1586}
1587";
1588 assert!(text.contains(expected), "{text}");
1589 }
1590
1591 #[test]
1592 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
1593 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
1594 assert!(!text.contains("alloca"), "{text}");
1595 assert!(!text.contains("load"), "{text}");
1596 assert!(!text.contains("store"), "{text}");
1597 }
1598
1599 #[test]
1600 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
1601 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
1602 let expected = "\
1603block0:
1604 %0 = alloca, size 4, align 4
1605 %1 = iconst.i32 1
1606 store %1 -> %0, align 4
1607 %2 = call @g(%0) : (ptr) -> i32
1608 return %2
1609";
1610 assert_eq!(text, expected);
1611 }
1612
1613 #[test]
1614 fn a_loop_carries_what_it_changes_as_block_parameters() {
1615 let text = body(
1618 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
1619 return total;\n}\n",
1620 );
1621 assert!(!text.contains("alloca"), "{text}");
1622 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
1623 assert!(text.contains("jump block1("), "{text}");
1624 }
1625
1626 #[test]
1627 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
1628 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
1629 assert!(text.contains("icmp slt %0, %1"), "{text}");
1630 assert!(!text.contains("zext"), "{text}");
1631 }
1632
1633 #[test]
1634 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
1635 let text = body("int f(int a, int b) { return a && b; }\n");
1636 let expected = "\
1637block0(%0: i32, %1: i32):
1638 %2 = iconst.i32 0
1639 %3 = icmp ne %0, %2
1640 %4 = iconst.i1 0
1641 br_if %3, block1, block2(%4)
1642
1643block1:
1644 %5 = iconst.i32 0
1645 %6 = icmp ne %1, %5
1646 jump block2(%6)
1647
1648block2(%7: i1):
1649 %8 = zext.i32 %7
1650 return %8
1651";
1652 assert_eq!(text, expected);
1653 }
1654
1655 #[test]
1656 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
1657 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
1658 assert!(!text.contains("block3"), "{text}");
1661 assert!(!text.contains("iconst.i32 3"), "{text}");
1662 }
1663
1664 #[test]
1665 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
1666 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
1667 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
1668 assert!(body("int f(void) { }\n").contains("unreachable"));
1669 }
1670
1671 #[test]
1672 fn a_structure_is_copied_rather_than_held_in_a_value() {
1673 let text = body(
1674 "struct point { int x, y; };\n\
1675 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
1676 );
1677 assert!(text.contains("memcpy"), "{text}");
1678 }
1679
1680 #[test]
1681 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
1682 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
1683 assert!(text.contains("memset"), "{text}");
1684 }
1685
1686 #[test]
1687 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
1688 let text = body(
1689 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
1690 default: r = 4; } return r; }\n",
1691 );
1692 let expected = "\
1693block0(%0: i32):
1694 %1 = iconst.i32 0
1695 switch %0, block1, [1 => block2, 2 => block3(%1)]
1696
1697block1:
1698 %2 = iconst.i32 4
1699 jump block4(%2)
1700
1701block2:
1702 %3 = iconst.i32 1
1703 jump block3(%3)
1704
1705block3(%4: i32):
1706 %5 = iconst.i32 2
1707 %6 = add.nsw %4, %5
1708 jump block4(%6)
1709
1710block4(%7: i32):
1711 return %7
1712";
1713 assert_eq!(text, expected);
1714 }
1715
1716 #[test]
1717 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
1718 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
1721 assert!(text.contains("%2 = sub %0, %1"), "{text}");
1722 assert!(text.contains("icmp ule"), "{text}");
1723 assert!(!text.contains("switch"), "{text}");
1724 }
1725
1726 #[test]
1727 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
1728 let text = body(
1729 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
1730 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
1731 );
1732 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
1735 assert!(text.contains("block5:\n jump block7("), "{text}");
1736 assert!(text.contains("block6:\n jump block8("), "{text}");
1737 }
1738
1739 #[test]
1740 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
1741 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
1742 }
1743
1744 #[test]
1745 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
1746 let text = body(
1751 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
1752 return n; }\n",
1753 );
1754 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
1757 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
1758 assert!(text.contains("block5:\n jump block3("), "{text}");
1759 }
1760
1761 #[test]
1762 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
1763 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
1766 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
1767 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
1768 assert!(text.contains("br_if %7, block3, block4"), "{text}");
1769 }
1770
1771 #[test]
1772 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
1773 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
1774 assert!(!text.contains("alloca"), "{text}");
1776 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
1777 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
1778 }
1779
1780 #[test]
1781 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
1782 let text =
1783 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
1784 assert!(!text.contains("alloca"), "{text}");
1785 assert!(text.contains("block1(%2: i32):"), "{text}");
1786 assert!(text.contains("jump block1(%5)"), "{text}");
1787 }
1788
1789 #[test]
1790 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
1791 assert_eq!(
1794 body("int f(int x) { return x; spare: return 0; }\n"),
1795 "block0(%0: i32):\n return %0\n"
1796 );
1797 }
1798
1799 #[test]
1800 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
1801 let text = body(
1802 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
1803 );
1804 assert_eq!(
1807 text,
1808 "\
1809block0(%0: ptr):
1810 %1 = load.i8 %0, align 1
1811 %2 = iconst.i8 3
1812 %3 = ashr %1, %2
1813 %4 = sext.i32 %3
1814 return %4
1815"
1816 );
1817 }
1818
1819 #[test]
1820 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
1821 let text =
1825 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
1826 assert_eq!(
1827 text,
1828 "\
1829block0(%0: ptr, %1: i32):
1830 %2 = iconst.i32 16777215
1831 %3 = and %1, %2
1832 %4 = trunc.i16 %3
1833 store %4 -> %0, align 2
1834 %5 = iconst.i32 16
1835 %6 = lshr %3, %5
1836 %7 = trunc.i8 %6
1837 %8 = iconst.i64 2
1838 %9 = ptr_add %0, %8
1839 store %7 -> %9, align 1
1840 return
1841"
1842 );
1843 }
1844
1845 #[test]
1846 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
1847 let text =
1848 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
1849 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
1852 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
1853 }
1854
1855 #[test]
1856 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
1857 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
1860 assert_eq!(text.matches("ashr").count(), 0, "{text}");
1861 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
1862 }
1863
1864 #[test]
1865 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
1866 let text = body(
1870 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
1871 );
1872 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
1873 }
1874
1875 #[test]
1876 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
1877 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
1880 assert!(
1881 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
1882 "{text}"
1883 );
1884 }
1885
1886 #[test]
1887 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
1888 let text = ir(concat!(
1893 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
1894 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
1895 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
1896 "char s[2] = \"hi\";\n",
1897 ));
1898 assert!(
1899 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
1900 "{text}"
1901 );
1902 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
1903 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
1904 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
1907 }
1908
1909 #[test]
1910 fn a_definition_takes_a_parameter_it_left_unnamed() {
1911 let text = ir("int f(int a, int) { return a; }\n");
1915 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
1916 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
1917
1918 let text = ir("int g(int, int n) { return n; }\n");
1921 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
1922 }
1923
1924 #[test]
1925 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
1926 let text = body(concat!(
1931 "struct s { int f; int g; };\n",
1932 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
1933 "{ *d = *e = a[0] = *c; }\n",
1934 ));
1935 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
1936 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
1937 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
1938 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
1939 }
1940
1941 #[test]
1942 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
1943 let mut opts = options();
1948 opts.emit = EmitKind::Ir;
1949 let result = run(
1950 &opts,
1951 concat!(
1952 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
1953 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
1954 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
1955 "const union u c = { { \"1234\", \"567\" } };\n",
1956 ),
1957 );
1958 let text = result.text;
1959 assert_eq!(
1960 result.messages,
1961 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
1962 (5 chars into 3 available) [E0637]"]
1963 );
1964 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
1965 assert!(
1966 text.contains(
1967 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
1968 bytes \"9\\00\", zero 3 }"
1969 ),
1970 "{text}"
1971 );
1972 assert!(
1975 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
1976 "{text}"
1977 );
1978 }
1979
1980 #[test]
1981 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
1982 let text = body(concat!(
1986 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
1987 "void g(struct v *);\n",
1988 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
1989 ));
1990 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
1991 }
1992
1993 #[test]
1994 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
1995 let text = ir(concat!(
2000 "struct s { int x; };\n",
2001 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2002 "int n = (int){ 7 };\n",
2003 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2004 ));
2005 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2006 assert!(text.contains("global @n : i32 = 7,"), "{text}");
2007 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2010 }
2011
2012 #[test]
2013 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2014 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2018 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2019 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2020 }
2021
2022 #[test]
2023 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2024 let text = ir("unsigned char foo[1][0];\n");
2028 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2029 }
2030
2031 #[test]
2032 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2033 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2036 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2037 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2038 }
2039
2040 #[test]
2041 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2042 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2046 assert!(
2047 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2048 "{text}"
2049 );
2050 }
2051
2052 #[test]
2053 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2054 let text = body(
2059 "\
2060struct s { int a, b; };
2061struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2062",
2063 );
2064 assert!(text.contains("block3(%7: ptr)"), "{text}");
2066 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2067 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2068 }
2069
2070 #[test]
2071 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2072 let text = ir("\
2076struct pair { int a, b; };
2077struct pair make(int a, int b);
2078struct pair twice(struct pair p) { return make(p.a, p.b); }
2079");
2080 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2081 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2082 }
2083
2084 #[test]
2085 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2086 let text = ir("\
2090struct big { double v[8]; };
2091struct big grow(struct big b);
2092struct big twice(struct big b) { return grow(grow(b)); }
2093");
2094 assert!(
2095 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2096 "{text}"
2097 );
2098 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2099 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2102 }
2103
2104 #[test]
2105 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2106 let text = ir("\
2111struct big { double v[8]; };
2112struct pair { int a, b; };
2113int p(const char *, ...);
2114int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2115");
2116 assert!(
2117 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2118 "{text}"
2119 );
2120 }
2121
2122 #[test]
2123 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2124 let body = body(
2127 "\
2128struct pair { int a, b; };
2129struct pair make(int a, int b);
2130int second(void) { return make(1, 2).b; }
2131",
2132 );
2133 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
2134 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2135 }
2136
2137 #[test]
2138 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2139 let source = "\
2143struct hfa { float x, y, z; };
2144int take(struct hfa h);
2145int give(struct hfa h) { return take(h); }
2146";
2147 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2148 let mut opts = options();
2149 opts.emit = EmitKind::Ir;
2150 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2151 let result = run(&opts, source);
2152 assert_eq!(result.messages, Vec::<String>::new());
2153 assert!(result.text.contains("func @take(f32, f32, f32) -> i32"), "{}", result.text);
2154 }
2155
2156 #[test]
2157 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
2158 let source = "\
2161int use(int *);
2162void f(int n) {
2163 {
2164 int a[n];
2165 use(a);
2166 }
2167 use(0);
2168}
2169";
2170 let body = body(source);
2171 assert!(body.contains("mul.nsw"), "{body}");
2172 assert!(body.contains("stacksave"), "{body}");
2173 assert!(body.contains("alloca %"), "{body}");
2174 assert!(body.contains("stackrestore"), "{body}");
2175 }
2176
2177 #[test]
2178 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
2179 let source = "\
2184int use(int *);
2185int f(int n) {
2186 {
2187 int a[n];
2188 if (use(a)) goto out;
2189 use(0);
2190 }
2191out:
2192 return 0;
2193}
2194";
2195 let body = body(source);
2196 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
2198 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2199 assert!(after.starts_with(" %4\n jump block"), "{body}");
2200 }
2201
2202 #[test]
2203 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
2204 let source = "\
2208int use(int *);
2209int f(int n) {
2210 int a[n];
2211again:
2212 if (use(a)) goto again;
2213 return 0;
2214}
2215";
2216 let body = body(source);
2217 assert!(body.contains("stacksave"), "{body}");
2218 assert!(!body.contains("stackrestore"), "{body}");
2219 }
2220
2221 #[test]
2222 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2223 let source = "\
2228int use(int *);
2229int f(int n) {
2230again:
2231 {
2232 int a[n];
2233 if (use(a)) goto again;
2234 }
2235 return 0;
2236}
2237";
2238 let body = body(source);
2239 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2240 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2241 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
2242 }
2243
2244 #[test]
2245 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2246 let source = "\
2252int f(void);
2253void t(void) {
2254 int count = 10;
2255 for (; count--;) {
2256 int b[f()];
2257 int i;
2258 for (i = 0; i < f(); i++) {
2259 b[i] = count;
2260 }
2261 }
2262}
2263";
2264 let body = body(source);
2265 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2269 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2270 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
2271 assert!(next.contains("jump block1("), "{body}");
2272 }
2273
2274 #[test]
2275 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
2276 let source = "\
2279unsigned long f(int n) {
2280 int a[n];
2281 n = 0;
2282 return sizeof a;
2283}
2284";
2285 let body = body(source);
2286 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
2288 }
2289
2290 #[test]
2291 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
2292 let source = "\
2295int use(int);
2296int f(int x) {
2297 return ({
2298 int t = use(x);
2299 t * t;
2300 });
2301}
2302";
2303 let expected = "\
2304block0(%0: i32):
2305 %1 = call @use(%0) : (i32) -> i32
2306 %2 = mul.nsw %1, %1
2307 return %2
2308";
2309 assert_eq!(body(source), expected);
2310 }
2311
2312 #[test]
2313 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
2314 let source = "int f(int x) { return ({ return x; 0; }); }\n";
2318 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
2319 }
2320
2321 #[test]
2322 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
2323 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
2327 let expected = "\
2328block0(%0: ptr):
2329 %1 = va_arg.f64 %0
2330 %2 = va_arg.f64 %0
2331 %3 = fadd %1, %2
2332 return %3
2333";
2334 assert_eq!(body(source), expected);
2335 }
2336
2337 #[test]
2338 fn one_that_reads_a_structure_answers_where_the_object_is() {
2339 let source = "\
2346struct s { int a; long b; };
2347long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
2348";
2349 let expected = "\
2350block0(%0: ptr):
2351 %1 = alloca, size 16, align 8
2352 %2 = va_object %0, size 16, align 8
2353 memcpy %1, %2, size 16, align 8
2354 %3 = iconst.i64 8
2355 %4 = ptr_add %1, %3
2356 %5 = load.i64 %4, align 8
2357 return %5
2358";
2359 assert_eq!(body(source), expected);
2360 }
2361
2362 #[test]
2363 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
2364 let source = "\
2368int f(int c) {
2369 void *p = c ? &&one : &&two;
2370 goto *p;
2371one:
2372 return 1;
2373two:
2374 return 2;
2375}
2376";
2377 let expected = "\
2378block0(%0: i32):
2379 %1 = iconst.i32 0
2380 %2 = icmp ne %0, %1
2381 br_if %2, block1, block2
2382
2383block1:
2384 %3 = block_addr block3
2385 jump block4(%3)
2386
2387block2:
2388 %4 = block_addr block5
2389 jump block4(%4)
2390
2391block3:
2392 %5 = iconst.i32 1
2393 return %5
2394
2395block4(%6: ptr):
2396 indirect_br %6, block3, block5
2397
2398block5:
2399 %7 = iconst.i32 2
2400 return %7
2401";
2402 assert_eq!(body(source), expected);
2403 }
2404
2405 #[test]
2406 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
2407 let source = "void **next(void);
2410void f(void) { goto *next(); }
2411";
2412 let expected = "\
2413block0:
2414 %0 = call @next() : () -> ptr
2415 unreachable
2416";
2417 assert_eq!(body(source), expected);
2418 }
2419
2420 #[test]
2421 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
2422 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
2425 let expected = "\
2426block0:
2427 inline_asm.volatile \"mfence\", \"\", \"memory\"()
2428 return
2429";
2430 assert_eq!(body(source), expected);
2431 }
2432
2433 #[test]
2434 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
2435 let source = "\
2438int f(int x, int y) {
2439 int r;
2440 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
2441 return r + y;
2442}
2443";
2444 let expected = "\
2445block0(%0: i32, %1: i32):
2446 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
2447 %4 = add.nsw %2, %3
2448 return %4
2449";
2450 assert_eq!(body(source), expected);
2451 }
2452
2453 #[test]
2454 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
2455 let source = "\
2460struct pair { int a, b; };
2461int f(int x) {
2462 int slot = x;
2463 struct pair p = { x, x };
2464 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
2465 return slot + p.a;
2466}
2467";
2468 let text = body(source);
2469 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
2470 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
2471 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
2472 }
2473
2474 #[test]
2475 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
2476 let source = "\
2481int f(int x) {
2482 int r = 7;
2483 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
2484 return r;
2485away:
2486 return r;
2487}
2488";
2489 let expected = "\
2490block0(%0: i32):
2491 %1 = iconst.i32 7
2492 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
2493
2494block1:
2495 return %2
2496
2497block2:
2498 return %1
2499";
2500 assert_eq!(body(source), expected);
2501 }
2502
2503 #[test]
2504 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
2505 let mut opts = options();
2509 opts.emit = EmitKind::Ir;
2510 for (source, expected) in [
2511 (
2512 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
2513 "output operand constraint lacks '='",
2514 ),
2515 (
2516 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
2517 "lvalue required in 'asm' statement",
2518 ),
2519 (
2520 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
2521 "read-only variable 'g' used as 'asm' output",
2522 ),
2523 (
2524 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
2525 "input operand constraint contains '='",
2526 ),
2527 (
2528 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
2529 "memory input 0 is not directly addressable",
2530 ),
2531 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
2532 (
2533 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
2534 "duplicate asm operand name 'a'",
2535 ),
2536 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
2537 ] {
2538 let result = run(&opts, source);
2539 assert!(result.failed(), "expected this to be reported:\n{source}");
2540 assert!(
2541 result.messages.iter().any(|m| m.contains(expected)),
2542 "{expected}\n{:?}",
2543 result.messages
2544 );
2545 }
2546 }
2547
2548 #[test]
2549 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
2550 let mut opts = options();
2551 opts.emit = EmitKind::Ir;
2552 for source in [
2553 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
2554 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
2555 ] {
2556 let result = run(&opts, source);
2557 assert!(result.failed(), "expected this to be reported:\n{source}");
2558 assert!(
2559 result.messages.iter().any(|m| m.contains("not supported yet")),
2560 "{:?}",
2561 result.messages
2562 );
2563 }
2564 }
2565
2566 fn round_trip(source: &str) -> (String, String) {
2568 let printed = ir(source);
2569 let mut opts = options();
2570 opts.emit = EmitKind::Ir;
2571 let mut fs = MemoryFileSystem::new();
2572 fs.insert("/main.ir", printed.clone().into_bytes());
2573 let result = compile_ir(&opts, "/main.ir", &fs);
2574 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
2575 (printed, result.text)
2576 }
2577
2578 #[test]
2579 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
2580 let (printed, again) = round_trip(
2584 "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",
2585 );
2586 assert_eq!(printed, again);
2587 }
2588
2589 #[test]
2590 fn ir_that_is_not_ir_says_which_line_stopped_it() {
2591 let mut opts = options();
2592 opts.emit = EmitKind::Ir;
2593 let mut fs = MemoryFileSystem::new();
2594 let text = "\
2595; ModuleID = 'a.c'
2596; format 0
2597target triple = \"x86_64-unknown-linux-gnu\"
2598target datalayout = \"e-p:64:64-i64:64-S128\"
2599
2600func @f(), linkage(external) {
2601block0:
2602 frobnicate
2603}
2604";
2605 fs.insert("/main.ir", text.as_bytes().to_vec());
2606 let result = compile_ir(&opts, "/main.ir", &fs);
2607 assert!(result.failed());
2608 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
2609 }
2610
2611 #[test]
2612 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
2613 let mut opts = options();
2616 opts.emit = EmitKind::Ir;
2617 let mut fs = MemoryFileSystem::new();
2618 let text = "\
2619; ModuleID = 'a.c'
2620; format 0
2621target triple = \"x86_64-unknown-linux-gnu\"
2622target datalayout = \"e-p:64:64-i64:64-S128\"
2623
2624func @f(), linkage(external) {
2625block0:
2626 %0 = iconst.i32 1
2627 return %0
2628}
2629";
2630 fs.insert("/main.ir", text.as_bytes().to_vec());
2631 let result = compile_ir(&opts, "/main.ir", &fs);
2632 assert!(result.failed());
2633 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
2634 }
2635
2636 #[test]
2637 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
2638 let mut fs = MemoryFileSystem::new();
2640 fs.insert("/main.ir", Vec::new());
2641 let result = compile_ir(&options(), "/main.ir", &fs);
2642 assert!(result.failed());
2643 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
2644 }
2645
2646 #[test]
2647 fn the_printed_ir_reads_back_as_the_same_module() {
2648 let text = ir("\
2651struct point { int x, y; };
2652static const char greeting[] = \"hi\";
2653int table[4] = { 1, 2, 3 };
2654int puts(const char *);
2655double half(double x) { return x / 2.0; }
2656int f(int n) {
2657 int total = 0;
2658 for (int i = 0; i < n; i++) {
2659 if (i == 3) continue;
2660 total += table[i];
2661 }
2662 switch (n) {
2663 case 0: total = 1;
2664 case 1: total++; break;
2665 default: total = -total;
2666 }
2667 struct point p = { total, 1 };
2668 int *q = &p.y;
2669 puts(greeting);
2670 return p.x + *q;
2671}
2672int dispatch(int c) {
2673 void *p = c ? &&one : &&two;
2674 goto *p;
2675one:
2676 return 1;
2677two:
2678 return 2;
2679}
2680int assembly(int x, int *p) {
2681 int r;
2682 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
2683 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
2684 return r;
2685away:
2686 return 0;
2687}
2688");
2689 let mut names = Interner::new();
2690 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
2691 assert_eq!(rucc_ir::print(&module, &names), text);
2692 }
2693}