Debian Codegraph @

mypyc/analysis/ircheck.py

raw
1 """Utilities for checking that internal ir is valid and consistent."""
2
3 from __future__ import annotations
4
5 from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR
6 from mypyc.ir.ops import (
7 Assign,
8 AssignMulti,
9 BaseAssign,
10 BasicBlock,
11 Box,
12 Branch,
13 Call,
14 CallC,
15 Cast,
16 ComparisonOp,
17 ControlOp,
18 DecRef,
19 Extend,
20 Float,
21 FloatComparisonOp,
22 FloatNeg,
23 FloatOp,
24 GetAttr,
25 GetElement,
26 GetElementPtr,
27 Goto,
28 IncRef,
29 InitStatic,
30 Integer,
31 IntOp,
32 KeepAlive,
33 LoadAddress,
34 LoadErrorValue,
35 LoadGlobal,
36 LoadLiteral,
37 LoadMem,
38 LoadStatic,
39 MethodCall,
40 Op,
41 OpVisitor,
42 PrimitiveOp,
43 RaiseStandardError,
44 Register,
45 Return,
46 SetAttr,
47 SetElement,
48 SetMem,
49 Truncate,
50 TupleGet,
51 TupleSet,
52 Unborrow,
53 Unbox,
54 Undef,
55 Unreachable,
56 Value,
57 )
58 from mypyc.ir.pprint import format_func
59 from mypyc.ir.rtypes import (
60 KNOWN_NATIVE_TYPES,
61 RArray,
62 RInstance,
63 RPrimitive,
64 RType,
65 RUnion,
66 RVec,
67 bytes_rprimitive,
68 dict_rprimitive,
69 int_rprimitive,
70 is_c_py_ssize_t_rprimitive,
71 is_fixed_width_rtype,
72 is_float_rprimitive,
73 is_object_rprimitive,
74 is_pointer_rprimitive,
75 list_rprimitive,
76 pointer_rprimitive,
77 range_rprimitive,
78 set_rprimitive,
79 str_rprimitive,
80 tuple_rprimitive,
81 )
82
83
84 class FnError:
85 def __init__(self, source: Op | BasicBlock, desc: str) -> None:
86 self.source = source
87 self.desc = desc
88
89 def __eq__(self, other: object) -> bool:
90 return (
91 isinstance(other, FnError) and self.source == other.source and self.desc == other.desc
92 )
93
94 def __repr__(self) -> str:
95 return f"FnError(source={self.source}, desc={self.desc})"
96
97
98 def check_func_ir(fn: FuncIR) -> list[FnError]:
99 """Applies validations to a given function ir and returns a list of errors found."""
100 errors = []
101
102 op_set = set()
103
104 for block in fn.blocks:
105 if not block.terminated:
106 errors.append(
107 FnError(source=block.ops[-1] if block.ops else block, desc="Block not terminated")
108 )
109 for op in block.ops[:-1]:
110 if isinstance(op, ControlOp):
111 errors.append(FnError(source=op, desc="Block has operations after control op"))
112
113 if op in op_set:
114 errors.append(FnError(source=op, desc="Func has a duplicate op"))
115 op_set.add(op)
116
117 errors.extend(check_op_sources_valid(fn))
118 if errors:
119 return errors
120
121 op_checker = OpChecker(fn)
122 for block in fn.blocks:
123 for op in block.ops:
124 op.accept(op_checker)
125
126 return op_checker.errors
127
128
129 class IrCheckException(Exception):
130 pass
131
132
133 def assert_func_ir_valid(fn: FuncIR) -> None:
134 errors = check_func_ir(fn)
135 if errors:
136 raise IrCheckException(
137 "Internal error: Generated invalid IR: \n"
138 + "\n".join(format_func(fn, [(e.source, e.desc) for e in errors]))
139 )
140
141
142 def check_op_sources_valid(fn: FuncIR) -> list[FnError]:
143 errors = []
144 valid_ops: set[Op] = set()
145 valid_registers: set[Register] = set()
146
147 for block in fn.blocks:
148 valid_ops.update(block.ops)
149
150 for op in block.ops:
151 if isinstance(op, BaseAssign):
152 valid_registers.add(op.dest)
153 elif isinstance(op, LoadAddress) and isinstance(op.src, Register):
154 valid_registers.add(op.src)
155
156 valid_registers.update(fn.arg_regs)
157
158 for block in fn.blocks:
159 for op in block.ops:
160 for source in op.sources():
161 if isinstance(source, (Integer, Float, Undef)):
162 pass
163 elif isinstance(source, Op):
164 if source not in valid_ops:
165 errors.append(
166 FnError(
167 source=op,
168 desc=f"Invalid op reference to op of type {type(source).__name__}",
169 )
170 )
171 elif isinstance(source, Register):
172 if source not in valid_registers:
173 errors.append(
174 FnError(
175 source=op, desc=f"Invalid op reference to register {source.name!r}"
176 )
177 )
178
179 return errors
180
181
182 disjoint_types = {
183 int_rprimitive.name,
184 bytes_rprimitive.name,
185 str_rprimitive.name,
186 dict_rprimitive.name,
187 list_rprimitive.name,
188 set_rprimitive.name,
189 tuple_rprimitive.name,
190 range_rprimitive.name,
191 } | set(KNOWN_NATIVE_TYPES)
192
193
194 def can_coerce_to(src: RType, dest: RType) -> bool:
195 """Check if src can be assigned to dest_rtype.
196
197 Currently okay to have false positives.
198 """
199 if isinstance(dest, RUnion):
200 return any(can_coerce_to(src, d) for d in dest.items)
201
202 if isinstance(dest, RPrimitive):
203 if isinstance(src, RPrimitive):
204 # If either src or dest is a disjoint type, then they must both be.
205 if src.name in disjoint_types and dest.name in disjoint_types:
206 return src.name == dest.name
207 return src.size == dest.size
208 if isinstance(src, (RInstance, RVec)):
209 return is_object_rprimitive(dest)
210 if isinstance(src, RUnion):
211 # IR doesn't have the ability to narrow unions based on
212 # control flow, so cannot be a strict all() here.
213 return any(can_coerce_to(s, dest) for s in src.items)
214 return False
215
216 return True
217
218
219 def is_valid_ptr_displacement_type(rtype: RType) -> bool:
220 """Check if rtype is a valid displacement type for pointer arithmetic."""
221 if not (is_fixed_width_rtype(rtype) or is_c_py_ssize_t_rprimitive(rtype)):
222 return False
223 assert isinstance(rtype, RPrimitive)
224 return rtype.size == pointer_rprimitive.size
225
226
227 def is_pointer_arithmetic(op: IntOp) -> bool:
228 """Check if op is add/subtract targeting pointer_rprimitive and integer of the same size."""
229 if op.op not in (IntOp.ADD, IntOp.SUB):
230 return False
231 if not is_pointer_rprimitive(op.type):
232 return False
233 left = op.lhs.type
234 right = op.rhs.type
235 if is_pointer_rprimitive(left):
236 return is_valid_ptr_displacement_type(right)
237 if is_pointer_rprimitive(right):
238 return is_valid_ptr_displacement_type(left)
239 return False
240
241
242 class OpChecker(OpVisitor[None]):
243 def __init__(self, parent_fn: FuncIR) -> None:
244 self.parent_fn = parent_fn
245 self.errors: list[FnError] = []
246
247 def fail(self, source: Op, desc: str) -> None:
248 self.errors.append(FnError(source=source, desc=desc))
249
250 def check_control_op_targets(self, op: ControlOp) -> None:
251 for target in op.targets():
252 if target not in self.parent_fn.blocks:
253 self.fail(source=op, desc=f"Invalid control operation target: {target.label}")
254
255 def check_type_coercion(self, op: Op, src: RType, dest: RType) -> None:
256 if not can_coerce_to(src, dest):
257 self.fail(
258 source=op, desc=f"Cannot coerce source type {src.name} to dest type {dest.name}"
259 )
260
261 def check_compatibility(self, op: Op, t: RType, s: RType) -> None:
262 if not can_coerce_to(t, s) or not can_coerce_to(s, t):
263 self.fail(source=op, desc=f"{t.name} and {s.name} are not compatible")
264
265 def expect_float(self, op: Op, v: Value) -> None:
266 if not is_float_rprimitive(v.type):
267 self.fail(op, f"Float expected (actual type is {v.type})")
268
269 def expect_non_float(self, op: Op, v: Value) -> None:
270 if is_float_rprimitive(v.type):
271 self.fail(op, "Float not expected")
272
273 def expect_primitive_type(self, op: Op, v: Value) -> None:
274 if not isinstance(v.type, RPrimitive):
275 self.fail(op, f"RPrimitive expected, got {type(v.type).__name__}")
276
277 def visit_goto(self, op: Goto) -> None:
278 self.check_control_op_targets(op)
279
280 def visit_branch(self, op: Branch) -> None:
281 self.check_control_op_targets(op)
282
283 def visit_return(self, op: Return) -> None:
284 self.check_type_coercion(op, op.value.type, self.parent_fn.decl.sig.ret_type)
285
286 def visit_unreachable(self, op: Unreachable) -> None:
287 # Unreachables are checked at a higher level since validation
288 # requires access to the entire basic block.
289 pass
290
291 def visit_assign(self, op: Assign) -> None:
292 self.check_type_coercion(op, op.src.type, op.dest.type)
293
294 def visit_assign_multi(self, op: AssignMulti) -> None:
295 for src in op.src:
296 assert isinstance(op.dest.type, RArray)
297 self.check_type_coercion(op, src.type, op.dest.type.item_type)
298
299 def visit_load_error_value(self, op: LoadErrorValue) -> None:
300 # Currently it is assumed that all types have an error value.
301 # Once this is fixed we can validate that the rtype here actually
302 # has an error value.
303 pass
304
305 def check_tuple_items_valid_literals(self, op: LoadLiteral, t: tuple[object, ...]) -> None:
306 for x in t:
307 if x is not None and not isinstance(x, (str, bytes, bool, int, float, complex, tuple)):
308 self.fail(op, f"Invalid type for item of tuple literal: {type(x)})")
309 if isinstance(x, tuple):
310 self.check_tuple_items_valid_literals(op, x)
311
312 def check_frozenset_items_valid_literals(self, op: LoadLiteral, s: frozenset[object]) -> None:
313 for x in s:
314 if x is None or isinstance(x, (str, bytes, bool, int, float, complex)):
315 pass
316 elif isinstance(x, tuple):
317 self.check_tuple_items_valid_literals(op, x)
318 else:
319 self.fail(op, f"Invalid type for item of frozenset literal: {type(x)})")
320
321 def visit_load_literal(self, op: LoadLiteral) -> None:
322 expected_type = None
323 if op.value is None:
324 expected_type = "builtins.object"
325 elif isinstance(op.value, int):
326 expected_type = "builtins.int"
327 elif isinstance(op.value, str):
328 expected_type = "builtins.str"
329 elif isinstance(op.value, bytes):
330 expected_type = "builtins.bytes"
331 elif isinstance(op.value, float):
332 expected_type = "builtins.float"
333 elif isinstance(op.value, complex):
334 expected_type = "builtins.object"
335 elif isinstance(op.value, tuple):
336 expected_type = "builtins.tuple"
337 self.check_tuple_items_valid_literals(op, op.value)
338 elif isinstance(op.value, frozenset):
339 # There's no frozenset_rprimitive type since it'd be pretty useless so we just pretend
340 # it's a set (when it's really a frozenset).
341 expected_type = "builtins.set"
342 self.check_frozenset_items_valid_literals(op, op.value)
343
344 assert expected_type is not None, "Missed a case for LoadLiteral check"
345
346 if op.type.name not in [expected_type, "builtins.object"]:
347 self.fail(
348 op,
349 f"Invalid literal value for type: value has "
350 f"type {expected_type}, but op has type {op.type.name}",
351 )
352
353 def visit_get_attr(self, op: GetAttr) -> None:
354 # Nothing to do.
355 pass
356
357 def visit_set_attr(self, op: SetAttr) -> None:
358 # Nothing to do.
359 pass
360
361 # Static operations cannot be checked at the function level.
362 def visit_load_static(self, op: LoadStatic) -> None:
363 pass
364
365 def visit_init_static(self, op: InitStatic) -> None:
366 pass
367
368 def visit_tuple_get(self, op: TupleGet) -> None:
369 # Nothing to do.
370 pass
371
372 def visit_tuple_set(self, op: TupleSet) -> None:
373 # Nothing to do.
374 pass
375
376 def visit_inc_ref(self, op: IncRef) -> None:
377 # Nothing to do.
378 pass
379
380 def visit_dec_ref(self, op: DecRef) -> None:
381 # Nothing to do.
382 pass
383
384 def visit_call(self, op: Call) -> None:
385 # Length is checked in constructor, and return type is set
386 # in a way that can't be incorrect
387 for arg_value, arg_runtime in zip(op.args, op.fn.sig.args):
388 self.check_type_coercion(op, arg_value.type, arg_runtime.type)
389
390 def visit_method_call(self, op: MethodCall) -> None:
391 # Similar to above, but we must look up method first.
392 method_decl = op.receiver_type.class_ir.method_decl(op.method)
393 if method_decl.kind == FUNC_STATICMETHOD:
394 decl_index = 0
395 else:
396 decl_index = 1
397
398 if len(op.args) + decl_index != len(method_decl.sig.args):
399 self.fail(op, "Incorrect number of args for method call.")
400
401 # Skip the receiver argument (self)
402 for arg_value, arg_runtime in zip(op.args, method_decl.sig.args[decl_index:]):
403 self.check_type_coercion(op, arg_value.type, arg_runtime.type)
404
405 def visit_cast(self, op: Cast) -> None:
406 pass
407
408 def visit_box(self, op: Box) -> None:
409 pass
410
411 def visit_unbox(self, op: Unbox) -> None:
412 pass
413
414 def visit_raise_standard_error(self, op: RaiseStandardError) -> None:
415 pass
416
417 def visit_call_c(self, op: CallC) -> None:
418 pass
419
420 def visit_primitive_op(self, op: PrimitiveOp) -> None:
421 pass
422
423 def visit_truncate(self, op: Truncate) -> None:
424 pass
425
426 def visit_extend(self, op: Extend) -> None:
427 pass
428
429 def visit_load_global(self, op: LoadGlobal) -> None:
430 pass
431
432 def visit_int_op(self, op: IntOp) -> None:
433 self.expect_primitive_type(op, op.lhs)
434 self.expect_primitive_type(op, op.rhs)
435 self.expect_non_float(op, op.lhs)
436 self.expect_non_float(op, op.rhs)
437 left = op.lhs.type
438 right = op.rhs.type
439 op_str = op.op_str[op.op]
440 if (
441 isinstance(left, RPrimitive)
442 and isinstance(right, RPrimitive)
443 and left.is_signed != right.is_signed
444 and (
445 op_str in ("+", "-", "*", "/", "%")
446 or (op_str not in ("<<", ">>") and left.size != right.size)
447 )
448 and not is_pointer_arithmetic(op)
449 ):
450 self.fail(op, f"Operand types have incompatible signs: {left}, {right}")
451
452 def visit_comparison_op(self, op: ComparisonOp) -> None:
453 self.check_compatibility(op, op.lhs.type, op.rhs.type)
454 self.expect_non_float(op, op.lhs)
455 self.expect_non_float(op, op.rhs)
456 left = op.lhs.type
457 right = op.rhs.type
458 if (
459 isinstance(left, RPrimitive)
460 and isinstance(right, RPrimitive)
461 and left.is_signed != right.is_signed
462 ):
463 self.fail(op, f"Operand types have incompatible signs: {left}, {right}")
464
465 def visit_float_op(self, op: FloatOp) -> None:
466 self.expect_float(op, op.lhs)
467 self.expect_float(op, op.rhs)
468
469 def visit_float_neg(self, op: FloatNeg) -> None:
470 self.expect_float(op, op.src)
471
472 def visit_float_comparison_op(self, op: FloatComparisonOp) -> None:
473 self.expect_float(op, op.lhs)
474 self.expect_float(op, op.rhs)
475
476 def visit_load_mem(self, op: LoadMem) -> None:
477 pass
478
479 def visit_set_mem(self, op: SetMem) -> None:
480 pass
481
482 def visit_get_element(self, op: GetElement) -> None:
483 pass
484
485 def visit_get_element_ptr(self, op: GetElementPtr) -> None:
486 pass
487
488 def visit_set_element(self, op: SetElement) -> None:
489 pass
490
491 def visit_load_address(self, op: LoadAddress) -> None:
492 pass
493
494 def visit_keep_alive(self, op: KeepAlive) -> None:
495 pass
496
497 def visit_unborrow(self, op: Unborrow) -> None:
498 pass