|
| 1 | +"""Numeric range analysis (architecture §18, §24). |
| 2 | +
|
| 3 | +Every value proven numeric gets an ``Interval``: numeric constants, arithmetic on |
| 4 | +numbers, the results of ``int()``, ``len()`` and friends. Comparisons refine the |
| 5 | +intervals of both sides on the branch they take, chained comparisons and ``and`` / ``or`` |
| 6 | +included, and loops converge by widening. Values not proven numeric have no interval: |
| 7 | +the domain doubles as a proof of numeric type, which is what the refutation engine |
| 8 | +needs, since a number cannot carry an injection. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +from collections.abc import Mapping |
| 14 | +from dataclasses import dataclass |
| 15 | +from types import MappingProxyType |
| 16 | +from typing import ClassVar |
| 17 | + |
| 18 | +from coretrace_python.analysis import AnalysisContext, AnyAnalysis, FunctionAnalysis |
| 19 | +from coretrace_python.cfg import CFG, BlockId, CFGAnalysis |
| 20 | +from coretrace_python.dataflow import DataflowProblem, Direction, solve |
| 21 | +from coretrace_python.hir import nodes |
| 22 | +from coretrace_python.ir.model import ( |
| 23 | + BasicBlock, |
| 24 | + BinaryOp, |
| 25 | + BoolOp, |
| 26 | + Branch, |
| 27 | + Call, |
| 28 | + Compare, |
| 29 | + Constant, |
| 30 | + ForNext, |
| 31 | + FunctionIR, |
| 32 | + Instruction, |
| 33 | + Jump, |
| 34 | + Phi, |
| 35 | + Symbol, |
| 36 | + UnaryOp, |
| 37 | + Value, |
| 38 | +) |
| 39 | +from coretrace_python.ir.ssa import SSAAnalysis |
| 40 | + |
| 41 | +INF = float("inf") |
| 42 | + |
| 43 | + |
| 44 | +def _format(bound: float) -> str: |
| 45 | + if bound in (INF, -INF): |
| 46 | + return "inf" if bound > 0 else "-inf" |
| 47 | + return str(int(bound)) if float(bound).is_integer() else str(bound) |
| 48 | + |
| 49 | + |
| 50 | +@dataclass(frozen=True) |
| 51 | +class Interval: |
| 52 | + """A closed range of numbers; ``inf`` bounds mean unbounded.""" |
| 53 | + |
| 54 | + low: float |
| 55 | + high: float |
| 56 | + |
| 57 | + def join(self, other: Interval) -> Interval: |
| 58 | + return Interval(min(self.low, other.low), max(self.high, other.high)) |
| 59 | + |
| 60 | + def widen(self, other: Interval) -> Interval: |
| 61 | + """``self`` extended to ``other``, jumping to infinity on any side that grew.""" |
| 62 | + |
| 63 | + return Interval( |
| 64 | + self.low if other.low >= self.low else -INF, |
| 65 | + self.high if other.high <= self.high else INF, |
| 66 | + ) |
| 67 | + |
| 68 | + def __str__(self) -> str: |
| 69 | + return f"[{_format(self.low)}, {_format(self.high)}]" |
| 70 | + |
| 71 | + |
| 72 | +UNBOUNDED = Interval(-INF, INF) |
| 73 | +NON_NEGATIVE = Interval(0, INF) |
| 74 | + |
| 75 | +_NUMERIC_CALLS: Mapping[str, Interval] = { |
| 76 | + "python.builtins.int": UNBOUNDED, |
| 77 | + "python.builtins.float": UNBOUNDED, |
| 78 | + "python.builtins.round": UNBOUNDED, |
| 79 | + "python.builtins.len": NON_NEGATIVE, |
| 80 | + "python.builtins.abs": NON_NEGATIVE, |
| 81 | + "python.builtins.ord": Interval(0, 0x10FFFF), |
| 82 | +} |
| 83 | +_HULL_CALLS = frozenset({"python.builtins.min", "python.builtins.max"}) |
| 84 | + |
| 85 | +State = Mapping[Value, Interval] |
| 86 | + |
| 87 | + |
| 88 | +def _times(a: float, b: float) -> float: |
| 89 | + return 0.0 if a == 0 or b == 0 else a * b |
| 90 | + |
| 91 | + |
| 92 | +class RangeFacts: |
| 93 | + def __init__(self, states: Mapping[BlockId, State]) -> None: |
| 94 | + self._states: Mapping[BlockId, State] = MappingProxyType( |
| 95 | + {block: MappingProxyType(dict(state)) for block, state in states.items()} |
| 96 | + ) |
| 97 | + |
| 98 | + def at(self, block: BlockId) -> State: |
| 99 | + """The intervals known at the end of ``block``; empty when it is unreachable.""" |
| 100 | + |
| 101 | + return self._states.get(block, MappingProxyType({})) |
| 102 | + |
| 103 | + |
| 104 | +class _RangeProblem(DataflowProblem[State]): |
| 105 | + direction: ClassVar[Direction] = Direction.FORWARD |
| 106 | + |
| 107 | + def __init__(self, function: FunctionIR) -> None: |
| 108 | + self.function = function |
| 109 | + self.blocks = {block.id: block for block in function.blocks} |
| 110 | + self.defs: dict[Value, Instruction] = { |
| 111 | + i.result: i for block in function.blocks for i in block.instructions if i.result |
| 112 | + } |
| 113 | + self._widened: dict[Value, Interval] = {} |
| 114 | + |
| 115 | + def initial(self) -> State: |
| 116 | + return MappingProxyType({}) |
| 117 | + |
| 118 | + def join(self, a: State, b: State) -> State: |
| 119 | + return MappingProxyType( |
| 120 | + {value: a[value].join(b[value]) for value in a if value in b} |
| 121 | + ) |
| 122 | + |
| 123 | + def evaluate(self, block: BasicBlock, incoming: Mapping[BlockId, State]) -> State: |
| 124 | + states = list(incoming.values()) |
| 125 | + state: dict[Value, Interval] = dict(states[0]) if states else {} |
| 126 | + for other in states[1:]: |
| 127 | + state = dict(self.join(state, other)) |
| 128 | + for instruction in block.instructions: |
| 129 | + if instruction.result is None: |
| 130 | + continue |
| 131 | + found = ( |
| 132 | + self.phi(instruction, incoming) |
| 133 | + if isinstance(instruction, Phi) |
| 134 | + else self.instruction(instruction, state) |
| 135 | + ) |
| 136 | + if found is None: |
| 137 | + state.pop(instruction.result, None) |
| 138 | + else: |
| 139 | + state[instruction.result] = found |
| 140 | + return MappingProxyType(state) |
| 141 | + |
| 142 | + def flow(self, cfg: CFG, block_id: BlockId, incoming: Mapping[BlockId, State]) -> Mapping[BlockId, State]: |
| 143 | + block = self.blocks[block_id] |
| 144 | + state = self.evaluate(block, incoming) |
| 145 | + exits = {target: state for target in block.exception_targets} |
| 146 | + terminator = block.terminator |
| 147 | + if isinstance(terminator, Branch): |
| 148 | + return { |
| 149 | + **exits, |
| 150 | + terminator.then_block: self.refined(state, terminator.condition, True), |
| 151 | + terminator.else_block: self.refined(state, terminator.condition, False), |
| 152 | + } |
| 153 | + if isinstance(terminator, Jump): |
| 154 | + return {**exits, terminator.target: state} |
| 155 | + if isinstance(terminator, ForNext): |
| 156 | + return {**exits, terminator.body: state, terminator.exit: state} |
| 157 | + return exits |
| 158 | + |
| 159 | + # ------------------------------------------------------------------ transfer |
| 160 | + |
| 161 | + def phi(self, phi: Phi, incoming: Mapping[BlockId, State]) -> Interval | None: |
| 162 | + result: Interval | None = None |
| 163 | + for value, predecessor in phi.incoming: |
| 164 | + if predecessor not in incoming: |
| 165 | + continue |
| 166 | + found = incoming[predecessor].get(value) |
| 167 | + if found is None: |
| 168 | + return None |
| 169 | + result = found if result is None else result.join(found) |
| 170 | + if result is None: |
| 171 | + return None |
| 172 | + previous = self._widened.get(phi.result) |
| 173 | + widened = result if previous is None else previous.widen(previous.join(result)) |
| 174 | + self._widened[phi.result] = widened |
| 175 | + return widened |
| 176 | + |
| 177 | + def instruction(self, instruction: Instruction, state: Mapping[Value, Interval]) -> Interval | None: |
| 178 | + if isinstance(instruction, Constant): |
| 179 | + value = instruction.value |
| 180 | + if isinstance(value, bool | int | float) and value == value: # noqa: PLR0124 - NaN |
| 181 | + return Interval(float(value), float(value)) |
| 182 | + return None |
| 183 | + if isinstance(instruction, BinaryOp): |
| 184 | + left, right = state.get(instruction.left), state.get(instruction.right) |
| 185 | + if left is None or right is None: |
| 186 | + return None |
| 187 | + return self.binary(instruction.operator, left, right) |
| 188 | + if isinstance(instruction, UnaryOp): |
| 189 | + operand = state.get(instruction.operand) |
| 190 | + if instruction.operator == "not": |
| 191 | + return Interval(0, 1) |
| 192 | + if operand is None: |
| 193 | + return None |
| 194 | + if instruction.operator == "neg": |
| 195 | + return Interval(-operand.high, -operand.low) |
| 196 | + return operand if instruction.operator == "pos" else UNBOUNDED |
| 197 | + if isinstance(instruction, Compare): |
| 198 | + return Interval(0, 1) |
| 199 | + if isinstance(instruction, Call): |
| 200 | + callee = self.defs.get(instruction.callee) |
| 201 | + if not isinstance(callee, Symbol): |
| 202 | + return None |
| 203 | + name = callee.symbol_id.canonical_name |
| 204 | + if name in _NUMERIC_CALLS: |
| 205 | + return _NUMERIC_CALLS[name] |
| 206 | + if name in _HULL_CALLS and instruction.arguments and not instruction.keywords: |
| 207 | + hull: Interval | None = None |
| 208 | + for argument in instruction.arguments: |
| 209 | + found = state.get(argument) |
| 210 | + if found is None: |
| 211 | + return None |
| 212 | + hull = found if hull is None else hull.join(found) |
| 213 | + return hull |
| 214 | + return None |
| 215 | + |
| 216 | + @staticmethod |
| 217 | + def binary(operator: str, left: Interval, right: Interval) -> Interval | None: |
| 218 | + if operator == "add": |
| 219 | + return Interval(left.low + right.low, left.high + right.high) |
| 220 | + if operator == "sub": |
| 221 | + return Interval(left.low - right.high, left.high - right.low) |
| 222 | + if operator == "mul": |
| 223 | + products = [ |
| 224 | + _times(a, b) for a in (left.low, left.high) for b in (right.low, right.high) |
| 225 | + ] |
| 226 | + return Interval(min(products), max(products)) |
| 227 | + if operator in ("div", "floor_div", "mod", "pow", "bit_or", "bit_xor", "bit_and", "lshift", "rshift"): |
| 228 | + return UNBOUNDED |
| 229 | + return None |
| 230 | + |
| 231 | + # ------------------------------------------------------------------ refinement |
| 232 | + |
| 233 | + def refined(self, state: State, condition: Value, truth: bool) -> State: |
| 234 | + overrides: dict[Value, Interval] = {} |
| 235 | + self.refine(dict(state), condition, truth, overrides) |
| 236 | + return MappingProxyType({**state, **overrides}) if overrides else state |
| 237 | + |
| 238 | + def refine( |
| 239 | + self, state: dict[Value, Interval], condition: Value, truth: bool, overrides: dict[Value, Interval] |
| 240 | + ) -> None: |
| 241 | + definition = self.defs.get(condition) |
| 242 | + if isinstance(definition, UnaryOp) and definition.operator == "not": |
| 243 | + self.refine(state, definition.operand, not truth, overrides) |
| 244 | + elif isinstance(definition, BoolOp) and (definition.operator == "and") == truth: |
| 245 | + for value in definition.values: |
| 246 | + self.refine(state, value, truth, overrides) |
| 247 | + elif isinstance(definition, Compare): |
| 248 | + left, right = definition.left, definition.right |
| 249 | + if left not in state or right not in state: |
| 250 | + return |
| 251 | + operator = definition.operator |
| 252 | + if operator == "eq" and truth or operator == "not_eq" and not truth: |
| 253 | + low = max(state[left].low, state[right].low) |
| 254 | + high = min(state[left].high, state[right].high) |
| 255 | + if low <= high: |
| 256 | + overrides[left] = overrides[right] = Interval(low, high) |
| 257 | + state[left] = state[right] = Interval(low, high) |
| 258 | + return |
| 259 | + if operator not in ("lt", "lt_eq", "gt", "gt_eq"): |
| 260 | + return |
| 261 | + ascending = (operator in ("lt", "lt_eq")) == truth |
| 262 | + lower, upper = (left, right) if ascending else (right, left) |
| 263 | + bounded_lower = Interval(state[lower].low, min(state[lower].high, state[upper].high)) |
| 264 | + bounded_upper = Interval(max(state[upper].low, state[lower].low), state[upper].high) |
| 265 | + overrides[lower], overrides[upper] = bounded_lower, bounded_upper |
| 266 | + state[lower], state[upper] = bounded_lower, bounded_upper |
| 267 | + |
| 268 | + |
| 269 | +def analyze_ranges(function: FunctionIR, cfg: CFG) -> RangeFacts: |
| 270 | + problem = _RangeProblem(function) |
| 271 | + solution = solve(problem, cfg) |
| 272 | + states: dict[BlockId, State] = {} |
| 273 | + for block in function.blocks: |
| 274 | + if solution.reached(block.id): |
| 275 | + states[block.id] = problem.evaluate(block, solution.incoming(block.id)) |
| 276 | + return RangeFacts(states) |
| 277 | + |
| 278 | + |
| 279 | +class RangeAnalysis(FunctionAnalysis[RangeFacts]): |
| 280 | + name: ClassVar[str] = "abstract.ranges" |
| 281 | + requires: ClassVar[frozenset[AnyAnalysis]] = frozenset({SSAAnalysis, CFGAnalysis}) |
| 282 | + |
| 283 | + @classmethod |
| 284 | + def compute(cls, ctx: AnalysisContext, function: nodes.Function) -> RangeFacts: |
| 285 | + return analyze_ranges(ctx.get(SSAAnalysis, function), ctx.get(CFGAnalysis, function)) |
0 commit comments