Compare commits

..

11 Commits

Author SHA1 Message Date
e251845d8c Merge remote-tracking branch 'origin/master' into fix/temp-count-if-condition 2026-09-24 16:44:47 +05:30
05660d46b4 Core: The pool-duplication TODO after #104: free with opt, 8 bytes without
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 16:44:44 +05:30
3179549760 Add LLVM optimizer (#104)
* Add LLVM optimizer

* expr_pass: add bpf_passthrough attributes to make tests pass
2026-09-23 21:05:33 +05:30
8290fecac2 tests: Add loop and AnnAssign xfail tests (#103)
- process_stmt now raises NotImplementedError on an unsupported statement
  instead of warning: a dropped statement silently changes what the
  program means (a for/while loop compiled to nothing).
- failing_tests/loops/: 8 xfail tests for for/while/break/continue/nested
  loops and map iteration
- failing_tests/assign/annotated_assign.py: xfail for `x: c_int64 = 0`
  (ast.AnnAssign is not handled)
2026-09-23 18:08:27 +05:30
5e5c14e210 Core: Correct the pool-duplication TODO: the dead allocas do cost stack
The previous note claimed LLVM deletes the unreferenced duplicate temps.
Measured: removing only the dead alloca from the IR moves the BPF frame
from r10-32 to r10-24, so llc keeps it through frame layout and each
duplicated i64 temp costs 8 bytes per nesting level. opt -O2 would
remove it; the pipeline is llc only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 15:31:27 +05:30
055a81b395 Core: Note the per-nesting-level pool allocation as a TODO
Verified against the emitted BPF: the duplicate allocas never reach the
frame, so there is no runtime cost. Left as a TODO by agreement.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 15:29:53 +05:30
ce4908a1c1 Tests: A map lookup that appears only in if and elif conditions
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 15:28:07 +05:30
b3d79afd85 Core: Count scratch temps needed by if conditions
The per-statement temp count returned early for an if after recursing
into its body and else, and never walked the condition. A helper call
whose only occurrence was in a condition, `if m.lookup(5):`, therefore
found no pool and failed with "Scratch pool exhausted" while the same
call on a line of its own compiled. The condition is evaluated before
any nested statement and the pool resets between statements, so it is
counted as a piece of its own and the bodies take the max, as before.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 15:28:04 +05:30
a949a90d0e Merge pull request #102 from pythonbpf/fix/enum-constant-local
Fix enum constant assignments to locals
2026-09-18 16:44:42 +05:30
dd744df0b2 Update Python version requirement to 3.10 2026-09-17 20:52:58 +05:30
60dcd4cc11 Update Python version classifiers in pyproject.toml
Removed specific Python versions 3.8 and 3.9 from the classifiers.
2026-09-17 20:52:37 +05:30
18 changed files with 371 additions and 30 deletions

View File

@ -48,7 +48,7 @@ Dependencies:
* `bpftool` * `bpftool`
* `clang` * `clang`
* Python ≥ 3.8 * Python ≥ 3.10
Install via pip: Install via pip:

View File

@ -15,8 +15,6 @@ classifiers = [
"Intended Audience :: Developers", "Intended Audience :: Developers",
"Operating System :: POSIX :: Linux", "Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3", "Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.12",

View File

@ -15,6 +15,7 @@ from .globals_pass import (
) )
from .debuginfo import DW_LANG_C11, DwarfBehaviorEnum, DebugInfoGenerator from .debuginfo import DW_LANG_C11, DwarfBehaviorEnum, DebugInfoGenerator
import os import os
import shutil
import subprocess import subprocess
import inspect import inspect
from pathlib import Path from pathlib import Path
@ -175,8 +176,66 @@ def compile_to_ir(filename: str, output: str, loglevel=logging.INFO):
return output, structs_sym_tab, maps_sym_tab return output, structs_sym_tab, maps_sym_tab
MIN_OPT_VERSION = 15
_OPT_VERSIONED_RE = re.compile(r"opt-(\d+)")
def _find_opt():
"""Locate an LLVM opt binary.
Prefers a plain ``opt`` on PATH. Otherwise falls back to the newest
versioned ``opt-N`` (N >= MIN_OPT_VERSION) that distros such as
Debian/Ubuntu install, e.g. ``opt-18``. Returns None if none is found.
"""
opt = shutil.which("opt")
if opt:
return opt
best_version, best_path = -1, None
for directory in os.environ.get("PATH", "").split(os.pathsep):
try:
entries = os.listdir(directory or ".")
except OSError:
continue
for entry in entries:
match = _OPT_VERSIONED_RE.fullmatch(entry)
if not match:
continue
version = int(match.group(1))
if version < MIN_OPT_VERSION or version <= best_version:
continue
path = shutil.which(entry, path=directory or ".")
if path:
best_version, best_path = version, path
return best_path
def _run_opt(ll_file):
"""Run the O2 pipeline over the IR and return it as bitcode, or None if
no opt binary is available."""
opt = _find_opt()
if opt is None:
logger.warning(
f"No LLVM 'opt' (or 'opt-N', N >= {MIN_OPT_VERSION}) found on PATH; "
"skipping IR optimization."
)
return None
logger.info(f"Optimizing IR with {opt} -O2: {ll_file}")
result = subprocess.run(
[opt, "-O2", str(ll_file), "-o", "-"],
check=True,
capture_output=True,
)
return result.stdout
def _run_llc(ll_file, obj_file): def _run_llc(ll_file, obj_file):
"""Compile LLVM IR to BPF object file using llc.""" """Optimize LLVM IR with opt (when available) and compile it to a BPF
object file using llc."""
bitcode = _run_opt(ll_file)
logger.info(f"Compiling IR to object: {ll_file} -> {obj_file}") logger.info(f"Compiling IR to object: {ll_file} -> {obj_file}")
result = subprocess.run( result = subprocess.run(
@ -185,20 +244,20 @@ def _run_llc(ll_file, obj_file):
"-march=bpf", "-march=bpf",
"-filetype=obj", "-filetype=obj",
"-O2", "-O2",
str(ll_file), "-" if bitcode is not None else str(ll_file),
"-o", "-o",
str(obj_file), str(obj_file),
], ],
input=bitcode,
check=True, check=True,
capture_output=True, capture_output=True,
text=True,
) )
if result.returncode == 0: if result.returncode == 0:
logger.info(f"Object file written to {obj_file}") logger.info(f"Object file written to {obj_file}")
return True return True
else: else:
logger.error(f"llc compilation failed: {result.stderr}") logger.error(f"llc compilation failed: {result.stderr.decode()}")
return False return False

View File

@ -72,6 +72,10 @@ class CompilationContext:
# Helper management # Helper management
self.scratch_pool = ScratchPoolManager() self.scratch_pool = ScratchPoolManager()
# Sequence numbers for llvm.bpf.passthrough barriers; each call needs a
# distinct one so the optimizer cannot CSE two barriers together.
self.passthrough_seq = 0
# Vmlinux handling (optional, specialized) # Vmlinux handling (optional, specialized)
self.vmlinux_handler = None # Can be VmlinuxHandler instance self.vmlinux_handler = None # Can be VmlinuxHandler instance

View File

@ -407,6 +407,28 @@ def _handle_unary_op(
# ============================================================================ # ============================================================================
def _bpf_passthrough(builder, compilation_context, val):
"""Wrap an i1 in llvm.bpf.passthrough, an optimization barrier the BPF
backend strips before instruction selection.
Without it, opt's SimplifyCFG speculates a short-circuit operand's compare
into the preceding block, and SelectionDAG then folds the two null checks
of `p1 or p2` into `(p1 | p2) != 0`. The verifier rejects that with
"pointer |= pointer prohibited". BPFAdjustOpt uses the same intrinsic to
keep compares serialized for the verifier.
"""
module = compilation_context.module
name = "llvm.bpf.passthrough.i1.i1"
fn = module.globals.get(name)
if fn is None:
fn_type = ir.FunctionType(ir.IntType(1), [ir.IntType(32), ir.IntType(1)])
fn = ir.Function(module, fn_type, name=name)
seq = ir.Constant(ir.IntType(32), compilation_context.passthrough_seq)
compilation_context.passthrough_seq += 1
return builder.call(fn, [seq, val])
def _handle_and_op(func, builder, expr, local_sym_tab, compilation_context): def _handle_and_op(func, builder, expr, local_sym_tab, compilation_context):
"""Handle `and` boolean operations.""" """Handle `and` boolean operations."""
@ -432,6 +454,8 @@ def _handle_and_op(func, builder, expr, local_sym_tab, compilation_context):
# Convert to boolean if needed # Convert to boolean if needed
operand_bool = convert_to_bool(builder, operand_val) operand_bool = convert_to_bool(builder, operand_val)
if i > 0:
operand_bool = _bpf_passthrough(builder, compilation_context, operand_bool)
current_block = builder.block current_block = builder.block
if is_last: if is_last:
@ -485,6 +509,8 @@ def _handle_or_op(func, builder, expr, local_sym_tab, compilation_context):
# Convert to boolean if needed # Convert to boolean if needed
operand_bool = convert_to_bool(builder, operand_val) operand_bool = convert_to_bool(builder, operand_val)
if i > 0:
operand_bool = _bpf_passthrough(builder, compilation_context, operand_bool)
current_block = builder.block current_block = builder.block
if is_last: if is_last:

View File

@ -109,23 +109,27 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
for typ, cnt in count_dict.items(): for typ, cnt in count_dict.items():
max_temps_needed[typ] = max(max_temps_needed.get(typ, 0), cnt) max_temps_needed[typ] = max(max_temps_needed.get(typ, 0), cnt)
def update_max_temps_for_stmt(stmt): def count_temps_in(node):
nonlocal max_temps_needed """Temps one statement-sized piece of AST needs, merged into the max."""
temps = {}
for sub in ast.walk(node):
if isinstance(sub, ast.Call):
for typ, cnt in count_temps_in_call(sub, local_sym_tab).items():
temps[typ] = temps.get(typ, 0) + cnt
merge_type_counts(temps)
def update_max_temps_for_stmt(stmt):
if isinstance(stmt, ast.If): if isinstance(stmt, ast.If):
# The condition is evaluated before any nested statement and the
# pool resets between statements, so it counts as a piece of its
# own; the bodies then take the max. `elif` is an If in orelse.
count_temps_in(stmt.test)
for s in stmt.body: for s in stmt.body:
update_max_temps_for_stmt(s) update_max_temps_for_stmt(s)
for s in stmt.orelse: for s in stmt.orelse:
update_max_temps_for_stmt(s) update_max_temps_for_stmt(s)
return return
count_temps_in(stmt)
stmt_temps = {}
for node in ast.walk(stmt):
if isinstance(node, ast.Call):
call_temps = count_temps_in_call(node, local_sym_tab)
for typ, cnt in call_temps.items():
stmt_temps[typ] = stmt_temps.get(typ, 0) + cnt
merge_type_counts(stmt_temps)
for stmt in body: for stmt in body:
update_max_temps_for_stmt(stmt) update_max_temps_for_stmt(stmt)
@ -143,6 +147,13 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
elif isinstance(stmt, ast.Assign): elif isinstance(stmt, ast.Assign):
handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab) handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab)
# TODO: allocate_mem is re-entered for every if body (handle_if_allocation),
# and each level allocates a pool of its own even though the top-level count
# already covers nested statements. Only the last-allocated pool stays in
# local_sym_tab; the others are unreferenced. The opt -O2 step (#104)
# deletes them, so with opt on PATH this costs nothing; on the no-opt
# fallback llc keeps them through frame layout, measured 8 bytes per i64
# temp per nesting level. Fix: count recursively, allocate once at the top.
allocate_temp_pool(builder, max_temps_needed, local_sym_tab) allocate_temp_pool(builder, max_temps_needed, local_sym_tab)
return local_sym_tab return local_sym_tab
@ -401,11 +412,11 @@ def process_stmt(
builder, stmt, local_sym_tab, ret_type, compilation_context builder, stmt, local_sym_tab, ret_type, compilation_context
) )
else: else:
# Silently dropping a statement makes the program mean something other # Dropping a statement makes the program mean something other than what
# than what it says, so say so. # it says (a loop compiles to nothing), so refuse rather than warn.
logger.warning( raise NotImplementedError(
f"Unsupported statement on line {getattr(stmt, 'lineno', '?')}, " f"Unsupported statement on line {getattr(stmt, 'lineno', '?')}: "
f"ignored: {type(stmt).__name__}" f"{type(stmt).__name__}"
) )
return did_return return did_return

View File

@ -0,0 +1,18 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,22 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(10):
if i == 5:
break
total = total + 1
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,22 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(10):
if i % 2 == 0:
continue
total = total + i
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,29 @@
from pythonbpf import bpf, map, bpfglobal, section, compile
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64, c_int32, c_uint64
@bpf
@map
def mymap() -> HashMap:
return HashMap(key=c_int32, value=c_uint64, max_entries=16)
# Imagined sugar over the kernel's bpf_for_each_map_elem() callback helper:
# iterating a map's entries directly from a `for` statement.
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for k, v in mymap.items():
total = total + 1
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,20 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(0, 10, 2):
total = total + i
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,20 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(10):
total = total + 1
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,21 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(3):
for j in range(3):
total = total + 1
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,20 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
i: c_int64 = 0
while i < 10:
i = i + 1
return i
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,22 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
while True:
total = total + 1
if total == 10:
break
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,32 @@
# A helper call that needs a scratch temp (the literal key has to be spilled
# to the stack for bpf_map_lookup_elem) appearing only in an `if` condition.
# The temp count used to skip conditions, so this failed with "Scratch pool
# exhausted" while the same lookup on a line of its own compiled.
from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64, c_uint32, c_uint64
@bpf
@map
def m() -> HashMap:
return HashMap(key=c_uint32, value=c_uint64, max_entries=4)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
if m.lookup(5):
return c_int64(1)
elif m.lookup(6):
return c_int64(2)
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -15,14 +15,6 @@
"failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"} "failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"}
# Compiles cleanly; rejected by the kernel. The `data + 34 < data_end` guard is
# emitted as a signed compare over values round-tripped through the stack, so the
# verifier never narrows the packet range (it stays r=0) and the later
# `iph.saddr` read fails with "invalid access to packet, off=26 size=4" /
# "R1 offset is outside of the packet". Direct packet access needs bounds checks
# in a form the verifier can follow.
"failing_tests/xdp/xdp_test_1.py" = {reason = "XDP direct packet access: the data/data_end guard does not establish a packet range the verifier can use", level = "verifier"}
"failing_tests/license.py" = {reason = "Missing LICENSE global produces IR that llc rejects — should be caught earlier with a clear error message", level = "llc"} "failing_tests/license.py" = {reason = "Missing LICENSE global produces IR that llc rejects — should be caught earlier with a clear error message", level = "llc"}
"failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"} "failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"}
@ -41,3 +33,28 @@
"failing_tests/globals_augassign_shadowing.py" = {reason = "`x += 1` on a global name without `global` binds a local and reads it unbound: UnboundLocalError in Python, a compile error here", level = "ir"} "failing_tests/globals_augassign_shadowing.py" = {reason = "`x += 1` on a global name without `global` binds a local and reads it unbound: UnboundLocalError in Python, a compile error here", level = "ir"}
"failing_tests/globals_parameter_and_global.py" = {reason = "A parameter may not be declared global (Python: name is parameter and global)", level = "ir"} "failing_tests/globals_parameter_and_global.py" = {reason = "A parameter may not be declared global (Python: name is parameter and global)", level = "ir"}
"failing_tests/assign/annotated_assign.py" = {reason = "Annotated assignment (ast.AnnAssign, e.g. `x: c_int64 = 0`) is not handled by process_stmt", level = "ir"}
# Loop constructs: ast.For/ast.While are not handled by the statement dispatcher
# (pythonbpf/functions/functions_pass.py process_stmt only matches Expr, Assign,
# AugAssign, If, Return) and the pre-pass variable scan does not descend into
# loop bodies. A loop is silently skipped rather than erroring, so anything
# that reads a variable assigned in/around the loop afterward blows up later
# with "Undefined variable ..." at the `return` statement. These document the
# intended surface for when loops are implemented.
"failing_tests/loops/for_range_sum.py" = {reason = "for/while loops not implemented: ast.For is silently skipped by the statement dispatcher", level = "ir"}
"failing_tests/loops/for_range_start_stop_step.py" = {reason = "for/while loops not implemented: range() with start/stop/step is not supported", level = "ir"}
"failing_tests/loops/while_basic.py" = {reason = "for/while loops not implemented: ast.While is silently skipped by the statement dispatcher", level = "ir"}
"failing_tests/loops/while_true_break.py" = {reason = "for/while loops not implemented: while True with a break-based exit is not supported", level = "ir"}
"failing_tests/loops/nested_for.py" = {reason = "for/while loops not implemented: nested for loops are not supported", level = "ir"}
"failing_tests/loops/for_break.py" = {reason = "for/while loops not implemented: break is not supported", level = "ir"}
"failing_tests/loops/for_continue.py" = {reason = "for/while loops not implemented: continue is not supported", level = "ir"}
"failing_tests/loops/for_map_items.py" = {reason = "for/while loops not implemented: no sugar over bpf_for_each_map_elem()-style map iteration exists yet", level = "ir"}