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 feature = "llvm18-0"
66))]
67pub extern crate inkwell_05 as inkwell;
68#[cfg(any(
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 = "llvm19-1",
109 feature = "llvm20-1",
110 feature = "llvm21-1",
111 feature = "llvm22-1"
112 )
113))]
114compile_error!(
115 "`llvm-plugin-crate` supports llvm-plugin-compatible LLVM features (llvm10-0 .. llvm18-0)."
116);
117
118pub struct ModuleAnalysisManager {
119 inner: *mut c_void,
120 from_analysis_id: Option<AnalysisKey>,
121}
122
123impl ModuleAnalysisManager {
124 pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<*const u8>) -> Self {
127 Self {
128 inner,
129 from_analysis_id,
130 }
131 }
132 pub fn as_raw(&self) -> *mut c_void {
133 self.inner
134 }
135 pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
136 self.from_analysis_id
137 }
138}
139
140pub struct FunctionAnalysisManager {
141 inner: *mut c_void,
142 from_analysis_id: Option<AnalysisKey>,
143}
144
145impl FunctionAnalysisManager {
146 pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<AnalysisKey>) -> Self {
149 Self {
150 inner,
151 from_analysis_id,
152 }
153 }
154 pub fn as_raw(&self) -> *mut c_void {
155 self.inner
156 }
157 pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
158 self.from_analysis_id
159 }
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
164pub enum OptLevel {
165 O0,
166 O1,
167 O2,
168 O3,
169 Os,
170 Oz,
171}
172
173impl OptLevel {
174 fn to_c(self) -> llvm_pm_sys::LlvmPmOptLevel {
175 match self {
176 OptLevel::O0 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O0,
177 OptLevel::O1 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O1,
178 OptLevel::O2 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O2,
179 OptLevel::O3 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O3,
180 OptLevel::Os => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Os,
181 OptLevel::Oz => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Oz,
182 }
183 }
184}
185
186#[derive(Debug)]
188pub struct Error {
189 message: String,
190}
191
192impl Error {
193 pub fn message(&self) -> &str {
195 &self.message
196 }
197}
198
199impl fmt::Display for Error {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 write!(f, "{}", self.message)
202 }
203}
204
205impl std::error::Error for Error {}
206
207unsafe fn consume_c_error(ptr: *mut std::ffi::c_char) -> Error {
213 let msg = CStr::from_ptr(ptr).to_string_lossy().into_owned();
215 llvm_pm_sys::llvm_pm_dispose_message(ptr);
216 Error { message: msg }
217}
218
219pub struct Options {
229 raw: llvm_pm_sys::LlvmPmOptionsRef,
230}
231
232impl Options {
233 pub fn new() -> Self {
235 let raw = unsafe { llvm_pm_sys::llvm_pm_options_create() };
237 Self { raw }
238 }
239
240 pub fn debug_logging(&mut self, val: bool) -> &mut Self {
242 unsafe {
244 llvm_pm_sys::llvm_pm_options_set_debug_logging(self.raw, val as i32);
245 }
246 self
247 }
248
249 pub fn verify_each(&mut self, val: bool) -> &mut Self {
251 unsafe {
253 llvm_pm_sys::llvm_pm_options_set_verify_each(self.raw, val as i32);
254 }
255 self
256 }
257
258 pub fn add_peephole_ep(&mut self, pipeline: &str) -> &mut Self {
260 let c = CString::new(pipeline).expect("pipeline contains null byte");
261 unsafe {
263 llvm_pm_sys::llvm_pm_options_add_peephole_ep(self.raw, c.as_ptr());
264 }
265 self
266 }
267
268 pub fn add_optimizer_early_ep(&mut self, pipeline: &str) -> &mut Self {
270 let c = CString::new(pipeline).expect("pipeline contains null byte");
271 unsafe {
273 llvm_pm_sys::llvm_pm_options_add_optimizer_early_ep(self.raw, c.as_ptr());
274 }
275 self
276 }
277
278 pub fn add_optimizer_last_ep(&mut self, pipeline: &str) -> &mut Self {
280 let c = CString::new(pipeline).expect("pipeline contains null byte");
281 unsafe {
283 llvm_pm_sys::llvm_pm_options_add_optimizer_last_ep(self.raw, c.as_ptr());
284 }
285 self
286 }
287
288 pub fn add_vectorizer_start_ep(&mut self, pipeline: &str) -> &mut Self {
290 let c = CString::new(pipeline).expect("pipeline contains null byte");
291 unsafe {
293 llvm_pm_sys::llvm_pm_options_add_vectorizer_start_ep(self.raw, c.as_ptr());
294 }
295 self
296 }
297
298 pub fn add_scalar_optimizer_late_ep(&mut self, pipeline: &str) -> &mut Self {
300 let c = CString::new(pipeline).expect("pipeline contains null byte");
301 unsafe {
303 llvm_pm_sys::llvm_pm_options_add_scalar_optimizer_late_ep(self.raw, c.as_ptr());
304 }
305 self
306 }
307
308 pub fn add_pipeline_start_ep(&mut self, pipeline: &str) -> &mut Self {
310 let c = CString::new(pipeline).expect("pipeline contains null byte");
311 unsafe {
313 llvm_pm_sys::llvm_pm_options_add_pipeline_start_ep(self.raw, c.as_ptr());
314 }
315 self
316 }
317
318 pub fn add_pipeline_early_simplification_ep(&mut self, pipeline: &str) -> &mut Self {
320 let c = CString::new(pipeline).expect("pipeline contains null byte");
321 unsafe {
323 llvm_pm_sys::llvm_pm_options_add_pipeline_early_simplification_ep(self.raw, c.as_ptr());
324 }
325 self
326 }
327}
328
329impl Default for Options {
330 fn default() -> Self {
331 Self::new()
332 }
333}
334
335impl Drop for Options {
336 fn drop(&mut self) {
337 unsafe {
339 llvm_pm_sys::llvm_pm_options_dispose(self.raw);
340 }
341 }
342}
343
344pub struct CgsccAnalysisManager {
346 raw: *mut c_void,
347 from_analysis_id: Option<AnalysisKey>,
348}
349
350impl CgsccAnalysisManager {
351 pub unsafe fn from_raw(raw: *mut c_void) -> Self {
356 Self {
357 raw,
358 from_analysis_id: None,
359 }
360 }
361
362 unsafe fn from_raw_with_analysis_id(
363 raw: *mut c_void,
364 from_analysis_id: Option<AnalysisKey>,
365 ) -> Self {
366 Self {
367 raw,
368 from_analysis_id,
369 }
370 }
371
372 pub fn as_raw(&self) -> *mut c_void {
374 self.raw
375 }
376
377 pub fn add_analysis<P>(&self, pass: P)
379 where
380 P: LlvmCgsccAnalysis,
381 P: 'static,
382 <P as LlvmCgsccAnalysis>::Result: 'static,
383 {
384 extern "C" fn pass_deleter<T: LlvmCgsccAnalysis>(pass: *mut c_void) {
385 drop(unsafe { Box::<T>::from_raw(pass.cast()) });
387 }
388
389 fn pass_entrypoint<T>(
390 pass: *mut c_void,
391 function: &inkwell::values::FunctionValue<'_>,
392 manager: *mut c_void,
393 ) -> *mut c_void
394 where
395 T: LlvmCgsccAnalysis,
396 T::Result: 'static,
397 {
398 let pass = unsafe { &*(pass as *const T) };
400 let manager =
402 unsafe { CgsccAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
403 let result = pass.run_analysis(function, &manager);
404 Box::into_raw(Box::new(result)) as *mut c_void
405 }
406
407 let manager_key = self.raw as usize;
408 let analysis_key = <P as LlvmCgsccAnalysis>::id() as usize;
409 let mut passes = cgscc_analysis_passes()
410 .lock()
411 .expect("poisoned cgscc analysis registry");
412 let entry_map = passes.entry(manager_key).or_default();
413 assert!(
414 !entry_map.contains_key(&analysis_key),
415 "analysis already registered"
416 );
417 entry_map.insert(
418 analysis_key,
419 CgsccAnalysisEntry {
420 pass: Box::into_raw(Box::new(pass)) as *mut c_void,
421 pass_deleter: pass_deleter::<P>,
422 pass_entrypoint: pass_entrypoint::<P>,
423 },
424 );
425 }
426
427 pub fn get_result<A>(&self, function: &inkwell::values::FunctionValue<'_>) -> &A::Result
429 where
430 A: LlvmCgsccAnalysis + 'static,
431 A::Result: 'static,
432 {
433 let id = A::id();
434 assert!(
435 !matches!(self.from_analysis_id, Some(n) if n == id),
436 "Analysis cannot request its own result"
437 );
438
439 let manager_key = self.raw as usize;
440 let analysis_key = id as usize;
441 let function_key = function.as_value_ref() as usize;
442
443 if let Some(result) = self.get_cached_result::<A>(function) {
444 return result;
445 }
446
447 let passes = cgscc_analysis_passes()
448 .lock()
449 .expect("poisoned cgscc analysis registry");
450 let entry = passes
451 .get(&manager_key)
452 .and_then(|m| m.get(&analysis_key))
453 .expect("analysis was not registered");
454 let result_ptr = (entry.pass_entrypoint)(entry.pass, function, self.raw);
455 drop(passes);
456
457 let mut cache = cgscc_analysis_cache()
458 .lock()
459 .expect("poisoned cgscc analysis cache");
460 cache
461 .entry(manager_key)
462 .or_default()
463 .insert((analysis_key, function_key), result_ptr as usize);
464 unsafe { &*(result_ptr as *const A::Result) }
466 }
467
468 pub fn get_cached_result<A>(
470 &self,
471 function: &inkwell::values::FunctionValue<'_>,
472 ) -> Option<&A::Result>
473 where
474 A: LlvmCgsccAnalysis + 'static,
475 A::Result: 'static,
476 {
477 let id = A::id();
478 assert!(
479 !matches!(self.from_analysis_id, Some(n) if n == id),
480 "Analysis cannot request its own result"
481 );
482
483 let manager_key = self.raw as usize;
484 let analysis_key = id as usize;
485 let function_key = function.as_value_ref() as usize;
486 let cache = cgscc_analysis_cache()
487 .lock()
488 .expect("poisoned cgscc analysis cache");
489 cache
490 .get(&manager_key)
491 .and_then(|m| m.get(&(analysis_key, function_key)))
492 .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
495 }
496}
497
498pub struct LoopAnalysisManager {
500 raw: *mut c_void,
501 from_analysis_id: Option<AnalysisKey>,
502}
503
504impl LoopAnalysisManager {
505 pub unsafe fn from_raw(raw: *mut c_void) -> Self {
510 Self {
511 raw,
512 from_analysis_id: None,
513 }
514 }
515
516 unsafe fn from_raw_with_analysis_id(
517 raw: *mut c_void,
518 from_analysis_id: Option<AnalysisKey>,
519 ) -> Self {
520 Self {
521 raw,
522 from_analysis_id,
523 }
524 }
525
526 pub fn as_raw(&self) -> *mut c_void {
528 self.raw
529 }
530
531 pub fn add_analysis<P>(&self, pass: P)
533 where
534 P: LlvmLoopAnalysis,
535 P: 'static,
536 <P as LlvmLoopAnalysis>::Result: 'static,
537 {
538 extern "C" fn pass_deleter<T: LlvmLoopAnalysis>(pass: *mut c_void) {
539 drop(unsafe { Box::<T>::from_raw(pass.cast()) });
541 }
542
543 fn pass_entrypoint<T>(
544 pass: *mut c_void,
545 loop_header: LLVMBasicBlockRef,
546 manager: *mut c_void,
547 ) -> *mut c_void
548 where
549 T: LlvmLoopAnalysis,
550 T::Result: 'static,
551 {
552 let pass = unsafe { &*(pass as *const T) };
554 let manager =
556 unsafe { LoopAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
557 let result = pass.run_analysis(loop_header, &manager);
558 Box::into_raw(Box::new(result)) as *mut c_void
559 }
560
561 let manager_key = self.raw as usize;
562 let analysis_key = <P as LlvmLoopAnalysis>::id() as usize;
563 let mut passes = loop_analysis_passes()
564 .lock()
565 .expect("poisoned loop analysis registry");
566 let entry_map = passes.entry(manager_key).or_default();
567 assert!(
568 !entry_map.contains_key(&analysis_key),
569 "analysis already registered"
570 );
571 entry_map.insert(
572 analysis_key,
573 LoopAnalysisEntry {
574 pass: Box::into_raw(Box::new(pass)) as *mut c_void,
575 pass_deleter: pass_deleter::<P>,
576 pass_entrypoint: pass_entrypoint::<P>,
577 },
578 );
579 }
580
581 pub fn get_result<A>(&self, loop_header: LLVMBasicBlockRef) -> &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
597 if let Some(result) = self.get_cached_result::<A>(loop_header) {
598 return result;
599 }
600
601 let passes = loop_analysis_passes()
602 .lock()
603 .expect("poisoned loop analysis registry");
604 let entry = passes
605 .get(&manager_key)
606 .and_then(|m| m.get(&analysis_key))
607 .expect("analysis was not registered");
608 let result_ptr = (entry.pass_entrypoint)(entry.pass, loop_header, self.raw);
609 drop(passes);
610
611 let mut cache = loop_analysis_cache()
612 .lock()
613 .expect("poisoned loop analysis cache");
614 cache
615 .entry(manager_key)
616 .or_default()
617 .insert((analysis_key, loop_key), result_ptr as usize);
618 unsafe { &*(result_ptr as *const A::Result) }
620 }
621
622 pub fn get_cached_result<A>(&self, loop_header: LLVMBasicBlockRef) -> Option<&A::Result>
624 where
625 A: LlvmLoopAnalysis + 'static,
626 A::Result: 'static,
627 {
628 let id = A::id();
629 assert!(
630 !matches!(self.from_analysis_id, Some(n) if n == id),
631 "Analysis cannot request its own result"
632 );
633
634 let manager_key = self.raw as usize;
635 let analysis_key = id as usize;
636 let loop_key = loop_header as usize;
637 let cache = loop_analysis_cache()
638 .lock()
639 .expect("poisoned loop analysis cache");
640 cache
641 .get(&manager_key)
642 .and_then(|m| m.get(&(analysis_key, loop_key)))
643 .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
646 }
647}
648
649struct CgsccAnalysisEntry {
650 pass: *mut c_void,
651 pass_deleter: extern "C" fn(*mut c_void),
652 pass_entrypoint:
653 fn(*mut c_void, &inkwell::values::FunctionValue<'_>, *mut c_void) -> *mut c_void,
654}
655
656struct LoopAnalysisEntry {
657 pass: *mut c_void,
658 pass_deleter: extern "C" fn(*mut c_void),
659 pass_entrypoint: fn(*mut c_void, LLVMBasicBlockRef, *mut c_void) -> *mut c_void,
660}
661
662impl Drop for CgsccAnalysisEntry {
663 fn drop(&mut self) {
664 (self.pass_deleter)(self.pass);
665 }
666}
667
668impl Drop for LoopAnalysisEntry {
669 fn drop(&mut self) {
670 (self.pass_deleter)(self.pass);
671 }
672}
673
674unsafe impl Send for CgsccAnalysisEntry {}
679unsafe impl Send for LoopAnalysisEntry {}
680
681type AnalysisPassMap<T> = HashMap<usize, HashMap<usize, T>>;
682type AnalysisCacheMap = HashMap<usize, HashMap<(usize, usize), usize>>;
683
684fn cgscc_analysis_passes() -> &'static Mutex<AnalysisPassMap<CgsccAnalysisEntry>> {
685 static INIT: Once = Once::new();
686 static mut CELL: *const Mutex<AnalysisPassMap<CgsccAnalysisEntry>> = ptr::null();
687 INIT.call_once(|| {
688 let value = Box::new(Mutex::new(HashMap::new()));
689 unsafe {
691 CELL = Box::into_raw(value);
692 }
693 });
694 unsafe { CELL.as_ref().expect("cgscc registry initialized") }
696}
697
698fn cgscc_analysis_cache() -> &'static Mutex<AnalysisCacheMap> {
699 static INIT: Once = Once::new();
700 static mut CELL: *const Mutex<AnalysisCacheMap> = ptr::null();
701 INIT.call_once(|| {
702 let value = Box::new(Mutex::new(HashMap::new()));
703 unsafe {
705 CELL = Box::into_raw(value);
706 }
707 });
708 unsafe { CELL.as_ref().expect("cgscc cache initialized") }
710}
711
712fn loop_analysis_passes() -> &'static Mutex<AnalysisPassMap<LoopAnalysisEntry>> {
713 static INIT: Once = Once::new();
714 static mut CELL: *const Mutex<AnalysisPassMap<LoopAnalysisEntry>> = ptr::null();
715 INIT.call_once(|| {
716 let value = Box::new(Mutex::new(HashMap::new()));
717 unsafe {
719 CELL = Box::into_raw(value);
720 }
721 });
722 unsafe { CELL.as_ref().expect("loop registry initialized") }
724}
725
726fn loop_analysis_cache() -> &'static Mutex<AnalysisCacheMap> {
727 static INIT: Once = Once::new();
728 static mut CELL: *const Mutex<AnalysisCacheMap> = ptr::null();
729 INIT.call_once(|| {
730 let value = Box::new(Mutex::new(HashMap::new()));
731 unsafe {
733 CELL = Box::into_raw(value);
734 }
735 });
736 unsafe { CELL.as_ref().expect("loop cache initialized") }
738}
739
740fn preserved_to_c(pa: traits::PreservedAnalyses) -> std::ffi::c_int {
741 match pa {
742 PreservedAnalyses::All => 0,
743 PreservedAnalyses::None => 1,
744 }
745}
746
747pub(crate) unsafe extern "C" fn module_pass_trampoline<T: LlvmModulePass>(
759 module: LLVMModuleRef,
760 manager: *mut c_void,
761 user_data: *mut c_void,
762) -> std::ffi::c_int {
763 let pass = &*(user_data as *const T);
765 let mut module = inkwell::module::Module::new(module);
769 let manager = ModuleAnalysisManager::from_raw(manager, None);
770 let result = pass.run_pass(&mut module, &manager);
771 std::mem::forget(module);
772 preserved_to_c(result)
773}
774
775pub(crate) unsafe extern "C" fn function_pass_trampoline<T: LlvmFunctionPass>(
787 function: LLVMValueRef,
788 manager: *mut c_void,
789 user_data: *mut c_void,
790) -> std::ffi::c_int {
791 let pass = &*(user_data as *const T);
793 let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
796 let manager = FunctionAnalysisManager::from_raw(manager, None);
797 let result = pass.run_pass(&mut function, &manager);
798 preserved_to_c(result)
799}
800
801pub(crate) unsafe extern "C" fn cgscc_pass_trampoline<T: LlvmCgsccPass>(
813 function: LLVMValueRef,
814 manager: *mut c_void,
815 user_data: *mut c_void,
816) -> std::ffi::c_int {
817 let pass = &*(user_data as *const T);
819 let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
820 let manager = CgsccAnalysisManager::from_raw(manager);
822 let result = pass.run_pass(&mut function, &manager);
823 preserved_to_c(result)
824}
825
826pub(crate) unsafe extern "C" fn loop_pass_trampoline<T: LlvmLoopPass>(
838 header: LLVMBasicBlockRef,
839 manager: *mut c_void,
840 user_data: *mut c_void,
841) -> std::ffi::c_int {
842 let pass = &*(user_data as *const T);
844 let manager = LoopAnalysisManager::from_raw(manager);
846 let result = pass.run_pass(header, &manager);
847 preserved_to_c(result)
848}
849
850pub struct ModulePassManager<'a> {
862 raw: llvm_pm_sys::LlvmPmPassManagerRef,
863 _passes: Vec<Box<dyn std::any::Any>>,
864 _phantom: PhantomData<&'a ()>,
865}
866
867impl<'a> fmt::Debug for ModulePassManager<'a> {
868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
869 f.debug_struct("ModulePassManager")
870 .field("raw", &self.raw)
871 .finish()
872 }
873}
874
875impl<'a> ModulePassManager<'a> {
876 pub fn with_opt_level(
878 target_machine: Option<&'a inkwell::targets::TargetMachine>,
879 level: OptLevel,
880 options: Option<&Options>,
881 ) -> Result<Self, Error> {
882 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
883 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
884 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
885
886 let raw = unsafe {
889 llvm_pm_sys::llvm_pm_create_with_opt_level(tm, level.to_c(), opts, &mut err_msg)
890 };
891
892 if raw.is_null() {
893 Err(unsafe { consume_c_error(err_msg) })
895 } else {
896 Ok(Self {
897 raw,
898 _passes: Vec::new(),
899 _phantom: PhantomData,
900 })
901 }
902 }
903
904 pub fn with_pipeline(
911 target_machine: Option<&'a inkwell::targets::TargetMachine>,
912 pipeline: &str,
913 options: Option<&Options>,
914 ) -> Result<Self, Error> {
915 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
916 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
917 let c_pipeline = CString::new(pipeline).map_err(|e| Error {
918 message: format!("Pipeline string contains null byte: {}", e),
919 })?;
920 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
921
922 let raw = unsafe {
924 llvm_pm_sys::llvm_pm_create_with_pipeline(tm, c_pipeline.as_ptr(), opts, &mut err_msg)
925 };
926
927 if raw.is_null() {
928 Err(unsafe { consume_c_error(err_msg) })
930 } else {
931 Ok(Self {
932 raw,
933 _passes: Vec::new(),
934 _phantom: PhantomData,
935 })
936 }
937 }
938
939 pub fn with_lto(
941 target_machine: Option<&'a inkwell::targets::TargetMachine>,
942 level: OptLevel,
943 options: Option<&Options>,
944 ) -> Result<Self, Error> {
945 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
946 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
947 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
948
949 let raw = unsafe { llvm_pm_sys::llvm_pm_create_lto(tm, level.to_c(), opts, &mut err_msg) };
951
952 if raw.is_null() {
953 Err(unsafe { consume_c_error(err_msg) })
955 } else {
956 Ok(Self {
957 raw,
958 _passes: Vec::new(),
959 _phantom: PhantomData,
960 })
961 }
962 }
963
964 pub fn with_lto_pre_link(
966 target_machine: Option<&'a inkwell::targets::TargetMachine>,
967 level: OptLevel,
968 options: Option<&Options>,
969 ) -> Result<Self, Error> {
970 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
971 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
972 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
973
974 let raw = unsafe {
976 llvm_pm_sys::llvm_pm_create_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
977 };
978
979 if raw.is_null() {
980 Err(unsafe { consume_c_error(err_msg) })
982 } else {
983 Ok(Self {
984 raw,
985 _passes: Vec::new(),
986 _phantom: PhantomData,
987 })
988 }
989 }
990
991 pub fn with_thin_lto_pre_link(
993 target_machine: Option<&'a inkwell::targets::TargetMachine>,
994 level: OptLevel,
995 options: Option<&Options>,
996 ) -> Result<Self, Error> {
997 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
998 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
999 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1000
1001 let raw = unsafe {
1003 llvm_pm_sys::llvm_pm_create_thin_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
1004 };
1005
1006 if raw.is_null() {
1007 Err(unsafe { consume_c_error(err_msg) })
1009 } else {
1010 Ok(Self {
1011 raw,
1012 _passes: Vec::new(),
1013 _phantom: PhantomData,
1014 })
1015 }
1016 }
1017
1018 pub fn new(
1022 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1023 options: Option<&Options>,
1024 ) -> Result<Self, Error> {
1025 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1026 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1027 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1028
1029 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1031
1032 if raw.is_null() {
1033 Err(unsafe { consume_c_error(err_msg) })
1035 } else {
1036 Ok(Self {
1037 raw,
1038 _passes: Vec::new(),
1039 _phantom: PhantomData,
1040 })
1041 }
1042 }
1043
1044 pub fn add_pass<P>(&mut self, pass: P)
1050 where
1051 P: LlvmModulePass + 'static,
1052 {
1053 let mut boxed = Box::new(pass);
1054 let ptr = &mut *boxed as *mut P as *mut c_void;
1055 unsafe {
1059 llvm_pm_sys::llvm_pm_add_module_pass(self.raw, Some(module_pass_trampoline::<P>), ptr);
1060 }
1061 self._passes.push(boxed);
1062 }
1063
1064 pub fn add_cgscc_pass<P>(&mut self, pass: P)
1069 where
1070 P: LlvmCgsccPass + 'static,
1071 {
1072 let mut boxed = Box::new(pass);
1073 let ptr = &mut *boxed as *mut P as *mut c_void;
1074 unsafe {
1078 llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
1079 }
1080 self._passes.push(boxed);
1081 }
1082
1083 pub fn add_function_pass_via_cgscc<P>(&mut self, pass: P)
1088 where
1089 P: LlvmFunctionPass + 'static,
1090 {
1091 let mut boxed = Box::new(pass);
1092 let ptr = &mut *boxed as *mut P as *mut c_void;
1093 unsafe {
1097 llvm_pm_sys::llvm_pm_add_function_pass_via_cgscc(
1098 self.raw,
1099 Some(function_pass_trampoline::<P>),
1100 ptr,
1101 );
1102 }
1103 self._passes.push(boxed);
1104 }
1105
1106 pub fn add_loop_pass_via_cgscc<P>(&mut self, pass: P)
1110 where
1111 P: LlvmLoopPass + 'static,
1112 {
1113 let mut boxed = Box::new(pass);
1114 let ptr = &mut *boxed as *mut P as *mut c_void;
1115 unsafe {
1119 llvm_pm_sys::llvm_pm_add_loop_pass_via_cgscc(
1120 self.raw,
1121 Some(loop_pass_trampoline::<P>),
1122 ptr,
1123 );
1124 }
1125 self._passes.push(boxed);
1126 }
1127
1128 pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1130 let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1133 if err.is_null() {
1134 Ok(())
1135 } else {
1136 Err(unsafe { consume_c_error(err) })
1138 }
1139 }
1140}
1141
1142impl<'a> Drop for ModulePassManager<'a> {
1143 fn drop(&mut self) {
1144 unsafe {
1148 llvm_pm_sys::llvm_pm_dispose(self.raw);
1149 }
1150 }
1151}
1152
1153unsafe impl<'a> Send for ModulePassManager<'a> {}
1161
1162pub struct FunctionPassManager<'a> {
1174 raw: llvm_pm_sys::LlvmPmPassManagerRef,
1175 _passes: Vec<Box<dyn std::any::Any>>,
1176 _phantom: PhantomData<&'a ()>,
1177}
1178
1179impl<'a> fmt::Debug for FunctionPassManager<'a> {
1180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181 f.debug_struct("FunctionPassManager")
1182 .field("raw", &self.raw)
1183 .finish()
1184 }
1185}
1186
1187impl<'a> FunctionPassManager<'a> {
1188 pub fn with_pipeline(
1192 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1193 pipeline: &str,
1194 options: Option<&Options>,
1195 ) -> Result<Self, Error> {
1196 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1197 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1198 let c_pipeline = CString::new(pipeline).map_err(|e| Error {
1199 message: format!("Pipeline string contains null byte: {}", e),
1200 })?;
1201 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1202
1203 let raw = unsafe {
1205 llvm_pm_sys::llvm_pm_create_function_with_pipeline(
1206 tm,
1207 c_pipeline.as_ptr(),
1208 opts,
1209 &mut err_msg,
1210 )
1211 };
1212
1213 if raw.is_null() {
1214 Err(unsafe { consume_c_error(err_msg) })
1216 } else {
1217 Ok(Self {
1218 raw,
1219 _passes: Vec::new(),
1220 _phantom: PhantomData,
1221 })
1222 }
1223 }
1224
1225 pub fn new(
1229 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1230 options: Option<&Options>,
1231 ) -> Result<Self, Error> {
1232 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1233 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1234 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1235
1236 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_function(tm, opts, &mut err_msg) };
1238
1239 if raw.is_null() {
1240 Err(unsafe { consume_c_error(err_msg) })
1242 } else {
1243 Ok(Self {
1244 raw,
1245 _passes: Vec::new(),
1246 _phantom: PhantomData,
1247 })
1248 }
1249 }
1250
1251 pub fn add_pass<P>(&mut self, pass: P)
1257 where
1258 P: LlvmFunctionPass + 'static,
1259 {
1260 let mut boxed = Box::new(pass);
1261 let ptr = &mut *boxed as *mut P as *mut c_void;
1262 unsafe {
1266 llvm_pm_sys::llvm_pm_add_function_pass(
1267 self.raw,
1268 Some(function_pass_trampoline::<P>),
1269 ptr,
1270 );
1271 }
1272 self._passes.push(boxed);
1273 }
1274
1275 pub fn add_loop_pass<P>(&mut self, pass: P)
1280 where
1281 P: traits::LlvmLoopPass + 'static,
1282 {
1283 let mut boxed = Box::new(pass);
1284 let ptr = &mut *boxed as *mut P as *mut c_void;
1285 unsafe {
1289 llvm_pm_sys::llvm_pm_add_loop_pass(self.raw, Some(loop_pass_trampoline::<P>), ptr);
1290 }
1291 self._passes.push(boxed);
1292 }
1293
1294 pub fn run(&mut self, function: inkwell::values::FunctionValue<'_>) -> Result<(), Error> {
1296 let err =
1299 unsafe { llvm_pm_sys::llvm_pm_run_on_function(self.raw, function.as_value_ref()) };
1300 if err.is_null() {
1301 Ok(())
1302 } else {
1303 Err(unsafe { consume_c_error(err) })
1305 }
1306 }
1307}
1308
1309impl<'a> Drop for FunctionPassManager<'a> {
1310 fn drop(&mut self) {
1311 unsafe {
1315 llvm_pm_sys::llvm_pm_dispose(self.raw);
1316 }
1317 }
1318}
1319
1320unsafe impl<'a> Send for FunctionPassManager<'a> {}
1323
1324pub struct CGSCCPassManager<'a> {
1341 raw: llvm_pm_sys::LlvmPmPassManagerRef,
1342 _passes: Vec<Box<dyn std::any::Any>>,
1343 _phantom: PhantomData<&'a ()>,
1344}
1345
1346impl<'a> fmt::Debug for CGSCCPassManager<'a> {
1347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1348 f.debug_struct("CGSCCPassManager")
1349 .field("raw", &self.raw)
1350 .finish()
1351 }
1352}
1353
1354impl<'a> CGSCCPassManager<'a> {
1355 pub fn new(
1361 target_machine: Option<&'a inkwell::targets::TargetMachine>,
1362 options: Option<&Options>,
1363 ) -> Result<Self, Error> {
1364 let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1365 let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1366 let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1367
1368 let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1370
1371 if raw.is_null() {
1372 Err(unsafe { consume_c_error(err_msg) })
1374 } else {
1375 Ok(Self {
1376 raw,
1377 _passes: Vec::new(),
1378 _phantom: PhantomData,
1379 })
1380 }
1381 }
1382
1383 pub fn add_pass<P>(&mut self, pass: P)
1389 where
1390 P: LlvmCgsccPass + 'static,
1391 {
1392 let mut boxed = Box::new(pass);
1393 let ptr = &mut *boxed as *mut P as *mut c_void;
1394 unsafe {
1398 llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
1399 }
1400 self._passes.push(boxed);
1401 }
1402
1403 pub fn add_function_pass<P>(&mut self, pass: P)
1408 where
1409 P: LlvmFunctionPass + 'static,
1410 {
1411 let mut boxed = Box::new(pass);
1412 let ptr = &mut *boxed as *mut P as *mut c_void;
1413 unsafe {
1417 llvm_pm_sys::llvm_pm_add_function_pass_via_cgscc(
1418 self.raw,
1419 Some(function_pass_trampoline::<P>),
1420 ptr,
1421 );
1422 }
1423 self._passes.push(boxed);
1424 }
1425
1426 pub fn add_loop_pass<P>(&mut self, pass: P)
1430 where
1431 P: LlvmLoopPass + 'static,
1432 {
1433 let mut boxed = Box::new(pass);
1434 let ptr = &mut *boxed as *mut P as *mut c_void;
1435 unsafe {
1439 llvm_pm_sys::llvm_pm_add_loop_pass_via_cgscc(
1440 self.raw,
1441 Some(loop_pass_trampoline::<P>),
1442 ptr,
1443 );
1444 }
1445 self._passes.push(boxed);
1446 }
1447
1448 pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1450 let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1453 if err.is_null() {
1454 Ok(())
1455 } else {
1456 Err(unsafe { consume_c_error(err) })
1458 }
1459 }
1460}
1461
1462impl<'a> Drop for CGSCCPassManager<'a> {
1463 fn drop(&mut self) {
1464 unsafe {
1468 llvm_pm_sys::llvm_pm_dispose(self.raw);
1469 }
1470 }
1471}
1472
1473unsafe impl<'a> Send for CGSCCPassManager<'a> {}