feat(furc/IR): move IR from furlang to furc

First try baby, whoo!
This commit is contained in:
2026-08-10 18:34:10 +02:00
parent b9d50c62af
commit 0e916c314a
8 changed files with 665 additions and 1298 deletions
+406
View File
@@ -0,0 +1,406 @@
#ifndef FURC_BACK_IR_HPP
#define FURC_BACK_IR_HPP
#include "furc/front/ast.hpp"
#include "furlang/arena.hpp"
#include <algorithm>
#include <cstdint>
#include <initializer_list>
#include <optional>
#include <stack>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
namespace furc {
struct ir_operand {
enum type_e {
Integer = 0,
Register,
Variable,
Function,
Block,
BlockPair,
PhiPair,
} type;
union value_u {
std::uint64_t integer;
struct register_s {
std::uint64_t name : 54;
std::uint64_t ver : 10;
} reg;
std::uint16_t variable;
std::uint64_t function;
std::uint64_t block;
struct block_pair_s {
std::uint64_t first;
std::uint64_t second;
} blockPair;
struct phi_pair_s {
register_s reg;
std::uint64_t block;
} phiPair;
value_u() = default;
value_u(std::uint64_t integer)
: integer(integer) {}
value_u(std::uint16_t variable)
: variable(variable) {}
value_u(std::uint64_t first, std::uint64_t second)
: blockPair({ first, second }) {}
value_u(register_s reg, std::uint64_t block)
: phiPair({ reg, block }) {}
} value;
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<value_u, Args...>>>
ir_operand(type_e type, Args&&... args)
: type(type), value(std::forward<Args>(args)...) {}
};
struct ir_type {
enum type_e {
Void = 0,
S8,
U8,
S16,
U16,
S32,
U32,
S64,
U64,
} type = Void;
};
// TODO: Add data types to instructions (like mov QWORD ... in x86 assembly)
struct ir_instruction {
enum type_e {
Move = 0,
Call,
Branch,
BranchCond,
Return,
Phi,
Add,
Sub,
Mul,
Div,
Mod,
Shl,
Shr,
BinAnd,
BinOr,
BinXor,
And,
Or,
Eq,
NotEq,
LessThan,
LessEq,
GreaterThan,
GreaterEq,
Positive,
Negative,
Increment,
Decrement,
BinNot,
Not,
Sizeof,
Pointerof,
Lenof,
} type;
std::optional<ir_operand> destination;
std::vector<ir_operand> sources;
ir_instruction(type_e type,
std::optional<ir_operand> destination = {},
std::initializer_list<ir_operand> sources = {})
: type(type), destination(destination), sources(sources) {}
static constexpr bool is_terminating(type_e type) {
switch (type) {
case Branch:
case BranchCond:
case Return: return true;
default: return false;
}
}
};
struct ir_basic_block {
std::vector<ir_instruction> instructions;
bool is_terminated() const {
return !instructions.empty() && ir_instruction::is_terminating(instructions.back().type);
}
};
struct ir_variable {
ir_variable() = default;
ir_variable(ir_type type)
: type(type) {}
virtual ~ir_variable() = default;
ir_variable(ir_variable&&) noexcept = default;
ir_variable& operator=(ir_variable&&) noexcept = default;
ir_variable(const ir_variable&) = default;
ir_variable& operator=(const ir_variable&) = default;
ir_type type;
virtual ir_operand operand() const = 0;
};
struct ir_module_variable : ir_variable {
ir_module_variable(ir_type type, std::uint16_t name)
: ir_variable(type), name(name) {}
std::uint16_t name;
ir_operand operand() const final { return { ir_operand::Variable, name }; }
};
struct ir_function_variable : ir_variable {
ir_function_variable(ir_type type, std::uint64_t name)
: ir_variable(type), name(name) {}
std::uint64_t name;
ir_operand operand() const final { return { ir_operand::Register, name }; }
};
struct ir_scope {
ir_scope() = default;
virtual ~ir_scope() = default;
ir_scope(ir_scope&&) noexcept = default;
ir_scope& operator=(ir_scope&&) noexcept = default;
ir_scope(const ir_scope&) = default;
ir_scope& operator=(const ir_scope&) = default;
ir_scope* previous = nullptr;
std::unordered_map<std::string, ir_variable*> variables;
const ir_variable* variable(const std::string& name) const {
if (auto it = variables.find(name); it != variables.end()) return it->second;
return (previous != nullptr) ? previous->variable(name) : nullptr;
}
virtual const ir_variable* allocate(furlang::arena& arena, const std::string& name, ir_type type) = 0;
};
struct ir_function : ir_scope {
enum type_e {
Normal = 0,
Import,
Native,
} type = Normal;
enum access_e {
Public = 0,
Private,
} access = Public;
std::string name;
std::vector<ir_type> params;
ir_type retType;
std::vector<ir_basic_block> blocks;
std::uint64_t regCount = 0;
const ir_variable* allocate(furlang::arena& arena, const std::string& name, ir_type type) final {
return variables[name] = arena.allocate<ir_function_variable>(type, regCount++);
}
static ir_function from_name(std::string&& name) {
ir_function func;
func.name = std::move(name);
return func;
}
};
struct ir_module : ir_scope {
std::vector<ir_function*> functions;
furlang::arena arena;
std::uint16_t varCount = 0;
const ir_variable* allocate(furlang::arena& arena, const std::string& name, ir_type type) final {
return variables[name] = arena.allocate<ir_module_variable>(type, varCount);
}
ir_function* add_function(ir_function&& function) {
return functions.emplace_back(arena.allocate<ir_function>(std::move(function)));
}
};
struct ir_context {
ir_context(ir_function* function)
: function(function) {
if (function->blocks.empty()) new_last();
blockPtr = &function->blocks.front();
}
~ir_context() {
if (blockPtr == nullptr) return;
if (!blockPtr->is_terminated()) {
if (blockIdx + 1 == function->blocks.size()) {
add_instr(ir_instruction::Return);
} else {
add_instr(ir_instruction::Branch, ir_operand{ ir_operand::Block, blockIdx + 1 });
}
}
}
ir_context(ir_context&& other) noexcept
: function(other.function), blockIdx(other.blockIdx), blockPtr(other.blockPtr) {
other.function = nullptr;
other.blockIdx = 0;
other.blockPtr = nullptr;
}
ir_context& operator=(ir_context&& other) noexcept {
if (this == &other) return *this;
function = other.function;
blockIdx = other.blockIdx;
blockPtr = other.blockPtr;
other.function = nullptr;
other.blockIdx = 0;
other.blockPtr = nullptr;
return *this;
}
ir_context(const ir_context&) = delete;
ir_context& operator=(const ir_context&) = delete;
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<ir_instruction, Args...>>>
ir_instruction& add_instr(Args&&... args) {
auto it = blockPtr->instructions.end();
if (!blockPtr->instructions.empty() && ir_instruction::is_terminating(blockPtr->instructions.back().type)) --it;
it = blockPtr->instructions.emplace(it, std::forward<Args>(args)...);
if (ir_instruction::is_terminating(it->type) && it + 1 != blockPtr->instructions.end())
blockPtr->instructions.pop_back();
return *it;
}
void terminate() { add_instr(ir_instruction::Return); }
void terminate(ir_operand value) { add_instr(ir_instruction::Return, value); }
void terminate(std::uint64_t block) { add_instr(ir_instruction::Branch, ir_operand{ ir_operand::Block, block }); }
ir_instruction* terminate(ir_operand cond, std::uint64_t thenBranch, std::uint64_t elseBranch) {
return &add_instr(ir_instruction{ ir_instruction::BranchCond,
ir_operand{ ir_operand::BlockPair, thenBranch, elseBranch },
{ cond } });
}
ir_context& new_next() {
if (blockPtr->instructions.empty()) return *this;
auto it = function->blocks.begin() + static_cast<std::ptrdiff_t>(++blockIdx);
if (!blockPtr->is_terminated()) terminate(blockIdx);
blockPtr = &*function->blocks.emplace(it);
return *this;
}
ir_context& new_last() {
blockIdx = function->blocks.size();
blockPtr = &*function->blocks.emplace(function->blocks.end());
return *this;
}
ir_context& go(std::uint64_t block) {
blockIdx = std::min(block, function->blocks.size() - 1);
blockPtr = function->blocks.data() + static_cast<std::ptrdiff_t>(blockIdx);
return *this;
}
ir_context& go_next() { return go(blockIdx + 1); }
ir_context& go_last() { return go(std::min<std::uint64_t>(0, function->blocks.size() - 1)); }
ir_operand last_register() const { return { ir_operand::Register, function->regCount - 1 }; }
ir_operand next_register() const { return { ir_operand::Register, function->regCount++ }; }
static ir_operand block_op(std::uint64_t blockIdx) { return { ir_operand::Block, blockIdx }; }
ir_function* function = nullptr;
std::uint64_t blockIdx = 0;
ir_basic_block* blockPtr = nullptr;
};
class ir_generator final : public ast_visitor {
public:
ir_generator()
: m_initContext(m_module.add_function(ir_function::from_name("module$init"))) {}
void finalize() {
m_module.functions.front()->blocks.emplace_back().instructions.push_back(
ir_instruction{ ir_instruction::Return });
}
ir_module build() {
m_scope = nullptr;
m_context = {};
m_initContext.blockPtr = nullptr;
return std::move(m_module);
}
static ir_module generate(const ast_node& node) {
ir_generator gen;
node.accept(gen);
gen.finalize();
return gen.build();
}
static ir_module generate(const ast& tree) {
ir_generator gen;
for (const auto& node : tree.decls)
node->accept(gen);
gen.finalize();
return gen.build();
}
private:
void visit_comp_stmt_node(const comp_stmt_node& node) override;
void visit_if_stmt_node(const if_stmt_node& node) override;
void visit_while_stmt_node(const while_stmt_node& node) override;
void visit_return_stmt_node(const return_stmt_node& node) override;
void visit_var_decl_node(const var_decl_node& node) override;
void visit_func_decl_node(const func_decl_node& node) override;
void visit_var_read_expr_node(const var_read_expr_node& node) override;
void visit_func_call_expr_node(const func_call_expr_node& node) override;
void visit_group_expr_node(const group_expr_node& node) override;
void visit_binary_op_expr_node(const binary_op_expr_node& node) override;
void visit_unary_op_expr_node(const unary_op_expr_node& node) override;
void visit_if_expr_node(const if_expr_node& node) override;
void visit_int_lit_node(const int_lit_node& node) override;
void visit_char_lit_node(const char_lit_node& node) override;
private:
ir_context& context() { return m_context.top(); }
private:
ir_module m_module;
ir_scope* m_scope = &m_module;
std::stack<ir_context> m_context;
ir_context m_initContext;
};
} // namespace furc
#endif // FURC_BACK_IR_HPP
+254
View File
@@ -0,0 +1,254 @@
#include "furc/back/ir.hpp"
#include "furc/front/ast.hpp"
#include <stdexcept>
#include <utility>
namespace furc {
static ir_type ast_type_to_ir(const ast_type& type) {
switch (type.type) {
case ast_type::Void: return { ir_type::Void };
case ast_type::S8: return { ir_type::S8 };
case ast_type::U8: return { ir_type::U8 };
case ast_type::S16: return { ir_type::S16 };
case ast_type::U16: return { ir_type::U16 };
case ast_type::S32: return { ir_type::S32 };
case ast_type::U32: return { ir_type::U32 };
case ast_type::S64: return { ir_type::S64 };
case ast_type::U64: return { ir_type::U64 };
}
throw std::runtime_error("unreachable");
}
void ir_generator::visit_comp_stmt_node(const comp_stmt_node& node) {
// TODO: Introduce scopes for statements to naturally allow variable shadowing.
for (const auto& stmt : node.stmts) {
stmt->accept(*this);
}
}
void ir_generator::visit_if_stmt_node(const if_stmt_node& node) {
node.cond->accept(*this);
auto* branch = context().terminate(context().last_register(), context().blockIdx + 1, 0);
context().new_next();
node.thenBranch->accept(*this);
context().new_next();
branch->destination->value.blockPair.second = context().blockIdx; // NOLINT
if (node.elseBranch != nullptr) {
node.elseBranch->accept(*this);
context().new_next();
}
}
void ir_generator::visit_while_stmt_node(const while_stmt_node& node) {
context().new_next();
auto header = context().blockIdx;
node.cond->accept(*this);
auto* branch = context().terminate(context().last_register(), context().blockIdx + 1, 0);
context().new_next();
auto body = context().blockIdx;
node.body->accept(*this);
if (!context().blockPtr->is_terminated()) context().terminate(header);
context().new_next();
branch->destination->value.blockPair.second = context().blockIdx; // NOLINT
}
void ir_generator::visit_return_stmt_node(const return_stmt_node& node) {
if (node.value == nullptr) {
context().terminate();
} else {
node.value->accept(*this);
context().terminate(context().last_register());
}
}
void ir_generator::visit_var_decl_node(const var_decl_node& node) {
const auto* var = m_scope->allocate(m_module.arena, node.name, ast_type_to_ir(node.type));
if (node.init != nullptr) {
if (m_context.empty()) {
m_initContext.new_next();
m_context.push(std::move(m_initContext));
node.init->accept(*this);
context().add_instr(ir_instruction{ ir_instruction::Move, var->operand(), { context().last_register() } });
m_initContext = std::move(m_context.top());
m_context.pop();
} else {
node.init->accept(*this);
context().add_instr(ir_instruction{ ir_instruction::Move, var->operand(), { context().last_register() } });
}
}
}
void ir_generator::visit_func_decl_node(const func_decl_node& node) {
ir_function function;
function.previous = m_scope;
function.name = node.name;
for (const auto& param : node.params) {
function.params.push_back(ast_type_to_ir(param.type));
function.allocate(m_module.arena, param.name, ast_type_to_ir(param.type));
}
function.retType = ast_type_to_ir(node.type);
if (node.def.has_value()) {
auto* func = m_module.functions.emplace_back(m_module.arena.allocate<ir_function>(std::move(function)));
m_context.emplace(func);
m_scope = func;
node.def->body.accept(*this);
m_scope = m_scope->previous;
m_context.pop();
}
}
void ir_generator::visit_var_read_expr_node(const var_read_expr_node& node) {
const auto* var = m_scope->variable(node.name);
if (var == nullptr) throw std::runtime_error("unknown variable");
context().add_instr(ir_instruction{ ir_instruction::Move, context().next_register(), { var->operand() } });
}
void ir_generator::visit_func_call_expr_node(const func_call_expr_node& node) {
throw std::runtime_error("not implemented");
}
void ir_generator::visit_group_expr_node(const group_expr_node& node) {
node.inner->accept(*this);
}
void ir_generator::visit_binary_op_expr_node(const binary_op_expr_node& node) {
node.lhs->accept(*this);
auto lhs = context().last_register();
node.rhs->accept(*this);
auto rhs = context().last_register();
switch (node.type) {
case binary_op_expr_node::Add:
context().add_instr(ir_instruction{ ir_instruction::Add, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Sub:
context().add_instr(ir_instruction{ ir_instruction::Sub, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Mul:
context().add_instr(ir_instruction{ ir_instruction::Mul, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Div:
context().add_instr(ir_instruction{ ir_instruction::Div, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Mod:
context().add_instr(ir_instruction{ ir_instruction::Mod, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Shl:
context().add_instr(ir_instruction{ ir_instruction::Shl, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Shr:
context().add_instr(ir_instruction{ ir_instruction::Shr, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::BinAnd:
context().add_instr(ir_instruction{ ir_instruction::BinAnd, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::BinOr:
context().add_instr(ir_instruction{ ir_instruction::BinOr, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::BinXor:
context().add_instr(ir_instruction{ ir_instruction::BinXor, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::And:
context().add_instr(ir_instruction{ ir_instruction::And, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Or:
context().add_instr(ir_instruction{ ir_instruction::Or, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::Equals:
context().add_instr(ir_instruction{ ir_instruction::Eq, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::NotEquals:
context().add_instr(ir_instruction{ ir_instruction::NotEq, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::LessThan:
context().add_instr(ir_instruction{ ir_instruction::LessThan, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::LessEquals:
context().add_instr(ir_instruction{ ir_instruction::LessEq, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::GreaterThan:
context().add_instr(ir_instruction{ ir_instruction::GreaterThan, context().next_register(), { lhs, rhs } });
return;
case binary_op_expr_node::GreaterEquals:
context().add_instr(ir_instruction{ ir_instruction::GreaterEq, context().next_register(), { lhs, rhs } });
return;
}
throw std::runtime_error("unreachable");
}
void ir_generator::visit_unary_op_expr_node(const unary_op_expr_node& node) {
if (node.type == unary_op_expr_node::PostInc || node.type == unary_op_expr_node::PostDec) {
node.lhs->accept(*this);
auto lhs = context().last_register();
node.lhs->accept(*this);
context().add_instr(node.type == unary_op_expr_node::PostInc ? ir_instruction::Increment
: ir_instruction::Decrement,
context().last_register());
return;
}
node.lhs->accept(*this);
auto lhs = context().last_register();
switch (node.type) {
case unary_op_expr_node::Positive: context().add_instr(ir_instruction::Positive, lhs);
case unary_op_expr_node::Negative: context().add_instr(ir_instruction::Negative, lhs);
case unary_op_expr_node::PreInc: context().add_instr(ir_instruction::Increment, lhs);
case unary_op_expr_node::PreDec: context().add_instr(ir_instruction::Decrement, lhs);
case unary_op_expr_node::BinNot: context().add_instr(ir_instruction::BinNot, lhs);
case unary_op_expr_node::Not: context().add_instr(ir_instruction::Not, lhs);
case unary_op_expr_node::Sizeof: context().add_instr(ir_instruction::Sizeof, lhs);
case unary_op_expr_node::Pointerof: context().add_instr(ir_instruction::Pointerof, lhs);
case unary_op_expr_node::Lengthof: context().add_instr(ir_instruction::Lenof, lhs);
case unary_op_expr_node::PostInc:
case unary_op_expr_node::PostDec: return;
}
throw std::runtime_error("unreachable");
}
void ir_generator::visit_if_expr_node(const if_expr_node& node) {
node.cond->accept(*this);
auto* branch = context().terminate(context().last_register(), context().blockIdx + 1, 0);
context().new_next();
auto thenBranch = context().blockIdx;
node.thenExpr->accept(*this);
auto thenReg = context().last_register();
context().new_next();
branch->destination->value.blockPair.second = context().blockIdx; // NOLINT
node.elseExpr->accept(*this);
auto elseReg = context().last_register();
auto resReg = context().next_register();
context().add_instr(ir_instruction{ ir_instruction::Move, resReg, { elseReg } });
context().new_next();
auto epilogue = context().blockIdx;
context().go(thenBranch);
context().add_instr(ir_instruction{ ir_instruction::Move, resReg, { thenReg } });
context().terminate(epilogue);
context().go(epilogue);
}
void ir_generator::visit_int_lit_node(const int_lit_node& node) {
context().add_instr(ir_instruction{ ir_instruction::Move,
context().next_register(),
{ ir_operand{ ir_operand::Integer, node.value } } });
}
void ir_generator::visit_char_lit_node(const char_lit_node& node) {
context().add_instr(ir_instruction{ ir_instruction::Move,
context().next_register(),
{ ir_operand{ ir_operand::Integer, static_cast<std::uint64_t>(node.value) } } });
}
} // namespace furc
+5 -6
View File
@@ -1,3 +1,4 @@
#include "furc/back/ir.hpp"
#include "furc/front/lexer.hpp"
#include "furc/front/parser.hpp"
#include "furlang/arena.hpp"
@@ -6,17 +7,15 @@ int main(void) {
furlang::arena arena;
std::string_view content = R"(
func main(argc: u64) -> s32 pre(arc > 1) {
func main(argc: u64) -> s32 {
x: s32 = 1 + 2 * 3;
println(x);
return if (x == 9) 1 else 0;
}
)";
furc::lexer lexer = { "<AK>", content };
furc::parser parser = { std::move(lexer), arena };
auto program = parser.parse();
furc::lexer lexer = { "<AK>", content };
furc::parser parser = { std::move(lexer), arena };
furc::ir_module irModule = furc::ir_generator::generate(parser.parse());
return 0;
}