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 complaints.push(unsupported(&format!("cannot generate code for '{name}': {why}")));
344 }
345 }
346 }
347 if !complaints.is_empty() {
348 return Err(complaints);
349 }
350 match opts.emit {
354 EmitKind::Asm => rucc_asm::print(&funcs, names, target)
355 .map(Artifact::Text)
356 .map_err(|why| vec![internal(&why.to_string())]),
357 EmitKind::Object | EmitKind::Executable => {
360 let text = rucc_asm::assemble(&funcs, names, target)
361 .map_err(|why| vec![internal(&why.to_string())])?;
362 rucc_object::write(&text, target).map(Artifact::Object).map_err(|why| match why {
365 rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
366 rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
367 })
368 }
369 _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
370 }
371}
372
373fn unsupported(message: &str) -> Diagnostic {
379 Diagnostic::error(message.to_owned(), Span::DUMMY)
380 .with_code("E0653")
381 .note("this construct is not lowered yet, see spec/17-milestones.md", Span::DUMMY)
382}
383
384fn invalid(message: &str) -> Diagnostic {
386 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
387}
388
389fn internal(message: &str) -> Diagnostic {
391 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
392 .with_code("E0652")
393 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
394}
395
396fn failure(message: String) -> Compiled {
399 Compiled {
400 artifact: Artifact::Nothing,
401 messages: vec![format!("rucc: error: {message}")],
402 errors: 1,
403 }
404}
405
406#[cfg(test)]
407mod tests {
408 use rucc_session::{MemoryFileSystem, Std};
409 use rucc_target::Triple;
410
411 use super::*;
412
413 fn options() -> Options {
414 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
415 opts.emit = EmitKind::Tast;
416 opts
417 }
418
419 fn run(opts: &Options, source: &str) -> Compiled {
420 let mut fs = MemoryFileSystem::new();
421 fs.insert("/main.c", source.to_owned().into_bytes());
422 compile(opts, "/main.c", &fs)
423 }
424
425 fn freestanding() -> Options {
429 let mut opts = options();
430 opts.hosted = false;
431 opts.search.push_system(rucc_session::runtime::DIR);
432 opts
433 }
434
435 fn shipped(source: &str) -> String {
437 let result = run(&freestanding(), source);
438 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
439 result.text().to_owned()
440 }
441
442 fn tast(source: &str) -> String {
444 let result = run(&options(), source);
445 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
446 result.text().to_owned()
447 }
448
449 #[test]
450 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
451 let text = shipped(concat!(
452 "#include <stdarg.h>\n",
453 "int sum(int n, ...) {\n",
454 " va_list ap, copy;\n",
455 " va_start(ap, n);\n",
456 " va_copy(copy, ap);\n",
457 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
458 " va_end(ap);\n",
459 " va_end(copy);\n",
460 " return total;\n",
461 "}\n",
462 ));
463 assert!(text.contains("va-start"), "{text}");
464 assert!(text.contains("va-copy"), "{text}");
465 assert!(text.contains("va-arg"), "{text}");
466 assert!(text.contains("va-end"), "{text}");
467 }
468
469 #[test]
473 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
474 let text = shipped(concat!(
475 "#define __need___va_list\n",
476 "#include <stdarg.h>\n",
477 "int vprint(const char *f, __gnuc_va_list ap);\n",
478 "#ifdef va_start\n",
479 "#error va_start should not be defined\n",
480 "#endif\n",
481 "#ifdef _VA_LIST_DEFINED\n",
482 "#error va_list should not have been made\n",
483 "#endif\n",
484 ));
485 assert!(text.contains("vprint"), "{text}");
486 }
487
488 #[test]
491 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
492 let text = shipped(concat!(
493 "#define __need_size_t\n",
494 "#include <stddef.h>\n",
495 "#ifdef offsetof\n",
496 "#error offsetof should not be defined yet\n",
497 "#endif\n",
498 "#define __need_ptrdiff_t\n",
499 "#include <stddef.h>\n",
500 "#include <stddef.h>\n",
501 "size_t a;\n",
502 "ptrdiff_t b;\n",
503 "wchar_t c;\n",
504 "max_align_t d;\n",
505 "void *e = NULL;\n",
506 "struct P { int x; long y; };\n",
507 "size_t f = offsetof(struct P, y);\n",
508 ));
509 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
510 assert!(text.contains("decl #1 b : long"), "{text}");
511 }
512
513 #[test]
514 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
515 let text = shipped(concat!(
516 "#include <limits.h>\n",
517 "#include <float.h>\n",
518 "int bits = CHAR_BIT;\n",
519 "long big = LONG_MAX;\n",
520 "int low = INT_MIN;\n",
521 "int radix = FLT_RADIX;\n",
522 "int digits = DBL_MANT_DIG;\n",
523 ));
524 assert!(text.contains("const 8 : int"), "{text}");
525 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
526 assert!(text.contains("const 2 : int"), "{text}");
527 assert!(text.contains("const 53 : int"), "{text}");
528 }
529
530 #[test]
534 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
535 let text = shipped(concat!(
536 "#include <stdint.h>\n",
537 "int64_t a = INT64_C(1);\n",
538 "uint_least16_t b;\n",
539 "intptr_t c;\n",
540 "uintmax_t d = UINTMAX_MAX;\n",
541 "int wide = sizeof(int_fast64_t);\n",
542 ));
543 assert!(text.contains("decl #0 a : long"), "{text}");
544 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
545 assert!(text.contains("decl #2 c : long"), "{text}");
546 }
547
548 #[test]
549 fn the_three_formality_headers_still_have_to_work() {
550 let text = shipped(concat!(
551 "#include <stdbool.h>\n",
552 "#include <stdalign.h>\n",
553 "#include <iso646.h>\n",
554 "#include <stdnoreturn.h>\n",
555 "int t = true and not false;\n",
556 "_Alignas(16) char buf[16];\n",
557 "int a = alignof(long);\n",
558 ));
559 assert!(text.contains("decl #0 t : int"), "{text}");
560 assert!(text.contains("const 8 : unsigned long"), "{text}");
561 }
562
563 #[test]
566 fn every_shipped_header_can_be_included_twice() {
567 let mut source = String::new();
568 for _ in 0..2 {
569 for name in rucc_session::runtime::names() {
570 source.push_str(&format!("#include <{name}>\n"));
571 }
572 }
573 source.push_str("int x;\n");
574 let text = shipped(&source);
575 assert!(text.starts_with("decl #0 x : int"), "{text}");
576 }
577
578 #[test]
579 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
580 let fs = MemoryFileSystem::new();
581 let result = compile(&options(), "/nope.c", &fs);
582 assert!(result.failed());
583 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
584 assert!(result.text().is_empty());
585 }
586
587 #[test]
588 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
589 let text = tast("int x = 1;\n");
590 let expected = "\
591decl #0 x : int object external static defined
592 init
593 +0
594 const 1 : int
595";
596 assert_eq!(text, expected);
597 }
598
599 #[test]
600 fn the_macros_are_expanded_before_anything_is_parsed() {
601 let text = tast("#define N 2\nint a[N];\n");
605 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
606 }
607
608 #[test]
614 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
615 let text = tast(concat!(
616 "#pragma pack(4)\n",
617 "struct s { int a; };\n",
618 "#pragma pack()\n",
619 "int b;\n",
620 "_Pragma(\"GCC visibility push(default)\") int c;\n",
621 ));
622 assert!(text.contains("decl #0 b : int"), "{text}");
623 assert!(text.contains("decl #1 c : int"), "{text}");
624 }
625
626 #[test]
634 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
635 tast(concat!(
636 "struct A { char c; int i; } __attribute__((packed));\n",
637 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
638 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
639 "struct B { char c; int i; } __attribute__((aligned));\n",
642 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
643 "struct C { char c; int i __attribute__((packed)); };\n",
644 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
645 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
646 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
647 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
648 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
649 "struct E { char c; _Alignas(8) int i; };\n",
650 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
651 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
652 "struct F { char c; int i __attribute__((aligned(8))); };\n",
653 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
654 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
657 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
658 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
659 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
660 "struct I { [[gnu::packed]] char c; int i; };\n",
663 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
664 "struct J { char c; [[gnu::packed]] int i; };\n",
665 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
666 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
667 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
668 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
669 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
670 "union L { char c; int i; } __attribute__((packed));\n",
671 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
672 ));
673 }
674
675 #[test]
685 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
686 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
688 assert_eq!(
689 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
690 1
691 );
692 assert_eq!(
693 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
694 1
695 );
696 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
697 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
699 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
700 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
702 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
703 }
704
705 fn bit_field_byte(record: &str) -> u64 {
707 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
708 let body = body(&source);
709 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
710 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
711 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
712 }
713
714 #[test]
720 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
721 tast(concat!(
722 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
723 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
724 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
725 "struct b { char c; __attribute__((packed)) int i; };\n",
726 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
727 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
728 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
729 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
730 ));
731 }
732
733 #[test]
739 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
740 tast(concat!(
741 "#pragma pack(1)\n",
742 "struct A { char c; int i; };\n",
743 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
744 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
745 "#pragma pack()\n",
746 "struct B { char c; int i; };\n",
747 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
748 "#pragma pack(2)\n",
749 "struct C { char c; int i; double d; };\n",
750 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
751 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
752 "struct K { char c; int i __attribute__((aligned(8))); };\n",
754 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
755 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
756 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
758 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
759 "#pragma pack()\n",
760 "#pragma pack(push, 1)\n",
761 "struct D { char c; short s; };\n",
762 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
763 "#pragma pack(pop)\n",
764 "struct E { char c; short s; };\n",
765 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
766 "struct H { char c;\n",
768 "#pragma pack(1)\n",
769 " int i; };\n",
770 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
771 "#pragma pack(1)\n",
772 "struct I { char c;\n",
773 "#pragma pack()\n",
774 " int i; };\n",
775 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
776 "#pragma pack()\n",
777 "#pragma pack(push, 8)\n",
779 "#pragma pack(push, 1)\n",
780 "struct P { char c; int i; };\n",
781 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
782 "#pragma pack(pop)\n",
783 "struct Q { char c; int i; };\n",
784 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
785 "#pragma pack(pop)\n",
786 "#pragma pack(16)\n",
788 "struct R { char c; int i; };\n",
789 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
790 "#pragma pack()\n",
791 "#pragma pack(1)\n",
792 "struct S { char c; int i : 5; int j : 20; };\n",
793 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
794 "union T { char c; int i; };\n",
795 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
796 "#pragma pack()\n",
797 ));
798 }
799
800 #[test]
804 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
805 let result = run(
806 &options(),
807 concat!(
808 "#pragma pack 4\n",
809 "#pragma pack(pop)\n",
810 "#pragma pack(3)\n",
811 "#pragma pack(1) junk\n",
812 "#pragma pack(push, 1\n",
813 "#pragma pack(x)\n",
814 "#pragma pack(0)\n",
817 "#pragma pack(push)\n",
818 "struct s { char c; int i; };\n",
819 "#pragma pack(pop)\n",
820 "#pragma pack(pop, foo)\n",
821 ),
822 );
823 let expected = [
824 "missing `(` after `#pragma pack` - ignored",
825 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
826 "alignment must be a small power of two, not 3",
827 "junk at end of `#pragma pack`",
828 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
829 "unknown action `x` for `#pragma pack` - ignored",
830 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
831 ];
832 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
833 for (message, want) in result.messages.iter().zip(expected) {
834 assert!(message.contains(want), "expected {want:?} in {message:?}");
835 }
836 }
837
838 #[test]
842 fn the_wide_integer_answers_to_all_three_of_its_names() {
843 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
844 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
845 assert!(text.contains("decl #1 b : __int128"), "{text}");
846 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
847 }
848
849 #[test]
850 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
851 let text = tast("long f(int a, long b) { return a + b; }\n");
855 assert!(text.contains("convert arithmetic"), "{text}");
856 }
857
858 #[test]
859 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
860 for source in [
861 "#error stop\n",
862 "int f(void) { return 1 + ; }\n",
863 "int f(void) { return undeclared; }\n",
864 ] {
865 let result = run(&options(), source);
866 assert!(result.failed(), "expected this to fail:\n{source}");
867 assert!(
868 result.text().is_empty(),
869 "a file that did not compile wrote a tree:\n{source}"
870 );
871 }
872 }
873
874 #[test]
875 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
876 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
880 assert_eq!(result.errors, 1, "{:?}", result.messages);
881 }
882
883 #[test]
884 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
885 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
889 assert_eq!(result.errors, 1, "{:?}", result.messages);
890 }
891
892 #[test]
893 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
894 let source = "int f(void) { char c = 300; return c; }\n";
895 let plain = run(&options(), source);
896 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
897 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
898 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
899
900 let mut opts = options();
901 opts.warnings_are_errors = true;
902 let strict = run(&opts, source);
903 assert!(strict.failed());
904 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
905 for message in &strict.messages {
906 assert!(!message.contains("warning:"), "{message}");
907 }
908 }
909
910 #[test]
911 fn the_dialect_reaches_the_keywords_and_the_checking() {
912 let source = "typeof(1) x;\n";
915 let mut opts = options();
916 opts.std = Std::C23;
917 opts.gnu_extensions = false;
918 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
919
920 opts.std = Std::C17;
921 assert!(run(&opts, source).failed());
922 }
923
924 #[test]
925 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
926 let mut opts = options();
927 opts.emit = EmitKind::Object;
928 let result = run(&opts, "int x = 1;\n");
929 assert!(!result.failed(), "{:?}", result.messages);
930 assert!(result.text().is_empty());
931 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
934 }
935
936 fn mir(source: &str) -> String {
938 let mut opts = options();
939 opts.emit = EmitKind::MirFinal;
940 let result = run(&opts, source);
941 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
942 result.text().to_owned()
943 }
944
945 #[test]
951 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
952 let text = mir("int add(int a, int b) { return a + b; }\n");
953 assert!(text.starts_with("mfunc @add {"), "{text}");
954 assert!(text.contains("x64.add_rr_32"), "{text}");
955 assert!(text.contains("x64.ret"), "{text}");
956 assert!(!text.contains('%'), "{text}");
959 }
960
961 #[test]
963 fn a_function_with_no_body_produces_no_machine_function() {
964 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
965 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
966 assert!(text.contains("mfunc @f {"), "{text}");
967 assert!(text.contains("x64.call"), "{text}");
968 }
969
970 #[test]
972 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
973 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
974 let first = text.find("mfunc @a").expect("the first function");
975 let second = text.find("mfunc @b").expect("the second function");
976 assert!(first < second, "{text}");
977 }
978
979 #[test]
981 fn the_target_decides_which_convention_the_generated_code_follows() {
982 let mut opts = options();
983 opts.emit = EmitKind::MirFinal;
984 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
985 assert!(linux.contains("$rdi"), "{linux}");
986
987 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
988 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
989 assert!(windows.contains("$rcx"), "{windows}");
990 assert!(!windows.contains("$rdi"), "{windows}");
991 }
992
993 #[test]
995 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
996 let mut opts = options();
997 opts.emit = EmitKind::MirFinal;
998 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
999 let result = run(&opts, "int f(int a) { return a; }\n");
1000 assert!(result.failed());
1001 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1002 assert!(result.text().is_empty());
1003 }
1004
1005 #[test]
1012 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1013 let mut opts = options();
1014 opts.emit = EmitKind::MirFinal;
1015 let result =
1016 run(&opts, "double a(double x) { return x; }\ndouble b(double x) { return x; }\n");
1017 assert!(result.failed());
1018 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1019 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1020 assert!(result.messages[0].contains("vector register"), "{:?}", result);
1021 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1022 assert!(result.text().is_empty());
1023 }
1024
1025 #[test]
1027 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1028 let source = "int f(int a) { return a; }\n";
1029 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1030
1031 let mut opts = options();
1032 opts.emit = EmitKind::MirFinal;
1033 opts.frame_pointer = true;
1034 let kept = run(&opts, source).text().to_owned();
1035 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1036 }
1037
1038 fn asm(source: &str) -> String {
1040 let mut opts = options();
1041 opts.emit = EmitKind::Asm;
1042 let result = run(&opts, source);
1043 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1044 result.text().to_owned()
1045 }
1046
1047 #[test]
1054 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1055 let text = asm("int add(int a, int b) { return a + b; }\n");
1056 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1057 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1058 assert!(text.contains("\nadd:\n"), "{text}");
1059 assert!(text.contains("\taddl\t"), "{text}");
1060 assert!(text.contains("\tret\n"), "{text}");
1061 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1062 assert!(text.contains(".note.GNU-stack"), "{text}");
1065 }
1066
1067 #[test]
1069 fn the_target_decides_how_the_assembly_is_spelled() {
1070 let mut opts = options();
1071 opts.emit = EmitKind::Asm;
1072 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1073 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1074 assert!(text.contains("__TEXT,__text"), "{text}");
1075 assert!(text.contains("\n_f:\n"), "{text}");
1076 assert!(!text.contains(".note.GNU-stack"), "{text}");
1077 }
1078
1079 fn obj(source: &str) -> Vec<u8> {
1081 let mut opts = options();
1082 opts.emit = EmitKind::Object;
1083 let result = run(&opts, source);
1084 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1085 match result.artifact {
1086 Artifact::Object(bytes) => bytes,
1087 other => panic!("expected an object, got {other:?}"),
1088 }
1089 }
1090
1091 #[test]
1097 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1098 let bytes = obj("int add(int a, int b) { return a + b; }\n");
1099 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1100 let text = asm("int add(int a, int b) { return a + b; }\n");
1101 assert!(
1102 text.contains("\taddl\t"),
1103 "and the listing of it is the same instructions:\n{text}"
1104 );
1105 }
1106
1107 #[test]
1109 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1110 let source = "int callee(void); int g(void) { return callee(); }\n";
1114 let bytes = obj(source);
1115 assert!(
1116 bytes.windows(7).any(|w| w == b"callee\0"),
1117 "the object has to name the callee for the linker to find it"
1118 );
1119 let text = asm(source);
1120 assert!(text.contains("\tcall\tcallee\n"), "{text}");
1121 }
1122
1123 #[test]
1129 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1130 let mut opts = options();
1131 opts.emit = EmitKind::Executable;
1133 let result = run(&opts, "int main(void) { return 0; }\n");
1134 assert_eq!(result.messages, Vec::<String>::new());
1135 match result.artifact {
1136 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1137 other => panic!("expected an object, got {other:?}"),
1138 }
1139 }
1140
1141 #[test]
1143 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1144 let mut opts = options();
1145 opts.emit = EmitKind::Object;
1146 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1147 let result = run(&opts, "int f(void) { return 0; }\n");
1148 assert!(result.failed(), "an object nobody can read is worse than a message");
1149 assert!(
1150 result.messages.iter().any(|m| m.contains("no object writer")),
1151 "{:?}",
1152 result.messages
1153 );
1154 }
1155
1156 fn ir(source: &str) -> String {
1158 let mut opts = options();
1159 opts.emit = EmitKind::Ir;
1160 let result = run(&opts, source);
1161 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1162 result.text().to_owned()
1163 }
1164
1165 fn body(source: &str) -> String {
1167 let text = ir(source);
1168 let (_, rest) = text.split_once("{\n").expect("a function definition");
1169 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1170 body.to_owned()
1171 }
1172
1173 #[test]
1181 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1182 let text = ir(concat!(
1183 "int g;\n",
1184 "int a = __builtin_constant_p(1);\n",
1185 "int b = __builtin_constant_p(g);\n",
1186 "int c = __builtin_constant_p(\"abc\");\n",
1187 "int d = __builtin_constant_p(&g);\n",
1188 "int e = __builtin_constant_p(1.5);\n",
1189 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1190 ));
1191 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1192 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1193 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1194 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1195 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1196 assert!(text.contains("global @h : i32 = 11,"), "{text}");
1197 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1198
1199 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1203 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
1204 }
1205
1206 #[test]
1215 fn a_call_to_a_library_builtin_reaches_the_library_function() {
1216 let text = body("void f(void) { __builtin_abort(); }\n");
1217 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
1218
1219 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1222 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1223 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1224 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1225 }
1226
1227 #[test]
1234 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1235 let mut opts = options();
1236 opts.emit = EmitKind::Ir;
1237 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1238 assert!(
1239 messages.iter().any(|m| m.contains("__builtin_abort")),
1240 "expected the written name in {messages:?}"
1241 );
1242 }
1243
1244 #[test]
1251 fn a_classification_c_has_an_operator_for_is_that_operator() {
1252 for (builtin, operator) in [
1253 ("__builtin_isgreater", "binary >"),
1254 ("__builtin_isgreaterequal", "binary >="),
1255 ("__builtin_isless", "binary <"),
1256 ("__builtin_islessequal", "binary <="),
1257 ] {
1258 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1259 let text = tast(&source);
1260 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1261 }
1262 }
1263
1264 #[test]
1273 fn the_classification_builtins_are_comparisons_and_not_calls() {
1274 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1275 assert_eq!(
1276 text,
1277 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
1278 %2\n return %3\n"
1279 );
1280
1281 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1283 assert!(text.contains("fcmp one %0, %1"), "{text}");
1284
1285 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1286 assert!(text.contains("fcmp uno %0, %0"), "{text}");
1287
1288 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1289 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1290 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1291 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1292 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1293 assert!(text.contains("%5 = or %3, %4"), "{text}");
1294
1295 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1298 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1299 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1300 assert!(text.contains("%5 = and %3, %4"), "{text}");
1301
1302 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1303 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1304 assert!(text.contains("icmp slt %1, %2"), "{text}");
1305
1306 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1309 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1310
1311 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1314 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1315 }
1316
1317 #[test]
1324 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1325 let text = ir(concat!(
1326 "int a = __builtin_isinff(1e300);\n",
1327 "int b = __builtin_isinf(1e300);\n",
1328 "int c = __builtin_isnan(0.0);\n",
1332 "int d = __builtin_signbit(-0.0);\n",
1333 "int e = __builtin_islessgreater(1.0, 2.0);\n",
1334 ));
1335 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1336 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1337 assert!(text.contains("global @c : i32 = 0,"), "{text}");
1338 assert!(text.contains("global @d : i32 = 1,"), "{text}");
1339 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1340 }
1341
1342 #[test]
1344 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1345 let mut opts = options();
1346 opts.emit = EmitKind::Ir;
1347 let source = concat!(
1348 "int a(int x) { return __builtin_isnan(x); }\n",
1349 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1350 "int c(double x) { return __builtin_isnan(x, x); }\n",
1351 );
1352 let messages = run(&opts, source).messages;
1353 assert_eq!(
1354 messages,
1355 [
1356 "/main.c:1:23: error: non-floating-point argument in call to function \
1357 '__builtin_isnan' [E0685]",
1358 "/main.c:2:30: error: non-floating-point arguments in call to function \
1359 '__builtin_isunordered' [E0685]",
1360 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1361 ]
1362 );
1363 }
1364
1365 #[test]
1373 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
1374 let text = ir(concat!(
1375 "double a = __builtin_inf();\n",
1376 "float b = __builtin_huge_valf();\n",
1377 "long double c = __builtin_infl();\n",
1378 "double d = __builtin_huge_val();\n",
1379 ));
1380 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1381 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1382 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1383 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1384 assert!(!text.contains("call"), "{text}");
1385 }
1386
1387 #[test]
1396 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1397 let text = ir(concat!(
1398 "double a = __builtin_nan(\"\");\n",
1399 "double b = __builtin_nan(\"0x1\");\n",
1400 "double c = __builtin_nan(\"010\");\n",
1402 "double d = __builtin_nans(\"\");\n",
1403 "double e = __builtin_nans(\"0x1\");\n",
1404 "float f = __builtin_nanf(\"0x1\");\n",
1405 "float g = __builtin_nansf(\"\");\n",
1406 "long double h = __builtin_nansl(\"\");\n",
1407 ));
1408 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1409 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1410 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1411 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1412 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1413 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1414 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1415 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1416
1417 let text = ir(concat!(
1420 "double f(const char *p) { return __builtin_nan(p); }\n",
1421 "double g(void) { return __builtin_nans(\"1x\"); }\n",
1422 ));
1423 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1424 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1425 }
1426
1427 #[test]
1435 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
1436 let text = ir(concat!(
1437 "unsigned long a = __builtin_strlen(\"hello\");\n",
1438 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
1439 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
1440 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
1441 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
1442 ));
1443 assert!(text.contains("global @a : i64 = 5,"), "{text}");
1444 assert!(text.contains("global @b : i64 = 1,"), "{text}");
1445 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1446 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1447 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1448 assert!(!text.contains("call"), "{text}");
1449
1450 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
1452 assert!(text.contains("call @strlen("), "{text}");
1453 }
1454
1455 #[test]
1462 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
1463 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
1464 assert!(text.contains("bitcast.i64 %0"), "{text}");
1465 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
1466 assert!(text.contains("and %1, %2"), "{text}");
1467 assert!(text.contains("bitcast.f64 %3"), "{text}");
1468 assert!(!text.contains("call"), "{text}");
1469
1470 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
1471 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
1472 assert!(text.contains("%8 = or %4, %7"), "{text}");
1473 assert!(!text.contains("call"), "{text}");
1474
1475 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
1478 assert!(text.contains("bitcast.i80 %0"), "{text}");
1479 assert!(text.contains("bitcast.f80"), "{text}");
1480
1481 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
1484 assert!(text.contains("fpext.f64 %0"), "{text}");
1485 assert!(text.contains("bitcast.i64 %1"), "{text}");
1486 }
1487
1488 #[test]
1497 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
1498 let text = ir(concat!(
1499 "double a = __builtin_fabs(-3.5);\n",
1500 "double b = __builtin_copysign(1.0, -0.0);\n",
1501 "double c = __builtin_copysign(0.0, -2.0);\n",
1502 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
1504 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
1505 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
1506 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
1507 "long double i = __builtin_fabsl(-__builtin_infl());\n",
1508 ));
1509 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
1510 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
1511 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
1512 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
1513 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
1514 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
1515 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
1516 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1517 }
1518
1519 #[test]
1526 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
1527 let text = ir(concat!(
1528 "constexpr int side = 4;\n",
1529 "constexpr int wider = side + 1;\n",
1530 "constexpr double half = 1.5;\n",
1531 "struct point { int x; int y; };\n",
1532 "constexpr struct point origin = { 5, 6 };\n",
1533 "int square[side * side];\n",
1534 "int rectangle[wider];\n",
1535 "int rounded[(int)half * 2];\n",
1536 "int across[origin.y];\n",
1537 "enum named { four = side };\n",
1538 "int e = four;\n",
1539 ));
1540 assert!(text.contains("global @square : bytes 64 ="), "{text}");
1541 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
1542 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
1543 assert!(text.contains("global @across : bytes 24 ="), "{text}");
1544 assert!(text.contains("global @e : i32 = 4,"), "{text}");
1545
1546 let mut opts = options();
1549 opts.emit = EmitKind::Ir;
1550 let konst = "const int n = 1;\nint a[n];\n";
1551 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
1552 assert_eq!(run(&opts, konst).messages, [message]);
1553
1554 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
1556 assert_eq!(run(&opts, subscript).messages, [message]);
1557
1558 let address = "constexpr int c = 3;\nint *p = &c;\n";
1560 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
1561 pointer target type [E0514]";
1562 assert_eq!(run(&opts, address).messages, [warning]);
1563 }
1564
1565 #[test]
1574 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
1575 let mut opts = options();
1578 opts.std = Std::C17;
1579 let source = concat!(
1580 "int add(a, b)\n",
1581 "int a;\n",
1582 "int b;\n",
1583 "{ return a + b; }\n",
1584 "int promoted(c)\n",
1585 "char c;\n",
1586 "{ return c; }\n",
1587 "int narrow(char);\n",
1588 "int narrow(c)\n",
1589 "char c;\n",
1590 "{ return c; }\n",
1591 "int first(a)\n",
1592 "int a[4];\n",
1593 "{ return a[0]; }\n",
1594 );
1595 let result = run(&opts, source);
1596 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1597 let text = result.text();
1598 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
1599 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
1600 assert!(text.contains("c : char object automatic defined"), "{text}");
1602 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
1603 assert!(text.contains("first : int(int *) function external defined"), "{text}");
1605 }
1606
1607 #[test]
1614 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
1615 let mut opts = options();
1616 opts.std = Std::C17;
1617 for (source, message) in [
1618 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
1619 (
1620 "int f(a)\nint a;\nint b;\n{ return a; }\n",
1621 "3:5: error: declaration for parameter 'b' but no such parameter",
1622 ),
1623 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
1624 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
1625 (
1626 "int f(a)\nstatic int a;\n{ return a; }\n",
1627 "2:12: error: storage class specified for parameter 'a'",
1628 ),
1629 (
1630 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
1631 "2:7: error: argument 'a' doesn't match prototype",
1632 ),
1633 ] {
1634 let result = run(&opts, source);
1635 assert!(result.failed(), "expected this to fail:\n{source}");
1636 assert!(result.messages[0].contains(message), "{:?}", result.messages);
1637 }
1638
1639 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
1642 let mut older = options();
1643 older.std = Std::C89;
1644 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
1645 let result = run(&opts, implicit);
1646 assert!(
1647 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
1648 "{:?}",
1649 result.messages
1650 );
1651
1652 let mut newer = options();
1656 newer.std = Std::C23;
1657 let plain = "int f(a)\nint a;\n{ return a; }\n";
1658 let result = run(&newer, plain);
1659 assert!(!result.failed(), "{:?}", result.messages);
1660 assert_eq!(
1661 result.messages,
1662 ["/main.c:1:5: warning: old-style function definition [E0412]"]
1663 );
1664 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
1665 }
1666
1667 #[test]
1674 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
1675 let text = ir(concat!(
1676 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
1677 "struct brim { char buf[9223372036854775807L]; };\n",
1678 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
1679 "unsigned long h = sizeof(struct huge_struct);\n",
1680 "unsigned long b = sizeof(struct brim);\n",
1681 "unsigned long y = sizeof(struct bitty);\n",
1682 ));
1683 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
1684 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
1685 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
1686
1687 let mut opts = options();
1688 opts.emit = EmitKind::Ir;
1689 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
1690 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
1691 assert_eq!(run(&opts, over).messages, [message]);
1692 let array = "struct wide { short buf[1L << 62]; };\n";
1693 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
1694 maximum object size '9223372036854775807' [E0537]";
1695 assert_eq!(run(&opts, array).messages[0], message);
1696 }
1697
1698 fn compile_bytes(source: &[u8]) -> Compiled {
1703 let mut opts = options();
1704 opts.emit = EmitKind::Ir;
1705 let mut fs = MemoryFileSystem::new();
1706 fs.insert("/main.c", source.to_vec());
1707 compile(&opts, "/main.c", &fs)
1708 }
1709
1710 #[test]
1717 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
1718 let mut source = b"char s[] = \"a".to_vec();
1719 source.push(0xff);
1720 source.extend_from_slice(b"b\";\nchar c = '");
1721 source.push(0xff);
1722 source.extend_from_slice(b"';\n");
1723 let result = compile_bytes(&source);
1724 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
1725 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
1726 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
1728
1729 let mut stray = b"int a".to_vec();
1730 stray.push(0xff);
1731 stray.extend_from_slice(b" = 1;\n");
1732 let result = compile_bytes(&stray);
1733 assert!(
1734 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
1735 "{:?}",
1736 result.messages
1737 );
1738 }
1739
1740 #[test]
1741 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
1742 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
1743 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
1744 let expected = "\
1745func @add(i32, i32) -> i32, linkage(external) {
1746block0(%0: i32, %1: i32):
1747 %2 = add.nsw %0, %1
1748 return %2
1749}
1750";
1751 assert!(text.contains(expected), "{text}");
1752 }
1753
1754 #[test]
1755 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
1756 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
1757 assert!(!text.contains("alloca"), "{text}");
1758 assert!(!text.contains("load"), "{text}");
1759 assert!(!text.contains("store"), "{text}");
1760 }
1761
1762 #[test]
1763 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
1764 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
1765 let expected = "\
1766block0:
1767 %0 = alloca, size 4, align 4
1768 %1 = iconst.i32 1
1769 store %1 -> %0, align 4
1770 %2 = call @g(%0) : (ptr) -> i32
1771 return %2
1772";
1773 assert_eq!(text, expected);
1774 }
1775
1776 #[test]
1777 fn a_loop_carries_what_it_changes_as_block_parameters() {
1778 let text = body(
1781 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
1782 return total;\n}\n",
1783 );
1784 assert!(!text.contains("alloca"), "{text}");
1785 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
1786 assert!(text.contains("jump block1("), "{text}");
1787 }
1788
1789 #[test]
1790 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
1791 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
1792 assert!(text.contains("icmp slt %0, %1"), "{text}");
1793 assert!(!text.contains("zext"), "{text}");
1794 }
1795
1796 #[test]
1797 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
1798 let text = body("int f(int a, int b) { return a && b; }\n");
1799 let expected = "\
1800block0(%0: i32, %1: i32):
1801 %2 = iconst.i32 0
1802 %3 = icmp ne %0, %2
1803 %4 = iconst.i1 0
1804 br_if %3, block1, block2(%4)
1805
1806block1:
1807 %5 = iconst.i32 0
1808 %6 = icmp ne %1, %5
1809 jump block2(%6)
1810
1811block2(%7: i1):
1812 %8 = zext.i32 %7
1813 return %8
1814";
1815 assert_eq!(text, expected);
1816 }
1817
1818 #[test]
1819 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
1820 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
1821 assert!(!text.contains("block3"), "{text}");
1824 assert!(!text.contains("iconst.i32 3"), "{text}");
1825 }
1826
1827 #[test]
1828 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
1829 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
1830 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
1831 assert!(body("int f(void) { }\n").contains("unreachable"));
1832 }
1833
1834 #[test]
1835 fn a_structure_is_copied_rather_than_held_in_a_value() {
1836 let text = body(
1837 "struct point { int x, y; };\n\
1838 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
1839 );
1840 assert!(text.contains("memcpy"), "{text}");
1841 }
1842
1843 #[test]
1844 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
1845 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
1846 assert!(text.contains("memset"), "{text}");
1847 }
1848
1849 #[test]
1850 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
1851 let text = body(
1852 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
1853 default: r = 4; } return r; }\n",
1854 );
1855 let expected = "\
1856block0(%0: i32):
1857 %1 = iconst.i32 0
1858 switch %0, block1, [1 => block2, 2 => block3(%1)]
1859
1860block1:
1861 %2 = iconst.i32 4
1862 jump block4(%2)
1863
1864block2:
1865 %3 = iconst.i32 1
1866 jump block3(%3)
1867
1868block3(%4: i32):
1869 %5 = iconst.i32 2
1870 %6 = add.nsw %4, %5
1871 jump block4(%6)
1872
1873block4(%7: i32):
1874 return %7
1875";
1876 assert_eq!(text, expected);
1877 }
1878
1879 #[test]
1880 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
1881 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
1884 assert!(text.contains("%2 = sub %0, %1"), "{text}");
1885 assert!(text.contains("icmp ule"), "{text}");
1886 assert!(!text.contains("switch"), "{text}");
1887 }
1888
1889 #[test]
1890 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
1891 let text = body(
1892 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
1893 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
1894 );
1895 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
1898 assert!(text.contains("block5:\n jump block7("), "{text}");
1899 assert!(text.contains("block6:\n jump block8("), "{text}");
1900 }
1901
1902 #[test]
1903 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
1904 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
1905 }
1906
1907 #[test]
1908 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
1909 let text = body(
1914 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
1915 return n; }\n",
1916 );
1917 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
1920 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
1921 assert!(text.contains("block5:\n jump block3("), "{text}");
1922 }
1923
1924 #[test]
1925 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
1926 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
1929 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
1930 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
1931 assert!(text.contains("br_if %7, block3, block4"), "{text}");
1932 }
1933
1934 #[test]
1935 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
1936 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
1937 assert!(!text.contains("alloca"), "{text}");
1939 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
1940 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
1941 }
1942
1943 #[test]
1944 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
1945 let text =
1946 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
1947 assert!(!text.contains("alloca"), "{text}");
1948 assert!(text.contains("block1(%2: i32):"), "{text}");
1949 assert!(text.contains("jump block1(%5)"), "{text}");
1950 }
1951
1952 #[test]
1953 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
1954 assert_eq!(
1957 body("int f(int x) { return x; spare: return 0; }\n"),
1958 "block0(%0: i32):\n return %0\n"
1959 );
1960 }
1961
1962 #[test]
1963 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
1964 let text = body(
1965 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
1966 );
1967 assert_eq!(
1970 text,
1971 "\
1972block0(%0: ptr):
1973 %1 = load.i8 %0, align 1
1974 %2 = iconst.i8 3
1975 %3 = ashr %1, %2
1976 %4 = sext.i32 %3
1977 return %4
1978"
1979 );
1980 }
1981
1982 #[test]
1983 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
1984 let text =
1988 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
1989 assert_eq!(
1990 text,
1991 "\
1992block0(%0: ptr, %1: i32):
1993 %2 = iconst.i32 16777215
1994 %3 = and %1, %2
1995 %4 = trunc.i16 %3
1996 store %4 -> %0, align 2
1997 %5 = iconst.i32 16
1998 %6 = lshr %3, %5
1999 %7 = trunc.i8 %6
2000 %8 = iconst.i64 2
2001 %9 = ptr_add %0, %8
2002 store %7 -> %9, align 1
2003 return
2004"
2005 );
2006 }
2007
2008 #[test]
2009 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2010 let text =
2011 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2012 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
2015 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
2016 }
2017
2018 #[test]
2019 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2020 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2023 assert_eq!(text.matches("ashr").count(), 0, "{text}");
2024 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
2025 }
2026
2027 #[test]
2028 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2029 let text = body(
2033 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2034 );
2035 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2036 }
2037
2038 #[test]
2039 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2040 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2043 assert!(
2044 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2045 "{text}"
2046 );
2047 }
2048
2049 #[test]
2050 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2051 let text = ir(concat!(
2056 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2057 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2058 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2059 "char s[2] = \"hi\";\n",
2060 ));
2061 assert!(
2062 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2063 "{text}"
2064 );
2065 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2066 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2067 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2070 }
2071
2072 #[test]
2073 fn a_definition_takes_a_parameter_it_left_unnamed() {
2074 let text = ir("int f(int a, int) { return a; }\n");
2078 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2079 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2080
2081 let text = ir("int g(int, int n) { return n; }\n");
2084 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
2085 }
2086
2087 #[test]
2088 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2089 let text = body(concat!(
2094 "struct s { int f; int g; };\n",
2095 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2096 "{ *d = *e = a[0] = *c; }\n",
2097 ));
2098 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2099 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2100 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2101 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2102 }
2103
2104 #[test]
2105 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2106 let mut opts = options();
2111 opts.emit = EmitKind::Ir;
2112 let result = run(
2113 &opts,
2114 concat!(
2115 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2116 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2117 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2118 "const union u c = { { \"1234\", \"567\" } };\n",
2119 ),
2120 );
2121 let text = result.text();
2122 assert_eq!(
2123 result.messages,
2124 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2125 (5 chars into 3 available) [E0637]"]
2126 );
2127 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2128 assert!(
2129 text.contains(
2130 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2131 bytes \"9\\00\", zero 3 }"
2132 ),
2133 "{text}"
2134 );
2135 assert!(
2138 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2139 "{text}"
2140 );
2141 }
2142
2143 #[test]
2144 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2145 let text = body(concat!(
2149 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2150 "void g(struct v *);\n",
2151 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2152 ));
2153 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2154 }
2155
2156 #[test]
2157 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2158 let text = ir(concat!(
2163 "struct s { int x; };\n",
2164 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2165 "int n = (int){ 7 };\n",
2166 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2167 ));
2168 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2169 assert!(text.contains("global @n : i32 = 7,"), "{text}");
2170 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2173 }
2174
2175 #[test]
2176 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2177 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2181 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2182 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2183 }
2184
2185 #[test]
2186 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2187 let text = ir("unsigned char foo[1][0];\n");
2191 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2192 }
2193
2194 #[test]
2195 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2196 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2199 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2200 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2201 }
2202
2203 #[test]
2204 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2205 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2209 assert!(
2210 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2211 "{text}"
2212 );
2213 }
2214
2215 #[test]
2216 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2217 let text = body(
2222 "\
2223struct s { int a, b; };
2224struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2225",
2226 );
2227 assert!(text.contains("block3(%7: ptr)"), "{text}");
2229 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2230 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2231 }
2232
2233 #[test]
2234 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2235 let text = ir("\
2239struct pair { int a, b; };
2240struct pair make(int a, int b);
2241struct pair twice(struct pair p) { return make(p.a, p.b); }
2242");
2243 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2244 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2245 }
2246
2247 #[test]
2248 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2249 let text = ir("\
2253struct big { double v[8]; };
2254struct big grow(struct big b);
2255struct big twice(struct big b) { return grow(grow(b)); }
2256");
2257 assert!(
2258 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2259 "{text}"
2260 );
2261 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2262 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2265 }
2266
2267 #[test]
2268 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2269 let text = ir("\
2274struct big { double v[8]; };
2275struct pair { int a, b; };
2276int p(const char *, ...);
2277int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2278");
2279 assert!(
2280 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2281 "{text}"
2282 );
2283 }
2284
2285 #[test]
2286 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2287 let body = body(
2290 "\
2291struct pair { int a, b; };
2292struct pair make(int a, int b);
2293int second(void) { return make(1, 2).b; }
2294",
2295 );
2296 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
2297 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2298 }
2299
2300 #[test]
2301 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2302 let source = "\
2306struct hfa { float x, y, z; };
2307int take(struct hfa h);
2308int give(struct hfa h) { return take(h); }
2309";
2310 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2311 let mut opts = options();
2312 opts.emit = EmitKind::Ir;
2313 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2314 let result = run(&opts, source);
2315 assert_eq!(result.messages, Vec::<String>::new());
2316 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
2317 }
2318
2319 #[test]
2320 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
2321 let source = "\
2324int use(int *);
2325void f(int n) {
2326 {
2327 int a[n];
2328 use(a);
2329 }
2330 use(0);
2331}
2332";
2333 let body = body(source);
2334 assert!(body.contains("mul.nsw"), "{body}");
2335 assert!(body.contains("stacksave"), "{body}");
2336 assert!(body.contains("alloca %"), "{body}");
2337 assert!(body.contains("stackrestore"), "{body}");
2338 }
2339
2340 #[test]
2341 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
2342 let source = "\
2347int use(int *);
2348int f(int n) {
2349 {
2350 int a[n];
2351 if (use(a)) goto out;
2352 use(0);
2353 }
2354out:
2355 return 0;
2356}
2357";
2358 let body = body(source);
2359 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
2361 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2362 assert!(after.starts_with(" %4\n jump block"), "{body}");
2363 }
2364
2365 #[test]
2366 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
2367 let source = "\
2371int use(int *);
2372int f(int n) {
2373 int a[n];
2374again:
2375 if (use(a)) goto again;
2376 return 0;
2377}
2378";
2379 let body = body(source);
2380 assert!(body.contains("stacksave"), "{body}");
2381 assert!(!body.contains("stackrestore"), "{body}");
2382 }
2383
2384 #[test]
2385 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2386 let source = "\
2391int use(int *);
2392int f(int n) {
2393again:
2394 {
2395 int a[n];
2396 if (use(a)) goto again;
2397 }
2398 return 0;
2399}
2400";
2401 let body = body(source);
2402 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2403 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2404 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
2405 }
2406
2407 #[test]
2408 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2409 let source = "\
2415int f(void);
2416void t(void) {
2417 int count = 10;
2418 for (; count--;) {
2419 int b[f()];
2420 int i;
2421 for (i = 0; i < f(); i++) {
2422 b[i] = count;
2423 }
2424 }
2425}
2426";
2427 let body = body(source);
2428 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2432 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2433 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
2434 assert!(next.contains("jump block1("), "{body}");
2435 }
2436
2437 #[test]
2438 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
2439 let source = "\
2442unsigned long f(int n) {
2443 int a[n];
2444 n = 0;
2445 return sizeof a;
2446}
2447";
2448 let body = body(source);
2449 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
2451 }
2452
2453 #[test]
2454 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
2455 let source = "\
2458int use(int);
2459int f(int x) {
2460 return ({
2461 int t = use(x);
2462 t * t;
2463 });
2464}
2465";
2466 let expected = "\
2467block0(%0: i32):
2468 %1 = call @use(%0) : (i32) -> i32
2469 %2 = mul.nsw %1, %1
2470 return %2
2471";
2472 assert_eq!(body(source), expected);
2473 }
2474
2475 #[test]
2476 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
2477 let source = "int f(int x) { return ({ return x; 0; }); }\n";
2481 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
2482 }
2483
2484 #[test]
2485 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
2486 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
2490 let expected = "\
2491block0(%0: ptr):
2492 %1 = va_arg.f64 %0
2493 %2 = va_arg.f64 %0
2494 %3 = fadd %1, %2
2495 return %3
2496";
2497 assert_eq!(body(source), expected);
2498 }
2499
2500 #[test]
2501 fn one_that_reads_a_structure_answers_where_the_object_is() {
2502 let source = "\
2509struct s { int a; long b; };
2510long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
2511";
2512 let expected = "\
2513block0(%0: ptr):
2514 %1 = alloca, size 16, align 8
2515 %2 = va_object %0, size 16, align 8
2516 memcpy %1, %2, size 16, align 8
2517 %3 = iconst.i64 8
2518 %4 = ptr_add %1, %3
2519 %5 = load.i64 %4, align 8
2520 return %5
2521";
2522 assert_eq!(body(source), expected);
2523 }
2524
2525 #[test]
2526 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
2527 let source = "\
2531int f(int c) {
2532 void *p = c ? &&one : &&two;
2533 goto *p;
2534one:
2535 return 1;
2536two:
2537 return 2;
2538}
2539";
2540 let expected = "\
2541block0(%0: i32):
2542 %1 = iconst.i32 0
2543 %2 = icmp ne %0, %1
2544 br_if %2, block1, block2
2545
2546block1:
2547 %3 = block_addr block3
2548 jump block4(%3)
2549
2550block2:
2551 %4 = block_addr block5
2552 jump block4(%4)
2553
2554block3:
2555 %5 = iconst.i32 1
2556 return %5
2557
2558block4(%6: ptr):
2559 indirect_br %6, block3, block5
2560
2561block5:
2562 %7 = iconst.i32 2
2563 return %7
2564";
2565 assert_eq!(body(source), expected);
2566 }
2567
2568 #[test]
2569 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
2570 let source = "void **next(void);
2573void f(void) { goto *next(); }
2574";
2575 let expected = "\
2576block0:
2577 %0 = call @next() : () -> ptr
2578 unreachable
2579";
2580 assert_eq!(body(source), expected);
2581 }
2582
2583 #[test]
2584 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
2585 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
2588 let expected = "\
2589block0:
2590 inline_asm.volatile \"mfence\", \"\", \"memory\"()
2591 return
2592";
2593 assert_eq!(body(source), expected);
2594 }
2595
2596 #[test]
2597 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
2598 let source = "\
2601int f(int x, int y) {
2602 int r;
2603 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
2604 return r + y;
2605}
2606";
2607 let expected = "\
2608block0(%0: i32, %1: i32):
2609 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
2610 %4 = add.nsw %2, %3
2611 return %4
2612";
2613 assert_eq!(body(source), expected);
2614 }
2615
2616 #[test]
2617 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
2618 let source = "\
2623struct pair { int a, b; };
2624int f(int x) {
2625 int slot = x;
2626 struct pair p = { x, x };
2627 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
2628 return slot + p.a;
2629}
2630";
2631 let text = body(source);
2632 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
2633 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
2634 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
2635 }
2636
2637 #[test]
2638 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
2639 let source = "\
2644int f(int x) {
2645 int r = 7;
2646 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
2647 return r;
2648away:
2649 return r;
2650}
2651";
2652 let expected = "\
2653block0(%0: i32):
2654 %1 = iconst.i32 7
2655 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
2656
2657block1:
2658 return %2
2659
2660block2:
2661 return %1
2662";
2663 assert_eq!(body(source), expected);
2664 }
2665
2666 #[test]
2667 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
2668 let mut opts = options();
2672 opts.emit = EmitKind::Ir;
2673 for (source, expected) in [
2674 (
2675 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
2676 "output operand constraint lacks '='",
2677 ),
2678 (
2679 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
2680 "lvalue required in 'asm' statement",
2681 ),
2682 (
2683 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
2684 "read-only variable 'g' used as 'asm' output",
2685 ),
2686 (
2687 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
2688 "input operand constraint contains '='",
2689 ),
2690 (
2691 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
2692 "memory input 0 is not directly addressable",
2693 ),
2694 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
2695 (
2696 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
2697 "duplicate asm operand name 'a'",
2698 ),
2699 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
2700 ] {
2701 let result = run(&opts, source);
2702 assert!(result.failed(), "expected this to be reported:\n{source}");
2703 assert!(
2704 result.messages.iter().any(|m| m.contains(expected)),
2705 "{expected}\n{:?}",
2706 result.messages
2707 );
2708 }
2709 }
2710
2711 #[test]
2712 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
2713 let mut opts = options();
2714 opts.emit = EmitKind::Ir;
2715 for source in [
2716 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
2717 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
2718 ] {
2719 let result = run(&opts, source);
2720 assert!(result.failed(), "expected this to be reported:\n{source}");
2721 assert!(
2722 result.messages.iter().any(|m| m.contains("not supported yet")),
2723 "{:?}",
2724 result.messages
2725 );
2726 }
2727 }
2728
2729 fn round_trip(source: &str) -> (String, String) {
2731 let printed = ir(source);
2732 let mut opts = options();
2733 opts.emit = EmitKind::Ir;
2734 let mut fs = MemoryFileSystem::new();
2735 fs.insert("/main.ir", printed.clone().into_bytes());
2736 let result = compile_ir(&opts, "/main.ir", &fs);
2737 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
2738 (printed, result.text().to_owned())
2739 }
2740
2741 #[test]
2742 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
2743 let (printed, again) = round_trip(
2747 "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",
2748 );
2749 assert_eq!(printed, again);
2750 }
2751
2752 #[test]
2753 fn ir_that_is_not_ir_says_which_line_stopped_it() {
2754 let mut opts = options();
2755 opts.emit = EmitKind::Ir;
2756 let mut fs = MemoryFileSystem::new();
2757 let text = "\
2758; ModuleID = 'a.c'
2759; format 0
2760target triple = \"x86_64-unknown-linux-gnu\"
2761target datalayout = \"e-p:64:64-i64:64-S128\"
2762
2763func @f(), linkage(external) {
2764block0:
2765 frobnicate
2766}
2767";
2768 fs.insert("/main.ir", text.as_bytes().to_vec());
2769 let result = compile_ir(&opts, "/main.ir", &fs);
2770 assert!(result.failed());
2771 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
2772 }
2773
2774 #[test]
2775 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
2776 let mut opts = options();
2779 opts.emit = EmitKind::Ir;
2780 let mut fs = MemoryFileSystem::new();
2781 let text = "\
2782; ModuleID = 'a.c'
2783; format 0
2784target triple = \"x86_64-unknown-linux-gnu\"
2785target datalayout = \"e-p:64:64-i64:64-S128\"
2786
2787func @f(), linkage(external) {
2788block0:
2789 %0 = iconst.i32 1
2790 return %0
2791}
2792";
2793 fs.insert("/main.ir", text.as_bytes().to_vec());
2794 let result = compile_ir(&opts, "/main.ir", &fs);
2795 assert!(result.failed());
2796 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
2797 }
2798
2799 #[test]
2800 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
2801 let mut fs = MemoryFileSystem::new();
2803 fs.insert("/main.ir", Vec::new());
2804 let result = compile_ir(&options(), "/main.ir", &fs);
2805 assert!(result.failed());
2806 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
2807 }
2808
2809 #[test]
2810 fn the_printed_ir_reads_back_as_the_same_module() {
2811 let text = ir("\
2814struct point { int x, y; };
2815static const char greeting[] = \"hi\";
2816int table[4] = { 1, 2, 3 };
2817int puts(const char *);
2818double half(double x) { return x / 2.0; }
2819int f(int n) {
2820 int total = 0;
2821 for (int i = 0; i < n; i++) {
2822 if (i == 3) continue;
2823 total += table[i];
2824 }
2825 switch (n) {
2826 case 0: total = 1;
2827 case 1: total++; break;
2828 default: total = -total;
2829 }
2830 struct point p = { total, 1 };
2831 int *q = &p.y;
2832 puts(greeting);
2833 return p.x + *q;
2834}
2835int dispatch(int c) {
2836 void *p = c ? &&one : &&two;
2837 goto *p;
2838one:
2839 return 1;
2840two:
2841 return 2;
2842}
2843int assembly(int x, int *p) {
2844 int r;
2845 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
2846 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
2847 return r;
2848away:
2849 return 0;
2850}
2851");
2852 let mut names = Interner::new();
2853 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
2854 assert_eq!(rucc_ir::print(&module, &names), text);
2855 }
2856}