[lab3] add print support for functions, blocks and instructions

This commit is contained in:
lixuanwang
2025-05-27 11:43:14 +08:00
parent dc7202849c
commit 29aea7781f
3 changed files with 21 additions and 8 deletions

View File

@@ -2,14 +2,26 @@ class MiddleFunction:
def __init__(self, name: str):
self.name = name
self.basic_blocks = [] # List[MiddleBasicBlock]
def __repr__(self):
return f"Function({self.name}):\n" + "\n".join(str(block) for block in self.basic_blocks)
def __str__(self):
return self.__repr__()
class MiddleBasicBlock:
def __init__(self, name: str):
self.name = name
self.instructions = [] # List[MiddleInstruction]
def __repr__(self):
return f"BasicBlock({self.name}):\n" + "\n".join(str(instr) for instr in self.instructions)
def __str__(self):
return self.__repr__()
class MiddleInstruction:
def __init__(self, opcode: str, operands: list, dest=None):
self.opcode = opcode # e.g., 'add'
self.operands = operands # e.g., ['5', '7']
self.dest = dest # e.g., '%0'
def __repr__(self):
return f"{self.dest} = {self.opcode} " + ", ".join(self.operands) if self.dest else f"{self.opcode} " + ", ".join(self.operands)
def __str__(self):
return self.__repr__()

View File

@@ -18,8 +18,7 @@ def parse_llvm_ir(ir_text: str) -> MiddleFunction:
for instr in block.instructions:
opcode = instr.opcode
operands = [str(op) for op in instr.operands]
# 调试输出
print(f"Instruction: {instr}, Opcode: {opcode}, Operands: {operands}")
# 如果是有返回值的指令(如 add第一个操作数是 dest
dest = None
if hasattr(instr, 'name') and instr.name:

View File

@@ -3,8 +3,9 @@ from sysy.utils.ir_parser import parse_llvm_ir
from sysy.backend.x86_emitter import X86Emitter
def main():
if len(sys.argv) != 3:
print("Usage: sysyc.py <input.ll> <output.s>")
if len(sys.argv) != 2:
# print("Usage: sysyc.py <input.ll> <output.s>")
print("Usage: sysyc.py <input.ll>")
sys.exit(1)
# 读取 LLVM IR
@@ -13,11 +14,12 @@ def main():
# 解析并生成汇编
func = parse_llvm_ir(ir_text)
print(func)
asm = X86Emitter().emit_function(func)
# 写入文件
with open(sys.argv[2], 'w') as f:
f.write(asm)
# with open(sys.argv[2], 'w') as f:
# f.write(asm)
print(asm)
if __name__ == "__main__":
main()