Add binops

This commit is contained in:
Sofia 2026-04-13 18:11:54 +03:00
parent 9791c9c8da
commit bb4d1c6045
2 changed files with 62 additions and 1 deletions

View File

@ -3,6 +3,61 @@
namespace types { namespace types {
std::vector<BinopDefinition> create_binops() { std::vector<BinopDefinition> create_binops() {
std::vector<BinopDefinition> definitions{};
auto int_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Int } };
auto char_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Char } };
auto bool_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Bool } };
for (auto& ty : { int_ty, char_ty, bool_ty }) {
// Arithmetic binops
definitions.push_back(BinopDefinition{
ty, types::BinOp::Add, ty,
ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateAdd(lhs, rhs, "add");
} });
definitions.push_back(BinopDefinition{
ty, types::BinOp::Sub, ty,
ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateSub(lhs, rhs, "sub");
} });
// Comparisons
definitions.push_back(BinopDefinition{
ty, types::BinOp::LessThan, ty,
bool_ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateICmpSLE(lhs, rhs, "icmpsle");
} });
definitions.push_back(BinopDefinition{
ty, types::BinOp::GreaterThan, ty,
bool_ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateICmpSGT(lhs, rhs, "icmpsgt");
} });
}
return definitions;
}
std::optional<BinopDefinition> find_binop(
std::vector<BinopDefinition>& binops,
std::shared_ptr<types::Type> lhs,
BinOp op,
std::shared_ptr<types::Type> rhs) {
for (auto& binop : binops) {
if (binop.op != op) {
continue;
}
if (!types_equal(lhs, binop.lhs) || !types_equal(rhs, binop.rhs)) {
continue;
}
return binop;
}
return {}; return {};
} }
} }

View File

@ -23,11 +23,17 @@ namespace types {
BinOp op; BinOp op;
std::shared_ptr<Type> rhs; std::shared_ptr<Type> rhs;
std::shared_ptr<Type> result; std::shared_ptr<Type> result;
llvm::Value* (*codegen)(codegen::Builder& builder); llvm::Value* (*codegen)(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs);
}; };
std::vector<BinopDefinition> create_binops(); std::vector<BinopDefinition> create_binops();
std::optional<BinopDefinition> find_binop(
std::vector<BinopDefinition>& binops,
std::shared_ptr<types::Type> lhs,
BinOp op,
std::shared_ptr<types::Type> rhs);
} }
#endif #endif