Work on intrinsics, clean up code a bit

This commit is contained in:
Sofia 2025-07-24 11:29:58 +03:00
parent 4f1dc5e59d
commit 5ff5651f5f
8 changed files with 71 additions and 58 deletions

View File

@ -18,11 +18,16 @@ pub struct Allocator {
pub struct AllocatorScope<'ctx, 'a> { pub struct AllocatorScope<'ctx, 'a> {
pub(super) block: &'a mut Block<'ctx>, pub(super) block: &'a mut Block<'ctx>,
pub(super) module_id: SourceModuleId, pub(super) module_id: SourceModuleId,
pub(super) types: &'a HashMap<TypeValue, TypeDefinition>,
pub(super) type_values: &'a HashMap<CustomTypeKey, TypeValue>, pub(super) type_values: &'a HashMap<CustomTypeKey, TypeValue>,
} }
impl Allocator { impl Allocator {
pub fn empty() -> Allocator {
Allocator {
allocations: Vec::new(),
}
}
pub fn from(func: &FunctionDefinition, scope: &mut AllocatorScope) -> Allocator { pub fn from(func: &FunctionDefinition, scope: &mut AllocatorScope) -> Allocator {
func.allocate(scope) func.allocate(scope)
} }
@ -44,22 +49,21 @@ impl mir::FunctionDefinition {
fn allocate<'ctx, 'a>(&self, scope: &mut AllocatorScope<'ctx, 'a>) -> Allocator { fn allocate<'ctx, 'a>(&self, scope: &mut AllocatorScope<'ctx, 'a>) -> Allocator {
let mut allocated = Vec::new(); let mut allocated = Vec::new();
match &self.kind { match &self.kind {
crate::mir::FunctionDefinitionKind::Local(block, _) => { mir::FunctionDefinitionKind::Local(block, _) => {
for param in &self.parameters { for param in &self.parameters {
let allocation = scope let allocation = scope
.block .block
.build_named( .build_named(
param.0.clone(), param.0.clone(),
reid_lib::Instr::Alloca( reid_lib::Instr::Alloca(param.1.get_type(scope.type_values)),
param.1.get_type(scope.type_values, scope.types),
),
) )
.unwrap(); .unwrap();
allocated.push(Allocation(param.0.clone(), param.1.clone(), allocation)); allocated.push(Allocation(param.0.clone(), param.1.clone(), allocation));
} }
allocated.extend(block.allocate(scope)); allocated.extend(block.allocate(scope));
} }
crate::mir::FunctionDefinitionKind::Extern(_) => {} mir::FunctionDefinitionKind::Extern(_) => {}
mir::FunctionDefinitionKind::Intrinsic(_) => {}
} }
Allocator { Allocator {
@ -95,11 +99,7 @@ impl mir::Statement {
.block .block
.build_named( .build_named(
named_variable_ref.1.clone(), named_variable_ref.1.clone(),
reid_lib::Instr::Alloca( reid_lib::Instr::Alloca(named_variable_ref.0.get_type(scope.type_values)),
named_variable_ref
.0
.get_type(scope.type_values, scope.types),
),
) )
.unwrap(); .unwrap();
allocated.push(Allocation( allocated.push(Allocation(

View File

@ -275,7 +275,7 @@ impl mir::Module {
// TODO: Reorder custom-type definitions such that // TODO: Reorder custom-type definitions such that
// inner types get evaluated first. Otherwise this // inner types get evaluated first. Otherwise this
// will cause a panic! // will cause a panic!
.map(|StructField(_, t, _)| t.get_type(&type_values, &types)) .map(|StructField(_, t, _)| t.get_type(&type_values))
.collect(), .collect(),
))) )))
} }
@ -291,14 +291,14 @@ impl mir::Module {
let param_types: Vec<Type> = function let param_types: Vec<Type> = function
.parameters .parameters
.iter() .iter()
.map(|(_, p)| p.get_type(&type_values, &types)) .map(|(_, p)| p.get_type(&type_values))
.collect(); .collect();
let is_main = self.is_main && function.name == "main"; let is_main = self.is_main && function.name == "main";
let func = match &function.kind { let func = match &function.kind {
mir::FunctionDefinitionKind::Local(_, _) => module.function( mir::FunctionDefinitionKind::Local(_, _) => module.function(
&function.name, &function.name,
function.return_type.get_type(&type_values, &types), function.return_type.get_type(&type_values),
param_types, param_types,
FunctionFlags { FunctionFlags {
is_pub: function.is_pub || is_main, is_pub: function.is_pub || is_main,
@ -309,7 +309,7 @@ impl mir::Module {
), ),
mir::FunctionDefinitionKind::Extern(imported) => module.function( mir::FunctionDefinitionKind::Extern(imported) => module.function(
&function.name, &function.name,
function.return_type.get_type(&type_values, &types), function.return_type.get_type(&type_values),
param_types, param_types,
FunctionFlags { FunctionFlags {
is_extern: true, is_extern: true,
@ -317,6 +317,7 @@ impl mir::Module {
..FunctionFlags::default() ..FunctionFlags::default()
}, },
), ),
mir::FunctionDefinitionKind::Intrinsic(instrinsic_kind) => todo!(),
}; };
functions.insert(function.name.clone(), StackFunction { ir: func }); functions.insert(function.name.clone(), StackFunction { ir: func });
@ -333,7 +334,6 @@ impl mir::Module {
&mut AllocatorScope { &mut AllocatorScope {
block: &mut entry, block: &mut entry,
module_id: self.module_id, module_id: self.module_id,
types: &types,
type_values: &type_values, type_values: &type_values,
}, },
); );
@ -470,6 +470,26 @@ impl mir::Module {
} }
} }
mir::FunctionDefinitionKind::Extern(_) => {} mir::FunctionDefinitionKind::Extern(_) => {}
mir::FunctionDefinitionKind::Intrinsic(kind) => {
let mut entry = function.ir.block("entry");
let mut scope = Scope {
context,
modules: &modules,
tokens,
module: &module,
module_id: self.module_id,
function,
block: entry,
functions: &functions,
types: &types,
type_values: &type_values,
stack_values: Default::default(),
debug: None,
allocator: Rc::new(RefCell::new(Allocator::empty())),
};
kind.codegen(&mut scope)?
}
} }
} }
@ -694,7 +714,7 @@ impl mir::Expression {
format!("{}", varref.1), format!("{}", varref.1),
Instr::Load( Instr::Load(
v.0.instr(), v.0.instr(),
inner.get_type(scope.type_values, scope.types), inner.get_type(scope.type_values),
), ),
) )
.unwrap(), .unwrap(),
@ -800,7 +820,7 @@ impl mir::Expression {
.known() .known()
.expect("function return type unknown"); .expect("function return type unknown");
let ret_type = ret_type_kind.get_type(scope.type_values, scope.types); let ret_type = ret_type_kind.get_type(scope.type_values);
let params = try_all( let params = try_all(
call.parameters call.parameters
@ -903,10 +923,7 @@ impl mir::Expression {
.block .block
.build_named( .build_named(
"load", "load",
Instr::Load( Instr::Load(kind.instr(), inner.get_type(scope.type_values)),
kind.instr(),
inner.get_type(scope.type_values, scope.types),
),
) )
.unwrap(); .unwrap();
( (
@ -962,10 +979,7 @@ impl mir::Expression {
.block .block
.build_named( .build_named(
"array.load", "array.load",
Instr::Load( Instr::Load(ptr, contained_ty.get_type(scope.type_values)),
ptr,
contained_ty.get_type(scope.type_values, scope.types),
),
) )
.unwrap() .unwrap()
.maybe_location(&mut scope.block, location), .maybe_location(&mut scope.block, location),
@ -1003,7 +1017,7 @@ impl mir::Expression {
.unwrap_or(TypeKind::Void); .unwrap_or(TypeKind::Void);
let array_ty = Type::Array( let array_ty = Type::Array(
Box::new(elem_ty_kind.get_type(scope.type_values, scope.types)), Box::new(elem_ty_kind.get_type(scope.type_values)),
instr_list.len() as u64, instr_list.len() as u64,
); );
let array_name = format!("{}.{}", elem_ty_kind, instr_list.len()); let array_name = format!("{}.{}", elem_ty_kind, instr_list.len());
@ -1086,10 +1100,7 @@ impl mir::Expression {
.block .block
.build_named( .build_named(
load_n, load_n,
Instr::Load( Instr::Load(value, type_kind.get_type(scope.type_values)),
value,
type_kind.get_type(scope.type_values, scope.types),
),
) )
.unwrap(), .unwrap(),
), ),
@ -1180,10 +1191,7 @@ impl mir::Expression {
.block .block
.build_named( .build_named(
format!("{}.deref", varref.1), format!("{}.deref", varref.1),
Instr::Load( Instr::Load(v.0.instr(), ptr_inner.get_type(scope.type_values)),
v.0.instr(),
ptr_inner.get_type(scope.type_values, scope.types),
),
) )
.unwrap(); .unwrap();
@ -1198,7 +1206,7 @@ impl mir::Expression {
format!("{}.deref.inner", varref.1), format!("{}.deref.inner", varref.1),
Instr::Load( Instr::Load(
var_ptr_instr, var_ptr_instr,
inner.get_type(scope.type_values, scope.types), inner.get_type(scope.type_values),
), ),
) )
.unwrap(), .unwrap(),
@ -1236,7 +1244,7 @@ impl mir::Expression {
.build(Instr::BitCast( .build(Instr::BitCast(
val.instr(), val.instr(),
Type::Ptr(Box::new( Type::Ptr(Box::new(
type_kind.get_type(scope.type_values, scope.types), type_kind.get_type(scope.type_values),
)), )),
)) ))
.unwrap(), .unwrap(),
@ -1254,7 +1262,7 @@ impl mir::Expression {
.block .block
.build(Instr::BitCast( .build(Instr::BitCast(
val.instr(), val.instr(),
type_kind.get_type(scope.type_values, scope.types), type_kind.get_type(scope.type_values),
)) ))
.unwrap(), .unwrap(),
), ),
@ -1263,10 +1271,10 @@ impl mir::Expression {
_ => { _ => {
let cast_instr = val let cast_instr = val
.1 .1
.get_type(scope.type_values, scope.types) .get_type(scope.type_values)
.cast_instruction( .cast_instruction(
val.instr(), val.instr(),
&type_kind.get_type(scope.type_values, scope.types), &type_kind.get_type(scope.type_values),
) )
.unwrap(); .unwrap();
@ -1438,11 +1446,7 @@ impl mir::Literal {
} }
impl TypeKind { impl TypeKind {
pub(super) fn get_type( pub(super) fn get_type(&self, type_vals: &HashMap<CustomTypeKey, TypeValue>) -> Type {
&self,
type_vals: &HashMap<CustomTypeKey, TypeValue>,
typedefs: &HashMap<TypeValue, TypeDefinition>,
) -> Type {
match &self { match &self {
TypeKind::I8 => Type::I8, TypeKind::I8 => Type::I8,
TypeKind::I16 => Type::I16, TypeKind::I16 => Type::I16,
@ -1463,24 +1467,16 @@ impl TypeKind {
TypeKind::F80 => Type::F80, TypeKind::F80 => Type::F80,
TypeKind::F128PPC => Type::F128PPC, TypeKind::F128PPC => Type::F128PPC,
TypeKind::Char => Type::U8, TypeKind::Char => Type::U8,
TypeKind::Array(elem_t, len) => { TypeKind::Array(elem_t, len) => Type::Array(Box::new(elem_t.get_type(type_vals)), *len),
Type::Array(Box::new(elem_t.get_type(type_vals, typedefs)), *len)
}
TypeKind::Void => Type::Void, TypeKind::Void => Type::Void,
TypeKind::Vague(_) => panic!("Tried to compile a vague type!"), TypeKind::Vague(_) => panic!("Tried to compile a vague type!"),
TypeKind::CustomType(n) => { TypeKind::CustomType(n) => {
let type_val = type_vals.get(n).unwrap().clone(); let type_val = type_vals.get(n).unwrap().clone();
Type::CustomType(type_val) Type::CustomType(type_val)
} }
TypeKind::UserPtr(type_kind) => { TypeKind::UserPtr(type_kind) => Type::Ptr(Box::new(type_kind.get_type(type_vals))),
Type::Ptr(Box::new(type_kind.get_type(type_vals, typedefs))) TypeKind::CodegenPtr(type_kind) => Type::Ptr(Box::new(type_kind.get_type(type_vals))),
} TypeKind::Borrow(type_kind, _) => Type::Ptr(Box::new(type_kind.get_type(type_vals))),
TypeKind::CodegenPtr(type_kind) => {
Type::Ptr(Box::new(type_kind.get_type(type_vals, typedefs)))
}
TypeKind::Borrow(type_kind, _) => {
Type::Ptr(Box::new(type_kind.get_type(type_vals, typedefs)))
}
} }
} }
} }

10
reid/src/intrinsics.rs Normal file
View File

@ -0,0 +1,10 @@
use crate::codegen::{ErrorKind, Scope, StackValue};
#[derive(Debug)]
pub enum InstrinsicKind {}
impl InstrinsicKind {
pub fn codegen<'ctx, 'a>(&self, mut scope: &mut Scope<'ctx, 'a>) -> Result<(), ErrorKind> {
Ok(())
}
}

View File

@ -56,6 +56,7 @@ mod allocator;
mod ast; mod ast;
mod codegen; mod codegen;
pub mod error_raporting; pub mod error_raporting;
pub mod intrinsics;
pub mod ld; pub mod ld;
mod lexer; mod lexer;
pub mod mir; pub mod mir;

View File

@ -5,6 +5,7 @@
use std::{collections::HashMap, path::PathBuf}; use std::{collections::HashMap, path::PathBuf};
use crate::{ use crate::{
intrinsics::InstrinsicKind,
lexer::{FullToken, Position}, lexer::{FullToken, Position},
token_stream::TokenRange, token_stream::TokenRange,
}; };
@ -303,7 +304,7 @@ pub enum FunctionDefinitionKind {
/// True = imported from other module, False = Is user defined extern /// True = imported from other module, False = Is user defined extern
Extern(bool), Extern(bool),
/// Intrinsic definition, defined within the compiler /// Intrinsic definition, defined within the compiler
Intrinsic(Block), Intrinsic(InstrinsicKind),
} }
impl FunctionDefinition { impl FunctionDefinition {

View File

@ -352,6 +352,7 @@ impl FunctionDefinition {
block.pass(pass, state, scope, mod_id)?; block.pass(pass, state, scope, mod_id)?;
} }
FunctionDefinitionKind::Extern(_) => {} FunctionDefinitionKind::Extern(_) => {}
FunctionDefinitionKind::Intrinsic(..) => {}
}; };
Ok(()) Ok(())
} }

View File

@ -196,6 +196,9 @@ impl FunctionDefinition {
FunctionDefinitionKind::Extern(_) => { FunctionDefinitionKind::Extern(_) => {
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown))) Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
} }
FunctionDefinitionKind::Intrinsic(..) => {
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
}
}; };
match inferred { match inferred {

View File

@ -69,6 +69,7 @@ impl FunctionDefinition {
} }
} }
FunctionDefinitionKind::Extern(_) => {} FunctionDefinitionKind::Extern(_) => {}
FunctionDefinitionKind::Intrinsic(_) => todo!(),
}; };
Ok(()) Ok(())