pipeline_script/llvm/value/
fucntion.rs

1use crate::context::Context;
2use crate::llvm::global::Global;
3use crate::llvm::types::LLVMType;
4use crate::llvm::value::pointer::PointerValue;
5use crate::llvm::value::pstruct::StructValue;
6use crate::llvm::value::LLVMValue;
7use llvm_sys::core::{LLVMAppendBasicBlock, LLVMGetParam};
8use llvm_sys::prelude::{LLVMBasicBlockRef, LLVMValueRef};
9use std::collections::HashMap;
10use std::ffi::c_char;
11
12#[derive(Clone, Debug)]
13pub struct FunctionValue {
14    reference: LLVMValueRef,
15    name: String,
16    return_type: Box<LLVMValue>,
17    args: Vec<(String, LLVMValue)>,
18    is_closure: bool,
19    is_vararg: bool,
20    is_array_vararg: bool,
21}
22
23impl FunctionValue {
24    pub fn new(
25        reference: LLVMValueRef,
26        name: String,
27        return_type: Box<LLVMValue>,
28        args: Vec<(String, LLVMValue)>,
29    ) -> Self {
30        Self {
31            reference,
32            name,
33            return_type,
34            args,
35            is_closure: false,
36            is_vararg: false,
37            is_array_vararg: false,
38        }
39    }
40    pub fn get_reference(&self) -> LLVMValueRef {
41        self.reference
42    }
43
44    pub fn append_basic_block(&self, name: impl Into<String>) -> LLVMBasicBlockRef {
45        unsafe { LLVMAppendBasicBlock(self.reference, name.into().as_mut_ptr() as *mut c_char) }
46    }
47    pub fn get_param(&self, name: impl AsRef<str>) -> Option<LLVMValue> {
48        let name_ref = name.as_ref();
49        for (index, (arg_name, v)) in self.args.iter().enumerate() {
50            if arg_name == name_ref {
51                let param = unsafe { LLVMGetParam(self.reference, index as u32) };
52                return match v {
53                    LLVMValue::Struct(v) => {
54                        return Some(LLVMValue::Struct(StructValue::new(
55                            param,
56                            v.get_name(),
57                            v.field_index.clone(),
58                            v.field_values.borrow().clone(),
59                        )))
60                    }
61                    LLVMValue::String(_) => Some(LLVMValue::String(param)),
62                    LLVMValue::Function(function_value) => {
63                        let mut function_value = function_value.clone();
64                        function_value.set_reference(param);
65                        Some(LLVMValue::Function(function_value))
66                    }
67                    LLVMValue::Pointer(p) => {
68                        let mut p = p.clone();
69                        p.set_reference(param);
70                        Some(LLVMValue::Pointer(p))
71                    }
72                    LLVMValue::Reference(r) => {
73                        let mut r = r.clone();
74                        r.set_reference(param);
75                        Some(LLVMValue::Reference(r))
76                    }
77                    _ => Some(param.into()),
78                };
79            }
80        }
81        None
82    }
83    pub fn set_reference(&mut self, reference: LLVMValueRef) {
84        self.reference = reference;
85    }
86    pub fn get_param_index(&self, name: impl AsRef<str>) -> Option<usize> {
87        let name_ref = name.as_ref();
88        for (i, (arg_name, _)) in self.args.iter().enumerate() {
89            if arg_name == name_ref {
90                return Some(i);
91            }
92        }
93        None
94    }
95    pub fn get_llvm_type(&self, ctx: &Context) -> LLVMType {
96        let mut args_type = vec![];
97        for (name, v) in &self.args {
98            args_type.push((name.clone(), v.get_llvm_type(ctx)))
99        }
100        let return_type = self.return_type.get_llvm_type(ctx);
101        Global::pointer_type(Global::function_type(return_type, args_type))
102    }
103    pub fn get_param_index_map(&self) -> HashMap<String, usize> {
104        let mut map = HashMap::new();
105        for (i, (name, _)) in self.args.iter().enumerate() {
106            map.insert(name.clone(), i);
107        }
108        map
109    }
110    pub fn call(&self, ctx: &Context, args: Vec<Option<LLVMValue>>) -> LLVMValue {
111        let builder = ctx.get_builder();
112        let mut function_call_args = vec![];
113        let r = if self.is_closure {
114            // 对于闭包,self.reference 就是结构体值
115            let mut field_index = HashMap::new();
116            field_index.insert("ptr".to_string(), 0);
117            field_index.insert("env".to_string(), 1);
118
119            let closure_struct = StructValue::new(
120                self.reference,
121                "Closure".into(),
122                field_index,
123                vec![
124                    LLVMValue::Function(self.clone()),
125                    LLVMValue::Pointer(PointerValue::new(self.reference, LLVMValue::Unit)),
126                ],
127            );
128
129            let function_ptr = builder.build_extract_value(ctx, &closure_struct, 0);
130            let env_ptr = builder.build_extract_value(ctx, &closure_struct, 1);
131
132            // 处理其他参数
133            for i in args.into_iter().flatten() {
134                function_call_args.push(i)
135            }
136            // 将环境指针作为第最后一个参数
137            function_call_args.push(env_ptr);
138            // 调用闭包函数
139            let function_value = function_ptr.as_function().unwrap();
140            builder.build_call(ctx, &function_value, &mut function_call_args, "")
141        } else {
142            // 处理普通函数调用
143            for i in args.into_iter().flatten() {
144                function_call_args.push(i)
145            }
146            builder.build_call(ctx, self, &mut function_call_args, "")
147        };
148        if self.name == "panic" || self.name == "exit" {
149            builder.build_unreachable();
150        }
151        r
152    }
153    pub fn get_return_value(&self) -> LLVMValue {
154        *self.return_type.clone()
155    }
156    pub fn get_args_count(&self) -> usize {
157        self.args.len()
158    }
159    pub fn get_arg_name(&self, index: usize) -> Option<String> {
160        self.args.get(index).map(|(name, _)| name.clone())
161    }
162    pub fn get_param_by_index(&self, index: usize) -> Option<LLVMValue> {
163        self.args.get(index).map(|(_, ty)| ty.clone())
164    }
165    pub fn is_undef(&self) -> bool {
166        unsafe { llvm_sys::core::LLVMIsUndef(self.reference) == 1 }
167    }
168    pub fn is_vararg(&self) -> bool {
169        self.is_vararg
170    }
171    pub fn is_array_vararg(&self) -> bool {
172        self.is_array_vararg
173    }
174    pub fn set_array_vararg(&mut self) {
175        self.is_array_vararg = true
176    }
177    pub fn set_vararg(&mut self) {
178        self.is_vararg = true;
179    }
180    pub fn is_arg_undef(&self, index: usize) -> bool {
181        if let Some((_, arg_value)) = self.args.get(index) {
182            arg_value.is_undef()
183        } else {
184            false
185        }
186    }
187    pub fn set_closure(&mut self) {
188        self.is_closure = true;
189    }
190    pub fn is_closure(&self) -> bool {
191        self.is_closure
192    }
193    pub fn get_function_arg_count(&self) -> usize {
194        self.args.len()
195    }
196    pub fn get_function_arg(&self, index: usize) -> Option<LLVMValue> {
197        self.args.get(index).map(|(_, ty)| ty.clone())
198    }
199    pub fn is_vararg_function(&self) -> bool {
200        self.is_vararg
201    }
202}
203
204impl From<FunctionValue> for LLVMValue {
205    fn from(value: FunctionValue) -> Self {
206        LLVMValue::Function(value)
207    }
208}