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.

79 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// IR Function
// - 保存参数列表、基本块列表
// - 记录函数属性/元信息(按需要扩展)
#include "ir/IR.h"
namespace ir {
Function::Function(std::string name, std::shared_ptr<Type> 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<Argument>(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<BasicBlock>(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<std::unique_ptr<BasicBlock>>& Function::GetBlocks() const {
return blocks_;
}
const std::vector<std::unique_ptr<Argument>>& 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<Type> Function::GetFunctionType() const { return type_; }
std::shared_ptr<Type> 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<Type> ty, std::string name, size_t index)
: Value(std::move(ty), std::move(name)), index_(index) {}
} // namespace ir