Skip to content

Commit 27ab3aa

Browse files
committed
Cleanup codegen.py
1 parent b34f7dd commit 27ab3aa

File tree

1 file changed

+29
-27
lines changed

1 file changed

+29
-27
lines changed

pythonbpf/codegen.py

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,33 @@ def compile_to_ir(filename: str, output: str, loglevel=logging.INFO):
130130
return output
131131

132132

133+
def _run_llc(ll_file, obj_file):
134+
"""Compile LLVM IR to BPF object file using llc."""
135+
136+
logger.info(f"Compiling IR to object: {ll_file} -> {obj_file}")
137+
result = subprocess.run(
138+
[
139+
"llc",
140+
"-march=bpf",
141+
"-filetype=obj",
142+
"-O2",
143+
str(ll_file),
144+
"-o",
145+
str(obj_file),
146+
],
147+
check=True,
148+
capture_output=True,
149+
text=True,
150+
)
151+
152+
if result.returncode == 0:
153+
logger.info(f"Object file written to {obj_file}")
154+
return True
155+
else:
156+
logger.error(f"llc compilation failed: {result.stderr}")
157+
return False
158+
159+
133160
def compile(loglevel=logging.INFO) -> bool:
134161
# Look one level up the stack to the caller of this function
135162
caller_frame = inspect.stack()[1]
@@ -143,21 +170,7 @@ def compile(loglevel=logging.INFO) -> bool:
143170
compile_to_ir(str(caller_file), str(ll_file), loglevel=loglevel) and success
144171
)
145172

146-
success = bool(
147-
subprocess.run(
148-
[
149-
"llc",
150-
"-march=bpf",
151-
"-filetype=obj",
152-
"-O2",
153-
str(ll_file),
154-
"-o",
155-
str(o_file),
156-
],
157-
check=True,
158-
)
159-
and success
160-
)
173+
success = _run_llc(ll_file, o_file) and success
161174

162175
logger.info(f"Object written to {o_file}")
163176
return success
@@ -177,17 +190,6 @@ def BPF(loglevel=logging.INFO) -> BpfProgram:
177190
f.flush()
178191
source = f.name
179192
compile_to_ir(source, str(inter.name), loglevel=loglevel)
180-
subprocess.run(
181-
[
182-
"llc",
183-
"-march=bpf",
184-
"-filetype=obj",
185-
"-O2",
186-
str(inter.name),
187-
"-o",
188-
str(obj_file.name),
189-
],
190-
check=True,
191-
)
193+
_run_llc(str(inter.name), str(obj_file.name))
192194

193195
return BpfProgram(str(obj_file.name))

0 commit comments

Comments
 (0)