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