sonatina_ir/
function.rs

1use fxhash::FxHashMap;
2use smallvec::SmallVec;
3
4use crate::{module::ModuleCtx, Linkage};
5
6use super::{module::FuncRef, DataFlowGraph, Layout, Type, Value};
7
8#[derive(Debug, Clone)]
9pub struct Function {
10    /// Signature of the function.
11    pub sig: Signature,
12    pub arg_values: smallvec::SmallVec<[Value; 8]>,
13
14    pub dfg: DataFlowGraph,
15    pub layout: Layout,
16
17    /// Stores signatures of all functions that called by the function.
18    pub callees: FxHashMap<FuncRef, Signature>,
19}
20
21impl Function {
22    pub fn new(ctx: &ModuleCtx, sig: Signature) -> Self {
23        let mut dfg = DataFlowGraph::new(ctx.clone());
24        let arg_values = sig
25            .args()
26            .iter()
27            .enumerate()
28            .map(|(idx, arg_ty)| {
29                let value = dfg.make_arg_value(*arg_ty, idx);
30                dfg.make_value(value)
31            })
32            .collect();
33
34        Self {
35            sig,
36            arg_values,
37            dfg,
38            layout: Layout::default(),
39            callees: FxHashMap::default(),
40        }
41    }
42}
43
44#[derive(Debug, Clone)]
45pub struct Signature {
46    /// Name of the function.
47    name: String,
48
49    /// Linkage of the function.
50    linkage: Linkage,
51
52    args: SmallVec<[Type; 8]>,
53    ret_ty: Type,
54}
55
56impl Signature {
57    pub fn new(name: &str, linkage: Linkage, args: &[Type], ret_ty: Type) -> Self {
58        Self {
59            name: name.to_string(),
60            linkage,
61            args: args.into(),
62            ret_ty,
63        }
64    }
65    pub fn name(&self) -> &str {
66        &self.name
67    }
68
69    pub fn linkage(&self) -> Linkage {
70        self.linkage
71    }
72
73    pub fn append_arg(&mut self, arg: Type) {
74        self.args.push(arg);
75    }
76
77    pub fn args(&self) -> &[Type] {
78        &self.args
79    }
80
81    pub fn ret_ty(&self) -> Type {
82        self.ret_ty
83    }
84
85    #[doc(hidden)]
86    pub fn set_ret_ty(&mut self, ty: Type) {
87        self.ret_ty = ty;
88    }
89}