#include "irgen/IRGen.h" #include #include "SysYParser.h" #include "ir/IR.h" #include "utils/Log.h" namespace { void VerifyFunctionStructure(const ir::Function& func) { // 当前 IRGen 仍是单入口、顺序生成;这里在生成结束后补一层块终结校验。 for (const auto& bb : func.blocks()) { if (!bb || !bb->HasTerminator()) { throw std::runtime_error( FormatError("irgen", "基本块未正确终结: " + (bb ? bb->name() : std::string("")))); } } } } // namespace IRGenImpl::IRGenImpl(ir::Module& module) : module_(module), func_(nullptr), builder_(nullptr) {} void IRGenImpl::Gen(SysYParser::CompUnitContext& cu) { if (!cu.funcDef()) { throw std::runtime_error(FormatError("irgen", "缺少 main 定义")); } GenFuncDef(*cu.funcDef()); } void IRGenImpl::GenFuncDef(SysYParser::FuncDefContext& func) { if (!func.block()) { throw std::runtime_error(FormatError("irgen", "函数体为空")); } if (!func.Ident()) { throw std::runtime_error(FormatError("irgen", "缺少函数名")); } func_ = module_.CreateFunction(func.Ident()->getText(), ir::Type::Int32()); builder_.SetInsertPoint(func_->entry()); locals_.clear(); GenBlock(*func.block()); // 语义正确性主要由 sema 保证,这里只兜底检查 IR 结构是否合法。 VerifyFunctionStructure(*func_); }