1use crate::entity::SecondaryMap;
7use crate::ir::entities::AnyEntity;
8use crate::ir::immediates::Ieee128;
9use crate::ir::{Block, DataFlowGraph, Function, Inst, Opcode, SigRef, Type, Value, ValueDef};
10use crate::packed_option::ReservedValue;
11use alloc::string::{String, ToString};
12use alloc::vec::Vec;
13use core::fmt::{self, Write};
14
15pub trait FuncWriter {
17 fn write_block_header(
19 &mut self,
20 w: &mut dyn Write,
21 func: &Function,
22 block: Block,
23 indent: usize,
24 ) -> fmt::Result;
25
26 fn write_instruction(
28 &mut self,
29 w: &mut dyn Write,
30 func: &Function,
31 aliases: &SecondaryMap<Value, Vec<Value>>,
32 inst: Inst,
33 indent: usize,
34 ) -> fmt::Result;
35
36 fn write_preamble(&mut self, w: &mut dyn Write, func: &Function) -> Result<bool, fmt::Error> {
38 self.super_preamble(w, func)
39 }
40
41 fn super_preamble(&mut self, w: &mut dyn Write, func: &Function) -> Result<bool, fmt::Error> {
43 let mut any = false;
44
45 for (ss, slot) in func.dynamic_stack_slots.iter() {
46 any = true;
47 self.write_entity_definition(w, func, ss.into(), slot)?;
48 }
49
50 for (ss, slot) in func.sized_stack_slots.iter() {
51 any = true;
52 self.write_entity_definition(w, func, ss.into(), slot)?;
53 }
54
55 for (ar, ar_data) in func.dfg.alias_regions.iter() {
56 any = true;
57 self.write_entity_definition(
58 w,
59 func,
60 ar.into(),
61 &format_args!("{} \"{}\"", ar_data.user_id, ar_data.description),
62 )?;
63 }
64
65 for (gv, gv_data) in &func.global_values {
66 any = true;
67 self.write_entity_definition(
68 w,
69 func,
70 gv.into(),
71 &gv_data.display(&func.dfg.mem_flags),
72 )?;
73 }
74
75 for (sig, sig_data) in &func.dfg.signatures {
78 any = true;
79 self.write_entity_definition(w, func, sig.into(), &sig_data)?;
80 }
81
82 for (fnref, ext_func) in &func.dfg.ext_funcs {
83 if ext_func.signature != SigRef::reserved_value() {
84 any = true;
85 self.write_entity_definition(
86 w,
87 func,
88 fnref.into(),
89 &ext_func.display(Some(&func.params)),
90 )?;
91 }
92 }
93
94 for (&cref, cval) in func.dfg.constants.iter() {
95 any = true;
96 self.write_entity_definition(w, func, cref.into(), cval)?;
97 }
98
99 if let Some(limit) = func.stack_limit {
100 any = true;
101 self.write_entity_definition(w, func, AnyEntity::StackLimit, &limit)?;
102 }
103
104 Ok(any)
105 }
106
107 fn write_entity_definition(
109 &mut self,
110 w: &mut dyn Write,
111 func: &Function,
112 entity: AnyEntity,
113 value: &dyn fmt::Display,
114 ) -> fmt::Result {
115 self.super_entity_definition(w, func, entity, value)
116 }
117
118 fn super_entity_definition(
120 &mut self,
121 w: &mut dyn Write,
122 _func: &Function,
123 entity: AnyEntity,
124 value: &dyn fmt::Display,
125 ) -> fmt::Result {
126 writeln!(w, " {entity} = {value}")
127 }
128}
129
130pub struct PlainWriter;
132
133impl FuncWriter for PlainWriter {
134 fn write_instruction(
135 &mut self,
136 w: &mut dyn Write,
137 func: &Function,
138 aliases: &SecondaryMap<Value, Vec<Value>>,
139 inst: Inst,
140 indent: usize,
141 ) -> fmt::Result {
142 write_instruction(w, func, aliases, inst, indent)
143 }
144
145 fn write_block_header(
146 &mut self,
147 w: &mut dyn Write,
148 func: &Function,
149 block: Block,
150 indent: usize,
151 ) -> fmt::Result {
152 write_block_header(w, func, block, indent)
153 }
154}
155
156pub fn write_function(w: &mut dyn Write, func: &Function) -> fmt::Result {
159 decorate_function(&mut PlainWriter, w, func)
160}
161
162fn alias_map(func: &Function) -> SecondaryMap<Value, Vec<Value>> {
164 let mut aliases = SecondaryMap::<_, Vec<_>>::new();
165 for v in func.dfg.values() {
166 if let Some(k) = func.dfg.value_alias_dest_for_serialization(v) {
168 aliases[k].push(v);
169 }
170 }
171 aliases
172}
173
174pub fn decorate_function<FW: FuncWriter>(
178 func_w: &mut FW,
179 w: &mut dyn Write,
180 func: &Function,
181) -> fmt::Result {
182 write!(w, "function ")?;
183 write_function_spec(w, func)?;
184 writeln!(w, " {{")?;
185 let aliases = alias_map(func);
186 let mut any = func_w.write_preamble(w, func)?;
187 for block in &func.layout {
188 if any {
189 writeln!(w)?;
190 }
191 decorate_block(func_w, w, func, &aliases, block)?;
192 any = true;
193 }
194 writeln!(w, "}}")
195}
196
197pub fn write_function_spec(w: &mut dyn Write, func: &Function) -> fmt::Result {
203 write!(w, "{}{}", func.name, func.signature)
204}
205
206fn write_arg(w: &mut dyn Write, func: &Function, arg: Value) -> fmt::Result {
211 let ty = func.dfg.value_type(arg);
212 write!(w, "{arg}: {ty}")
213}
214
215pub fn write_block_header(
222 w: &mut dyn Write,
223 func: &Function,
224 block: Block,
225 indent: usize,
226) -> fmt::Result {
227 let cold = if func.layout.is_cold(block) {
228 " cold"
229 } else {
230 ""
231 };
232
233 write!(w, "{1:0$}{2}", indent - 4, "", block)?;
235
236 let mut args = func.dfg.block_params(block).iter().cloned();
237 match args.next() {
238 None => return writeln!(w, "{cold}:"),
239 Some(arg) => {
240 write!(w, "(")?;
241 write_arg(w, func, arg)?;
242 }
243 }
244 for arg in args {
246 write!(w, ", ")?;
247 write_arg(w, func, arg)?;
248 }
249 writeln!(w, "){cold}:")
250}
251
252fn decorate_block<FW: FuncWriter>(
253 func_w: &mut FW,
254 w: &mut dyn Write,
255 func: &Function,
256 aliases: &SecondaryMap<Value, Vec<Value>>,
257 block: Block,
258) -> fmt::Result {
259 let indent = if func.rel_srclocs().is_empty() && func.debug_tags.is_empty() {
261 4
262 } else {
263 36
264 };
265
266 func_w.write_block_header(w, func, block, indent)?;
267 for a in func.dfg.block_params(block).iter().cloned() {
268 write_value_aliases(w, aliases, a, indent)?;
269 }
270
271 for inst in func.layout.block_insts(block) {
272 func_w.write_instruction(w, func, aliases, inst, indent)?;
273 }
274
275 Ok(())
276}
277
278fn type_suffix(func: &Function, inst: Inst) -> Option<Type> {
288 let inst_data = &func.dfg.insts[inst];
289 let constraints = inst_data.opcode().constraints();
290
291 if !constraints.is_polymorphic() {
292 return None;
293 }
294
295 if constraints.use_typevar_operand() {
298 let ctrl_var = inst_data.typevar_operand(&func.dfg.value_lists).unwrap();
299 let def_block = match func.dfg.value_def(ctrl_var) {
300 ValueDef::Result(instr, _) => func.layout.inst_block(instr),
301 ValueDef::Param(block, _) => Some(block),
302 ValueDef::Union(..) => None,
303 };
304 if def_block.is_some() && def_block == func.layout.inst_block(inst) {
305 return None;
306 }
307 }
308
309 let rtype = func.dfg.ctrl_typevar(inst);
310 assert!(
311 !rtype.is_invalid(),
312 "Polymorphic instruction must produce a result"
313 );
314 Some(rtype)
315}
316
317fn write_value_aliases(
319 w: &mut dyn Write,
320 aliases: &SecondaryMap<Value, Vec<Value>>,
321 target: Value,
322 indent: usize,
323) -> fmt::Result {
324 let mut todo_stack = vec![target];
325 while let Some(target) = todo_stack.pop() {
326 for &a in &aliases[target] {
327 writeln!(w, "{1:0$}{2} -> {3}", indent, "", a, target)?;
328 todo_stack.push(a);
329 }
330 }
331
332 Ok(())
333}
334
335fn write_instruction(
336 w: &mut dyn Write,
337 func: &Function,
338 aliases: &SecondaryMap<Value, Vec<Value>>,
339 inst: Inst,
340 mut indent: usize,
341) -> fmt::Result {
342 let mut s = String::with_capacity(16);
344
345 let srcloc = func.srcloc(inst);
347 if !srcloc.is_default() {
348 write!(s, "{srcloc} ")?;
349 }
350
351 write_debug_tags(w, &func, inst, &mut indent)?;
353
354 write!(w, "{s:indent$}")?;
356
357 let mut has_results = false;
359 for r in func.dfg.inst_results(inst) {
360 if !has_results {
361 has_results = true;
362 write!(w, "{r}")?;
363 } else {
364 write!(w, ", {r}")?;
365 }
366 }
367 if has_results {
368 write!(w, " = ")?;
369 }
370
371 let opcode = func.dfg.insts[inst].opcode();
373
374 match type_suffix(func, inst) {
375 Some(suf) => write!(w, "{opcode}.{suf}")?,
376 None => write!(w, "{opcode}")?,
377 }
378
379 write_operands(w, &func.dfg, inst)?;
380 writeln!(w)?;
381
382 for r in func.dfg.inst_results(inst) {
384 write_value_aliases(w, aliases, *r, indent)?;
385 }
386 Ok(())
387}
388
389pub fn write_operands(w: &mut dyn Write, dfg: &DataFlowGraph, inst: Inst) -> fmt::Result {
391 let pool = &dfg.value_lists;
392 let jump_tables = &dfg.jump_tables;
393 let exception_tables = &dfg.exception_tables;
394 use crate::ir::instructions::InstructionData::*;
395 let ctrl_ty = dfg.ctrl_typevar(inst);
396 match dfg.insts[inst] {
397 AtomicRmw {
398 op, args, flags, ..
399 } => write!(
400 w,
401 "{} {} {}, {}",
402 dfg.mem_flags[flags], op, args[0], args[1]
403 ),
404 AtomicCas { args, flags, .. } => write!(
405 w,
406 "{} {}, {}, {}",
407 dfg.mem_flags[flags], args[0], args[1], args[2]
408 ),
409 LoadNoOffset { flags, arg, .. } => write!(w, "{} {arg}", dfg.mem_flags[flags]),
410 StoreNoOffset { flags, args, .. } => {
411 write!(w, "{} {}, {}", dfg.mem_flags[flags], args[0], args[1])
412 }
413 Unary { arg, .. } => write!(w, " {arg}"),
414 UnaryImm { imm, .. } => write!(w, " {}", {
415 let mut imm = imm;
416 if ctrl_ty.bits() != 0 {
417 imm = imm.sign_extend_from_width(ctrl_ty.bits());
418 }
419 imm
420 }),
421 UnaryIeee16 { imm, .. } => write!(w, " {imm}"),
422 UnaryIeee32 { imm, .. } => write!(w, " {imm}"),
423 UnaryIeee64 { imm, .. } => write!(w, " {imm}"),
424 UnaryGlobalValue { global_value, .. } => write!(w, " {global_value}"),
425 UnaryConst {
426 constant_handle, ..
427 } => write!(w, " {constant_handle}"),
428 Binary { args, .. } => write!(w, " {}, {}", args[0], args[1]),
429 BinaryImm8 { arg, imm, .. } => write!(w, " {arg}, {imm}"),
430 Ternary { args, .. } => write!(w, " {}, {}, {}", args[0], args[1], args[2]),
431 MultiAry { ref args, .. } => {
432 if args.is_empty() {
433 write!(w, "")
434 } else {
435 write!(w, " {}", DisplayValues(args.as_slice(pool)))
436 }
437 }
438 NullAry { .. } => write!(w, " "),
439 TernaryImm8 { imm, args, .. } => write!(w, " {}, {}, {}", args[0], args[1], imm),
440 Shuffle { imm, args, .. } => {
441 let data = dfg.immediates.get(imm).expect(
442 "Expected the shuffle mask to already be inserted into the immediates table",
443 );
444 write!(w, " {}, {}, {}", args[0], args[1], data)
445 }
446 IntCompare { cond, args, .. } => write!(w, " {} {}, {}", cond, args[0], args[1]),
447 IntAddTrap { args, code, .. } => write!(w, " {}, {}, {}", args[0], args[1], code),
448 FloatCompare { cond, args, .. } => write!(w, " {} {}, {}", cond, args[0], args[1]),
449 Jump { destination, .. } => {
450 write!(w, " {}", destination.display(pool))
451 }
452 Brif {
453 arg,
454 blocks: [block_then, block_else],
455 ..
456 } => {
457 write!(w, " {}, {}", arg, block_then.display(pool))?;
458 write!(w, ", {}", block_else.display(pool))
459 }
460 BranchTable { arg, table, .. } => {
461 write!(w, " {}, {}", arg, jump_tables[table].display(pool))
462 }
463 Call {
464 func_ref, ref args, ..
465 } => {
466 write!(w, " {}({})", func_ref, DisplayValues(args.as_slice(pool)))
467 }
468 CallIndirect {
469 sig_ref, ref args, ..
470 } => {
471 let args = args.as_slice(pool);
472 write!(
473 w,
474 " {}, {}({})",
475 sig_ref,
476 args[0],
477 DisplayValues(&args[1..])
478 )
479 }
480 TryCall {
481 func_ref,
482 ref args,
483 exception,
484 ..
485 } => {
486 write!(
487 w,
488 " {}({}), {}",
489 func_ref,
490 DisplayValues(args.as_slice(pool)),
491 exception_tables[exception].display(pool),
492 )
493 }
494 TryCallIndirect {
495 ref args,
496 exception,
497 ..
498 } => {
499 let args = args.as_slice(pool);
500 write!(
501 w,
502 " {}({}), {}",
503 args[0],
504 DisplayValues(&args[1..]),
505 exception_tables[exception].display(pool),
506 )
507 }
508 FuncAddr { func_ref, .. } => write!(w, " {func_ref}"),
509 StackAddr {
510 stack_slot, offset, ..
511 } => write!(w, " {stack_slot}{offset}"),
512 DynamicStackAddr {
513 dynamic_stack_slot, ..
514 } => write!(w, " {dynamic_stack_slot}"),
515 Load {
516 flags, arg, offset, ..
517 } => write!(w, "{} {arg}{offset}", dfg.mem_flags[flags]),
518 Store {
519 flags,
520 args,
521 offset,
522 ..
523 } => write!(
524 w,
525 "{} {}, {}{}",
526 dfg.mem_flags[flags], args[0], args[1], offset
527 ),
528 Trap { code, .. } => write!(w, " {code}"),
529 CondTrap { arg, code, .. } => write!(w, " {arg}, {code}"),
530 ExceptionHandlerAddress { block, imm, .. } => write!(w, " {block}, {imm}"),
531 }?;
532
533 write_user_stack_map_entries(w, dfg, inst)?;
538
539 let mut sep = " ; ";
540 for arg in dfg.inst_values(inst) {
541 if let ValueDef::Result(src, _) = dfg.value_def(arg) {
542 let imm = match dfg.insts[src] {
543 UnaryImm { imm, .. } => {
544 let mut imm = imm;
545 if dfg.ctrl_typevar(src).bits() != 0 {
546 imm = imm.sign_extend_from_width(dfg.ctrl_typevar(src).bits());
547 }
548 imm.to_string()
549 }
550 UnaryIeee16 { imm, .. } => imm.to_string(),
551 UnaryIeee32 { imm, .. } => imm.to_string(),
552 UnaryIeee64 { imm, .. } => imm.to_string(),
553 UnaryConst {
554 constant_handle,
555 opcode: Opcode::F128const,
556 } => Ieee128::try_from(dfg.constants.get(constant_handle))
557 .expect("16-byte f128 constant")
558 .to_string(),
559 UnaryConst {
560 constant_handle, ..
561 } => constant_handle.to_string(),
562 _ => continue,
563 };
564 write!(w, "{sep}{arg} = {imm}")?;
565 sep = ", ";
566 }
567 }
568 Ok(())
569}
570
571fn write_debug_tags(
572 w: &mut dyn Write,
573 func: &Function,
574 inst: Inst,
575 indent: &mut usize,
576) -> fmt::Result {
577 let tags = func.debug_tags.get(inst);
578 if !tags.is_empty() {
579 let tags = tags
580 .iter()
581 .map(|tag| format!("{tag}"))
582 .collect::<Vec<_>>()
583 .join(", ");
584 let s = format!("<{tags}> ");
585 write!(w, "{s}")?;
586 *indent = indent.saturating_sub(s.len());
587 }
588 Ok(())
589}
590
591fn write_user_stack_map_entries(w: &mut dyn Write, dfg: &DataFlowGraph, inst: Inst) -> fmt::Result {
592 let entries = match dfg.user_stack_map_entries(inst) {
593 None => return Ok(()),
594 Some(es) => es,
595 };
596 write!(w, ", stack_map=[")?;
597 let mut need_comma = false;
598 for entry in entries {
599 if need_comma {
600 write!(w, ", ")?;
601 }
602 write!(w, "{} @ {}+{}", entry.ty, entry.slot, entry.offset)?;
603 need_comma = true;
604 }
605 write!(w, "]")?;
606 Ok(())
607}
608
609struct DisplayValues<'a>(&'a [Value]);
611
612impl<'a> fmt::Display for DisplayValues<'a> {
613 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614 for (i, val) in self.0.iter().enumerate() {
615 if i == 0 {
616 write!(f, "{val}")?;
617 } else {
618 write!(f, ", {val}")?;
619 }
620 }
621 Ok(())
622 }
623}
624
625#[cfg(test)]
626mod tests {
627 use crate::cursor::{Cursor, CursorPosition, FuncCursor};
628 use crate::ir::types;
629 use crate::ir::{Function, InstBuilder, StackSlotData, StackSlotKind, UserFuncName};
630 use alloc::string::ToString;
631
632 #[test]
633 fn basic() {
634 let mut f = Function::new();
635 assert_eq!(f.to_string(), "function u0:0() fast {\n}\n");
636
637 f.name = UserFuncName::testcase("foo");
638 assert_eq!(f.to_string(), "function %foo() fast {\n}\n");
639
640 f.create_sized_stack_slot(StackSlotData::new(StackSlotKind::ExplicitSlot, 4, 0));
641 assert_eq!(
642 f.to_string(),
643 "function %foo() fast {\n ss0 = explicit_slot 4\n}\n"
644 );
645
646 let block = f.dfg.make_block();
647 f.layout.append_block(block);
648 assert_eq!(
649 f.to_string(),
650 "function %foo() fast {\n ss0 = explicit_slot 4\n\nblock0:\n}\n"
651 );
652
653 f.dfg.append_block_param(block, types::I8);
654 assert_eq!(
655 f.to_string(),
656 "function %foo() fast {\n ss0 = explicit_slot 4\n\nblock0(v0: i8):\n}\n"
657 );
658
659 f.dfg.append_block_param(block, types::F32.by(4).unwrap());
660 assert_eq!(
661 f.to_string(),
662 "function %foo() fast {\n ss0 = explicit_slot 4\n\nblock0(v0: i8, v1: f32x4):\n}\n"
663 );
664
665 {
666 let mut cursor = FuncCursor::new(&mut f);
667 cursor.set_position(CursorPosition::After(block));
668 cursor.ins().return_(&[])
669 };
670 assert_eq!(
671 f.to_string(),
672 "function %foo() fast {\n ss0 = explicit_slot 4\n\nblock0(v0: i8, v1: f32x4):\n return\n}\n"
673 );
674
675 let mut f = Function::new();
676 f.create_sized_stack_slot(StackSlotData::new(StackSlotKind::ExplicitSlot, 4, 2));
677 assert_eq!(
678 f.to_string(),
679 "function u0:0() fast {\n ss0 = explicit_slot 4, align = 4\n}\n"
680 );
681 }
682
683 #[test]
684 fn aliases() {
685 use crate::ir::InstBuilder;
686
687 let mut func = Function::new();
688 {
689 let block0 = func.dfg.make_block();
690 let mut pos = FuncCursor::new(&mut func);
691 pos.insert_block(block0);
692
693 let v0 = pos.func.dfg.append_block_param(block0, types::I32);
695 let v1 = pos.func.dfg.append_block_param(block0, types::I32);
696 let v2 = pos.func.dfg.append_block_param(block0, types::I32);
697 pos.func.dfg.detach_block_params(block0);
698
699 let v3 = pos.func.dfg.append_block_param(block0, types::I32);
701 pos.func.dfg.change_to_alias(v0, v3);
702
703 pos.func.dfg.make_value_alias_for_serialization(v0, v2); let _dummy0 = pos.ins().iconst(types::I32, 42);
708 let v4 = pos.ins().iadd(v0, v0);
709 pos.func.dfg.change_to_alias(v1, v4);
710 let _dummy1 = pos.ins().iconst(types::I32, 23);
711 let _v7 = pos.ins().iadd(v1, v1);
712 }
713 assert_eq!(
714 func.to_string(),
715 "function u0:0() fast {\nblock0(v3: i32):\n v0 -> v3\n v2 -> v0\n v4 = iconst.i32 42\n v5 = iadd v0, v0\n v1 -> v5\n v6 = iconst.i32 23\n v7 = iadd v1, v1\n}\n"
716 );
717 }
718
719 #[test]
720 fn cold_blocks() {
721 let mut func = Function::new();
722 {
723 let mut pos = FuncCursor::new(&mut func);
724
725 let block0 = pos.func.dfg.make_block();
726 pos.insert_block(block0);
727 pos.func.layout.set_cold(block0);
728
729 let block1 = pos.func.dfg.make_block();
730 pos.insert_block(block1);
731 pos.func.dfg.append_block_param(block1, types::I32);
732 pos.func.layout.set_cold(block1);
733 }
734
735 assert_eq!(
736 func.to_string(),
737 "function u0:0() fast {\nblock0 cold:\n\nblock1(v0: i32) cold:\n}\n"
738 );
739 }
740}