1#[cfg(any(
22 feature = "llvm10-0",
23 feature = "llvm11-0",
24 feature = "llvm12-0",
25 feature = "llvm13-0",
26 feature = "llvm14-0",
27 feature = "llvm15-0",
28 feature = "llvm16-0",
29 feature = "llvm17-0",
30 feature = "llvm18-0"
31))]
32pub extern crate inkwell_05 as inkwell;
33#[cfg(any(
34 feature = "llvm19-1",
35 feature = "llvm20-1",
36 feature = "llvm21-1",
37 feature = "llvm22-1"
38))]
39pub extern crate inkwell_09 as inkwell;
40
41pub mod traits;
42
43#[cfg(feature = "llvm-plugin-crate")]
44mod llvm_plugin_harness;
45
46use inkwell::values::AsValueRef;
47use std::cell::OnceCell;
48use std::collections::HashMap;
49use std::ffi::{c_void, CStr, CString};
50use std::fmt;
51use std::marker::PhantomData;
52#[cfg(feature = "llvm-plugin-crate")]
53use std::mem::ManuallyDrop;
54use std::ptr;
55use std::sync::{Mutex, Once};
56
57pub use llvm_pm_sys::{LLVMBasicBlockRef, LLVMModuleRef, LLVMValueRef};
58use traits::{
59 LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionPass, LlvmLoopAnalysis, LlvmLoopPass,
60 LlvmModulePass, PreservedAnalyses,
61};
62pub type AnalysisKey = *const u8;
63
64#[cfg(all(
65 feature = "llvm-plugin-crate",
66 any(
67 feature = "llvm19-1",
68 feature = "llvm20-1",
69 feature = "llvm21-1",
70 feature = "llvm22-1"
71 )
72))]
73compile_error!(
74 "`llvm-plugin-crate` supports llvm-plugin-compatible LLVM features (llvm10-0 .. llvm18-0)."
75);
76
77pub struct ModuleAnalysisManager {
78 inner: *mut c_void,
79 from_analysis_id: Option<AnalysisKey>,
80}
81
82impl ModuleAnalysisManager {
83 pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<AnalysisKey>) -> Self {
86 Self {
87 inner,
88 from_analysis_id,
89 }
90 }
91 pub fn as_raw(&self) -> *mut c_void {
92 self.inner
93 }
94 pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
95 self.from_analysis_id
96 }
97}
98
99pub struct FunctionAnalysisManager {
100 inner: *mut c_void,
101 from_analysis_id: Option<AnalysisKey>,
102}
103
104impl FunctionAnalysisManager {
105 pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<AnalysisKey>) -> Self {
108 Self {
109 inner,
110 from_analysis_id,
111 }
112 }
113 pub fn as_raw(&self) -> *mut c_void {
114 self.inner
115 }
116 pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
117 self.from_analysis_id
118 }
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123pub enum OptLevel {
124 O0,
125 O1,
126 O2,
127 O3,
128 Os,
129 Oz,
130}
131
132impl OptLevel {
133 fn to_c(self) -> llvm_pm_sys::LlvmPmOptLevel {
134 match self {
135 OptLevel::O0 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O0,
136 OptLevel::O1 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O1,
137 OptLevel::O2 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O2,
138 OptLevel::O3 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O3,
139 OptLevel::Os => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Os,
140 OptLevel::Oz => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Oz,
141 }
142 }
143}
144
145#[derive(Debug)]
147pub struct Error {
148 message: String,
149}
150
151impl Error {
152 pub fn message(&self) -> &str {
154 &self.message
155 }
156}
157
158impl fmt::Display for Error {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 write!(f, "{}", self.message)
161 }
162}
163
164impl std::error::Error for Error {}
165
166unsafe fn consume_c_error(ptr: *mut std::ffi::c_char) -> Error {
172 let msg = CStr::from_ptr(ptr).to_string_lossy().into_owned();
174 llvm_pm_sys::llvm_pm_dispose_message(ptr);
175 Error { message: msg }
176}
177
178pub struct Options {
188 raw: llvm_pm_sys::LlvmPmOptionsRef,
189}
190
191impl Options {
192 pub fn new() -> Self {
194 let raw = unsafe { llvm_pm_sys::llvm_pm_options_create() };
196 Self { raw }
197 }
198
199 pub fn debug_logging(&mut self, val: bool) -> &mut Self {
201 unsafe {
203 llvm_pm_sys::llvm_pm_options_set_debug_logging(self.raw, val as i32);
204 }
205 self
206 }
207
208 pub fn verify_each(&mut self, val: bool) -> &mut Self {
210 unsafe {
212 llvm_pm_sys::llvm_pm_options_set_verify_each(self.raw, val as i32);
213 }
214 self
215 }
216
217 pub fn add_peephole_ep(&mut self, pipeline: &str) -> &mut Self {
219 let c = CString::new(pipeline).expect("pipeline contains null byte");
220 unsafe {
222 llvm_pm_sys::llvm_pm_options_add_peephole_ep(self.raw, c.as_ptr());
223 }
224 self
225 }
226
227 pub fn add_optimizer_early_ep(&mut self, pipeline: &str) -> &mut Self {
229 let c = CString::new(pipeline).expect("pipeline contains null byte");
230 unsafe {
232 llvm_pm_sys::llvm_pm_options_add_optimizer_early_ep(self.raw, c.as_ptr());
233 }
234 self
235 }
236
237 pub fn add_optimizer_last_ep(&mut self, pipeline: &str) -> &mut Self {
239 let c = CString::new(pipeline).expect("pipeline contains null byte");
240 unsafe {
242 llvm_pm_sys::llvm_pm_options_add_optimizer_last_ep(self.raw, c.as_ptr());
243 }
244 self
245 }
246
247 pub fn add_vectorizer_start_ep(&mut self, pipeline: &str) -> &mut Self {
249 let c = CString::new(pipeline).expect("pipeline contains null byte");
250 unsafe {
252 llvm_pm_sys::llvm_pm_options_add_vectorizer_start_ep(self.raw, c.as_ptr());
253 }
254 self
255 }
256
257 pub fn add_scalar_optimizer_late_ep(&mut self, pipeline: &str) -> &mut Self {
259 let c = CString::new(pipeline).expect("pipeline contains null byte");
260 unsafe {
262 llvm_pm_sys::llvm_pm_options_add_scalar_optimizer_late_ep(self.raw, c.as_ptr());
263 }
264 self
265 }
266
267 pub fn add_pipeline_start_ep(&mut self, pipeline: &str) -> &mut Self {
269 let c = CString::new(pipeline).expect("pipeline contains null byte");
270 unsafe {
272 llvm_pm_sys::llvm_pm_options_add_pipeline_start_ep(self.raw, c.as_ptr());
273 }
274 self
275 }
276
277 pub fn add_pipeline_early_simplification_ep(&mut self, pipeline: &str) -> &mut Self {
279 let c = CString::new(pipeline).expect("pipeline contains null byte");
280 unsafe {
282 llvm_pm_sys::llvm_pm_options_add_pipeline_early_simplification_ep(self.raw, c.as_ptr());
283 }
284 self
285 }
286}
287
288impl Default for Options {
289 fn default() -> Self {
290 Self::new()
291 }
292}
293
294impl Drop for Options {
295 fn drop(&mut self) {
296 unsafe {
298 llvm_pm_sys::llvm_pm_options_dispose(self.raw);
299 }
300 }
301}
302
303pub struct CgsccAnalysisManager {
305 raw: *mut c_void,
306 from_analysis_id: Option<AnalysisKey>,
307}
308
309impl CgsccAnalysisManager {
310 pub unsafe fn from_raw(raw: *mut c_void) -> Self {
315 Self {
316 raw,
317 from_analysis_id: None,
318 }
319 }
320
321 unsafe fn from_raw_with_analysis_id(
322 raw: *mut c_void,
323 from_analysis_id: Option<AnalysisKey>,
324 ) -> Self {
325 Self {
326 raw,
327 from_analysis_id,
328 }
329 }
330
331 pub fn as_raw(&self) -> *mut c_void {
333 self.raw
334 }
335
336 pub fn add_analysis<P>(&self, pass: P)
338 where
339 P: LlvmCgsccAnalysis,
340 P: 'static,
341 <P as LlvmCgsccAnalysis>::Result: 'static,
342 {
343 extern "C" fn pass_deleter<T: LlvmCgsccAnalysis>(pass: *mut c_void) {
344 drop(unsafe { Box::<T>::from_raw(pass.cast()) });
346 }
347
348 fn pass_entrypoint<T>(
349 pass: *mut c_void,
350 function: &inkwell::values::FunctionValue<'_>,
351 manager: *mut c_void,
352 ) -> *mut c_void
353 where
354 T: LlvmCgsccAnalysis,
355 T::Result: 'static,
356 {
357 let pass = unsafe { &*(pass as *const T) };
359 let manager =
361 unsafe { CgsccAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
362 let result = pass.run_analysis(function, &manager);
363 Box::into_raw(Box::new(result)) as *mut c_void
364 }
365
366 let manager_key = self.raw as usize;
367 let analysis_key = <P as LlvmCgsccAnalysis>::id() as usize;
368 let mut passes = cgscc_analysis_passes()
369 .lock()
370 .expect("poisoned cgscc analysis registry");
371 let entry_map = passes.entry(manager_key).or_default();
372 assert!(
373 !entry_map.contains_key(&analysis_key),
374 "analysis already registered"
375 );
376 entry_map.insert(
377 analysis_key,
378 CgsccAnalysisEntry {
379 pass: Box::into_raw(Box::new(pass)) as *mut c_void,
380 pass_deleter: pass_deleter::<P>,
381 pass_entrypoint: pass_entrypoint::<P>,
382 },
383 );
384 }
385
386 pub fn get_result<A>(&self, function: &inkwell::values::FunctionValue<'_>) -> &A::Result
388 where
389 A: LlvmCgsccAnalysis + 'static,
390 A::Result: 'static,
391 {
392 let id = A::id();
393 assert!(
394 !matches!(self.from_analysis_id, Some(n) if n == id),
395 "Analysis cannot request its own result"
396 );
397
398 let manager_key = self.raw as usize;
399 let analysis_key = id as usize;
400 let function_key = function.as_value_ref() as usize;
401
402 if let Some(result) = self.get_cached_result::<A>(function) {
403 return result;
404 }
405
406 let passes = cgscc_analysis_passes()
407 .lock()
408 .expect("poisoned cgscc analysis registry");
409 let entry = passes
410 .get(&manager_key)
411 .and_then(|m| m.get(&analysis_key))
412 .expect("analysis was not registered");
413 let result_ptr = (entry.pass_entrypoint)(entry.pass, function, self.raw);
414 drop(passes);
415
416 let mut cache = cgscc_analysis_cache()
417 .lock()
418 .expect("poisoned cgscc analysis cache");
419 cache
420 .entry(manager_key)
421 .or_default()
422 .insert((analysis_key, function_key), result_ptr as usize);
423 unsafe { &*(result_ptr as *const A::Result) }
425 }
426
427 pub fn get_cached_result<A>(
429 &self,
430 function: &inkwell::values::FunctionValue<'_>,
431 ) -> Option<&A::Result>
432 where
433 A: LlvmCgsccAnalysis + 'static,
434 A::Result: 'static,
435 {
436 let id = A::id();
437 assert!(
438 !matches!(self.from_analysis_id, Some(n) if n == id),
439 "Analysis cannot request its own result"
440 );
441
442 let manager_key = self.raw as usize;
443 let analysis_key = id as usize;
444 let function_key = function.as_value_ref() as usize;
445 let cache = cgscc_analysis_cache()
446 .lock()
447 .expect("poisoned cgscc analysis cache");
448 cache
449 .get(&manager_key)
450 .and_then(|m| m.get(&(analysis_key, function_key)))
451 .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
454 }
455}
456
457pub struct LoopAnalysisManager {
459 raw: *mut c_void,
460 from_analysis_id: Option<AnalysisKey>,
461}
462
463impl LoopAnalysisManager {
464 pub unsafe fn from_raw(raw: *mut c_void) -> Self {
469 Self {
470 raw,
471 from_analysis_id: None,
472 }
473 }
474
475 unsafe fn from_raw_with_analysis_id(
476 raw: *mut c_void,
477 from_analysis_id: Option<AnalysisKey>,
478 ) -> Self {
479 Self {
480 raw,
481 from_analysis_id,
482 }
483 }
484
485 pub fn as_raw(&self) -> *mut c_void {
487 self.raw
488 }
489
490 pub fn add_analysis<P>(&self, pass: P)
492 where
493 P: LlvmLoopAnalysis,
494 P: 'static,
495 <P as LlvmLoopAnalysis>::Result: 'static,
496 {
497 extern "C" fn pass_deleter<T: LlvmLoopAnalysis>(pass: *mut c_void) {
498 drop(unsafe { Box::<T>::from_raw(pass.cast()) });
500 }
501
502 fn pass_entrypoint<T>(
503 pass: *mut c_void,
504 loop_header: LLVMBasicBlockRef,
505 manager: *mut c_void,
506 ) -> *mut c_void
507 where
508 T: LlvmLoopAnalysis,
509 T::Result: 'static,
510 {
511 let pass = unsafe { &*(pass as *const T) };
513 let manager =
515 unsafe { LoopAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
516 let result = pass.run_analysis(loop_header, &manager);
517 Box::into_raw(Box::new(result)) as *mut c_void
518 }
519
520 let manager_key = self.raw as usize;
521 let analysis_key = <P as LlvmLoopAnalysis>::id() as usize;
522 let mut passes = loop_analysis_passes()
523 .lock()
524 .expect("poisoned loop analysis registry");
525 let entry_map = passes.entry(manager_key).or_default();
526 assert!(
527 !entry_map.contains_key(&analysis_key),
528 "analysis already registered"
529 );
530 entry_map.insert(
531 analysis_key,
532 LoopAnalysisEntry {
533 pass: Box::into_raw(Box::new(pass)) as *mut c_void,
534 pass_deleter: pass_deleter::<P>,
535 pass_entrypoint: pass_entrypoint::<P>,
536 },
537 );
538 }
539
540 pub fn get_result<A>(&self, loop_header: LLVMBasicBlockRef) -> &A::Result
542 where
543 A: LlvmLoopAnalysis + 'static,
544 A::Result: 'static,
545 {
546 let id = A::id();
547 assert!(
548 !matches!(self.from_analysis_id, Some(n) if n == id),
549 "Analysis cannot request its own result"
550 );
551
552 let manager_key = self.raw as usize;
553 let analysis_key = id as usize;
554 let loop_key = loop_header as usize;
555
556 if let Some(result) = self.get_cached_result::<A>(loop_header) {
557 return result;
558 }
559
560 let passes = loop_analysis_passes()
561 .lock()
562 .expect("poisoned loop analysis registry");
563 let entry = passes
564 .get(&manager_key)
565 .and_then(|m| m.get(&analysis_key))
566 .expect("analysis was not registered");
567 let result_ptr = (entry.pass_entrypoint)(entry.pass, loop_header, self.raw);
568 drop(passes);
569
570 let mut cache = loop_analysis_cache()
571 .lock()
572 .expect("poisoned loop analysis cache");
573 cache
574 .entry(manager_key)
575 .or_default()
576 .insert((analysis_key, loop_key), result_ptr as usize);
577 unsafe { &*(result_ptr as *const A::Result) }
579 }
580
581 pub fn get_cached_result<A>(&self, loop_header: LLVMBasicBlockRef) -> Option<&A::Result>
583 where
584 A: LlvmLoopAnalysis + 'static,
585 A::Result: 'static,
586 {
587 let id = A::id();
588 assert!(
589 !matches!(self.from_analysis_id, Some(n) if n == id),
590 "Analysis cannot request its own result"
591 );
592
593 let manager_key = self.raw as usize;
594 let analysis_key = id as usize;
595 let loop_key = loop_header as usize;
596 let cache = loop_analysis_cache()
597 .lock()
598 .expect("poisoned loop analysis cache");
599 cache
600 .get(&manager_key)
601 .and_then(|m| m.get(&(analysis_key, loop_key)))
602 .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
605 }
606}
607
608struct CgsccAnalysisEntry {
609 pass: *mut c_void,
610 pass_deleter: extern "C" fn(*mut c_void),
611 pass_entrypoint:
612 fn(*mut c_void, &inkwell::values::FunctionValue<'_>, *mut c_void) -> *mut c_void,
613}
614
615struct LoopAnalysisEntry {
616 pass: *mut c_void,
617 pass_deleter: extern "C" fn(*mut c_void),
618 pass_entrypoint: fn(*mut c_void, LLVMBasicBlockRef, *mut c_void) -> *mut c_void,
619}
620
621impl Drop for CgsccAnalysisEntry {
622 fn drop(&mut self) {
623 (self.pass_deleter)(self.pass);
624 }
625}
626
627impl Drop for LoopAnalysisEntry {
628 fn drop(&mut self) {
629 (self.pass_deleter)(self.pass);
630 }
631}
632
633unsafe impl Send for CgsccAnalysisEntry {}
636unsafe impl Send for LoopAnalysisEntry {}
637
638struct SyncOnceCell<T>(OnceCell<T>);
639
640impl<T> SyncOnceCell<T> {
641 const fn new() -> Self {
642 Self(OnceCell::new())
643 }
644}
645
646unsafe impl<T: Sync> Sync for SyncOnceCell<T> {}
649
650fn cgscc_analysis_passes() -> &'static Mutex<HashMap<usize, HashMap<usize, CgsccAnalysisEntry>>> {
651 static INIT: Once = Once::new();
652 static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<usize, CgsccAnalysisEntry>>>> =
653 SyncOnceCell::new();
654 INIT.call_once(|| {
655 let _ = CELL.0.set(Mutex::new(HashMap::new()));
656 });
657 CELL.0.get().expect("cgscc registry initialized")
658}
659
660fn cgscc_analysis_cache() -> &'static Mutex<HashMap<usize, HashMap<(usize, usize), usize>>> {
661 static INIT: Once = Once::new();
662 static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<(usize, usize), usize>>>> =
663 SyncOnceCell::new();
664 INIT.call_once(|| {
665 let _ = CELL.0.set(Mutex::new(HashMap::new()));
666 });
667 CELL.0.get().expect("cgscc cache initialized")
668}
669
670fn loop_analysis_passes() -> &'static Mutex<HashMap<usize, HashMap<usize, LoopAnalysisEntry>>> {
671 static INIT: Once = Once::new();
672 static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<usize, LoopAnalysisEntry>>>> =
673 SyncOnceCell::new();
674 INIT.call_once(|| {
675 let _ = CELL.0.set(Mutex::new(HashMap::new()));
676 });
677 CELL.0.get().expect("loop registry initialized")
678}
679
680fn loop_analysis_cache() -> &'static Mutex<HashMap<usize, HashMap<(usize, usize), usize>>> {
681 static INIT: Once = Once::new();
682 static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<(usize, usize), usize>>>> =
683 SyncOnceCell::new();
684 INIT.call_once(|| {
685 let _ = CELL.0.set(Mutex::new(HashMap::new()));
686 });
687 CELL.0.get().expect("loop cache initialized")
688}
689
690fn preserved_to_c(pa: traits::PreservedAnalyses) -> std::ffi::c_int {
691 match pa {
692 PreservedAnalyses::All => 0,
693 PreservedAnalyses::None => 1,
694 }
695}
696
697unsafe extern "C" fn module_pass_trampoline<T: LlvmModulePass>(
703 module: LLVMModuleRef,
704 manager: *mut c_void,
705 user_data: *mut c_void,
706) -> std::ffi::c_int {
707 let pass = &*(user_data as *const T);
709 let mut module = inkwell::module::Module::new(module);
710 let manager = ModuleAnalysisManager::from_raw(manager, None);
711 let result = pass.run_pass(&mut module, &manager);
712 std::mem::forget(module);
713 preserved_to_c(result)
714}
715
716unsafe extern "C" fn function_pass_trampoline<T: LlvmFunctionPass>(
722 function: LLVMValueRef,
723 manager: *mut c_void,
724 user_data: *mut c_void,
725) -> std::ffi::c_int {
726 let pass = &*(user_data as *const T);
727 let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
728 let manager = FunctionAnalysisManager::from_raw(manager, None);
729 let result = pass.run_pass(&mut function, &manager);
730 preserved_to_c(result)
731}
732
733unsafe extern "C" fn cgscc_pass_trampoline<T: LlvmCgsccPass>(
739 function: LLVMValueRef,
740 manager: *mut c_void,
741 user_data: *mut c_void,
742) -> std::ffi::c_int {
743 let pass = &*(user_data as *const T);
744 let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
745 let manager = CgsccAnalysisManager::from_raw(manager);
746 let result = pass.run_pass(&mut function, &manager);
747 preserved_to_c(result)
748}
749
750unsafe extern "C" fn loop_pass_trampoline<T: LlvmLoopPass>(
756 header: LLVMBasicBlockRef,
757 manager: *mut c_void,
758 user_data: *mut c_void,
759) -> std::ffi::c_int {
760 let pass = &*(user_data as *const T);
761 let manager = LoopAnalysisManager::from_raw(manager);
762 let result = pass.run_pass(header, &manager);
763 preserved_to_c(result)
764}
765
766pub struct ModulePassManager<'a> {
778 raw: llvm_pm_sys::LlvmPmPassManagerRef,
779 _passes: Vec<Box<dyn std::any::Any>>,
780 _phantom: PhantomData<&'a ()>,
781}
782
783impl<'a> fmt::Debug for ModulePassManager<'a> {
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 f.debug_struct("ModulePassManager")
786 .field("raw", &self.raw)
787 .finish()
788 }
789}
790
791impl<'a> ModulePassManager<'a> {
792 pub fn with_opt_level(
794 target_machine: Option<&'a inkwell::targets::TargetMachine>,
795 level: OptLevel,
796 options: Option<&Options>,
797 ) -> Result<Self, Error> {
798 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
799 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
800 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
801
802 let raw = unsafe {
805 llvm_pm_sys::llvm_pm_create_with_opt_level(tm, level.to_c(), opts, &mut err_msg)
806 };
807
808 if raw.is_null() {
809 Err(unsafe { consume_c_error(err_msg) })
811 } else {
812 Ok(Self {
813 raw,
814 _passes: Vec::new(),
815 _phantom: PhantomData,
816 })
817 }
818 }
819
820 pub fn with_pipeline(
827 target_machine: Option<&'a inkwell::targets::TargetMachine>,
828 pipeline: &str,
829 options: Option<&Options>,
830 ) -> Result<Self, Error> {
831 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
832 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
833 let c_pipeline = CString::new(pipeline).map_err(|e| Error {
834 message: format!("Pipeline string contains null byte: {}", e),
835 })?;
836 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
837
838 let raw = unsafe {
840 llvm_pm_sys::llvm_pm_create_with_pipeline(tm, c_pipeline.as_ptr(), opts, &mut err_msg)
841 };
842
843 if raw.is_null() {
844 Err(unsafe { consume_c_error(err_msg) })
846 } else {
847 Ok(Self {
848 raw,
849 _passes: Vec::new(),
850 _phantom: PhantomData,
851 })
852 }
853 }
854
855 pub fn with_lto(
857 target_machine: Option<&'a inkwell::targets::TargetMachine>,
858 level: OptLevel,
859 options: Option<&Options>,
860 ) -> Result<Self, Error> {
861 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
862 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
863 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
864
865 let raw = unsafe { llvm_pm_sys::llvm_pm_create_lto(tm, level.to_c(), opts, &mut err_msg) };
867
868 if raw.is_null() {
869 Err(unsafe { consume_c_error(err_msg) })
871 } else {
872 Ok(Self {
873 raw,
874 _passes: Vec::new(),
875 _phantom: PhantomData,
876 })
877 }
878 }
879
880 pub fn with_lto_pre_link(
882 target_machine: Option<&'a inkwell::targets::TargetMachine>,
883 level: OptLevel,
884 options: Option<&Options>,
885 ) -> Result<Self, Error> {
886 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
887 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
888 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
889
890 let raw = unsafe {
892 llvm_pm_sys::llvm_pm_create_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
893 };
894
895 if raw.is_null() {
896 Err(unsafe { consume_c_error(err_msg) })
898 } else {
899 Ok(Self {
900 raw,
901 _passes: Vec::new(),
902 _phantom: PhantomData,
903 })
904 }
905 }
906
907 pub fn with_thin_lto_pre_link(
909 target_machine: Option<&'a inkwell::targets::TargetMachine>,
910 level: OptLevel,
911 options: Option<&Options>,
912 ) -> Result<Self, Error> {
913 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
914 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
915 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
916
917 let raw = unsafe {
919 llvm_pm_sys::llvm_pm_create_thin_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
920 };
921
922 if raw.is_null() {
923 Err(unsafe { consume_c_error(err_msg) })
925 } else {
926 Ok(Self {
927 raw,
928 _passes: Vec::new(),
929 _phantom: PhantomData,
930 })
931 }
932 }
933
934 pub fn new(
938 target_machine: Option<&'a inkwell::targets::TargetMachine>,
939 options: Option<&Options>,
940 ) -> Result<Self, Error> {
941 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
942 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
943 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
944
945 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
947
948 if raw.is_null() {
949 Err(unsafe { consume_c_error(err_msg) })
951 } else {
952 Ok(Self {
953 raw,
954 _passes: Vec::new(),
955 _phantom: PhantomData,
956 })
957 }
958 }
959
960 pub fn add_pass<P>(&mut self, pass: P)
966 where
967 P: LlvmModulePass + 'static,
968 {
969 let mut boxed = Box::new(pass);
970 let ptr = &mut *boxed as *mut P as *mut c_void;
971 unsafe {
975 llvm_pm_sys::llvm_pm_add_module_pass(self.raw, Some(module_pass_trampoline::<P>), ptr);
976 }
977 self._passes.push(boxed);
978 }
979
980 pub fn add_cgscc_pass<P>(&mut self, pass: P)
985 where
986 P: LlvmCgsccPass + 'static,
987 {
988 let mut boxed = Box::new(pass);
989 let ptr = &mut *boxed as *mut P as *mut c_void;
990 unsafe {
994 llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
995 }
996 self._passes.push(boxed);
997 }
998
999 pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1001 let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1004 if err.is_null() {
1005 Ok(())
1006 } else {
1007 Err(unsafe { consume_c_error(err) })
1009 }
1010 }
1011}
1012
1013impl<'a> Drop for ModulePassManager<'a> {
1014 fn drop(&mut self) {
1015 unsafe {
1019 llvm_pm_sys::llvm_pm_dispose(self.raw);
1020 }
1021 }
1022}
1023
1024unsafe impl<'a> Send for ModulePassManager<'a> {}
1030
1031pub struct FunctionPassManager<'a> {
1043 raw: llvm_pm_sys::LlvmPmPassManagerRef,
1044 _passes: Vec<Box<dyn std::any::Any>>,
1045 _phantom: PhantomData<&'a ()>,
1046}
1047
1048impl<'a> fmt::Debug for FunctionPassManager<'a> {
1049 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1050 f.debug_struct("FunctionPassManager")
1051 .field("raw", &self.raw)
1052 .finish()
1053 }
1054}
1055
1056impl<'a> FunctionPassManager<'a> {
1057 pub fn with_pipeline(
1061 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1062 pipeline: &str,
1063 options: Option<&Options>,
1064 ) -> Result<Self, Error> {
1065 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1066 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1067 let c_pipeline = CString::new(pipeline).map_err(|e| Error {
1068 message: format!("Pipeline string contains null byte: {}", e),
1069 })?;
1070 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1071
1072 let raw = unsafe {
1074 llvm_pm_sys::llvm_pm_create_function_with_pipeline(
1075 tm,
1076 c_pipeline.as_ptr(),
1077 opts,
1078 &mut err_msg,
1079 )
1080 };
1081
1082 if raw.is_null() {
1083 Err(unsafe { consume_c_error(err_msg) })
1085 } else {
1086 Ok(Self {
1087 raw,
1088 _passes: Vec::new(),
1089 _phantom: PhantomData,
1090 })
1091 }
1092 }
1093
1094 pub fn new(
1098 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1099 options: Option<&Options>,
1100 ) -> Result<Self, Error> {
1101 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1102 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1103 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1104
1105 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_function(tm, opts, &mut err_msg) };
1107
1108 if raw.is_null() {
1109 Err(unsafe { consume_c_error(err_msg) })
1111 } else {
1112 Ok(Self {
1113 raw,
1114 _passes: Vec::new(),
1115 _phantom: PhantomData,
1116 })
1117 }
1118 }
1119
1120 pub fn add_pass<P>(&mut self, pass: P)
1126 where
1127 P: LlvmFunctionPass + 'static,
1128 {
1129 let mut boxed = Box::new(pass);
1130 let ptr = &mut *boxed as *mut P as *mut c_void;
1131 unsafe {
1135 llvm_pm_sys::llvm_pm_add_function_pass(
1136 self.raw,
1137 Some(function_pass_trampoline::<P>),
1138 ptr,
1139 );
1140 }
1141 self._passes.push(boxed);
1142 }
1143
1144 pub fn add_loop_pass<P>(&mut self, pass: P)
1149 where
1150 P: traits::LlvmLoopPass + 'static,
1151 {
1152 let mut boxed = Box::new(pass);
1153 let ptr = &mut *boxed as *mut P as *mut c_void;
1154 unsafe {
1158 llvm_pm_sys::llvm_pm_add_loop_pass(self.raw, Some(loop_pass_trampoline::<P>), ptr);
1159 }
1160 self._passes.push(boxed);
1161 }
1162
1163 pub fn run(&mut self, function: inkwell::values::FunctionValue<'_>) -> Result<(), Error> {
1165 use inkwell::values::AsValueRef;
1166 let err =
1169 unsafe { llvm_pm_sys::llvm_pm_run_on_function(self.raw, function.as_value_ref()) };
1170 if err.is_null() {
1171 Ok(())
1172 } else {
1173 Err(unsafe { consume_c_error(err) })
1175 }
1176 }
1177}
1178
1179impl<'a> Drop for FunctionPassManager<'a> {
1180 fn drop(&mut self) {
1181 unsafe {
1185 llvm_pm_sys::llvm_pm_dispose(self.raw);
1186 }
1187 }
1188}
1189
1190unsafe impl<'a> Send for FunctionPassManager<'a> {}