Debian Codegraph @

mypyc/analysis/attrdefined.py

raw
1 """Always defined attribute analysis.
2
3 An always defined attribute has some statements in __init__ or the
4 class body that cause the attribute to be always initialized when an
5 instance is constructed. It must also not be possible to read the
6 attribute before initialization, and it can't be deletable.
7
8 We can assume that the value is always defined when reading an always
9 defined attribute. Otherwise we'll need to raise AttributeError if the
10 value is undefined (i.e. has the error value).
11
12 We use data flow analysis to figure out attributes that are always
13 defined. Example:
14
15 class C:
16 def __init__(self) -> None:
17 self.x = 0
18 if func():
19 self.y = 1
20 else:
21 self.y = 2
22 self.z = 3
23
24 In this example, the attributes 'x' and 'y' are always defined, but 'z'
25 is not. The analysis assumes that we know that there won't be any subclasses.
26
27 The analysis also works if there is a known, closed set of subclasses.
28 An attribute defined in a base class can only be always defined if it's
29 also always defined in all subclasses.
30
31 As soon as __init__ contains an op that can 'leak' self to another
32 function, we will stop inferring always defined attributes, since the
33 analysis is mostly intra-procedural and only looks at __init__ methods.
34 The called code could read an uninitialized attribute. Example:
35
36 class C:
37 def __init__(self) -> None:
38 self.x = self.foo()
39
40 def foo(self) -> int:
41 ...
42
43 Now we won't infer 'x' as always defined, since 'foo' might read 'x'
44 before initialization.
45
46 As an exception to the above limitation, we perform inter-procedural
47 analysis of super().__init__ calls, since these are very common.
48
49 Our analysis is somewhat optimistic. We assume that nobody calls a
50 method of a partially uninitialized object through gc.get_objects(), in
51 particular. Code like this could potentially cause a segfault with a null
52 pointer dereference. This seems very unlikely to be an issue in practice,
53 however.
54
55 Accessing an attribute via getattr always checks for undefined attributes
56 and thus works if the object is partially uninitialized. This can be used
57 as a workaround if somebody ever needs to inspect partially uninitialized
58 objects via gc.get_objects().
59
60 The analysis runs after IR building as a separate pass. Since we only
61 run this on __init__ methods, this analysis pass will be fairly quick.
62 """
63
64 from __future__ import annotations
65
66 from typing import Final
67
68 from mypyc.analysis.dataflow import (
69 CFG,
70 MAYBE_ANALYSIS,
71 AnalysisResult,
72 BaseAnalysisVisitor,
73 get_cfg,
74 run_analysis,
75 )
76 from mypyc.analysis.selfleaks import analyze_self_leaks
77 from mypyc.ir.class_ir import ClassIR
78 from mypyc.ir.ops import (
79 Assign,
80 AssignMulti,
81 BasicBlock,
82 Branch,
83 Call,
84 ControlOp,
85 GetAttr,
86 Register,
87 RegisterOp,
88 Return,
89 SetAttr,
90 SetMem,
91 Unreachable,
92 )
93 from mypyc.ir.rtypes import RInstance
94
95 # If True, print out all always-defined attributes of native classes (to aid
96 # debugging and testing)
97 dump_always_defined: Final = False
98
99
100 def analyze_always_defined_attrs(class_irs: list[ClassIR]) -> None:
101 """Find always defined attributes all classes of a compilation unit.
102
103 Also tag attribute initialization ops to not decref the previous
104 value (as this would read a NULL pointer and segfault).
105
106 Update the _always_initialized_attrs, _sometimes_initialized_attrs
107 and init_self_leak attributes in ClassIR instances.
108
109 This is the main entry point.
110 """
111 seen: set[ClassIR] = set()
112
113 # First pass: only look at target class and classes in MRO
114 for cl in class_irs:
115 analyze_always_defined_attrs_in_class(cl, seen)
116
117 # Second pass: look at all derived class
118 seen = set()
119 for cl in class_irs:
120 update_always_defined_attrs_using_subclasses(cl, seen)
121
122 # Final pass: detect attributes that need to use a bitmap to track definedness
123 seen = set()
124 for cl in class_irs:
125 detect_undefined_bitmap(cl, seen)
126
127
128 def analyze_always_defined_attrs_in_class(cl: ClassIR, seen: set[ClassIR]) -> None:
129 if cl in seen:
130 return
131
132 seen.add(cl)
133
134 if (
135 cl.is_trait
136 or cl.inherits_python
137 or cl.allow_interpreted_subclasses
138 or cl.builtin_base is not None
139 or cl.children is None
140 or cl.is_serializable()
141 or cl.has_method("__new__")
142 ):
143 # Give up -- we can't enforce that attributes are always defined.
144 return
145
146 # First analyze all base classes. Track seen classes to avoid duplicate work.
147 for base in cl.mro[1:]:
148 analyze_always_defined_attrs_in_class(base, seen)
149
150 m = cl.get_method("__init__")
151 if m is None:
152 cl._always_initialized_attrs = cl.attrs_with_defaults.copy()
153 cl._sometimes_initialized_attrs = cl.attrs_with_defaults.copy()
154 return
155 self_reg = m.arg_regs[0]
156 cfg = get_cfg(m.blocks)
157 dirty = analyze_self_leaks(m.blocks, self_reg, cfg)
158 maybe_defined = analyze_maybe_defined_attrs_in_init(
159 m.blocks, self_reg, cl.attrs_with_defaults, cfg
160 )
161 all_attrs: set[str] = set()
162 for base in cl.mro:
163 all_attrs.update(base.attributes)
164 maybe_undefined = analyze_maybe_undefined_attrs_in_init(
165 m.blocks, self_reg, initial_undefined=all_attrs - cl.attrs_with_defaults, cfg=cfg
166 )
167
168 always_defined = find_always_defined_attributes(
169 m.blocks, self_reg, all_attrs, maybe_defined, maybe_undefined, dirty
170 )
171 always_defined = {a for a in always_defined if not cl.is_deletable(a)}
172
173 cl._always_initialized_attrs = always_defined
174 if dump_always_defined:
175 print(cl.name, sorted(always_defined))
176 cl._sometimes_initialized_attrs = find_sometimes_defined_attributes(
177 m.blocks, self_reg, maybe_defined, dirty
178 )
179
180 mark_attr_initialization_ops(m.blocks, self_reg, maybe_defined, dirty)
181
182 # Check if __init__ can run unpredictable code (leak 'self').
183 any_dirty = False
184 for b in m.blocks:
185 for i, op in enumerate(b.ops):
186 if dirty.after[b, i] and not isinstance(op, Return):
187 any_dirty = True
188 break
189 cl.init_self_leak = any_dirty
190
191
192 def find_always_defined_attributes(
193 blocks: list[BasicBlock],
194 self_reg: Register,
195 all_attrs: set[str],
196 maybe_defined: AnalysisResult[str],
197 maybe_undefined: AnalysisResult[str],
198 dirty: AnalysisResult[None],
199 ) -> set[str]:
200 """Find attributes that are always initialized in some basic blocks.
201
202 The analysis results are expected to be up-to-date for the blocks.
203
204 Return a set of always defined attributes.
205 """
206 attrs = all_attrs.copy()
207 for block in blocks:
208 for i, op in enumerate(block.ops):
209 # If an attribute we *read* may be undefined, it isn't always defined.
210 if isinstance(op, GetAttr) and op.obj is self_reg:
211 if op.attr in maybe_undefined.before[block, i]:
212 attrs.discard(op.attr)
213 # If an attribute we *set* may be sometimes undefined and
214 # sometimes defined, don't consider it always defined. Unlike
215 # the get case, it's fine for the attribute to be undefined.
216 # The set operation will then be treated as initialization.
217 if isinstance(op, SetAttr) and op.obj is self_reg:
218 if (
219 op.attr in maybe_undefined.before[block, i]
220 and op.attr in maybe_defined.before[block, i]
221 ):
222 attrs.discard(op.attr)
223 # Treat an op that might run arbitrary code as an "exit"
224 # in terms of the analysis -- we can't do any inference
225 # afterwards reliably.
226 if dirty.after[block, i]:
227 if not dirty.before[block, i]:
228 attrs = attrs & (
229 maybe_defined.after[block, i] - maybe_undefined.after[block, i]
230 )
231 break
232 if isinstance(op, ControlOp):
233 for target in op.targets():
234 # Gotos/branches can also be "exits".
235 if not dirty.after[block, i] and dirty.before[target, 0]:
236 attrs = attrs & (
237 maybe_defined.after[target, 0] - maybe_undefined.after[target, 0]
238 )
239 return attrs
240
241
242 def find_sometimes_defined_attributes(
243 blocks: list[BasicBlock],
244 self_reg: Register,
245 maybe_defined: AnalysisResult[str],
246 dirty: AnalysisResult[None],
247 ) -> set[str]:
248 """Find attributes that are sometimes initialized in some basic blocks."""
249 attrs: set[str] = set()
250 for block in blocks:
251 for i, op in enumerate(block.ops):
252 # Only look at possibly defined attributes at exits.
253 if dirty.after[block, i]:
254 if not dirty.before[block, i]:
255 attrs = attrs | maybe_defined.after[block, i]
256 break
257 if isinstance(op, ControlOp):
258 for target in op.targets():
259 if not dirty.after[block, i] and dirty.before[target, 0]:
260 attrs = attrs | maybe_defined.after[target, 0]
261 return attrs
262
263
264 def mark_attr_initialization_ops(
265 blocks: list[BasicBlock],
266 self_reg: Register,
267 maybe_defined: AnalysisResult[str],
268 dirty: AnalysisResult[None],
269 ) -> None:
270 """Tag all SetAttr ops in the basic blocks that initialize attributes.
271
272 Initialization ops assume that the previous attribute value is the error value,
273 so there's no need to decref or check for definedness.
274 """
275 for block in blocks:
276 for i, op in enumerate(block.ops):
277 if isinstance(op, SetAttr) and op.obj is self_reg:
278 attr = op.attr
279 if attr not in maybe_defined.before[block, i] and not dirty.after[block, i]:
280 op.mark_as_initializer()
281
282
283 GenAndKill = tuple[set[str], set[str]]
284
285
286 def attributes_initialized_by_init_call(op: Call) -> set[str]:
287 """Calculate attributes that are always initialized by a super().__init__ call."""
288 self_type = op.fn.sig.args[0].type
289 assert isinstance(self_type, RInstance), self_type
290 cl = self_type.class_ir
291 return {a for base in cl.mro for a in base.attributes if base.is_always_defined(a)}
292
293
294 def attributes_maybe_initialized_by_init_call(op: Call) -> set[str]:
295 """Calculate attributes that may be initialized by a super().__init__ call."""
296 self_type = op.fn.sig.args[0].type
297 assert isinstance(self_type, RInstance), self_type
298 cl = self_type.class_ir
299 return attributes_initialized_by_init_call(op) | cl._sometimes_initialized_attrs
300
301
302 class AttributeMaybeDefinedVisitor(BaseAnalysisVisitor[str]):
303 """Find attributes that may have been defined via some code path.
304
305 Consider initializations in class body and assignments to 'self.x'
306 and calls to base class '__init__'.
307 """
308
309 def __init__(self, self_reg: Register) -> None:
310 self.self_reg = self_reg
311
312 def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]:
313 return set(), set()
314
315 def visit_return(self, op: Return) -> tuple[set[str], set[str]]:
316 return set(), set()
317
318 def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]:
319 return set(), set()
320
321 def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]:
322 if isinstance(op, SetAttr) and op.obj is self.self_reg:
323 return {op.attr}, set()
324 if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__":
325 return attributes_maybe_initialized_by_init_call(op), set()
326 return set(), set()
327
328 def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]:
329 return set(), set()
330
331 def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]:
332 return set(), set()
333
334 def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]:
335 return set(), set()
336
337
338 def analyze_maybe_defined_attrs_in_init(
339 blocks: list[BasicBlock], self_reg: Register, attrs_with_defaults: set[str], cfg: CFG
340 ) -> AnalysisResult[str]:
341 return run_analysis(
342 blocks=blocks,
343 cfg=cfg,
344 gen_and_kill=AttributeMaybeDefinedVisitor(self_reg),
345 initial=attrs_with_defaults,
346 backward=False,
347 kind=MAYBE_ANALYSIS,
348 )
349
350
351 class AttributeMaybeUndefinedVisitor(BaseAnalysisVisitor[str]):
352 """Find attributes that may be undefined via some code path.
353
354 Consider initializations in class body, assignments to 'self.x'
355 and calls to base class '__init__'.
356 """
357
358 def __init__(self, self_reg: Register) -> None:
359 self.self_reg = self_reg
360
361 def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]:
362 return set(), set()
363
364 def visit_return(self, op: Return) -> tuple[set[str], set[str]]:
365 return set(), set()
366
367 def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]:
368 return set(), set()
369
370 def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]:
371 if isinstance(op, SetAttr) and op.obj is self.self_reg:
372 return set(), {op.attr}
373 if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__":
374 return set(), attributes_initialized_by_init_call(op)
375 return set(), set()
376
377 def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]:
378 return set(), set()
379
380 def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]:
381 return set(), set()
382
383 def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]:
384 return set(), set()
385
386
387 def analyze_maybe_undefined_attrs_in_init(
388 blocks: list[BasicBlock], self_reg: Register, initial_undefined: set[str], cfg: CFG
389 ) -> AnalysisResult[str]:
390 return run_analysis(
391 blocks=blocks,
392 cfg=cfg,
393 gen_and_kill=AttributeMaybeUndefinedVisitor(self_reg),
394 initial=initial_undefined,
395 backward=False,
396 kind=MAYBE_ANALYSIS,
397 )
398
399
400 def update_always_defined_attrs_using_subclasses(cl: ClassIR, seen: set[ClassIR]) -> None:
401 """Remove attributes not defined in all subclasses from always defined attrs."""
402 if cl in seen:
403 return
404 if cl.children is None:
405 # Subclasses are unknown
406 return
407 removed = set()
408 for attr in cl._always_initialized_attrs:
409 for child in cl.children:
410 update_always_defined_attrs_using_subclasses(child, seen)
411 if attr not in child._always_initialized_attrs:
412 removed.add(attr)
413 cl._always_initialized_attrs -= removed
414 seen.add(cl)
415
416
417 def detect_undefined_bitmap(cl: ClassIR, seen: set[ClassIR]) -> None:
418 if cl.is_trait:
419 return
420
421 if cl in seen:
422 return
423 seen.add(cl)
424 for base in cl.base_mro[1:]:
425 detect_undefined_bitmap(base, seen)
426
427 # Build fresh and assign once. This function is called per SCC and `seen`
428 # only dedupes within a single call, so appending in place to a shared base
429 # would accumulate duplicates across SCCs and produce non-deterministic
430 # struct layouts under separate=True.
431 new_attrs: list[str] = []
432 if len(cl.base_mro) > 1:
433 new_attrs.extend(cl.base_mro[1].bitmap_attrs)
434 for n, t in cl.attributes.items():
435 if t.error_overlap and not cl.is_always_defined(n):
436 new_attrs.append(n)
437
438 for base in cl.mro[1:]:
439 if base.is_trait:
440 for n, t in base.attributes.items():
441 if t.error_overlap and not cl.is_always_defined(n) and n not in new_attrs:
442 new_attrs.append(n)
443 cl.bitmap_attrs = new_attrs