Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new_runtime: impl. if #552

Merged
merged 2 commits into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 83 additions & 4 deletions lib/skc_async_experiment/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,12 @@ impl<'run, 'ictx: 'run> CodeGen<'run, 'ictx> {
// self.compile_op_call(blocks, block, lvars, op, lhs, rhs)
// }
hir::Expr::FunCall(fexpr, arg_exprs) => self.compile_funcall(ctx, fexpr, arg_exprs),
// hir::Expr::If(cond, then, els) => {
// self.compile_if(blocks, block, lvars, cond, then, els, &texpr.1)
// }
// hir::Expr::Yield(expr) => self.compile_yield(blocks, block, lvars, expr),
hir::Expr::If(cond, then, els) => self.compile_if(ctx, cond, then, els),
// hir::Expr::While(cond, exprs) => self.compile_while(blocks, block, lvars, cond, exprs),
hir::Expr::Alloc(name) => self.compile_alloc(ctx, name),
hir::Expr::Assign(name, rhs) => self.compile_assign(ctx, name, rhs),
hir::Expr::Return(val_expr) => self.compile_return(ctx, val_expr),
hir::Expr::Exprs(exprs) => self.compile_exprs(ctx, exprs),
hir::Expr::Cast(expr, cast_type) => self.compile_cast(ctx, expr, cast_type),
hir::Expr::Unbox(expr) => self.compile_unbox(ctx, expr),
hir::Expr::RawI64(n) => self.compile_raw_i64(*n),
Expand Down Expand Up @@ -194,6 +192,59 @@ impl<'run, 'ictx: 'run> CodeGen<'run, 'ictx> {
Some(ret.try_as_basic_value().left().unwrap())
}

fn compile_if(
&mut self,
ctx: &mut CodeGenContext<'run>,
cond_expr: &hir::TypedExpr,
then_exprs: &hir::TypedExpr,
else_exprs: &Option<Box<hir::TypedExpr>>,
) -> Option<inkwell::values::BasicValueEnum<'run>> {
let begin_block = self.context.append_basic_block(ctx.function, "IfBegin");
let then_block = self.context.append_basic_block(ctx.function, "IfThen");
let else_block = self.context.append_basic_block(ctx.function, "IfElse");
let merge_block = self.context.append_basic_block(ctx.function, "IfEnd");

// IfBegin:
self.builder.build_unconditional_branch(begin_block);
self.builder.position_at_end(begin_block);
let cond_value = self.compile_value_expr(ctx, cond_expr);
self.gen_conditional_branch(cond_value, then_block, else_block);
// IfThen:
self.builder.position_at_end(then_block);
let then_value = self.compile_expr(ctx, then_exprs);
if then_value.is_some() {
self.builder.build_unconditional_branch(merge_block);
}
let then_block_end = self.builder.get_insert_block().unwrap();
// IfElse:
self.builder.position_at_end(else_block);
let else_value = if let Some(else_exprs) = else_exprs {
self.compile_expr(ctx, else_exprs)
} else {
None
};
if else_value.is_some() {
self.builder.build_unconditional_branch(merge_block);
}
let else_block_end = self.builder.get_insert_block().unwrap();

// IfEnd:
self.builder.position_at_end(merge_block);
match (then_value, else_value) {
(None, None) => {
self.builder.build_unreachable();
None
}
(None, else_value) => else_value,
(then_value, None) => then_value,
(Some(then_val), Some(else_val)) => {
let phi_node = self.builder.build_phi(self.ptr_type(), "ifResult");
phi_node.add_incoming(&[(&then_val, then_block_end), (&else_val, else_block_end)]);
Some(phi_node.as_basic_value())
}
}
}

fn compile_alloc(
&self,
ctx: &mut CodeGenContext<'run>,
Expand Down Expand Up @@ -226,6 +277,18 @@ impl<'run, 'ictx: 'run> CodeGen<'run, 'ictx> {
None
}

fn compile_exprs(
&mut self,
ctx: &mut CodeGenContext<'run>,
exprs: &[hir::TypedExpr],
) -> Option<inkwell::values::BasicValueEnum<'run>> {
let mut last_val = None;
for e in exprs {
last_val = self.compile_expr(ctx, e);
}
last_val
}

// TODO: just remove this?
fn compile_cast<'a>(
&mut self,
Expand Down Expand Up @@ -257,6 +320,22 @@ impl<'run, 'ictx: 'run> CodeGen<'run, 'ictx> {
Some(llvm_n.into())
}

/// Generate conditional branch by Shiika Bool
fn gen_conditional_branch(
&mut self,
cond: inkwell::values::BasicValueEnum<'run>,
then_block: inkwell::basic_block::BasicBlock,
else_block: inkwell::basic_block::BasicBlock,
) {
let i = intrinsics::unbox_bool(self, SkObj::from_basic_value_enum(cond));
let one = self.context.bool_type().const_int(1, false);
let istrue = self
.builder
.build_int_compare(inkwell::IntPredicate::EQ, i, one, "istrue");
self.builder
.build_conditional_branch(istrue, then_block, else_block);
}

fn llvm_function_type(&self, fun_ty: &hir::FunTy) -> inkwell::types::FunctionType<'ictx> {
let param_tys = self.llvm_types(&fun_ty.param_tys);
let ret_ty = self.llvm_type(&fun_ty.ret_ty);
Expand Down
10 changes: 10 additions & 0 deletions lib/skc_async_experiment/src/codegen/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,13 @@ pub fn box_bool<'run>(gen: &mut CodeGen<'run, '_>, b: bool) -> SkObj<'run> {
.into_pointer_value(),
)
}

pub fn unbox_bool<'run>(
gen: &mut CodeGen<'run, '_>,
sk_obj: SkObj<'run>,
) -> inkwell::values::IntValue<'run> {
let struct_type = llvm_struct::get(gen, "::Bool");
let item_type = gen.context.bool_type().into();
let x = instance::build_ivar_load_raw(gen, sk_obj, struct_type, item_type, 0, "llvm_bool");
x.into_int_value()
}
4 changes: 2 additions & 2 deletions lib/skc_async_experiment/src/hir.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
pub mod asyncness_check;
mod expr;
pub mod expr;
pub mod rewriter;
mod ty;
pub mod typing;
pub mod untyped;
pub mod visitor;
pub use expr::{yielded_ty, CastType, Expr, PseudoVar, Typed, TypedExpr};
pub use expr::{CastType, Expr, PseudoVar, Typed, TypedExpr};
use std::fmt;
pub use ty::{FunTy, Ty};

Expand Down
71 changes: 36 additions & 35 deletions lib/skc_async_experiment/src/hir/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ pub enum Expr {
FuncRef(String),
OpCall(String, Box<Typed<Expr>>, Box<Typed<Expr>>),
FunCall(Box<Typed<Expr>>, Vec<Typed<Expr>>),
If(Box<Typed<Expr>>, Vec<Typed<Expr>>, Vec<Typed<Expr>>),
Yield(Box<Typed<Expr>>),
If(Box<Typed<Expr>>, Box<Typed<Expr>>, Option<Box<Typed<Expr>>>),
While(Box<Typed<Expr>>, Vec<Typed<Expr>>),
Spawn(Box<Typed<Expr>>),
Alloc(String),
Assign(String, Box<Typed<Expr>>),
Return(Box<Typed<Expr>>),
Exprs(Vec<Typed<Expr>>),
Cast(CastType, Box<Typed<Expr>>),
Unbox(Box<Typed<Expr>>),
RawI64(i64),
Expand Down Expand Up @@ -77,20 +77,15 @@ impl std::fmt::Display for Expr {
}
Expr::If(cond, then, else_) => {
write!(f, "if ({}) {{\n", cond.0)?;
for stmt in then {
write!(f, " {}\n", stmt.0)?;
}
write!(f, "{}\n", then.0)?;
write!(f, " }}")?;
if !else_.is_empty() {
if let Some(else_) = else_ {
write!(f, " else {{\n")?;
for stmt in else_ {
write!(f, " {}\n", stmt.0)?;
}
write!(f, " {}\n", else_.0)?;
write!(f, " }}")?;
}
Ok(())
}
Expr::Yield(e) => write!(f, "yield {} # {}", e.0, e.1),
Expr::While(cond, body) => {
write!(f, "while {} {{\n", cond.0)?;
for stmt in body {
Expand All @@ -102,6 +97,12 @@ impl std::fmt::Display for Expr {
Expr::Alloc(name) => write!(f, "alloc {}", name),
Expr::Assign(name, e) => write!(f, "{} = {}", name, e.0),
Expr::Return(e) => write!(f, "return {} # {}", e.0, e.1),
Expr::Exprs(exprs) => {
for expr in exprs {
write!(f, " {}\n", expr.0)?;
}
Ok(())
}
Expr::Cast(cast_type, e) => write!(f, "({} as {})", e.0, cast_type.result_ty()),
Expr::Unbox(e) => write!(f, "unbox {}", e.0),
Expr::RawI64(n) => write!(f, "{}.raw", n),
Expand Down Expand Up @@ -154,33 +155,29 @@ impl Expr {
(Expr::FunCall(Box::new(func), args), result_ty)
}

pub fn if_(cond: TypedExpr, then: Vec<TypedExpr>, else_: Vec<TypedExpr>) -> TypedExpr {
pub fn if_(cond: TypedExpr, then: TypedExpr, else_: Option<TypedExpr>) -> TypedExpr {
if cond.1 != Ty::Bool {
panic!("[BUG] if cond not bool: {:?}", cond);
}
let t1 = yielded_ty(&then);
let t2 = yielded_ty(&else_);
let if_ty = if t1 == Ty::Void {
t2
let t1 = &then.1;
let t2 = match &else_ {
Some(e) => e.1.clone(),
None => Ty::Void,
};
let if_ty = if *t1 == Ty::Void {
t2.clone()
} else if t2 == Ty::Void {
t1
} else if t1 == t2 {
t1
t1.clone()
} else if *t1 == t2 {
t1.clone()
} else {
panic!("[BUG] if types mismatch (t1: {:?}, t2: {:?})", t1, t2);
};

(Expr::If(Box::new(cond), then, else_), if_ty)
}

pub fn yield_(expr: TypedExpr) -> TypedExpr {
let t = expr.1.clone();
(Expr::Yield(Box::new(expr)), t)
}

pub fn yield_null() -> TypedExpr {
let null = (Expr::PseudoVar(PseudoVar::Void), Ty::Void);
(Expr::Yield(Box::new(null)), Ty::Void)
(
Expr::If(Box::new(cond), Box::new(then), else_.map(Box::new)),
if_ty,
)
}

pub fn while_(cond: TypedExpr, body: Vec<TypedExpr>) -> TypedExpr {
Expand All @@ -206,6 +203,12 @@ impl Expr {
(Expr::Return(Box::new(e)), Ty::Void)
}

pub fn exprs(exprs: Vec<TypedExpr>) -> TypedExpr {
debug_assert!(!exprs.is_empty());
let t = exprs.last().unwrap().1.clone();
(Expr::Exprs(exprs), t)
}

pub fn cast(cast_type: CastType, e: TypedExpr) -> TypedExpr {
let ty = match &cast_type {
CastType::AnyToFun(f) => f.clone().into(),
Expand Down Expand Up @@ -240,11 +243,9 @@ impl Expr {
}
}

pub fn yielded_ty(stmts: &[TypedExpr]) -> Ty {
let stmt = stmts.last().unwrap();
match &stmt.0 {
Expr::Yield(val) => val.1.clone(),
Expr::Return(_) => Ty::Void,
_ => panic!("[BUG] if branch not terminated with yield: {:?}", stmt),
pub fn into_exprs(expr: TypedExpr) -> Vec<TypedExpr> {
match expr.0 {
Expr::Exprs(exprs) => exprs,
_ => vec![expr],
}
}
10 changes: 6 additions & 4 deletions lib/skc_async_experiment/src/hir/rewriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,21 @@ pub trait HirRewriter {
hir::Expr::FunCall(fexpr, arg_exprs) => {
hir::Expr::fun_call(self.walk_expr(*fexpr)?, self.walk_exprs(arg_exprs)?)
}
hir::Expr::If(cond_expr, then_exprs, else_exprs) => hir::Expr::if_(
hir::Expr::If(cond_expr, then_exprs, opt_else_exprs) => hir::Expr::if_(
self.walk_expr(*cond_expr)?,
self.walk_exprs(then_exprs)?,
self.walk_exprs(else_exprs)?,
self.walk_expr(*then_exprs)?,
opt_else_exprs
.map(|else_exprs| self.walk_expr(*else_exprs))
.transpose()?,
),
hir::Expr::Yield(expr) => hir::Expr::yield_(self.walk_expr(*expr)?),
hir::Expr::While(cond_expr, body_exprs) => {
hir::Expr::while_(self.walk_expr(*cond_expr)?, self.walk_exprs(body_exprs)?)
}
hir::Expr::Spawn(expr) => hir::Expr::spawn(self.walk_expr(*expr)?),
hir::Expr::Alloc(_) => expr,
hir::Expr::Assign(name, rhs) => hir::Expr::assign(name, self.walk_expr(*rhs)?),
hir::Expr::Return(expr) => hir::Expr::return_(self.walk_expr(*expr)?),
hir::Expr::Exprs(exprs) => hir::Expr::exprs(self.walk_exprs(exprs)?),
hir::Expr::Cast(cast_type, expr) => hir::Expr::cast(cast_type, self.walk_expr(*expr)?),
_ => panic!("not supported by hir::rewriter: {:?}", expr),
};
Expand Down
48 changes: 22 additions & 26 deletions lib/skc_async_experiment/src/hir/typing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,17 @@ impl<'f> Typing<'f> {
if cond.1 != hir::Ty::Bool {
return Err(anyhow!("condition should be bool but got {:?}", cond.1));
}
self.compile_exprs(lvars, then)?;
self.compile_exprs(lvars, els)?;
let t1 = hir::yielded_ty(&then);
let t2 = hir::yielded_ty(&els);
let t = if t1 == hir::Ty::Void {
self.compile_expr(lvars, then)?;
let t1 = &then.1;
let t2 = if let Some(els) = els {
self.compile_expr(lvars, els)?;
&els.1
} else {
&hir::Ty::Void
};
let t = if *t1 == hir::Ty::Void {
t2
} else if t2 == hir::Ty::Void {
} else if *t2 == hir::Ty::Void {
t1
} else if t1 != t2 {
return Err(anyhow!(
Expand All @@ -119,15 +123,11 @@ impl<'f> Typing<'f> {
};
e.1 = t.clone();
}
hir::Expr::Yield(val) => {
self.compile_expr(lvars, val)?;
e.1 = val.1.clone();
}
hir::Expr::While(cond, body) => {
self.compile_expr(lvars, cond)?;
self.compile_exprs(lvars, body)?;
e.1 = hir::Ty::Void;
}
//hir::Expr::While(cond, body) => {
// self.compile_expr(lvars, cond)?;
// self.compile_expr(lvars, body)?;
// e.1 = hir::Ty::Void;
//}
hir::Expr::Spawn(func) => {
self.compile_expr(lvars, func)?;
e.1 = hir::Ty::Void;
Expand All @@ -153,21 +153,17 @@ impl<'f> Typing<'f> {
}
e.1 = hir::Ty::Never;
}
hir::Expr::Exprs(exprs) => {
for e in exprs.iter_mut() {
self.compile_expr(lvars, e)?;
}
e.1 = exprs.last().unwrap().1.clone();
}
hir::Expr::Cast(_, _) => {
return Err(anyhow!("[BUG] Cast unexpected here"));
}
_ => panic!("must not occur in hir::typing"),
_ => panic!("must not occur in hir::typing: {:?}", e.0),
};
Ok(())
}

fn compile_exprs(
&mut self,
lvars: &mut HashMap<String, hir::Ty>,
es: &mut [hir::TypedExpr],
) -> Result<()> {
es.iter_mut()
.try_for_each(|e| self.compile_expr(lvars, e))?;
Ok(())
}
}
Loading
Loading