1use crate::compiler::LLVMCompiler;
2pub use inkwell::OptimizationLevel as LLVMOptLevel;
3use inkwell::targets::{
4 CodeModel, InitializationConfig, RelocMode, Target as InkwellTarget, TargetMachine,
5 TargetMachineOptions, TargetTriple,
6};
7use itertools::Itertools;
8use std::fs::File;
9use std::io::{self, Write};
10use std::path::PathBuf;
11use std::sync::Arc;
12use std::{fmt::Debug, num::NonZero};
13use target_lexicon::BinaryFormat;
14use wasmer_compiler::misc::{CompiledKind, function_kind_to_filename};
15use wasmer_compiler::{Compiler, CompilerConfig, Engine, EngineBuilder, ModuleMiddleware};
16use wasmer_types::{
17 Features,
18 target::{Architecture, OperatingSystem, Target, Triple},
19};
20
21pub type InkwellModule<'ctx> = inkwell::module::Module<'ctx>;
23
24pub type InkwellMemoryBuffer = inkwell::memory_buffer::MemoryBuffer;
26
27#[derive(Debug, Clone)]
29pub struct LLVMCallbacks {
30 debug_dir: PathBuf,
31}
32
33impl LLVMCallbacks {
34 pub fn new(debug_dir: PathBuf) -> Result<Self, io::Error> {
35 std::fs::create_dir_all(&debug_dir)?;
37 Ok(Self { debug_dir })
38 }
39
40 fn base_path(&self, module_hash: &Option<String>) -> PathBuf {
41 let mut path = self.debug_dir.clone();
42 if let Some(hash) = module_hash {
43 path.push(hash);
44 }
45 std::fs::create_dir_all(&path)
46 .unwrap_or_else(|_| panic!("cannot create debug directory: {}", path.display()));
47 path
48 }
49
50 pub fn preopt_ir(
51 &self,
52 kind: &CompiledKind,
53 module_hash: &Option<String>,
54 module: &InkwellModule,
55 ) {
56 let mut path = self.base_path(module_hash);
57 path.push(function_kind_to_filename(kind, ".preopt.ll"));
58 module
59 .print_to_file(&path)
60 .expect("Error while dumping pre optimized LLVM IR");
61 }
62 pub fn postopt_ir(
63 &self,
64 kind: &CompiledKind,
65 module_hash: &Option<String>,
66 module: &InkwellModule,
67 ) {
68 let mut path = self.base_path(module_hash);
69 path.push(function_kind_to_filename(kind, ".postopt.ll"));
70 module
71 .print_to_file(&path)
72 .expect("Error while dumping post optimized LLVM IR");
73 }
74 pub fn obj_memory_buffer(
75 &self,
76 kind: &CompiledKind,
77 module_hash: &Option<String>,
78 memory_buffer: &InkwellMemoryBuffer,
79 ) {
80 let mut path = self.base_path(module_hash);
81 path.push(function_kind_to_filename(kind, ".o"));
82 let mem_buf_slice = memory_buffer.as_slice();
83 let mut file =
84 File::create(path).expect("Error while creating debug object file from LLVM IR");
85 file.write_all(mem_buf_slice).unwrap();
86 }
87
88 pub fn asm_memory_buffer(
89 &self,
90 kind: &CompiledKind,
91 module_hash: &Option<String>,
92 asm_memory_buffer: &InkwellMemoryBuffer,
93 ) {
94 let mut path = self.base_path(module_hash);
95 path.push(function_kind_to_filename(kind, ".s"));
96 let mem_buf_slice = asm_memory_buffer.as_slice();
97 let mut file =
98 File::create(path).expect("Error while creating debug assembly file from LLVM IR");
99 file.write_all(mem_buf_slice).unwrap();
100 }
101}
102
103#[derive(Debug, Clone)]
104pub struct LLVM {
105 pub(crate) enable_nan_canonicalization: bool,
106 pub(crate) enable_g0m0_opt: bool,
107 pub(crate) enable_verifier: bool,
108 pub(crate) enable_perfmap: bool,
109 pub(crate) opt_level: LLVMOptLevel,
110 is_pic: bool,
111 pub(crate) callbacks: Option<LLVMCallbacks>,
112 pub(crate) middlewares: Vec<Arc<dyn ModuleMiddleware>>,
114 pub(crate) num_threads: NonZero<usize>,
116}
117
118impl LLVM {
119 pub fn new() -> Self {
122 Self {
123 enable_nan_canonicalization: false,
124 enable_verifier: false,
125 enable_perfmap: false,
126 opt_level: LLVMOptLevel::Aggressive,
127 is_pic: false,
128 callbacks: None,
129 middlewares: vec![],
130 enable_g0m0_opt: false,
131 num_threads: std::thread::available_parallelism().unwrap_or(NonZero::new(1).unwrap()),
132 }
133 }
134
135 pub fn opt_level(&mut self, opt_level: LLVMOptLevel) -> &mut Self {
137 self.opt_level = opt_level;
138 self
139 }
140
141 pub fn enable_pass_params_opt(&mut self) -> &mut Self {
144 self.enable_g0m0_opt = true;
146 self
147 }
148
149 pub fn num_threads(&mut self, num_threads: NonZero<usize>) -> &mut Self {
150 self.num_threads = num_threads;
151 self
152 }
153
154 pub fn callbacks(&mut self, callbacks: Option<LLVMCallbacks>) -> &mut Self {
157 self.callbacks = callbacks;
158 self
159 }
160
161 fn reloc_mode(&self, binary_format: BinaryFormat) -> RelocMode {
162 if matches!(binary_format, BinaryFormat::Macho) {
163 return RelocMode::Static;
164 }
165
166 if self.is_pic {
167 RelocMode::PIC
168 } else {
169 RelocMode::Static
170 }
171 }
172
173 fn code_model(&self, binary_format: BinaryFormat) -> CodeModel {
174 if matches!(binary_format, BinaryFormat::Macho) {
180 return CodeModel::Default;
181 }
182
183 if self.is_pic {
184 CodeModel::Small
185 } else {
186 CodeModel::Large
187 }
188 }
189
190 pub(crate) fn target_operating_system(&self, target: &Target) -> OperatingSystem {
191 match target.triple().operating_system {
192 OperatingSystem::Darwin(deployment) if !self.is_pic => {
193 #[allow(clippy::match_single_binding)]
201 match target.triple().architecture {
202 Architecture::Aarch64(_) => OperatingSystem::Darwin(deployment),
203 _ => OperatingSystem::Linux,
204 }
205 }
206 other => other,
207 }
208 }
209
210 pub(crate) fn target_binary_format(&self, target: &Target) -> target_lexicon::BinaryFormat {
211 if self.is_pic {
212 target.triple().binary_format
213 } else {
214 match self.target_operating_system(target) {
215 OperatingSystem::Darwin(_) => target_lexicon::BinaryFormat::Macho,
216 _ => target_lexicon::BinaryFormat::Elf,
217 }
218 }
219 }
220
221 fn target_triple(&self, target: &Target) -> TargetTriple {
222 let architecture = if target.triple().architecture
223 == Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64gc)
224 {
225 target_lexicon::Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64)
226 } else {
227 target.triple().architecture
228 };
229 let operating_system = self.target_operating_system(target);
233 let binary_format = self.target_binary_format(target);
234
235 let triple = Triple {
236 architecture,
237 vendor: target.triple().vendor.clone(),
238 operating_system,
239 environment: target.triple().environment,
240 binary_format,
241 };
242 TargetTriple::create(&triple.to_string())
243 }
244
245 pub fn target_machine(&self, target: &Target) -> TargetMachine {
247 self.target_machine_with_opt(target, true)
248 }
249
250 pub(crate) fn target_machine_with_opt(
251 &self,
252 target: &Target,
253 enable_optimization: bool,
254 ) -> TargetMachine {
255 let triple = target.triple();
256 let cpu_features = &target.cpu_features();
257
258 match triple.architecture {
259 Architecture::X86_64 | Architecture::X86_32(_) => {
260 InkwellTarget::initialize_x86(&InitializationConfig {
261 asm_parser: true,
262 asm_printer: true,
263 base: true,
264 disassembler: true,
265 info: true,
266 machine_code: true,
267 })
268 }
269 Architecture::Aarch64(_) => InkwellTarget::initialize_aarch64(&InitializationConfig {
270 asm_parser: true,
271 asm_printer: true,
272 base: true,
273 disassembler: true,
274 info: true,
275 machine_code: true,
276 }),
277 Architecture::Riscv64(_) | Architecture::Riscv32(_) => {
278 InkwellTarget::initialize_riscv(&InitializationConfig {
279 asm_parser: true,
280 asm_printer: true,
281 base: true,
282 disassembler: true,
283 info: true,
284 machine_code: true,
285 })
286 }
287 Architecture::LoongArch64 => {
288 InkwellTarget::initialize_loongarch(&InitializationConfig {
289 asm_parser: true,
290 asm_printer: true,
291 base: true,
292 disassembler: true,
293 info: true,
294 machine_code: true,
295 })
296 }
297 _ => unimplemented!("target {} not yet supported in Wasmer", triple),
298 }
299
300 let llvm_cpu_features = cpu_features
304 .iter()
305 .map(|feature| format!("+{feature}"))
306 .join(",");
307
308 let target_triple = self.target_triple(target);
309 let llvm_target = InkwellTarget::from_triple(&target_triple).unwrap();
310 let mut llvm_target_machine_options = TargetMachineOptions::new()
311 .set_cpu(match triple.architecture {
312 Architecture::Riscv64(_) => "generic-rv64",
313 Architecture::Riscv32(_) => "generic-rv32",
314 Architecture::LoongArch64 => "generic-la64",
315 _ => "generic",
316 })
317 .set_features(match triple.architecture {
318 Architecture::Riscv64(_) => "+m,+a,+c,+d,+f",
319 Architecture::Riscv32(_) => "+m,+a,+c,+d,+f",
320 Architecture::LoongArch64 => "+f,+d",
321 _ => &llvm_cpu_features,
322 })
323 .set_level(if enable_optimization {
324 self.opt_level
325 } else {
326 LLVMOptLevel::None
327 })
328 .set_reloc_mode(self.reloc_mode(self.target_binary_format(target)))
329 .set_code_model(match triple.architecture {
330 Architecture::LoongArch64 | Architecture::Riscv64(_) | Architecture::Riscv32(_) => {
331 CodeModel::Medium
332 }
333 _ => self.code_model(self.target_binary_format(target)),
334 });
335 if let Architecture::Riscv64(_) = triple.architecture {
336 llvm_target_machine_options = llvm_target_machine_options.set_abi("lp64d");
337 }
338 llvm_target
339 .create_target_machine_from_options(&target_triple, llvm_target_machine_options)
340 .unwrap()
341 }
342}
343
344impl CompilerConfig for LLVM {
345 fn enable_pic(&mut self) {
347 self.is_pic = true;
350 }
351
352 fn enable_perfmap(&mut self) {
353 self.enable_perfmap = true
354 }
355
356 fn enable_verifier(&mut self) {
358 self.enable_verifier = true;
359 }
360
361 fn canonicalize_nans(&mut self, enable: bool) {
362 self.enable_nan_canonicalization = enable;
363 }
364
365 fn compiler(self: Box<Self>) -> Box<dyn Compiler> {
367 Box::new(LLVMCompiler::new(*self))
368 }
369
370 fn push_middleware(&mut self, middleware: Arc<dyn ModuleMiddleware>) {
372 self.middlewares.push(middleware);
373 }
374
375 fn supported_features_for_target(&self, _target: &Target) -> wasmer_types::Features {
376 let mut feats = Features::default();
377 feats.exceptions(true);
378 feats
379 }
380}
381
382impl Default for LLVM {
383 fn default() -> LLVM {
384 Self::new()
385 }
386}
387
388impl From<LLVM> for Engine {
389 fn from(config: LLVM) -> Self {
390 EngineBuilder::new(config).engine()
391 }
392}