1#![doc = include_str!("../README.md")]
55
56#[cfg(any(
57 feature = "llvm10-0",
58 feature = "llvm11-0",
59 feature = "llvm12-0",
60 feature = "llvm13-0",
61 feature = "llvm14-0",
62 feature = "llvm15-0",
63 feature = "llvm16-0",
64 feature = "llvm17-0"
65))]
66pub extern crate inkwell_05 as inkwell;
67#[cfg(any(
68 feature = "llvm18-1",
69 feature = "llvm19-1",
70 feature = "llvm20-1",
71 feature = "llvm21-1",
72 feature = "llvm22-1"
73))]
74pub extern crate inkwell_09 as inkwell;
75
76pub mod traits;
77
78pub mod plugin;
79
80#[cfg(feature = "plugin-macros")]
83pub use llvm_pm_macros::plugin;
84
85#[cfg(feature = "llvm-plugin-crate")]
86mod llvm_plugin_harness;
87
88use inkwell::values::AsValueRef;
89use std::collections::HashMap;
90use std::ffi::{c_void, CStr, CString};
91use std::fmt;
92use std::marker::PhantomData;
93#[cfg(feature = "llvm-plugin-crate")]
94use std::mem::ManuallyDrop;
95use std::ptr;
96use std::sync::{Mutex, Once};
97
98use llvm_pm_sys::{LLVMBasicBlockRef, LLVMModuleRef, LLVMValueRef};
99use traits::{
100 LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionPass, LlvmLoopAnalysis, LlvmLoopPass,
101 LlvmModulePass, PreservedAnalyses,
102};
103type AnalysisKey = *const u8;
104
105#[cfg(all(
106 feature = "llvm-plugin-crate",
107 any(
108 feature = "llvm18-1",
109 feature = "llvm19-1",
110 feature = "llvm20-1",
111 feature = "llvm21-1",
112 feature = "llvm22-1"
113 )
114))]
115compile_error!(
116 "`llvm-plugin-crate` supports llvm-plugin-compatible LLVM features (llvm10-0 .. llvm7-0)."
117);
118
119pub struct ModuleAnalysisManager {
120 inner: *mut c_void,
121 from_analysis_id: Option<AnalysisKey>,
122}
123
124impl ModuleAnalysisManager {
125 pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<*const u8>) -> Self {
128 Self {
129 inner,
130 from_analysis_id,
131 }
132 }
133 pub fn as_raw(&self) -> *mut c_void {
134 self.inner
135 }
136 pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
137 self.from_analysis_id
138 }
139}
140
141pub struct FunctionAnalysisManager {
142 inner: *mut c_void,
143 from_analysis_id: Option<AnalysisKey>,
144}
145
146impl FunctionAnalysisManager {
147 pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<AnalysisKey>) -> Self {
150 Self {
151 inner,
152 from_analysis_id,
153 }
154 }
155 pub fn as_raw(&self) -> *mut c_void {
156 self.inner
157 }
158 pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
159 self.from_analysis_id
160 }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub enum OptLevel {
166 O0,
167 O1,
168 O2,
169 O3,
170 Os,
171 Oz,
172}
173
174impl OptLevel {
175 fn to_c(self) -> llvm_pm_sys::LlvmPmOptLevel {
176 match self {
177 OptLevel::O0 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O0,
178 OptLevel::O1 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O1,
179 OptLevel::O2 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O2,
180 OptLevel::O3 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O3,
181 OptLevel::Os => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Os,
182 OptLevel::Oz => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Oz,
183 }
184 }
185}
186
187#[derive(Debug)]
189pub struct Error {
190 message: String,
191}
192
193impl Error {
194 pub fn message(&self) -> &str {
196 &self.message
197 }
198}
199
200impl fmt::Display for Error {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 write!(f, "{}", self.message)
203 }
204}
205
206impl std::error::Error for Error {}
207
208unsafe fn consume_c_error(ptr: *mut std::ffi::c_char) -> Error {
214 let msg = CStr::from_ptr(ptr).to_string_lossy().into_owned();
216 llvm_pm_sys::llvm_pm_dispose_message(ptr);
217 Error { message: msg }
218}
219
220pub struct Options {
230 raw: llvm_pm_sys::LlvmPmOptionsRef,
231}
232
233impl Options {
234 pub fn new() -> Self {
236 let raw = unsafe { llvm_pm_sys::llvm_pm_options_create() };
238 Self { raw }
239 }
240
241 pub fn debug_logging(&mut self, val: bool) -> &mut Self {
243 unsafe {
245 llvm_pm_sys::llvm_pm_options_set_debug_logging(self.raw, val as i32);
246 }
247 self
248 }
249
250 pub fn verify_each(&mut self, val: bool) -> &mut Self {
252 unsafe {
254 llvm_pm_sys::llvm_pm_options_set_verify_each(self.raw, val as i32);
255 }
256 self
257 }
258
259 pub fn add_peephole_ep(&mut self, pipeline: &str) -> &mut Self {
261 let c = CString::new(pipeline).expect("pipeline contains null byte");
262 unsafe {
264 llvm_pm_sys::llvm_pm_options_add_peephole_ep(self.raw, c.as_ptr());
265 }
266 self
267 }
268
269 pub fn add_optimizer_early_ep(&mut self, pipeline: &str) -> &mut Self {
271 let c = CString::new(pipeline).expect("pipeline contains null byte");
272 unsafe {
274 llvm_pm_sys::llvm_pm_options_add_optimizer_early_ep(self.raw, c.as_ptr());
275 }
276 self
277 }
278
279 pub fn add_optimizer_last_ep(&mut self, pipeline: &str) -> &mut Self {
281 let c = CString::new(pipeline).expect("pipeline contains null byte");
282 unsafe {
284 llvm_pm_sys::llvm_pm_options_add_optimizer_last_ep(self.raw, c.as_ptr());
285 }
286 self
287 }
288
289 pub fn add_vectorizer_start_ep(&mut self, pipeline: &str) -> &mut Self {
291 let c = CString::new(pipeline).expect("pipeline contains null byte");
292 unsafe {
294 llvm_pm_sys::llvm_pm_options_add_vectorizer_start_ep(self.raw, c.as_ptr());
295 }
296 self
297 }
298
299 pub fn add_scalar_optimizer_late_ep(&mut self, pipeline: &str) -> &mut Self {
301 let c = CString::new(pipeline).expect("pipeline contains null byte");
302 unsafe {
304 llvm_pm_sys::llvm_pm_options_add_scalar_optimizer_late_ep(self.raw, c.as_ptr());
305 }
306 self
307 }
308
309 pub fn add_pipeline_start_ep(&mut self, pipeline: &str) -> &mut Self {
311 let c = CString::new(pipeline).expect("pipeline contains null byte");
312 unsafe {
314 llvm_pm_sys::llvm_pm_options_add_pipeline_start_ep(self.raw, c.as_ptr());
315 }
316 self
317 }
318
319 pub fn add_pipeline_early_simplification_ep(&mut self, pipeline: &str) -> &mut Self {
321 let c = CString::new(pipeline).expect("pipeline contains null byte");
322 unsafe {
324 llvm_pm_sys::llvm_pm_options_add_pipeline_early_simplification_ep(self.raw, c.as_ptr());
325 }
326 self
327 }
328}
329
330impl Default for Options {
331 fn default() -> Self {
332 Self::new()
333 }
334}
335
336impl Drop for Options {
337 fn drop(&mut self) {
338 unsafe {
340 llvm_pm_sys::llvm_pm_options_dispose(self.raw);
341 }
342 }
343}
344
345pub struct CgsccAnalysisManager {
347 raw: *mut c_void,
348 from_analysis_id: Option<AnalysisKey>,
349}
350
351impl CgsccAnalysisManager {
352 pub unsafe fn from_raw(raw: *mut c_void) -> Self {
357 Self {
358 raw,
359 from_analysis_id: None,
360 }
361 }
362
363 unsafe fn from_raw_with_analysis_id(
364 raw: *mut c_void,
365 from_analysis_id: Option<AnalysisKey>,
366 ) -> Self {
367 Self {
368 raw,
369 from_analysis_id,
370 }
371 }
372
373 pub fn as_raw(&self) -> *mut c_void {
375 self.raw
376 }
377
378 pub fn add_analysis<P>(&self, pass: P)
380 where
381 P: LlvmCgsccAnalysis,
382 P: 'static,
383 <P as LlvmCgsccAnalysis>::Result: 'static,
384 {
385 extern "C" fn pass_deleter<T: LlvmCgsccAnalysis>(pass: *mut c_void) {
386 drop(unsafe { Box::<T>::from_raw(pass.cast()) });
388 }
389
390 fn pass_entrypoint<T>(
391 pass: *mut c_void,
392 function: &inkwell::values::FunctionValue<'_>,
393 manager: *mut c_void,
394 ) -> *mut c_void
395 where
396 T: LlvmCgsccAnalysis,
397 T::Result: 'static,
398 {
399 let pass = unsafe { &*(pass as *const T) };
401 let manager =
403 unsafe { CgsccAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
404 let result = pass.run_analysis(function, &manager);
405 Box::into_raw(Box::new(result)) as *mut c_void
406 }
407
408 let manager_key = self.raw as usize;
409 let analysis_key = <P as LlvmCgsccAnalysis>::id() as usize;
410 let mut passes = cgscc_analysis_passes()
411 .lock()
412 .expect("poisoned cgscc analysis registry");
413 let entry_map = passes.entry(manager_key).or_default();
414 assert!(
415 !entry_map.contains_key(&analysis_key),
416 "analysis already registered"
417 );
418 entry_map.insert(
419 analysis_key,
420 CgsccAnalysisEntry {
421 pass: Box::into_raw(Box::new(pass)) as *mut c_void,
422 pass_deleter: pass_deleter::<P>,
423 pass_entrypoint: pass_entrypoint::<P>,
424 },
425 );
426 }
427
428 pub fn get_result<A>(&self, function: &inkwell::values::FunctionValue<'_>) -> &A::Result
430 where
431 A: LlvmCgsccAnalysis + 'static,
432 A::Result: 'static,
433 {
434 let id = A::id();
435 assert!(
436 !matches!(self.from_analysis_id, Some(n) if n == id),
437 "Analysis cannot request its own result"
438 );
439
440 let manager_key = self.raw as usize;
441 let analysis_key = id as usize;
442 let function_key = function.as_value_ref() as usize;
443
444 if let Some(result) = self.get_cached_result::<A>(function) {
445 return result;
446 }
447
448 let passes = cgscc_analysis_passes()
449 .lock()
450 .expect("poisoned cgscc analysis registry");
451 let entry = passes
452 .get(&manager_key)
453 .and_then(|m| m.get(&analysis_key))
454 .expect("analysis was not registered");
455 let result_ptr = (entry.pass_entrypoint)(entry.pass, function, self.raw);
456 drop(passes);
457
458 let mut cache = cgscc_analysis_cache()
459 .lock()
460 .expect("poisoned cgscc analysis cache");
461 cache
462 .entry(manager_key)
463 .or_default()
464 .insert((analysis_key, function_key), result_ptr as usize);
465 unsafe { &*(result_ptr as *const A::Result) }
467 }
468
469 pub fn get_cached_result<A>(
471 &self,
472 function: &inkwell::values::FunctionValue<'_>,
473 ) -> Option<&A::Result>
474 where
475 A: LlvmCgsccAnalysis + 'static,
476 A::Result: 'static,
477 {
478 let id = A::id();
479 assert!(
480 !matches!(self.from_analysis_id, Some(n) if n == id),
481 "Analysis cannot request its own result"
482 );
483
484 let manager_key = self.raw as usize;
485 let analysis_key = id as usize;
486 let function_key = function.as_value_ref() as usize;
487 let cache = cgscc_analysis_cache()
488 .lock()
489 .expect("poisoned cgscc analysis cache");
490 cache
491 .get(&manager_key)
492 .and_then(|m| m.get(&(analysis_key, function_key)))
493 .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
496 }
497}
498
499pub struct LoopAnalysisManager {
501 raw: *mut c_void,
502 from_analysis_id: Option<AnalysisKey>,
503}
504
505impl LoopAnalysisManager {
506 pub unsafe fn from_raw(raw: *mut c_void) -> Self {
511 Self {
512 raw,
513 from_analysis_id: None,
514 }
515 }
516
517 unsafe fn from_raw_with_analysis_id(
518 raw: *mut c_void,
519 from_analysis_id: Option<AnalysisKey>,
520 ) -> Self {
521 Self {
522 raw,
523 from_analysis_id,
524 }
525 }
526
527 pub fn as_raw(&self) -> *mut c_void {
529 self.raw
530 }
531
532 pub fn add_analysis<P>(&self, pass: P)
534 where
535 P: LlvmLoopAnalysis,
536 P: 'static,
537 <P as LlvmLoopAnalysis>::Result: 'static,
538 {
539 extern "C" fn pass_deleter<T: LlvmLoopAnalysis>(pass: *mut c_void) {
540 drop(unsafe { Box::<T>::from_raw(pass.cast()) });
542 }
543
544 fn pass_entrypoint<T>(
545 pass: *mut c_void,
546 loop_header: LLVMBasicBlockRef,
547 manager: *mut c_void,
548 ) -> *mut c_void
549 where
550 T: LlvmLoopAnalysis,
551 T::Result: 'static,
552 {
553 let pass = unsafe { &*(pass as *const T) };
555 let manager =
557 unsafe { LoopAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
558 let result = pass.run_analysis(loop_header, &manager);
559 Box::into_raw(Box::new(result)) as *mut c_void
560 }
561
562 let manager_key = self.raw as usize;
563 let analysis_key = <P as LlvmLoopAnalysis>::id() as usize;
564 let mut passes = loop_analysis_passes()
565 .lock()
566 .expect("poisoned loop analysis registry");
567 let entry_map = passes.entry(manager_key).or_default();
568 assert!(
569 !entry_map.contains_key(&analysis_key),
570 "analysis already registered"
571 );
572 entry_map.insert(
573 analysis_key,
574 LoopAnalysisEntry {
575 pass: Box::into_raw(Box::new(pass)) as *mut c_void,
576 pass_deleter: pass_deleter::<P>,
577 pass_entrypoint: pass_entrypoint::<P>,
578 },
579 );
580 }
581
582 pub fn get_result<A>(&self, loop_header: LLVMBasicBlockRef) -> &A::Result
584 where
585 A: LlvmLoopAnalysis + 'static,
586 A::Result: 'static,
587 {
588 let id = A::id();
589 assert!(
590 !matches!(self.from_analysis_id, Some(n) if n == id),
591 "Analysis cannot request its own result"
592 );
593
594 let manager_key = self.raw as usize;
595 let analysis_key = id as usize;
596 let loop_key = loop_header as usize;
597
598 if let Some(result) = self.get_cached_result::<A>(loop_header) {
599 return result;
600 }
601
602 let passes = loop_analysis_passes()
603 .lock()
604 .expect("poisoned loop analysis registry");
605 let entry = passes
606 .get(&manager_key)
607 .and_then(|m| m.get(&analysis_key))
608 .expect("analysis was not registered");
609 let result_ptr = (entry.pass_entrypoint)(entry.pass, loop_header, self.raw);
610 drop(passes);
611
612 let mut cache = loop_analysis_cache()
613 .lock()
614 .expect("poisoned loop analysis cache");
615 cache
616 .entry(manager_key)
617 .or_default()
618 .insert((analysis_key, loop_key), result_ptr as usize);
619 unsafe { &*(result_ptr as *const A::Result) }
621 }
622
623 pub fn get_cached_result<A>(&self, loop_header: LLVMBasicBlockRef) -> Option<&A::Result>
625 where
626 A: LlvmLoopAnalysis + 'static,
627 A::Result: 'static,
628 {
629 let id = A::id();
630 assert!(
631 !matches!(self.from_analysis_id, Some(n) if n == id),
632 "Analysis cannot request its own result"
633 );
634
635 let manager_key = self.raw as usize;
636 let analysis_key = id as usize;
637 let loop_key = loop_header as usize;
638 let cache = loop_analysis_cache()
639 .lock()
640 .expect("poisoned loop analysis cache");
641 cache
642 .get(&manager_key)
643 .and_then(|m| m.get(&(analysis_key, loop_key)))
644 .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
647 }
648}
649
650struct CgsccAnalysisEntry {
651 pass: *mut c_void,
652 pass_deleter: extern "C" fn(*mut c_void),
653 pass_entrypoint:
654 fn(*mut c_void, &inkwell::values::FunctionValue<'_>, *mut c_void) -> *mut c_void,
655}
656
657struct LoopAnalysisEntry {
658 pass: *mut c_void,
659 pass_deleter: extern "C" fn(*mut c_void),
660 pass_entrypoint: fn(*mut c_void, LLVMBasicBlockRef, *mut c_void) -> *mut c_void,
661}
662
663impl Drop for CgsccAnalysisEntry {
664 fn drop(&mut self) {
665 (self.pass_deleter)(self.pass);
666 }
667}
668
669impl Drop for LoopAnalysisEntry {
670 fn drop(&mut self) {
671 (self.pass_deleter)(self.pass);
672 }
673}
674
675unsafe impl Send for CgsccAnalysisEntry {}
680unsafe impl Send for LoopAnalysisEntry {}
681
682type AnalysisPassMap<T> = HashMap<usize, HashMap<usize, T>>;
683type AnalysisCacheMap = HashMap<usize, HashMap<(usize, usize), usize>>;
684
685fn cgscc_analysis_passes() -> &'static Mutex<AnalysisPassMap<CgsccAnalysisEntry>> {
686 static INIT: Once = Once::new();
687 static mut CELL: *const Mutex<AnalysisPassMap<CgsccAnalysisEntry>> = ptr::null();
688 INIT.call_once(|| {
689 let value = Box::new(Mutex::new(HashMap::new()));
690 unsafe {
692 CELL = Box::into_raw(value);
693 }
694 });
695 unsafe { CELL.as_ref().expect("cgscc registry initialized") }
697}
698
699fn cgscc_analysis_cache() -> &'static Mutex<AnalysisCacheMap> {
700 static INIT: Once = Once::new();
701 static mut CELL: *const Mutex<AnalysisCacheMap> = ptr::null();
702 INIT.call_once(|| {
703 let value = Box::new(Mutex::new(HashMap::new()));
704 unsafe {
706 CELL = Box::into_raw(value);
707 }
708 });
709 unsafe { CELL.as_ref().expect("cgscc cache initialized") }
711}
712
713fn loop_analysis_passes() -> &'static Mutex<AnalysisPassMap<LoopAnalysisEntry>> {
714 static INIT: Once = Once::new();
715 static mut CELL: *const Mutex<AnalysisPassMap<LoopAnalysisEntry>> = ptr::null();
716 INIT.call_once(|| {
717 let value = Box::new(Mutex::new(HashMap::new()));
718 unsafe {
720 CELL = Box::into_raw(value);
721 }
722 });
723 unsafe { CELL.as_ref().expect("loop registry initialized") }
725}
726
727fn loop_analysis_cache() -> &'static Mutex<AnalysisCacheMap> {
728 static INIT: Once = Once::new();
729 static mut CELL: *const Mutex<AnalysisCacheMap> = ptr::null();
730 INIT.call_once(|| {
731 let value = Box::new(Mutex::new(HashMap::new()));
732 unsafe {
734 CELL = Box::into_raw(value);
735 }
736 });
737 unsafe { CELL.as_ref().expect("loop cache initialized") }
739}
740
741fn preserved_to_c(pa: traits::PreservedAnalyses) -> std::ffi::c_int {
742 match pa {
743 PreservedAnalyses::All => 0,
744 PreservedAnalyses::None => 1,
745 }
746}
747
748pub(crate) unsafe extern "C" fn module_pass_trampoline<T: LlvmModulePass>(
760 module: LLVMModuleRef,
761 manager: *mut c_void,
762 user_data: *mut c_void,
763) -> std::ffi::c_int {
764 let pass = &*(user_data as *const T);
766 let mut module = inkwell::module::Module::new(module);
770 let manager = ModuleAnalysisManager::from_raw(manager, None);
771 let result = pass.run_pass(&mut module, &manager);
772 std::mem::forget(module);
773 preserved_to_c(result)
774}
775
776pub(crate) unsafe extern "C" fn function_pass_trampoline<T: LlvmFunctionPass>(
788 function: LLVMValueRef,
789 manager: *mut c_void,
790 user_data: *mut c_void,
791) -> std::ffi::c_int {
792 let pass = &*(user_data as *const T);
794 let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
797 let manager = FunctionAnalysisManager::from_raw(manager, None);
798 let result = pass.run_pass(&mut function, &manager);
799 preserved_to_c(result)
800}
801
802pub(crate) unsafe extern "C" fn cgscc_pass_trampoline<T: LlvmCgsccPass>(
814 function: LLVMValueRef,
815 manager: *mut c_void,
816 user_data: *mut c_void,
817) -> std::ffi::c_int {
818 let pass = &*(user_data as *const T);
820 let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
821 let manager = CgsccAnalysisManager::from_raw(manager);
823 let result = pass.run_pass(&mut function, &manager);
824 preserved_to_c(result)
825}
826
827pub(crate) unsafe extern "C" fn loop_pass_trampoline<T: LlvmLoopPass>(
839 header: LLVMBasicBlockRef,
840 manager: *mut c_void,
841 user_data: *mut c_void,
842) -> std::ffi::c_int {
843 let pass = &*(user_data as *const T);
845 let manager = LoopAnalysisManager::from_raw(manager);
847 let result = pass.run_pass(header, &manager);
848 preserved_to_c(result)
849}
850
851pub struct ModulePassManager<'a> {
863 raw: llvm_pm_sys::LlvmPmPassManagerRef,
864 _passes: Vec<Box<dyn std::any::Any>>,
865 _phantom: PhantomData<&'a ()>,
866}
867
868impl<'a> fmt::Debug for ModulePassManager<'a> {
869 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870 f.debug_struct("ModulePassManager")
871 .field("raw", &self.raw)
872 .finish()
873 }
874}
875
876impl<'a> ModulePassManager<'a> {
877 pub fn with_opt_level(
879 target_machine: Option<&'a inkwell::targets::TargetMachine>,
880 level: OptLevel,
881 options: Option<&Options>,
882 ) -> Result<Self, Error> {
883 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
884 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
885 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
886
887 let raw = unsafe {
890 llvm_pm_sys::llvm_pm_create_with_opt_level(tm, level.to_c(), opts, &mut err_msg)
891 };
892
893 if raw.is_null() {
894 Err(unsafe { consume_c_error(err_msg) })
896 } else {
897 Ok(Self {
898 raw,
899 _passes: Vec::new(),
900 _phantom: PhantomData,
901 })
902 }
903 }
904
905 pub fn with_pipeline(
912 target_machine: Option<&'a inkwell::targets::TargetMachine>,
913 pipeline: &str,
914 options: Option<&Options>,
915 ) -> Result<Self, Error> {
916 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
917 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
918 let c_pipeline = CString::new(pipeline).map_err(|e| Error {
919 message: format!("Pipeline string contains null byte: {}", e),
920 })?;
921 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
922
923 let raw = unsafe {
925 llvm_pm_sys::llvm_pm_create_with_pipeline(tm, c_pipeline.as_ptr(), opts, &mut err_msg)
926 };
927
928 if raw.is_null() {
929 Err(unsafe { consume_c_error(err_msg) })
931 } else {
932 Ok(Self {
933 raw,
934 _passes: Vec::new(),
935 _phantom: PhantomData,
936 })
937 }
938 }
939
940 pub fn with_lto(
942 target_machine: Option<&'a inkwell::targets::TargetMachine>,
943 level: OptLevel,
944 options: Option<&Options>,
945 ) -> Result<Self, Error> {
946 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
947 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
948 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
949
950 let raw = unsafe { llvm_pm_sys::llvm_pm_create_lto(tm, level.to_c(), opts, &mut err_msg) };
952
953 if raw.is_null() {
954 Err(unsafe { consume_c_error(err_msg) })
956 } else {
957 Ok(Self {
958 raw,
959 _passes: Vec::new(),
960 _phantom: PhantomData,
961 })
962 }
963 }
964
965 pub fn with_lto_pre_link(
967 target_machine: Option<&'a inkwell::targets::TargetMachine>,
968 level: OptLevel,
969 options: Option<&Options>,
970 ) -> Result<Self, Error> {
971 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
972 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
973 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
974
975 let raw = unsafe {
977 llvm_pm_sys::llvm_pm_create_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
978 };
979
980 if raw.is_null() {
981 Err(unsafe { consume_c_error(err_msg) })
983 } else {
984 Ok(Self {
985 raw,
986 _passes: Vec::new(),
987 _phantom: PhantomData,
988 })
989 }
990 }
991
992 pub fn with_thin_lto_pre_link(
994 target_machine: Option<&'a inkwell::targets::TargetMachine>,
995 level: OptLevel,
996 options: Option<&Options>,
997 ) -> Result<Self, Error> {
998 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
999 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1000 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1001
1002 let raw = unsafe {
1004 llvm_pm_sys::llvm_pm_create_thin_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
1005 };
1006
1007 if raw.is_null() {
1008 Err(unsafe { consume_c_error(err_msg) })
1010 } else {
1011 Ok(Self {
1012 raw,
1013 _passes: Vec::new(),
1014 _phantom: PhantomData,
1015 })
1016 }
1017 }
1018
1019 pub fn new(
1023 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1024 options: Option<&Options>,
1025 ) -> Result<Self, Error> {
1026 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1027 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1028 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1029
1030 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1032
1033 if raw.is_null() {
1034 Err(unsafe { consume_c_error(err_msg) })
1036 } else {
1037 Ok(Self {
1038 raw,
1039 _passes: Vec::new(),
1040 _phantom: PhantomData,
1041 })
1042 }
1043 }
1044
1045 pub fn add_pass<P>(&mut self, pass: P)
1051 where
1052 P: LlvmModulePass + 'static,
1053 {
1054 let mut boxed = Box::new(pass);
1055 let ptr = &mut *boxed as *mut P as *mut c_void;
1056 unsafe {
1060 llvm_pm_sys::llvm_pm_add_module_pass(self.raw, Some(module_pass_trampoline::<P>), ptr);
1061 }
1062 self._passes.push(boxed);
1063 }
1064
1065 pub fn add_cgscc_pass<P>(&mut self, pass: P)
1070 where
1071 P: LlvmCgsccPass + 'static,
1072 {
1073 let mut boxed = Box::new(pass);
1074 let ptr = &mut *boxed as *mut P as *mut c_void;
1075 unsafe {
1079 llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
1080 }
1081 self._passes.push(boxed);
1082 }
1083
1084 pub fn add_function_pass_via_cgscc<P>(&mut self, pass: P)
1089 where
1090 P: LlvmFunctionPass + 'static,
1091 {
1092 let mut boxed = Box::new(pass);
1093 let ptr = &mut *boxed as *mut P as *mut c_void;
1094 unsafe {
1098 llvm_pm_sys::llvm_pm_add_function_pass_via_cgscc(
1099 self.raw,
1100 Some(function_pass_trampoline::<P>),
1101 ptr,
1102 );
1103 }
1104 self._passes.push(boxed);
1105 }
1106
1107 pub fn add_loop_pass_via_cgscc<P>(&mut self, pass: P)
1111 where
1112 P: LlvmLoopPass + 'static,
1113 {
1114 let mut boxed = Box::new(pass);
1115 let ptr = &mut *boxed as *mut P as *mut c_void;
1116 unsafe {
1120 llvm_pm_sys::llvm_pm_add_loop_pass_via_cgscc(
1121 self.raw,
1122 Some(loop_pass_trampoline::<P>),
1123 ptr,
1124 );
1125 }
1126 self._passes.push(boxed);
1127 }
1128
1129 pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1131 let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1134 if err.is_null() {
1135 Ok(())
1136 } else {
1137 Err(unsafe { consume_c_error(err) })
1139 }
1140 }
1141}
1142
1143impl<'a> Drop for ModulePassManager<'a> {
1144 fn drop(&mut self) {
1145 unsafe {
1149 llvm_pm_sys::llvm_pm_dispose(self.raw);
1150 }
1151 }
1152}
1153
1154unsafe impl<'a> Send for ModulePassManager<'a> {}
1162
1163pub struct FunctionPassManager<'a> {
1175 raw: llvm_pm_sys::LlvmPmPassManagerRef,
1176 _passes: Vec<Box<dyn std::any::Any>>,
1177 _phantom: PhantomData<&'a ()>,
1178}
1179
1180impl<'a> fmt::Debug for FunctionPassManager<'a> {
1181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1182 f.debug_struct("FunctionPassManager")
1183 .field("raw", &self.raw)
1184 .finish()
1185 }
1186}
1187
1188impl<'a> FunctionPassManager<'a> {
1189 pub fn with_pipeline(
1193 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1194 pipeline: &str,
1195 options: Option<&Options>,
1196 ) -> Result<Self, Error> {
1197 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1198 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1199 let c_pipeline = CString::new(pipeline).map_err(|e| Error {
1200 message: format!("Pipeline string contains null byte: {}", e),
1201 })?;
1202 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1203
1204 let raw = unsafe {
1206 llvm_pm_sys::llvm_pm_create_function_with_pipeline(
1207 tm,
1208 c_pipeline.as_ptr(),
1209 opts,
1210 &mut err_msg,
1211 )
1212 };
1213
1214 if raw.is_null() {
1215 Err(unsafe { consume_c_error(err_msg) })
1217 } else {
1218 Ok(Self {
1219 raw,
1220 _passes: Vec::new(),
1221 _phantom: PhantomData,
1222 })
1223 }
1224 }
1225
1226 pub fn new(
1230 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1231 options: Option<&Options>,
1232 ) -> Result<Self, Error> {
1233 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1234 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1235 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1236
1237 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_function(tm, opts, &mut err_msg) };
1239
1240 if raw.is_null() {
1241 Err(unsafe { consume_c_error(err_msg) })
1243 } else {
1244 Ok(Self {
1245 raw,
1246 _passes: Vec::new(),
1247 _phantom: PhantomData,
1248 })
1249 }
1250 }
1251
1252 pub fn add_pass<P>(&mut self, pass: P)
1258 where
1259 P: LlvmFunctionPass + 'static,
1260 {
1261 let mut boxed = Box::new(pass);
1262 let ptr = &mut *boxed as *mut P as *mut c_void;
1263 unsafe {
1267 llvm_pm_sys::llvm_pm_add_function_pass(
1268 self.raw,
1269 Some(function_pass_trampoline::<P>),
1270 ptr,
1271 );
1272 }
1273 self._passes.push(boxed);
1274 }
1275
1276 pub fn add_loop_pass<P>(&mut self, pass: P)
1281 where
1282 P: traits::LlvmLoopPass + 'static,
1283 {
1284 let mut boxed = Box::new(pass);
1285 let ptr = &mut *boxed as *mut P as *mut c_void;
1286 unsafe {
1290 llvm_pm_sys::llvm_pm_add_loop_pass(self.raw, Some(loop_pass_trampoline::<P>), ptr);
1291 }
1292 self._passes.push(boxed);
1293 }
1294
1295 pub fn run(&mut self, function: inkwell::values::FunctionValue<'_>) -> Result<(), Error> {
1297 let err =
1300 unsafe { llvm_pm_sys::llvm_pm_run_on_function(self.raw, function.as_value_ref()) };
1301 if err.is_null() {
1302 Ok(())
1303 } else {
1304 Err(unsafe { consume_c_error(err) })
1306 }
1307 }
1308}
1309
1310impl<'a> Drop for FunctionPassManager<'a> {
1311 fn drop(&mut self) {
1312 unsafe {
1316 llvm_pm_sys::llvm_pm_dispose(self.raw);
1317 }
1318 }
1319}
1320
1321unsafe impl<'a> Send for FunctionPassManager<'a> {}
1324
1325pub struct CGSCCPassManager<'a> {
1342 raw: llvm_pm_sys::LlvmPmPassManagerRef,
1343 _passes: Vec<Box<dyn std::any::Any>>,
1344 _phantom: PhantomData<&'a ()>,
1345}
1346
1347impl<'a> fmt::Debug for CGSCCPassManager<'a> {
1348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1349 f.debug_struct("CGSCCPassManager")
1350 .field("raw", &self.raw)
1351 .finish()
1352 }
1353}
1354
1355impl<'a> CGSCCPassManager<'a> {
1356 pub fn new(
1362 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1363 options: Option<&Options>,
1364 ) -> Result<Self, Error> {
1365 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1366 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1367 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1368
1369 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1371
1372 if raw.is_null() {
1373 Err(unsafe { consume_c_error(err_msg) })
1375 } else {
1376 Ok(Self {
1377 raw,
1378 _passes: Vec::new(),
1379 _phantom: PhantomData,
1380 })
1381 }
1382 }
1383
1384 pub fn add_pass<P>(&mut self, pass: P)
1390 where
1391 P: LlvmCgsccPass + 'static,
1392 {
1393 let mut boxed = Box::new(pass);
1394 let ptr = &mut *boxed as *mut P as *mut c_void;
1395 unsafe {
1399 llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
1400 }
1401 self._passes.push(boxed);
1402 }
1403
1404 pub fn add_function_pass<P>(&mut self, pass: P)
1409 where
1410 P: LlvmFunctionPass + 'static,
1411 {
1412 let mut boxed = Box::new(pass);
1413 let ptr = &mut *boxed as *mut P as *mut c_void;
1414 unsafe {
1418 llvm_pm_sys::llvm_pm_add_function_pass_via_cgscc(
1419 self.raw,
1420 Some(function_pass_trampoline::<P>),
1421 ptr,
1422 );
1423 }
1424 self._passes.push(boxed);
1425 }
1426
1427 pub fn add_loop_pass<P>(&mut self, pass: P)
1431 where
1432 P: LlvmLoopPass + 'static,
1433 {
1434 let mut boxed = Box::new(pass);
1435 let ptr = &mut *boxed as *mut P as *mut c_void;
1436 unsafe {
1440 llvm_pm_sys::llvm_pm_add_loop_pass_via_cgscc(
1441 self.raw,
1442 Some(loop_pass_trampoline::<P>),
1443 ptr,
1444 );
1445 }
1446 self._passes.push(boxed);
1447 }
1448
1449 pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1451 let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1454 if err.is_null() {
1455 Ok(())
1456 } else {
1457 Err(unsafe { consume_c_error(err) })
1459 }
1460 }
1461}
1462
1463impl<'a> Drop for CGSCCPassManager<'a> {
1464 fn drop(&mut self) {
1465 unsafe {
1469 llvm_pm_sys::llvm_pm_dispose(self.raw);
1470 }
1471 }
1472}
1473
1474unsafe impl<'a> Send for CGSCCPassManager<'a> {}