fix(ir): 修改了一下context的管理

This commit is contained in:
jing
2026-03-11 23:04:28 +08:00
parent fab6983d40
commit 0e5a75eaf3
13 changed files with 112 additions and 106 deletions

View File

@@ -4,9 +4,9 @@
#include "ir/IR.h"
#include <iostream>
#include <string>
#include <ostream>
#include <stdexcept>
#include <string>
namespace ir {
@@ -49,15 +49,15 @@ static std::string ValueToString(const Value* v) {
return v ? v->name() : "<null>";
}
void IRPrinter::Print(const Module& module) {
void IRPrinter::Print(const Module& module, std::ostream& os) {
for (const auto& func : module.functions()) {
std::cout << "define " << TypeToString(*func->type()) << " @"
<< func->name() << "() {\n";
os << "define " << TypeToString(*func->type()) << " @" << func->name()
<< "() {\n";
for (const auto& bb : func->blocks()) {
if (!bb) {
continue;
}
std::cout << bb->name() << ":\n";
os << bb->name() << ":\n";
for (const auto& instPtr : bb->instructions()) {
const auto* inst = instPtr.get();
switch (inst->opcode()) {
@@ -65,39 +65,39 @@ void IRPrinter::Print(const Module& module) {
case Opcode::Sub:
case Opcode::Mul: {
auto* bin = static_cast<const BinaryInst*>(inst);
std::cout << " " << bin->name() << " = " << OpcodeToString(bin->opcode())
<< " " << TypeToString(*bin->lhs()->type()) << " "
<< ValueToString(bin->lhs()) << ", "
<< ValueToString(bin->rhs()) << "\n";
os << " " << bin->name() << " = " << OpcodeToString(bin->opcode())
<< " " << TypeToString(*bin->lhs()->type()) << " "
<< ValueToString(bin->lhs()) << ", "
<< ValueToString(bin->rhs()) << "\n";
break;
}
case Opcode::Alloca: {
auto* alloca = static_cast<const AllocaInst*>(inst);
std::cout << " " << alloca->name() << " = alloca i32\n";
os << " " << alloca->name() << " = alloca i32\n";
break;
}
case Opcode::Load: {
auto* load = static_cast<const LoadInst*>(inst);
std::cout << " " << load->name() << " = load i32, i32* "
<< ValueToString(load->ptr()) << "\n";
os << " " << load->name() << " = load i32, i32* "
<< ValueToString(load->ptr()) << "\n";
break;
}
case Opcode::Store: {
auto* store = static_cast<const StoreInst*>(inst);
std::cout << " store i32 " << ValueToString(store->value()) << ", i32* "
<< ValueToString(store->ptr()) << "\n";
os << " 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()) << " "
<< ValueToString(ret->value()) << "\n";
os << " ret " << TypeToString(*ret->value()->type()) << " "
<< ValueToString(ret->value()) << "\n";
break;
}
}
}
}
std::cout << "}\n";
os << "}\n";
}
}