// IR Function: // - 保存参数列表、基本块列表 // - 记录函数属性/元信息(按需要扩展) #include "ir/IR.h" namespace ir { Function::Function(std::string name, std::shared_ptr func_type, bool is_declaration) : Value(std::move(func_type), std::move(name)), is_declaration_(is_declaration) { if (!type_ || !type_->IsFunction()) { throw std::runtime_error("Function 需要 function type"); } const auto& params = type_->GetParamTypes(); args_.reserve(params.size()); for (size_t i = 0; i < params.size(); ++i) { args_.push_back(std::make_unique(params[i], "%arg" + std::to_string(i), i)); } if (!is_declaration_) { entry_ = CreateBlock("entry"); } } BasicBlock* Function::CreateBlock(const std::string& name) { std::string base = name.empty() ? "bb" : name; auto& count = block_name_counts_[base]; std::string final_name = base; if (count > 0) { final_name = base + "." + std::to_string(count); } ++count; auto block = std::make_unique(final_name); auto* ptr = block.get(); ptr->SetParent(this); blocks_.push_back(std::move(block)); if (!entry_) { entry_ = ptr; } return ptr; } BasicBlock* Function::GetEntry() { return entry_; } const BasicBlock* Function::GetEntry() const { return entry_; } const std::vector>& Function::GetBlocks() const { return blocks_; } const std::vector>& Function::GetArguments() const { return args_; } size_t Function::GetNumArgs() const { return args_.size(); } Argument* Function::GetArg(size_t index) { if (index >= args_.size()) { throw std::out_of_range("Function arg index out of range"); } return args_[index].get(); } std::shared_ptr Function::GetFunctionType() const { return type_; } std::shared_ptr Function::GetReturnType() const { if (!type_ || !type_->IsFunction()) { throw std::runtime_error("Function type 缺失"); } return type_->GetReturnType(); } bool Function::IsDeclaration() const { return is_declaration_; } Argument::Argument(std::shared_ptr ty, std::string name, size_t index) : Value(std::move(ty), std::move(name)), index_(index) {} } // namespace ir