1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use fmt::Formatter;
use std::fmt;

use id_arena::{Arena, Id};

use crate::core;

pub type FunctionId = Id<Function>;

/// An representation of LLVMFunction.
/// LLVMFunction を表す構造体
pub struct Function {
    return_type: ReturnType,
    name: core::llvm_string::LLVMString,
    arg_list: ParameterSet,

    entry_block: core::basic_block::BasicBlockId,
    bb_allocator: Arena<core::basic_block::BasicBlock>,
}

impl fmt::Display for Function {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "define {} @{} {} {{",
            self.return_type, self.name, self.arg_list
        )?;

        let entry_bb = self.bb_allocator.get(self.entry_block).unwrap();

        writeln!(f, "{}", entry_bb)?;

        {
            entry_bb.print_successors(f, &self.bb_allocator)?;
        }

        writeln!(f, "}}")?;

        Ok(())
    }
}

impl Function {
    pub fn new(func_name: &str, ret_type: ReturnType) -> Self {
        let mut bb_alloc = Arena::new();
        let entry_block_id = bb_alloc.alloc(Default::default());
        Self {
            return_type: ret_type,
            name: core::llvm_string::LLVMString::from(func_name),
            arg_list: Default::default(),
            entry_block: entry_block_id,
            bb_allocator: bb_alloc,
        }
    }

    pub fn returns_void(&self) -> bool {
        self.return_type.is_void()
    }

    pub fn get_name_ref(&self) -> &core::llvm_string::LLVMString {
        &self.name
    }

    pub fn get_entry_bb(&self) -> core::basic_block::BasicBlockId {
        self.entry_block
    }

    pub fn args_empty(&self) -> bool {
        self.arg_list.is_empty()
    }

    pub fn new_basic_block(
        &mut self,
        l: &str,
        pred: Option<core::basic_block::BasicBlockId>,
        k: core::basic_block::BasicBlockKind,
    ) -> core::basic_block::BasicBlockId {
        self.bb_allocator.alloc(core::basic_block::BasicBlock::new(
            core::llvm_string::LLVMString::from(l),
            pred,
            k,
        ))
    }
}

/// each function has a type signature.
#[derive(Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct FunctionType {
    return_type: ReturnType,
    arg_list: ParameterSet,
}

impl FunctionType {
    pub fn new(ret_type: ReturnType, args: ParameterSet) -> Self {
        Self {
            return_type: ret_type,
            arg_list: args,
        }
    }
}

impl fmt::Display for FunctionType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.return_type, self.arg_list)
    }
}

/// each llvm function must have a return type.
/// LLVMFunctionに必ず存在する,返り値の型
#[derive(Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct ReturnType {
    return_type: core::llvm_type::LLVMType,
    /// a ReturnType may have a set of Attributes
    /// return_type は Attribute を持つ可能性がある
    attributes: Option<core::function::ParameterAttributes>,
}

impl ReturnType {
    pub fn new(
        ret_type: core::llvm_type::LLVMType,
        attrs: Option<core::function::ParameterAttributes>,
    ) -> Self {
        Self {
            return_type: ret_type,
            attributes: attrs,
        }
    }

    fn is_void(&self) -> bool {
        match &self.return_type.kind {
            core::llvm_type::LLVMTypeKind::VOID => true,
            _ => false,
        }
    }
}

impl fmt::Display for ReturnType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.attributes {
            Some(attrs) => write!(f, "{} {}", attrs, self.return_type),
            None => write!(f, "{}", self.return_type),
        }
    }
}

/// each llvm function must have a set of Parameter.
/// LLVMFunction が持つ引数リストの実装
#[derive(Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct ParameterSet {
    params: Vec<Parameter>,
}

impl Default for ParameterSet {
    fn default() -> Self {
        Self { params: Vec::new() }
    }
}

impl ParameterSet {
    pub fn new(args: Vec<Parameter>) -> Self {
        Self { params: args }
    }

    fn is_empty(&self) -> bool {
        self.params.is_empty()
    }
}

impl fmt::Display for ParameterSet {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let fmt_string = self
            .params
            .iter()
            .map(|attr| attr.to_string())
            .collect::<Vec<String>>()
            .join(", ");

        write!(f, "{}", fmt_string)
    }
}

/// LLVMFunction が持つ各引数
#[derive(Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct Parameter {
    name: core::llvm_string::LLVMString,
    attributes: Option<core::function::ParameterAttributes>,
    param_type: core::llvm_type::LLVMType,
}

impl Parameter {
    pub fn new(
        param_name: core::llvm_string::LLVMString,
        attrs: Option<core::function::ParameterAttributes>,
        arg_type: core::llvm_type::LLVMType,
    ) -> Self {
        Self {
            name: param_name,
            attributes: attrs,
            param_type: arg_type,
        }
    }
}

impl fmt::Display for Parameter {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.attributes {
            Some(attrs) => write!(f, "{} {} {}", self.param_type, attrs, self.name),
            None => write!(f, "{} {}", self.param_type, self.name),
        }
    }
}