Debian Codegraph @

mypyc/ir/pprint.py

raw
1 """Utilities for pretty-printing IR in a human-readable form."""
2
3 from __future__ import annotations
4
5 from collections import defaultdict
6 from collections.abc import Sequence
7 from typing import Any, Final
8
9 from mypyc.common import short_name
10 from mypyc.ir.func_ir import FuncIR, all_values_full
11 from mypyc.ir.module_ir import ModuleIRs
12 from mypyc.ir.ops import (
13 ERR_NEVER,
14 Assign,
15 AssignMulti,
16 BasicBlock,
17 Box,
18 Branch,
19 Call,
20 CallC,
21 Cast,
22 ComparisonOp,
23 ControlOp,
24 CString,
25 DecRef,
26 Extend,
27 Float,
28 FloatComparisonOp,
29 FloatNeg,
30 FloatOp,
31 GetAttr,
32 GetElement,
33 GetElementPtr,
34 Goto,
35 IncRef,
36 InitStatic,
37 Integer,
38 IntOp,
39 KeepAlive,
40 LoadAddress,
41 LoadErrorValue,
42 LoadGlobal,
43 LoadLiteral,
44 LoadMem,
45 LoadStatic,
46 MethodCall,
47 Op,
48 OpVisitor,
49 PrimitiveOp,
50 RaiseStandardError,
51 Register,
52 Return,
53 SetAttr,
54 SetElement,
55 SetMem,
56 Truncate,
57 TupleGet,
58 TupleSet,
59 Unborrow,
60 Unbox,
61 Undef,
62 Unreachable,
63 Value,
64 )
65 from mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive
66
67 ErrorSource = BasicBlock | Op
68
69
70 class IRPrettyPrintVisitor(OpVisitor[str]):
71 """Internal visitor that pretty-prints ops."""
72
73 def __init__(self, names: dict[Value, str]) -> None:
74 # This should contain a name for all values that are shown as
75 # registers in the output. This is not just for Register
76 # instances -- all Ops that produce values need (generated) names.
77 self.names = names
78
79 def visit_goto(self, op: Goto) -> str:
80 return self.format("goto %l", op.label)
81
82 branch_op_names: Final = {Branch.BOOL: ("%r", "bool"), Branch.IS_ERROR: ("is_error(%r)", "")}
83
84 def visit_branch(self, op: Branch) -> str:
85 fmt, typ = self.branch_op_names[op.op]
86 if op.negated:
87 fmt = f"not {fmt}"
88
89 cond = self.format(fmt, op.value)
90 tb = ""
91 if op.traceback_entry:
92 tb = " (error at %s:%d)" % op.traceback_entry
93 fmt = f"if {cond} goto %l{tb} else goto %l"
94 if typ:
95 fmt += f" :: {typ}"
96 return self.format(fmt, op.true, op.false)
97
98 def visit_return(self, op: Return) -> str:
99 return self.format("return %r", op.value)
100
101 def visit_unreachable(self, op: Unreachable) -> str:
102 return "unreachable"
103
104 def visit_assign(self, op: Assign) -> str:
105 return self.format("%r = %r", op.dest, op.src)
106
107 def visit_assign_multi(self, op: AssignMulti) -> str:
108 return self.format("%r = [%s]", op.dest, ", ".join(self.format("%r", v) for v in op.src))
109
110 def visit_load_error_value(self, op: LoadErrorValue) -> str:
111 return self.format("%r = <error> :: %s", op, op.type)
112
113 def visit_load_literal(self, op: LoadLiteral) -> str:
114 prefix = ""
115 # For values that have a potential unboxed representation, make
116 # it explicit that this is a Python object.
117 if isinstance(op.value, int):
118 prefix = "object "
119
120 rvalue = repr(op.value)
121 if isinstance(op.value, frozenset):
122 # We need to generate a string representation that won't vary
123 # run-to-run because sets are unordered, otherwise we may get
124 # spurious irbuild test failures.
125 #
126 # Sorting by the item's string representation is a bit of a
127 # hack, but it's stable and won't cause TypeErrors.
128 formatted_items = [repr(i) for i in sorted(op.value, key=str)]
129 rvalue = "frozenset({" + ", ".join(formatted_items) + "})"
130 return self.format("%r = %s%s", op, prefix, rvalue)
131
132 def visit_get_attr(self, op: GetAttr) -> str:
133 return self.format("%r = %s%r.%s", op, self.borrow_prefix(op), op.obj, op.attr)
134
135 def borrow_prefix(self, op: Op) -> str:
136 if op.is_borrowed:
137 return "borrow "
138 return ""
139
140 def visit_set_attr(self, op: SetAttr) -> str:
141 if op.is_init:
142 assert op.error_kind == ERR_NEVER
143 if op.error_kind == ERR_NEVER:
144 # Initialization and direct struct access can never fail
145 return self.format("%r.%s = %r", op.obj, op.attr, op.src)
146 else:
147 return self.format("%r.%s = %r; %r = is_error", op.obj, op.attr, op.src, op)
148
149 def visit_load_static(self, op: LoadStatic) -> str:
150 ann = f" ({repr(op.ann)})" if op.ann else ""
151 name = op.identifier
152 if op.module_name is not None:
153 name = f"{op.module_name}.{name}"
154 return self.format("%r = %s :: %s%s", op, name, op.namespace, ann)
155
156 def visit_init_static(self, op: InitStatic) -> str:
157 name = op.identifier
158 if op.module_name is not None:
159 name = f"{op.module_name}.{name}"
160 return self.format("%s = %r :: %s", name, op.value, op.namespace)
161
162 def visit_tuple_get(self, op: TupleGet) -> str:
163 return self.format("%r = %s%r[%d]", op, self.borrow_prefix(op), op.src, op.index)
164
165 def visit_tuple_set(self, op: TupleSet) -> str:
166 item_str = ", ".join(self.format("%r", item) for item in op.items)
167 return self.format("%r = (%s)", op, item_str)
168
169 def visit_inc_ref(self, op: IncRef) -> str:
170 s = self.format("inc_ref %r", op.src)
171 # TODO: Remove bool check (it's unboxed)
172 if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
173 s += f" :: {short_name(op.src.type.name)}"
174 return s
175
176 def visit_dec_ref(self, op: DecRef) -> str:
177 s = self.format("%sdec_ref %r", "x" if op.is_xdec else "", op.src)
178 # TODO: Remove bool check (it's unboxed)
179 if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
180 s += f" :: {short_name(op.src.type.name)}"
181 return s
182
183 def visit_call(self, op: Call) -> str:
184 args = ", ".join(self.format("%r", arg) for arg in op.args)
185 # TODO: Display long name?
186 short_name = op.fn.shortname
187 s = f"{short_name}({args})"
188 if not op.is_void:
189 s = self.format("%r = ", op) + s
190 return s
191
192 def visit_method_call(self, op: MethodCall) -> str:
193 args = ", ".join(self.format("%r", arg) for arg in op.args)
194 s = self.format("%r.%s(%s)", op.obj, op.method, args)
195 if not op.is_void:
196 s = self.format("%r = ", op) + s
197 return s
198
199 def visit_cast(self, op: Cast) -> str:
200 if op.is_unchecked:
201 prefix = "unchecked "
202 else:
203 prefix = ""
204 return self.format(
205 "%r = %s%scast(%s, %r)", op, prefix, self.borrow_prefix(op), op.type, op.src
206 )
207
208 def visit_box(self, op: Box) -> str:
209 return self.format("%r = box(%s, %r)", op, op.src.type, op.src)
210
211 def visit_unbox(self, op: Unbox) -> str:
212 return self.format("%r = unbox(%s, %r)", op, op.type, op.src)
213
214 def visit_raise_standard_error(self, op: RaiseStandardError) -> str:
215 if op.value is not None:
216 if isinstance(op.value, str):
217 return self.format("%r = raise %s(%s)", op, op.class_name, repr(op.value))
218 elif isinstance(op.value, Value):
219 return self.format("%r = raise %s(%r)", op, op.class_name, op.value)
220 else:
221 assert False, "value type must be either str or Value"
222 else:
223 return self.format("%r = raise %s", op, op.class_name)
224
225 def visit_call_c(self, op: CallC) -> str:
226 args_str = ", ".join(self.format("%r", arg) for arg in op.args)
227 if op.is_void:
228 return self.format("%s(%s)", op.function_name, args_str)
229 else:
230 return self.format("%r = %s(%s)", op, op.function_name, args_str)
231
232 def visit_primitive_op(self, op: PrimitiveOp) -> str:
233 args_str = ", ".join(self.format("%r", arg) for arg in op.args)
234 if op.type_args:
235 joined = ", ".join(str(arg) for arg in op.type_args)
236 type_args = f"[{joined}]"
237 else:
238 type_args = ""
239 if op.is_void:
240 return self.format("%s%s %s", op.desc.name, type_args, args_str)
241 else:
242 return self.format("%r = %s%s %s", op, op.desc.name, type_args, args_str)
243
244 def visit_truncate(self, op: Truncate) -> str:
245 return self.format("%r = truncate %r: %t to %t", op, op.src, op.src_type, op.type)
246
247 def visit_extend(self, op: Extend) -> str:
248 if op.signed:
249 extra = " signed"
250 else:
251 extra = ""
252 return self.format("%r = extend%s %r: %t to %t", op, extra, op.src, op.src_type, op.type)
253
254 def visit_load_global(self, op: LoadGlobal) -> str:
255 ann = f" ({repr(op.ann)})" if op.ann else ""
256 return self.format("%r = load_global %s :: static%s", op, op.identifier, ann)
257
258 def visit_int_op(self, op: IntOp) -> str:
259 return self.format("%r = %r %s %r", op, op.lhs, IntOp.op_str[op.op], op.rhs)
260
261 def visit_comparison_op(self, op: ComparisonOp) -> str:
262 if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):
263 sign_format = " :: signed"
264 elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):
265 sign_format = " :: unsigned"
266 else:
267 sign_format = ""
268 return self.format(
269 "%r = %r %s %r%s", op, op.lhs, ComparisonOp.op_str[op.op], op.rhs, sign_format
270 )
271
272 def visit_float_op(self, op: FloatOp) -> str:
273 return self.format("%r = %r %s %r", op, op.lhs, FloatOp.op_str[op.op], op.rhs)
274
275 def visit_float_neg(self, op: FloatNeg) -> str:
276 return self.format("%r = -%r", op, op.src)
277
278 def visit_float_comparison_op(self, op: FloatComparisonOp) -> str:
279 return self.format("%r = %r %s %r", op, op.lhs, op.op_str[op.op], op.rhs)
280
281 def visit_load_mem(self, op: LoadMem) -> str:
282 return self.format(
283 "%r = %sload_mem %r :: %t*", op, self.borrow_prefix(op), op.src, op.type
284 )
285
286 def visit_set_mem(self, op: SetMem) -> str:
287 return self.format("set_mem %r, %r :: %t*", op.dest, op.src, op.dest_type)
288
289 def visit_get_element(self, op: GetElement) -> str:
290 return self.format("%r = %r.%s", op, op.src, op.field)
291
292 def visit_get_element_ptr(self, op: GetElementPtr) -> str:
293 return self.format("%r = get_element_ptr %r %s :: %t", op, op.src, op.field, op.src_type)
294
295 def visit_set_element(self, op: SetElement) -> str:
296 return self.format("%r = set_element %r, %s, %r", op, op.src, op.field, op.item)
297
298 def visit_load_address(self, op: LoadAddress) -> str:
299 if isinstance(op.src, Register):
300 return self.format("%r = load_address %r", op, op.src)
301 elif isinstance(op.src, LoadStatic):
302 name = op.src.identifier
303 if op.src.module_name is not None:
304 name = f"{op.src.module_name}.{name}"
305 return self.format("%r = load_address %s :: %s", op, name, op.src.namespace)
306 else:
307 return self.format("%r = load_address %s", op, op.src)
308
309 def visit_keep_alive(self, op: KeepAlive) -> str:
310 if op.steal:
311 steal = "steal "
312 else:
313 steal = ""
314 return self.format(
315 "keep_alive {}{}".format(steal, ", ".join(self.format("%r", v) for v in op.src))
316 )
317
318 def visit_unborrow(self, op: Unborrow) -> str:
319 return self.format("%r = unborrow %r", op, op.src)
320
321 # Helpers
322
323 def format(self, fmt: str, *args: Any) -> str:
324 """Helper for formatting strings.
325
326 These format sequences are supported in fmt:
327
328 %s: arbitrary object converted to string using str()
329 %r: name of IR value/register
330 %d: int
331 %f: float
332 %l: BasicBlock (formatted as label 'Ln')
333 %t: RType
334 """
335 result = []
336 i = 0
337 arglist = list(args)
338 while i < len(fmt):
339 n = fmt.find("%", i)
340 if n < 0:
341 n = len(fmt)
342 result.append(fmt[i:n])
343 if n < len(fmt):
344 typespec = fmt[n + 1]
345 arg = arglist.pop(0)
346 if typespec == "r":
347 # Register/value
348 assert isinstance(arg, Value)
349 if isinstance(arg, Integer):
350 result.append(str(arg.value))
351 elif isinstance(arg, Float):
352 result.append(repr(arg.value))
353 elif isinstance(arg, CString):
354 result.append(f"CString({arg.value!r})")
355 elif isinstance(arg, Undef):
356 result.append(f"undef {arg.type.name}")
357 else:
358 result.append(self.names[arg])
359 elif typespec == "d":
360 # Integer
361 result.append("%d" % arg)
362 elif typespec == "f":
363 # Float
364 result.append("%f" % arg)
365 elif typespec == "l":
366 # Basic block (label)
367 assert isinstance(arg, BasicBlock)
368 result.append("L%s" % arg.label)
369 elif typespec == "t":
370 # RType
371 assert isinstance(arg, RType)
372 result.append(arg.name)
373 elif typespec == "s":
374 # String
375 result.append(str(arg))
376 else:
377 raise ValueError(f"Invalid format sequence %{typespec}")
378 i = n + 2
379 else:
380 i = n
381 return "".join(result)
382
383
384 def format_registers(func_ir: FuncIR, names: dict[Value, str]) -> list[str]:
385 result = []
386 i = 0
387 regs = all_values_full(func_ir.arg_regs, func_ir.blocks)
388 while i < len(regs):
389 i0 = i
390 group = [names[regs[i0]]]
391 while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type:
392 i += 1
393 group.append(names[regs[i]])
394 i += 1
395 result.append("{} :: {}".format(", ".join(group), regs[i0].type))
396 return result
397
398
399 def format_blocks(
400 blocks: list[BasicBlock],
401 names: dict[Value, str],
402 source_to_error: dict[ErrorSource, list[str]],
403 ) -> list[str]:
404 """Format a list of IR basic blocks into a human-readable form."""
405 # First label all of the blocks
406 for i, block in enumerate(blocks):
407 block.label = i
408
409 handler_map: dict[BasicBlock, list[BasicBlock]] = {}
410 for b in blocks:
411 if b.error_handler:
412 handler_map.setdefault(b.error_handler, []).append(b)
413
414 visitor = IRPrettyPrintVisitor(names)
415
416 lines = []
417 for i, block in enumerate(blocks):
418 handler_msg = ""
419 if block in handler_map:
420 labels = sorted("L%d" % b.label for b in handler_map[block])
421 handler_msg = " (handler for {})".format(", ".join(labels))
422
423 lines.append("L%d:%s" % (block.label, handler_msg))
424 if block in source_to_error:
425 for error in source_to_error[block]:
426 lines.append(f" ERROR: {error}")
427 ops = block.ops
428 if (
429 isinstance(ops[-1], Goto)
430 and i + 1 < len(blocks)
431 and ops[-1].label == blocks[i + 1]
432 and not source_to_error.get(ops[-1], [])
433 ):
434 # Hide the last goto if it just goes to the next basic block,
435 # and there are no assocatiated errors with the op.
436 ops = ops[:-1]
437 for op in ops:
438 line = " " + op.accept(visitor)
439 lines.append(line)
440 if op in source_to_error:
441 first = len(lines) - 1
442 # Use emojis to highlight the error
443 for error in source_to_error[op]:
444 lines.append(f" \U0001f446 ERROR: {error}")
445 lines[first] = " \U0000274c " + lines[first][4:]
446
447 if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)):
448 # Each basic block needs to exit somewhere.
449 lines.append(" [MISSING BLOCK EXIT OPCODE]")
450 return lines
451
452
453 def format_func(fn: FuncIR, errors: Sequence[tuple[ErrorSource, str]] = ()) -> list[str]:
454 lines = []
455 cls_prefix = fn.class_name + "." if fn.class_name else ""
456 lines.append(
457 "def {}{}({}):".format(cls_prefix, fn.name, ", ".join(arg.name for arg in fn.args))
458 )
459 names = generate_names_for_ir(fn.arg_regs, fn.blocks)
460 for line in format_registers(fn, names):
461 lines.append(" " + line)
462
463 source_to_error = defaultdict(list)
464 for source, error in errors:
465 source_to_error[source].append(error)
466
467 code = format_blocks(fn.blocks, names, source_to_error)
468 lines.extend(code)
469 return lines
470
471
472 def format_modules(modules: ModuleIRs) -> list[str]:
473 ops = []
474 for module in modules.values():
475 for fn in module.functions:
476 ops.extend(format_func(fn))
477 ops.append("")
478 return ops
479
480
481 def generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]:
482 """Generate unique names for IR values.
483
484 Give names such as 'r5' to temp values in IR which are useful when
485 pretty-printing or generating C. Ensure generated names are unique.
486 """
487 names: dict[Value, str] = {}
488 used_names = set()
489
490 temp_index = 0
491
492 for arg in args:
493 names[arg] = arg.name
494 used_names.add(arg.name)
495
496 for block in blocks:
497 for op in block.ops:
498 values = []
499
500 for source in op.sources():
501 if source not in names:
502 values.append(source)
503
504 if isinstance(op, (Assign, AssignMulti)):
505 values.append(op.dest)
506 elif isinstance(op, ControlOp) or op.is_void:
507 continue
508 elif op not in names:
509 values.append(op)
510
511 for value in values:
512 if value in names:
513 continue
514 if isinstance(value, Register) and value.name:
515 name = value.name
516 elif isinstance(value, (Integer, Float, Undef)):
517 continue
518 else:
519 name = "r%d" % temp_index
520 temp_index += 1
521
522 # Append _2, _3, ... if needed to make the name unique.
523 if name in used_names:
524 n = 2
525 while True:
526 candidate = "%s_%d" % (name, n)
527 if candidate not in used_names:
528 name = candidate
529 break
530 n += 1
531
532 names[value] = name
533 used_names.add(name)
534
535 return names