Skip to content

Commit

Permalink
[cpp] added __builtin_sizeof, and binary addition/subtraction now und…
Browse files Browse the repository at this point in the history
…ertakes integer promotio
  • Loading branch information
harrand committed Apr 30, 2024
1 parent b45389e commit 3881642
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
26 changes: 22 additions & 4 deletions cpp/src/codegen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -637,11 +637,11 @@ namespace codegen
case lexer::token::type::plus:
if(lhs_value.ty.is_floating_point_type())
{
ret.llv = builder->CreateFAdd(lhs_value.llv, rhs_value.llv);
ret.llv = builder->CreateFAdd(lhs_value.llv, load_as(rhs_value.llv, d.state, rhs_value.ty, lhs_value.ty));
}
else if(lhs_value.ty.is_integer_type())
{
ret.llv = builder->CreateAdd(lhs_value.llv, rhs_value.llv);
ret.llv = builder->CreateAdd(lhs_value.llv, load_as(rhs_value.llv, d.state, rhs_value.ty, lhs_value.ty));
}
else
{
Expand All @@ -653,11 +653,11 @@ namespace codegen
case lexer::token::type::minus:
if(lhs_value.ty.is_floating_point_type())
{
ret.llv = builder->CreateFSub(lhs_value.llv, rhs_value.llv);
ret.llv = builder->CreateFSub(lhs_value.llv, load_as(rhs_value.llv, d.state, rhs_value.ty, lhs_value.ty));
}
else if(lhs_value.ty.is_integer_type())
{
ret.llv = builder->CreateSub(lhs_value.llv, rhs_value.llv);
ret.llv = builder->CreateSub(lhs_value.llv, load_as(rhs_value.llv, d.state, rhs_value.ty, lhs_value.ty));
}
else
{
Expand Down Expand Up @@ -1364,6 +1364,24 @@ namespace codegen
type ty = this->state.try_get_type_from_payload(ptr_expr, this->tree, this->path);
ret = string_literal(*this, {.val = ty.name()});
}
if(call.function_name == "__builtin_sizeof")
{
this->assert_that(call.params.size() == 1, "__builtin_typename requires one argument.");
const ast::expression& ptr_expr = call.params.front();
// if you call any codegen functions, you will uh... generate code.
// we *must* only rely on semantic analysis here.
type ty = type::undefined();
if(std::holds_alternative<ast::identifier>(ptr_expr.expr))
{
ty = this->state.get_type_from_name(std::get<ast::identifier>(ptr_expr.expr).name).first;
}
if(ty.is_undefined())
{
ty = this->state.try_get_type_from_payload(ptr_expr, this->tree, this->path);
}
int size = program->getDataLayout().getTypeAllocSize(as_llvm_type(ty, state));
ret = integer_literal(*this, {.val = size});
}
return ret;
}
}
2 changes: 1 addition & 1 deletion samples/scratchpad.psy
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ triangle : struct

main : (argc : i64, argv : i8**) -> i64
{
shape_ptr : triangle* = default_malloc(64);
shape_ptr : triangle* = default_malloc(__builtin_sizeof(triangle));
defer default_free(shape_ptr);
= shape_ptr->base 'A';
= shape_ptr->height 19;
Expand Down

0 comments on commit 3881642

Please sign in to comment.