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
mod expression;
mod function;
mod program;
mod statement;
use crate::llvm_str;
use crate::parser::program::Program;
use llvm_sys::analysis::LLVMVerifierFailureAction;
use llvm_sys::prelude::{LLVMBuilderRef, LLVMContextRef, LLVMModuleRef, LLVMTypeRef, LLVMValueRef};
use llvm_sys::target_machine::{
LLVMCodeGenFileType, LLVMCodeGenOptLevel, LLVMCodeModel, LLVMRelocMode, LLVMTargetRef,
};
use llvm_sys::{analysis, core, target, target_machine};
use log::{debug, error, info, warn};
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::CStr;
use std::process;
use std::process::Command;
pub struct Generator {
program: Program,
context: LLVMContextRef,
module: LLVMModuleRef,
builder: LLVMBuilderRef,
local_vars: RefCell<HashMap<String, LLVMValueRef>>,
fn_args: RefCell<Vec<String>>,
}
impl Generator {
pub fn new(program: Program, name: &str) -> Self {
let context = unsafe { core::LLVMContextCreate() };
Generator {
program,
context,
module: unsafe { core::LLVMModuleCreateWithNameInContext(llvm_str!(name), context) },
builder: unsafe { core::LLVMCreateBuilderInContext(context) },
local_vars: RefCell::new(HashMap::new()),
fn_args: RefCell::new(Vec::new()),
}
}
pub fn generate(&self) {
if let Err(e) = self.gen_program(&self.program) {
error!("IR Generation error: {}", e);
process::exit(1);
};
debug!("Successfuly generated IR");
unsafe {
analysis::LLVMVerifyModule(
self.module,
LLVMVerifierFailureAction::LLVMAbortProcessAction,
["".as_ptr() as *mut _].as_mut_ptr(),
)
};
debug!("Successfuly verified module");
}
pub fn generate_ir(&self, output: &str) {
unsafe {
core::LLVMPrintModuleToFile(
self.module,
llvm_str!(output),
["".as_ptr() as *mut _].as_mut_ptr(),
);
}
}
pub fn generate_object_file(&self, optimization: u32, output: &str) {
let target_triple = unsafe { target_machine::LLVMGetDefaultTargetTriple() };
info!("Target: {}", unsafe {
CStr::from_ptr(target_triple).to_str().unwrap()
});
unsafe {
target::LLVM_InitializeAllTargetInfos();
target::LLVM_InitializeAllTargets();
target::LLVM_InitializeAllTargetMCs();
target::LLVM_InitializeAllAsmParsers();
target::LLVM_InitializeAllAsmPrinters();
}
debug!("Successfully initialized all LLVM targets");
let mut target = std::mem::MaybeUninit::<LLVMTargetRef>::uninit();
unsafe {
target_machine::LLVMGetTargetFromTriple(
target_triple,
target.as_mut_ptr(),
["".as_ptr() as *mut _].as_mut_ptr(),
);
target.assume_init();
}
let optimization_level = match optimization {
0 => LLVMCodeGenOptLevel::LLVMCodeGenLevelNone,
1 => LLVMCodeGenOptLevel::LLVMCodeGenLevelLess,
2 => LLVMCodeGenOptLevel::LLVMCodeGenLevelDefault,
3 => LLVMCodeGenOptLevel::LLVMCodeGenLevelAggressive,
_ => {
warn!("Invalid optimization level, defaulting to 2");
LLVMCodeGenOptLevel::LLVMCodeGenLevelDefault
}
};
info!("Optimization level: {}", optimization);
let target_machine = unsafe {
target_machine::LLVMCreateTargetMachine(
*target.as_ptr(),
target_triple,
llvm_str!(""),
llvm_str!(""),
optimization_level,
LLVMRelocMode::LLVMRelocDefault,
LLVMCodeModel::LLVMCodeModelDefault,
)
};
debug!("Successfully created target machine");
unsafe {
target_machine::LLVMTargetMachineEmitToFile(
target_machine,
self.module,
llvm_str!(output) as *mut _,
LLVMCodeGenFileType::LLVMObjectFile,
["".as_ptr() as *mut _].as_mut_ptr(),
)
};
debug!("Successfully emitted to file");
}
pub fn generate_executable(&self, object_file: &str, output: &str) {
match Command::new("gcc")
.args(&[object_file, "-o", output])
.output()
{
Ok(_) => debug!("Successfully generated executable"),
Err(e) => {
error!("Unable to link object file:\n{}", e);
process::exit(1);
}
}
}
#[inline]
fn i32_type(&self) -> LLVMTypeRef {
unsafe { core::LLVMInt32TypeInContext(self.context) }
}
}
impl Drop for Generator {
fn drop(&mut self) {
debug!("Cleaning up generator");
unsafe {
core::LLVMDisposeBuilder(self.builder);
core::LLVMDisposeModule(self.module);
core::LLVMContextDispose(self.context);
}
}
}
#[macro_export]
macro_rules! llvm_str {
($s:expr) => {
format!("{}\0", $s).as_ptr() as *const i8
};
}