IR生成文件即IRGenxx设计
This commit is contained in:
@@ -2,3 +2,35 @@
|
||||
// - 处理算术运算、比较、逻辑运算、函数调用等表达式
|
||||
// - 生成对应的 IR 指令并返回 SSA 值
|
||||
|
||||
#include "irgen/IRGen.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#include "ast/AstNodes.h"
|
||||
#include "ir/IR.h"
|
||||
|
||||
ir::Value* IRGenImpl::GenExpr(const ast::Expr& expr) {
|
||||
if (auto num = dynamic_cast<const ast::NumberExpr*>(&expr)) {
|
||||
return ir::DefaultContext().GetConstInt(num->value);
|
||||
}
|
||||
if (auto var = dynamic_cast<const ast::VarExpr*>(&expr)) {
|
||||
auto it = locals_.find(var->name);
|
||||
if (it == locals_.end()) {
|
||||
throw std::runtime_error("变量未找到: " + var->name);
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
if (auto bin = dynamic_cast<const ast::BinaryExpr*>(&expr)) {
|
||||
auto* lhs = GenExpr(*bin->lhs);
|
||||
auto* rhs = GenExpr(*bin->rhs);
|
||||
std::string name = ir::DefaultContext().NextTemp();
|
||||
if (bin->op == ast::BinaryOp::Add) {
|
||||
return builder_.CreateBinary(ir::Opcode::Add, lhs, rhs, name);
|
||||
}
|
||||
if (bin->op == ast::BinaryOp::Sub) {
|
||||
// 当前子集只需要加法,减法复用 add 但保留分支,便于扩展
|
||||
return builder_.CreateBinary(ir::Opcode::Add, lhs, rhs, name);
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("不支持的表达式类型");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user