From aa321dbd47713473249c4f05301128ab40b0dc5e Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Thu, 3 Sep 2026 07:19:07 +0530 Subject: [PATCH] Core: Lower augmented assignment directly instead of desugaring The first version synthesised an Assign(BinOp(...)) node and fed it back through handle_assign. That is a standard compiler move, but it is not how this compiler works: every pass walks the tree the user wrote, and a node invented mid-codegen is invisible to the allocation pass that already ran, carries no source location for diagnostics, and shows up in logs as a statement nobody typed. handle_aug_assign now resolves the target slot (declared global, local, or struct field), loads it, evaluates the right-hand side, applies the operator, and stores back. Semantic agreement with "x = x op v" no longer rests on shared AST but on shared value-level helpers: the RHS goes through get_operand_value like any other read, and the operator table is extracted from binary-op evaluation into apply_binop so it exists exactly once. Two behavioural refinements fall out: augmented assignment to a global name without a global statement is now the same loud SyntaxError plain assignment gives (previously it slipped past the allocation pass, which only walks Assign), and struct-field targets compute their GEP once rather than twice. Target read precedes RHS evaluation, matching Python. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF --- pythonbpf/expr/__init__.py | 3 +- pythonbpf/expr/expr_pass.py | 45 ++++++--------- pythonbpf/expr/ir_ops.py | 28 +++++++++ pythonbpf/functions/functions_pass.py | 83 ++++++++++++++++++++++----- 4 files changed, 116 insertions(+), 43 deletions(-) diff --git a/pythonbpf/expr/__init__.py b/pythonbpf/expr/__init__.py index dfd2128..7ab5f8d 100644 --- a/pythonbpf/expr/__init__.py +++ b/pythonbpf/expr/__init__.py @@ -1,6 +1,6 @@ from .expr_pass import eval_expr, handle_expr, get_operand_value from .type_normalization import convert_to_bool, get_base_type_and_depth -from .ir_ops import deref_to_depth, access_struct_field +from .ir_ops import deref_to_depth, access_struct_field, apply_binop from .call_registry import CallHandlerRegistry from .vmlinux_registry import VmlinuxHandlerRegistry @@ -10,6 +10,7 @@ __all__ = [ "convert_to_bool", "get_base_type_and_depth", "deref_to_depth", + "apply_binop", "access_struct_field", "get_operand_value", "CallHandlerRegistry", diff --git a/pythonbpf/expr/expr_pass.py b/pythonbpf/expr/expr_pass.py index 08967fb..a4854a6 100644 --- a/pythonbpf/expr/expr_pass.py +++ b/pythonbpf/expr/expr_pass.py @@ -6,7 +6,7 @@ from typing import Dict from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes from .call_registry import CallHandlerRegistry -from .ir_ops import deref_to_depth, access_struct_field +from .ir_ops import deref_to_depth, access_struct_field, apply_binop from .type_normalization import ( convert_to_bool, handle_comparator, @@ -31,8 +31,7 @@ def _handle_name_expr( val = builder.load(var) return val, local_sym_tab[expr.id].ir_type elif expr.id in compilation_context.bpf_globals: - # A @bpfglobal: read straight off the global symbol, exactly the - # `load i64, ptr @counter` form clang emits (tests/c-form/global_vars). + # A @bpfglobal sym = compilation_context.bpf_globals[expr.id] val = builder.load(sym.var) return val, sym.ir_type @@ -86,7 +85,9 @@ def _handle_attribute_expr( var_ptr, var_type, var_metadata = local_sym_tab[var_name] logger.info(f"Loading attribute {attr_name} from variable {var_name}") logger.info( - f"Variable type: {var_type}, Variable ptr: {var_ptr}, Variable Metadata: {var_metadata}" + f"Variable type: {var_type}, Variable ptr: { + var_ptr + }, Variable Metadata: {var_metadata}" ) if ( hasattr(var_metadata, "__module__") @@ -104,7 +105,9 @@ def _handle_attribute_expr( elif isinstance(var_metadata, Field): logger.error( - f"Cannot access field '{attr_name}' on already-loaded field value '{var_name}'" + f"Cannot access field '{attr_name}' on already-loaded field value '{ + var_name + }'" ) return None @@ -234,25 +237,7 @@ def _handle_binary_op_impl(func, compilation_context, rval, builder, local_sym_t right = builder.sext(right, ir.IntType(64)) # Map AST operation nodes to LLVM IR builder methods - op_map = { - ast.Add: builder.add, - ast.Sub: builder.sub, - ast.Mult: builder.mul, - ast.Div: builder.sdiv, - ast.Mod: builder.srem, - ast.LShift: builder.shl, - ast.RShift: builder.lshr, - ast.BitOr: builder.or_, - ast.BitXor: builder.xor, - ast.BitAnd: builder.and_, - ast.FloorDiv: builder.udiv, - } - - if type(op) in op_map: - result = op_map[type(op)](left, right) - return result - else: - raise SyntaxError("Unsupported binary operation") + return apply_binop(builder, op, left, right) def _handle_binary_op( @@ -315,7 +300,9 @@ def _handle_ctypes_call( # Get the IR type from the value itself actual_ir_type = value.type logger.info( - f"Converting vmlinux field {val_type.name} (IR type: {actual_ir_type}) to {call_type}" + f"Converting vmlinux field {val_type.name} (IR type: {actual_ir_type}) to { + call_type + }" ) else: actual_ir_type = val_type @@ -328,7 +315,9 @@ def _handle_ctypes_call( if actual_ir_type.width < expected_type.width: value = builder.sext(value, expected_type) logger.info( - f"Sign-extended from i{actual_ir_type.width} to i{expected_type.width}" + f"Sign-extended from i{actual_ir_type.width} to i{ + expected_type.width + }" ) elif actual_ir_type.width > expected_type.width: value = builder.trunc(value, expected_type) @@ -340,7 +329,9 @@ def _handle_ctypes_call( pass else: raise ValueError( - f"Type mismatch: expected {expected_type}, got {actual_ir_type} (original type: {val_type})" + f"Type mismatch: expected {expected_type}, got { + actual_ir_type + } (original type: {val_type})" ) return value, expected_type diff --git a/pythonbpf/expr/ir_ops.py b/pythonbpf/expr/ir_ops.py index 3f10d19..d593f90 100644 --- a/pythonbpf/expr/ir_ops.py +++ b/pythonbpf/expr/ir_ops.py @@ -1,9 +1,37 @@ +import ast import logging from llvmlite import ir logger = logging.getLogger(__name__) +BINOP_METHODS = { + ast.Add: "add", + ast.Sub: "sub", + ast.Mult: "mul", + ast.Div: "sdiv", + ast.Mod: "srem", + ast.LShift: "shl", + ast.RShift: "lshr", + ast.BitOr: "or_", + ast.BitXor: "xor", + ast.BitAnd: "and_", + ast.FloorDiv: "udiv", +} + + +def apply_binop(builder, op, left, right): + """Emit the LLVM instruction for a Python binary operator. + + Shared by binary-op evaluation and augmented assignment so the operator + table exists exactly once. + """ + method = BINOP_METHODS.get(type(op)) + if method is None: + raise SyntaxError("Unsupported binary operation") + return getattr(builder, method)(left, right) + + def deref_to_depth(func, builder, val, target_depth): """Dereference a pointer to a certain depth.""" diff --git a/pythonbpf/functions/functions_pass.py b/pythonbpf/functions/functions_pass.py index 6ccf2f2..2bebd09 100644 --- a/pythonbpf/functions/functions_pass.py +++ b/pythonbpf/functions/functions_pass.py @@ -11,6 +11,8 @@ from pythonbpf.expr import ( eval_expr, handle_expr, convert_to_bool, + get_operand_value, + apply_binop, VmlinuxHandlerRegistry, ) from pythonbpf.assign_pass import ( @@ -190,30 +192,81 @@ def handle_assign(func, compilation_context, builder, stmt, local_sym_tab): def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab): - """Handle `x += v` by desugaring to `x = x op v` and reusing handle_assign. + """Handle `x += v` and friends by direct lowering: resolve the target's + slot, load it, apply the operator, store back. - That is the statement's Python semantics for the targets we support, and it - means globals come along for free: `counter += 1` under `global counter` - becomes load/add/store on @counter. + No desugaring into synthetic Assign/BinOp nodes: every pass in this + compiler walks the tree the user wrote, and nodes invented mid-codegen are + invisible to the passes that already ran and carry no source locations. + Semantic agreement with `x = x op v` comes from sharing the value-level + helpers instead — the RHS goes through get_operand_value like any other + read, and the operator table is apply_binop, the same one binary-op + evaluation uses. """ if isinstance(stmt.target, ast.Name): - load_target = ast.Name(id=stmt.target.id, ctx=ast.Load()) - elif isinstance(stmt.target, ast.Attribute): - load_target = ast.Attribute( - value=stmt.target.value, attr=stmt.target.attr, ctx=ast.Load() - ) + name = stmt.target.id + if name in compilation_context.current_func_globals: + sym = compilation_context.bpf_globals[name] + slot, slot_type = sym.var, sym.ir_type + elif name in compilation_context.bpf_globals: + raise SyntaxError( + f"augmented assignment to '{name}' shadows the BPF global of " + f"the same name — add 'global {name}' to write to it" + ) + elif name in local_sym_tab: + slot = local_sym_tab[name].var + slot_type = local_sym_tab[name].ir_type + else: + raise SyntaxError(f"augmented assignment to undefined variable '{name}'") + elif isinstance(stmt.target, ast.Attribute) and isinstance( + stmt.target.value, ast.Name + ): + var_name, field_name = stmt.target.value.id, stmt.target.attr + if var_name not in local_sym_tab: + raise SyntaxError( + f"augmented assignment to field of undefined variable '{var_name}'" + ) + metadata = local_sym_tab[var_name].metadata + structs_sym_tab = compilation_context.structs_sym_tab + if metadata not in structs_sym_tab: + raise SyntaxError( + f"augmented assignment to '{var_name}.{field_name}' is only " + f"supported for struct fields" + ) + struct_info = structs_sym_tab[metadata] + if field_name not in struct_info.fields: + raise SyntaxError(f"Field '{field_name}' not found in struct '{metadata}'") + slot = struct_info.gep(builder, local_sym_tab[var_name].var, field_name) + slot_type = struct_info.field_type(field_name) else: raise SyntaxError( f"Unsupported augmented-assignment target: {ast.dump(stmt.target)}" ) - desugared = ast.Assign( - targets=[stmt.target], - value=ast.BinOp(left=load_target, op=stmt.op, right=stmt.value), + if not isinstance(slot_type, ir.IntType): + raise SyntaxError( + f"augmented assignment needs an integer target, got {slot_type}" + ) + + # Python evaluates the target's current value before the right-hand side. + current = builder.load(slot) + rhs = get_operand_value( + func, compilation_context, stmt.value, builder, local_sym_tab ) - ast.copy_location(desugared, stmt) - ast.fix_missing_locations(desugared) - handle_assign(func, compilation_context, builder, desugared, local_sym_tab) + if rhs is None: + raise SyntaxError( + f"Failed to evaluate augmented-assignment value: {ast.dump(stmt.value)}" + ) + # Same width discipline as binary-op evaluation: compute in i64, narrow + # back to the slot's width on the way out. + if current.type.width < 64: + current = builder.sext(current, ir.IntType(64)) + if isinstance(rhs.type, ir.IntType) and rhs.type.width < 64: + rhs = builder.sext(rhs, ir.IntType(64)) + result = apply_binop(builder, stmt.op, current, rhs) + if result.type.width > slot_type.width: + result = builder.trunc(result, slot_type) + builder.store(result, slot) def handle_cond(func, compilation_context, builder, cond, local_sym_tab):