refactor(irgen): IR改成alloca和store形式
This commit is contained in:
@@ -5,11 +5,18 @@
|
||||
#include "irgen/IRGen.h"
|
||||
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "ast/AstNodes.h"
|
||||
#include "ir/IR.h"
|
||||
|
||||
void IRGenImpl::GenBlock(const ast::Block& block) {
|
||||
// 先为所有局部变量创建栈槽,使 alloca 聚集在入口块前部。
|
||||
for (const auto& decl : block.varDecls) {
|
||||
auto* slot = builder_.CreateAllocaI32(ir::DefaultContext().NextTemp());
|
||||
locals_[decl->name] = slot;
|
||||
}
|
||||
|
||||
for (const auto& decl : block.varDecls) {
|
||||
GenVarDecl(*decl);
|
||||
}
|
||||
@@ -19,11 +26,16 @@ void IRGenImpl::GenBlock(const ast::Block& block) {
|
||||
}
|
||||
|
||||
void IRGenImpl::GenVarDecl(const ast::VarDecl& decl) {
|
||||
auto it = locals_.find(decl.name);
|
||||
if (it == locals_.end()) {
|
||||
throw std::runtime_error("变量栈槽未创建: " + decl.name);
|
||||
}
|
||||
|
||||
ir::Value* init = nullptr;
|
||||
if (decl.init) {
|
||||
init = GenExpr(*decl.init);
|
||||
} else {
|
||||
init = ir::DefaultContext().GetConstInt(0);
|
||||
}
|
||||
locals_[decl.name] = init;
|
||||
builder_.CreateStore(init, it->second);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,8 @@ ir::Value* IRGenImpl::GenExpr(const ast::Expr& expr) {
|
||||
if (it == locals_.end()) {
|
||||
throw std::runtime_error("变量未找到: " + var->name);
|
||||
}
|
||||
return it->second;
|
||||
std::string name = ir::DefaultContext().NextTemp();
|
||||
return builder_.CreateLoad(it->second, name);
|
||||
}
|
||||
if (auto bin = dynamic_cast<const ast::BinaryExpr*>(&expr)) {
|
||||
auto* lhs = GenExpr(*bin->lhs);
|
||||
|
||||
Reference in New Issue
Block a user