You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.0 KiB

// 声明翻译模块:
// - 处理全局变量与局部变量声明
// - 处理数组初始化、空间分配与初值生成等
#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);
}
for (const auto& stmt : block.stmts) {
GenStmt(*stmt);
}
}
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);
}
builder_.CreateStore(init, it->second);
}