fix(ir): 规范ir实现

This commit is contained in:
jing
2026-03-11 00:38:05 +08:00
parent c72ffa6e39
commit 8f448df4bc
8 changed files with 132 additions and 22 deletions

View File

@@ -5,6 +5,7 @@
#include "ir/IR.h"
#include <iostream>
#include <string>
#include <stdexcept>
namespace ir {
@@ -41,6 +42,13 @@ static const char* OpcodeToString(Opcode op) {
return "?";
}
static std::string ValueToString(const Value* v) {
if (auto* ci = dynamic_cast<const ConstantInt*>(v)) {
return std::to_string(ci->value());
}
return v ? v->name() : "<null>";
}
void IRPrinter::Print(const Module& module) {
for (const auto& func : module.functions()) {
std::cout << "define " << TypeToString(*func->type()) << " @"
@@ -60,7 +68,8 @@ void IRPrinter::Print(const Module& module) {
auto* bin = static_cast<const BinaryInst*>(inst);
std::cout << " " << bin->name() << " = " << OpcodeToString(bin->opcode())
<< " " << TypeToString(*bin->lhs()->type()) << " "
<< bin->lhs()->name() << ", " << bin->rhs()->name() << "\n";
<< ValueToString(bin->lhs()) << ", "
<< ValueToString(bin->rhs()) << "\n";
break;
}
case Opcode::Alloca: {
@@ -71,19 +80,19 @@ void IRPrinter::Print(const Module& module) {
case Opcode::Load: {
auto* load = static_cast<const LoadInst*>(inst);
std::cout << " " << load->name() << " = load i32, i32* "
<< load->ptr()->name() << "\n";
<< ValueToString(load->ptr()) << "\n";
break;
}
case Opcode::Store: {
auto* store = static_cast<const StoreInst*>(inst);
std::cout << " store i32 " << store->value()->name() << ", i32* "
<< store->ptr()->name() << "\n";
std::cout << " store i32 " << ValueToString(store->value()) << ", i32* "
<< ValueToString(store->ptr()) << "\n";
break;
}
case Opcode::Ret: {
auto* ret = static_cast<const ReturnInst*>(inst);
std::cout << " ret " << TypeToString(*ret->value()->type()) << " "
<< ret->value()->name() << "\n";
<< ValueToString(ret->value()) << "\n";
break;
}
}