| 1 |
"""Transformation for inserting refrecence count inc/dec opcodes. |
| 2 |
|
| 3 |
This transformation happens towards the end of compilation. Before this |
| 4 |
transformation, reference count management is not explicitly handled at all. |
| 5 |
By postponing this pass, the previous passes are simpler as they don't have |
| 6 |
to update reference count opcodes. |
| 7 |
|
| 8 |
The approach is to decrement reference counts soon after a value is no |
| 9 |
longer live, to quickly free memory (and call __del__ methods), though |
| 10 |
there are no strict guarantees -- other than that local variables are |
| 11 |
freed before return from a function. |
| 12 |
|
| 13 |
Function arguments are a little special. They are initially considered |
| 14 |
'borrowed' from the caller and their reference counts don't need to be |
| 15 |
decremented before returning. An assignment to a borrowed value turns it |
| 16 |
into a regular, owned reference that needs to freed before return. |
| 17 |
""" |
| 18 |
|
| 19 |
from __future__ import annotations |
| 20 |
|
| 21 |
from collections.abc import Iterable |
| 22 |
|
| 23 |
from mypyc.analysis.dataflow import ( |
| 24 |
AnalysisDict, |
| 25 |
analyze_borrowed_arguments, |
| 26 |
analyze_live_regs, |
| 27 |
analyze_must_defined_regs, |
| 28 |
cleanup_cfg, |
| 29 |
get_cfg, |
| 30 |
) |
| 31 |
from mypyc.ir.func_ir import FuncIR, all_values |
| 32 |
from mypyc.ir.ops import ( |
| 33 |
Assign, |
| 34 |
BasicBlock, |
| 35 |
Branch, |
| 36 |
CallC, |
| 37 |
ControlOp, |
| 38 |
DecRef, |
| 39 |
Goto, |
| 40 |
IncRef, |
| 41 |
Integer, |
| 42 |
KeepAlive, |
| 43 |
LoadAddress, |
| 44 |
Op, |
| 45 |
Register, |
| 46 |
RegisterOp, |
| 47 |
Undef, |
| 48 |
Value, |
| 49 |
) |
| 50 |
|
| 51 |
Decs = tuple[tuple[Value, bool], ...] |
| 52 |
Incs = tuple[Value, ...] |
| 53 |
|
| 54 |
# A cache of basic blocks that decrement and increment specific values |
| 55 |
# and then jump to some target block. This lets us cut down on how |
| 56 |
# much code we generate in some circumstances. |
| 57 |
BlockCache = dict[tuple[BasicBlock, Decs, Incs], BasicBlock] |
| 58 |
|
| 59 |
|
| 60 |
def insert_ref_count_opcodes(ir: FuncIR) -> None: |
| 61 |
"""Insert reference count inc/dec opcodes to a function. |
| 62 |
|
| 63 |
This is the entry point to this module. |
| 64 |
""" |
| 65 |
cfg = get_cfg(ir.blocks) |
| 66 |
values = all_values(ir.arg_regs, ir.blocks) |
| 67 |
|
| 68 |
borrowed = {value for value in values if value.is_borrowed} |
| 69 |
args: set[Value] = set(ir.arg_regs) |
| 70 |
live = analyze_live_regs(ir.blocks, cfg) |
| 71 |
borrow = analyze_borrowed_arguments(ir.blocks, cfg, borrowed) |
| 72 |
defined = analyze_must_defined_regs(ir.blocks, cfg, args, values, strict_errors=True) |
| 73 |
ordering = make_value_ordering(ir) |
| 74 |
cache: BlockCache = {} |
| 75 |
for block in ir.blocks.copy(): |
| 76 |
if isinstance(block.ops[-1], (Branch, Goto)): |
| 77 |
insert_branch_inc_and_decrefs( |
| 78 |
block, |
| 79 |
cache, |
| 80 |
ir.blocks, |
| 81 |
live.before, |
| 82 |
borrow.before, |
| 83 |
borrow.after, |
| 84 |
defined.after, |
| 85 |
ordering, |
| 86 |
) |
| 87 |
transform_block(block, live.before, live.after, borrow.before, defined.after) |
| 88 |
|
| 89 |
cleanup_cfg(ir.blocks) |
| 90 |
|
| 91 |
|
| 92 |
def is_maybe_undefined(post_must_defined: set[Value], src: Value) -> bool: |
| 93 |
return (isinstance(src, Register) and src not in post_must_defined) or ( |
| 94 |
isinstance(src, CallC) and src.returns_null |
| 95 |
) |
| 96 |
|
| 97 |
|
| 98 |
def maybe_append_dec_ref( |
| 99 |
ops: list[Op], dest: Value, defined: AnalysisDict[Value], key: tuple[BasicBlock, int] |
| 100 |
) -> None: |
| 101 |
if dest.type.is_refcounted and not isinstance(dest, (Integer, Undef)): |
| 102 |
ops.append(DecRef(dest, is_xdec=is_maybe_undefined(defined[key], dest))) |
| 103 |
|
| 104 |
|
| 105 |
def maybe_append_inc_ref(ops: list[Op], dest: Value) -> None: |
| 106 |
if dest.type.is_refcounted: |
| 107 |
ops.append(IncRef(dest)) |
| 108 |
|
| 109 |
|
| 110 |
def transform_block( |
| 111 |
block: BasicBlock, |
| 112 |
pre_live: AnalysisDict[Value], |
| 113 |
post_live: AnalysisDict[Value], |
| 114 |
pre_borrow: AnalysisDict[Value], |
| 115 |
post_must_defined: AnalysisDict[Value], |
| 116 |
) -> None: |
| 117 |
old_ops = block.ops |
| 118 |
ops: list[Op] = [] |
| 119 |
for i, op in enumerate(old_ops): |
| 120 |
key = (block, i) |
| 121 |
|
| 122 |
assert op not in pre_live[key] |
| 123 |
dest = op.dest if isinstance(op, Assign) else op |
| 124 |
stolen = op.stolen() |
| 125 |
|
| 126 |
# Incref any references that are being stolen that stay live, were borrowed, |
| 127 |
# or are stolen more than once by this operation. |
| 128 |
for j, src in enumerate(stolen): |
| 129 |
if src in post_live[key] or src in pre_borrow[key] or src in stolen[:j]: |
| 130 |
maybe_append_inc_ref(ops, src) |
| 131 |
# For assignments to registers that were already live, |
| 132 |
# decref the old value. |
| 133 |
if dest not in pre_borrow[key] and dest in pre_live[key]: |
| 134 |
assert isinstance(op, Assign), op |
| 135 |
maybe_append_dec_ref(ops, dest, post_must_defined, key) |
| 136 |
|
| 137 |
# Strip KeepAlive. Its only purpose is to help with this transform. |
| 138 |
if not isinstance(op, KeepAlive): |
| 139 |
ops.append(op) |
| 140 |
|
| 141 |
# Control ops don't have any space to insert ops after them, so |
| 142 |
# their inc/decrefs get inserted by insert_branch_inc_and_decrefs. |
| 143 |
if isinstance(op, ControlOp): |
| 144 |
continue |
| 145 |
|
| 146 |
for src in op.unique_sources(): |
| 147 |
# Decrement source that won't be live afterwards. |
| 148 |
if src not in post_live[key] and src not in pre_borrow[key] and src not in stolen: |
| 149 |
maybe_append_dec_ref(ops, src, post_must_defined, key) |
| 150 |
# Decrement the destination if it is dead after the op and |
| 151 |
# wasn't a borrowed RegisterOp |
| 152 |
if ( |
| 153 |
not dest.is_void |
| 154 |
and dest not in post_live[key] |
| 155 |
and not (isinstance(op, RegisterOp) and dest.is_borrowed) |
| 156 |
): |
| 157 |
maybe_append_dec_ref(ops, dest, post_must_defined, key) |
| 158 |
block.ops = ops |
| 159 |
|
| 160 |
|
| 161 |
def insert_branch_inc_and_decrefs( |
| 162 |
block: BasicBlock, |
| 163 |
cache: BlockCache, |
| 164 |
blocks: list[BasicBlock], |
| 165 |
pre_live: AnalysisDict[Value], |
| 166 |
pre_borrow: AnalysisDict[Value], |
| 167 |
post_borrow: AnalysisDict[Value], |
| 168 |
post_must_defined: AnalysisDict[Value], |
| 169 |
ordering: dict[Value, int], |
| 170 |
) -> None: |
| 171 |
"""Insert inc_refs and/or dec_refs after a branch/goto. |
| 172 |
|
| 173 |
Add dec_refs for registers that become dead after a branch. |
| 174 |
Add inc_refs for registers that become unborrowed after a branch or goto. |
| 175 |
|
| 176 |
Branches are special as the true and false targets may have a different |
| 177 |
live and borrowed register sets. Add new blocks before the true/false target |
| 178 |
blocks that tweak reference counts. |
| 179 |
|
| 180 |
Example where we need to add an inc_ref: |
| 181 |
|
| 182 |
def f(a: int) -> None |
| 183 |
if a: |
| 184 |
a = 1 |
| 185 |
return a # a is borrowed if condition is false and unborrowed if true |
| 186 |
""" |
| 187 |
prev_key = (block, len(block.ops) - 1) |
| 188 |
source_live_regs = pre_live[prev_key] |
| 189 |
source_borrowed = post_borrow[prev_key] |
| 190 |
source_defined = post_must_defined[prev_key] |
| 191 |
|
| 192 |
term = block.terminator |
| 193 |
for i, target in enumerate(term.targets()): |
| 194 |
# HAX: After we've checked against an error value the value we must not touch the |
| 195 |
# refcount since it will be a null pointer. The correct way to do this would be |
| 196 |
# to perform data flow analysis on whether a value can be null (or is always |
| 197 |
# null). |
| 198 |
omitted: Iterable[Value] |
| 199 |
if isinstance(term, Branch) and term.op == Branch.IS_ERROR and i == 0: |
| 200 |
omitted = (term.value,) |
| 201 |
else: |
| 202 |
omitted = () |
| 203 |
|
| 204 |
decs = after_branch_decrefs( |
| 205 |
target, pre_live, source_defined, source_borrowed, source_live_regs, ordering, omitted |
| 206 |
) |
| 207 |
incs = after_branch_increfs(target, pre_live, pre_borrow, source_borrowed, ordering) |
| 208 |
term.set_target(i, add_block(decs, incs, cache, blocks, target)) |
| 209 |
|
| 210 |
|
| 211 |
def after_branch_decrefs( |
| 212 |
label: BasicBlock, |
| 213 |
pre_live: AnalysisDict[Value], |
| 214 |
source_defined: set[Value], |
| 215 |
source_borrowed: set[Value], |
| 216 |
source_live_regs: set[Value], |
| 217 |
ordering: dict[Value, int], |
| 218 |
omitted: Iterable[Value], |
| 219 |
) -> tuple[tuple[Value, bool], ...]: |
| 220 |
target_pre_live = pre_live[label, 0] |
| 221 |
decref = source_live_regs - target_pre_live - source_borrowed |
| 222 |
if decref: |
| 223 |
return tuple( |
| 224 |
(reg, is_maybe_undefined(source_defined, reg)) |
| 225 |
for reg in sorted(decref, key=lambda r: ordering[r]) |
| 226 |
if reg.type.is_refcounted and reg not in omitted |
| 227 |
) |
| 228 |
return () |
| 229 |
|
| 230 |
|
| 231 |
def after_branch_increfs( |
| 232 |
label: BasicBlock, |
| 233 |
pre_live: AnalysisDict[Value], |
| 234 |
pre_borrow: AnalysisDict[Value], |
| 235 |
source_borrowed: set[Value], |
| 236 |
ordering: dict[Value, int], |
| 237 |
) -> tuple[Value, ...]: |
| 238 |
target_pre_live = pre_live[label, 0] |
| 239 |
target_borrowed = pre_borrow[label, 0] |
| 240 |
incref = (source_borrowed - target_borrowed) & target_pre_live |
| 241 |
if incref: |
| 242 |
return tuple( |
| 243 |
reg for reg in sorted(incref, key=lambda r: ordering[r]) if reg.type.is_refcounted |
| 244 |
) |
| 245 |
return () |
| 246 |
|
| 247 |
|
| 248 |
def add_block( |
| 249 |
decs: Decs, incs: Incs, cache: BlockCache, blocks: list[BasicBlock], label: BasicBlock |
| 250 |
) -> BasicBlock: |
| 251 |
if not decs and not incs: |
| 252 |
return label |
| 253 |
|
| 254 |
# TODO: be able to share *partial* results |
| 255 |
if (label, decs, incs) in cache: |
| 256 |
return cache[label, decs, incs] |
| 257 |
|
| 258 |
block = BasicBlock() |
| 259 |
blocks.append(block) |
| 260 |
block.ops.extend(DecRef(reg, is_xdec=xdec) for reg, xdec in decs) |
| 261 |
block.ops.extend(IncRef(reg) for reg in incs) |
| 262 |
block.ops.append(Goto(label)) |
| 263 |
cache[label, decs, incs] = block |
| 264 |
return block |
| 265 |
|
| 266 |
|
| 267 |
def make_value_ordering(ir: FuncIR) -> dict[Value, int]: |
| 268 |
"""Create a ordering of values that allows them to be sorted. |
| 269 |
|
| 270 |
This omits registers that are only ever read. |
| 271 |
""" |
| 272 |
# TODO: Never initialized values?? |
| 273 |
result: dict[Value, int] = {} |
| 274 |
n = 0 |
| 275 |
|
| 276 |
for arg in ir.arg_regs: |
| 277 |
result[arg] = n |
| 278 |
n += 1 |
| 279 |
|
| 280 |
for block in ir.blocks: |
| 281 |
for op in block.ops: |
| 282 |
if ( |
| 283 |
isinstance(op, LoadAddress) |
| 284 |
and isinstance(op.src, Register) |
| 285 |
and op.src not in result |
| 286 |
): |
| 287 |
# Taking the address of a register allows initialization. |
| 288 |
result[op.src] = n |
| 289 |
n += 1 |
| 290 |
if isinstance(op, Assign): |
| 291 |
if op.dest not in result: |
| 292 |
result[op.dest] = n |
| 293 |
n += 1 |
| 294 |
elif op not in result: |
| 295 |
result[op] = n |
| 296 |
n += 1 |
| 297 |
|
| 298 |
return result |