Skip to main content

llvm_pm/
lib.rs

1// # Safety overview
2//
3// This crate wraps LLVM's C++ PassManager through an `extern "C"` FFI layer.
4// All unsafe usage falls into these categories:
5//
6// ## FFI calls (Options, PassManager constructors, run, dispose)
7// Each C++ function receives either null or a valid handle created by a prior
8// C++ call. Handles are stored in private fields and never exposed, ensuring
9// validity until `Drop`. Error strings returned by C++ stubs are malloc'd
10// and freed exactly once via `consume_c_error`.
11//
12// ## Pass trampolines (`module_pass_trampoline`, etc.)
13// These `extern "C"` callbacks bridge C++ PassManager invocations to Rust
14// `LlvmModulePass`/`LlvmFunctionPass` trait methods. Safety relies on:
15// - `user_data` pointing to a `Box<T>` kept alive in `_passes: Vec<Box<dyn Any>>`
16// - Monomorphization ensuring the correct type `T` at each call site
17// - `Module::new()` + `mem::forget()` avoiding double-free of LLVM-owned modules
18//
19// **Panic safety**: if a pass's `run_pass` panics, the unwind would cross
20// an `extern "C"` boundary. Rust >= 1.71 aborts in this case; older versions
21// exhibit undefined behavior. Users must ensure their passes do not panic.
22//
23// ## `Send` implementations
24// `ModulePassManager` and `FunctionPassManager` implement `Send` because:
25// - The C++ handle owns all internal state (no shared mutable aliases)
26// - `_passes` contains only owned `Box`es
27// - All mutation requires `&mut self`, preventing concurrent access
28//
29// ## Global analysis registries (`cgscc_analysis_passes`, etc.)
30// Use `Once` + `static mut` to lazily initialize `&'static Mutex<HashMap<…>>`.
31// The `Box` is intentionally leaked to obtain `'static` lifetime. All access
32// is synchronized through `Mutex`.
33//
34// ## Analysis result caches
35// `get_result()` stores analysis results as leaked `Box<A::Result>` (cast to
36// `usize`) in a global cache keyed by `(manager_ptr, analysis_id, ir_key)`.
37// The leaked allocation is never freed, so the returned `&A::Result` reference
38// remains valid for the program's lifetime. Type safety is maintained because
39// the cache key includes the analysis type's `id()` and the lookup is generic
40// over `A`.
41//
42// **Known limitation**: after a PassManager is dropped, a new PM *could* receive
43// the same heap address, causing `get_result` to return stale (but type-safe and
44// dereferenceable) cached results from the previous PM. This is a correctness
45// concern, not a memory-safety issue, and only affects CGSCC/loop analyses
46// registered via the Rust-side analysis manager.
47//
48// ## Drop ordering
49// `ModulePassManager::drop` calls `llvm_pm_dispose` (freeing C++ infrastructure)
50// before Rust drops `_passes`. This is correct because the C++ `RustModulePass`
51// destructor does NOT free `user_data`—it only stores a raw pointer. After
52// `llvm_pm_dispose`, no C++ code will access the pass pointers.
53
54#![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// Re-export the #[plugin] attribute macro at crate root for ergonomic usage:
81// #[llvm_pm::plugin(name = "...", version = "...")]
82#[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    /// # Safety
125    /// `inner` must be a valid pointer to LLVM's `ModuleAnalysisManager`.
126    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    /// # Safety
147    /// `inner` must be a valid pointer to LLVM's `FunctionAnalysisManager`.
148    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/// Optimization level for the default pass pipeline.
163#[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/// Error type for pass manager operations.
187#[derive(Debug)]
188pub struct Error {
189    message: String,
190}
191
192impl Error {
193    /// Returns the error message.
194    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
207/// Consume a C error string into a Rust [`Error`], freeing the C string.
208///
209/// # Safety
210/// `ptr` must be a non-null pointer to a C string allocated by the C++ stubs
211/// (via `malloc`/`copyString`). Ownership is transferred to this function.
212unsafe fn consume_c_error(ptr: *mut std::ffi::c_char) -> Error {
213    // SAFETY: Caller guarantees ptr is a valid, non-null, malloc'd C string.
214    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
219// =========================================================================
220// Options
221// =========================================================================
222
223/// Builder for pass manager options.
224///
225/// Controls debug logging, IR verification, and extension point pipeline
226/// additions. Pass to [`ModulePassManager`] or [`FunctionPassManager`]
227/// constructors via `Option<&Options>`.
228pub struct Options {
229    raw: llvm_pm_sys::LlvmPmOptionsRef,
230}
231
232impl Options {
233    /// Create default options (debug logging off, verify each off).
234    pub fn new() -> Self {
235        // SAFETY: llvm_pm_options_create always returns a valid handle.
236        let raw = unsafe { llvm_pm_sys::llvm_pm_options_create() };
237        Self { raw }
238    }
239
240    /// Enable or disable debug logging output during pass execution.
241    pub fn debug_logging(&mut self, val: bool) -> &mut Self {
242        // SAFETY: self.raw is a valid options handle created by llvm_pm_options_create.
243        unsafe {
244            llvm_pm_sys::llvm_pm_options_set_debug_logging(self.raw, val as i32);
245        }
246        self
247    }
248
249    /// Enable or disable IR verification after each pass.
250    pub fn verify_each(&mut self, val: bool) -> &mut Self {
251        // SAFETY: self.raw is a valid options handle created by llvm_pm_options_create.
252        unsafe {
253            llvm_pm_sys::llvm_pm_options_set_verify_each(self.raw, val as i32);
254        }
255        self
256    }
257
258    /// Add a pass pipeline at the peephole extension point (after instcombine, function-level).
259    pub fn add_peephole_ep(&mut self, pipeline: &str) -> &mut Self {
260        let c = CString::new(pipeline).expect("pipeline contains null byte");
261        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
262        unsafe {
263            llvm_pm_sys::llvm_pm_options_add_peephole_ep(self.raw, c.as_ptr());
264        }
265        self
266    }
267
268    /// Add a pass pipeline at the optimizer-early extension point (module-level).
269    pub fn add_optimizer_early_ep(&mut self, pipeline: &str) -> &mut Self {
270        let c = CString::new(pipeline).expect("pipeline contains null byte");
271        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
272        unsafe {
273            llvm_pm_sys::llvm_pm_options_add_optimizer_early_ep(self.raw, c.as_ptr());
274        }
275        self
276    }
277
278    /// Add a pass pipeline at the optimizer-last extension point (module-level).
279    pub fn add_optimizer_last_ep(&mut self, pipeline: &str) -> &mut Self {
280        let c = CString::new(pipeline).expect("pipeline contains null byte");
281        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
282        unsafe {
283            llvm_pm_sys::llvm_pm_options_add_optimizer_last_ep(self.raw, c.as_ptr());
284        }
285        self
286    }
287
288    /// Add a pass pipeline at the vectorizer-start extension point (function-level).
289    pub fn add_vectorizer_start_ep(&mut self, pipeline: &str) -> &mut Self {
290        let c = CString::new(pipeline).expect("pipeline contains null byte");
291        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
292        unsafe {
293            llvm_pm_sys::llvm_pm_options_add_vectorizer_start_ep(self.raw, c.as_ptr());
294        }
295        self
296    }
297
298    /// Add a pass pipeline at the scalar-optimizer-late extension point (function-level).
299    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        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
302        unsafe {
303            llvm_pm_sys::llvm_pm_options_add_scalar_optimizer_late_ep(self.raw, c.as_ptr());
304        }
305        self
306    }
307
308    /// Add a pass pipeline at the pipeline-start extension point (module-level).
309    pub fn add_pipeline_start_ep(&mut self, pipeline: &str) -> &mut Self {
310        let c = CString::new(pipeline).expect("pipeline contains null byte");
311        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
312        unsafe {
313            llvm_pm_sys::llvm_pm_options_add_pipeline_start_ep(self.raw, c.as_ptr());
314        }
315        self
316    }
317
318    /// Add a pass pipeline at the pipeline-early-simplification extension point (module-level).
319    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        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
322        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        // SAFETY: self.raw is a valid options handle, and Drop runs at most once.
338        unsafe {
339            llvm_pm_sys::llvm_pm_options_dispose(self.raw);
340        }
341    }
342}
343
344/// Analysis manager handle for CGSCC passes and analyses.
345pub struct CgsccAnalysisManager {
346    raw: *mut c_void,
347    from_analysis_id: Option<AnalysisKey>,
348}
349
350impl CgsccAnalysisManager {
351    /// Construct from an opaque manager pointer passed by the C++ layer.
352    ///
353    /// # Safety
354    /// `raw` must be a valid pointer to LLVM's `CGSCCAnalysisManager`.
355    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    /// Get the underlying opaque pointer.
373    pub fn as_raw(&self) -> *mut c_void {
374        self.raw
375    }
376
377    /// Register a CGSCC analysis pass.
378    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            // SAFETY: Pointer was created by Box::into_raw in add_pass.
386            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            // SAFETY: pass is a valid pointer to T stored in registry.
399            let pass = unsafe { &*(pass as *const T) };
400            // SAFETY: manager is valid for callback duration.
401            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    /// Get (or compute) analysis result for a function in current SCC.
428    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        // SAFETY: result_ptr points to a leaked Box<A::Result> stored in cache.
465        unsafe { &*(result_ptr as *const A::Result) }
466    }
467
468    /// Get cached analysis result if present.
469    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            // SAFETY: cached pointer values are inserted only from `Box<A::Result>` in
493            // `get_result`, keyed by the same analysis type `A`.
494            .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
495    }
496}
497
498/// Analysis manager handle for loop passes and analyses.
499pub struct LoopAnalysisManager {
500    raw: *mut c_void,
501    from_analysis_id: Option<AnalysisKey>,
502}
503
504impl LoopAnalysisManager {
505    /// Construct from an opaque manager pointer passed by the C++ layer.
506    ///
507    /// # Safety
508    /// `raw` must be a valid pointer to LLVM's `LoopAnalysisManager`.
509    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    /// Get the underlying opaque pointer.
527    pub fn as_raw(&self) -> *mut c_void {
528        self.raw
529    }
530
531    /// Register a loop analysis pass.
532    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            // SAFETY: Pointer was created by Box::into_raw in add_pass.
540            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            // SAFETY: pass is a valid pointer to T stored in registry.
553            let pass = unsafe { &*(pass as *const T) };
554            // SAFETY: manager is valid for callback duration.
555            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    /// Get (or compute) analysis result for a loop header.
582    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        // SAFETY: result_ptr points to a leaked Box<A::Result> stored in cache.
619        unsafe { &*(result_ptr as *const A::Result) }
620    }
621
622    /// Get cached analysis result if present.
623    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            // SAFETY: cached pointer values are inserted only from `Box<A::Result>` in
644            // `get_result`, keyed by the same analysis type `A`.
645            .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
674// SAFETY: Entries contain raw pointers (`pass: *mut c_void`) to heap-allocated
675// `Box<T>` values and function pointers (`pass_deleter`, `pass_entrypoint`).
676// All access to entries is behind a `Mutex`, so no data races are possible.
677// The pointed-to data is owned exclusively by this entry (freed in Drop).
678unsafe 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        // SAFETY: `call_once` guarantees this assignment runs once.
690        unsafe {
691            CELL = Box::into_raw(value);
692        }
693    });
694    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
695    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        // SAFETY: `call_once` guarantees this assignment runs once.
704        unsafe {
705            CELL = Box::into_raw(value);
706        }
707    });
708    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
709    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        // SAFETY: `call_once` guarantees this assignment runs once.
718        unsafe {
719            CELL = Box::into_raw(value);
720        }
721    });
722    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
723    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        // SAFETY: `call_once` guarantees this assignment runs once.
732        unsafe {
733            CELL = Box::into_raw(value);
734        }
735    });
736    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
737    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
747/// Generic trampoline for module passes. Monomorphized per `T`.
748///
749/// # Safety
750/// - `user_data` must be a valid pointer to a `T` that was stored in
751///   [`ModulePassManager::_passes`].
752/// - `module` must be a valid `LLVMModuleRef` owned by the caller (not consumed).
753/// - `manager` must be a valid `ModuleAnalysisManager*` from the C++ layer.
754///
755/// # Panics
756/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
757/// Rust >= 1.71 aborts; older versions have undefined behavior.
758pub(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    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
764    let pass = &*(user_data as *const T);
765    // SAFETY: Module::new wraps the LLVMModuleRef without taking ownership.
766    // We must call forget() to avoid dropping (and freeing) the LLVM module,
767    // which is owned by the caller (C++ PassManager).
768    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
775/// Generic trampoline for function passes. Monomorphized per `T`.
776///
777/// # Safety
778/// - `user_data` must be a valid pointer to a `T` that was stored in
779///   [`FunctionPassManager::_passes`].
780/// - `function` must be a valid `LLVMValueRef` representing a function.
781/// - `manager` must be a valid `FunctionAnalysisManager*` from the C++ layer.
782///
783/// # Panics
784/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
785/// Rust >= 1.71 aborts; older versions have undefined behavior.
786pub(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    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
792    let pass = &*(user_data as *const T);
793    // SAFETY: FunctionValue::new wraps the LLVMValueRef without ownership.
794    // FunctionValue has no Drop impl, so no forget() needed.
795    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
801/// Generic trampoline for CGSCC passes. Monomorphized per `T`.
802///
803/// # Safety
804/// - `user_data` must be a valid pointer to a `T` that was stored in
805///   [`ModulePassManager::_passes`].
806/// - `function` must be a valid `LLVMValueRef` representing a function in the SCC.
807/// - `manager` must be a valid `CGSCCAnalysisManager*` from the C++ layer.
808///
809/// # Panics
810/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
811/// Rust >= 1.71 aborts; older versions have undefined behavior.
812pub(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    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
818    let pass = &*(user_data as *const T);
819    let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
820    // SAFETY: manager is valid for callback duration (owned by C++ PM infrastructure).
821    let manager = CgsccAnalysisManager::from_raw(manager);
822    let result = pass.run_pass(&mut function, &manager);
823    preserved_to_c(result)
824}
825
826/// Generic trampoline for loop passes. Monomorphized per `T`.
827///
828/// # Safety
829/// - `user_data` must be a valid pointer to a `T` that was stored in
830///   [`FunctionPassManager::_passes`].
831/// - `header` must be a valid `LLVMBasicBlockRef` for the loop header.
832/// - `manager` must be a valid `LoopAnalysisManager*` from the C++ layer.
833///
834/// # Panics
835/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
836/// Rust >= 1.71 aborts; older versions have undefined behavior.
837pub(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    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
843    let pass = &*(user_data as *const T);
844    // SAFETY: manager is valid for callback duration (owned by C++ PM infrastructure).
845    let manager = LoopAnalysisManager::from_raw(manager);
846    let result = pass.run_pass(header, &manager);
847    preserved_to_c(result)
848}
849
850// =========================================================================
851// ModulePassManager
852// =========================================================================
853
854/// A configured LLVM module pass manager using the new PassManager infrastructure.
855///
856/// Bundles all analysis managers, PassBuilder, StandardInstrumentations, and the
857/// ModulePassManager into a single object with correct lifetime management.
858///
859/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
860/// ensuring the target machine outlives the pass manager.
861pub 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    /// Create a pass manager with a standard optimization pipeline.
877    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        // SAFETY: tm is either null or a valid LLVMTargetMachineRef from inkwell.
887        // opts is either null or a valid options handle. err_msg is a valid out-pointer.
888        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            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
894            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    /// Create a pass manager from a textual pipeline description.
905    ///
906    /// The format matches `opt -passes=...` syntax, e.g.:
907    /// - `"instcombine,dce,sroa"`
908    /// - `"default<O2>"`
909    /// - `"module(function(instcombine,sroa))"`
910    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        // SAFETY: tm is either null or valid. c_pipeline is a valid null-terminated string.
923        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            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
929            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    /// Create a pass manager with the full-LTO default pipeline.
940    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        // SAFETY: tm is either null or valid. opts is either null or valid.
950        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            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
954            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    /// Create a pass manager with the full-LTO pre-link pipeline.
965    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        // SAFETY: tm is either null or valid. opts is either null or valid.
975        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            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
981            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    /// Create a pass manager with the ThinLTO pre-link pipeline.
992    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        // SAFETY: tm is either null or valid. opts is either null or valid.
1002        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            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1008            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    /// Create an empty module pass manager with no built-in passes.
1019    ///
1020    /// Use [`add_pass()`](ModulePassManager::add_pass) to add custom passes.
1021    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        // SAFETY: tm is either null or valid. opts is either null or valid.
1030        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1031
1032        if raw.is_null() {
1033            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1034            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    /// Add a custom module pass to this pass manager.
1045    ///
1046    /// The pass is moved into the pass manager and kept alive until the pass
1047    /// manager is dropped. The pass is appended after any existing passes in
1048    /// the pipeline.
1049    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        // SAFETY: self.raw is a valid PM handle. module_pass_trampoline::<T> is the
1056        // correct monomorphized trampoline. The pass pointer is valid for the
1057        // lifetime of the PM because the Box is stored in _passes.
1058        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    /// Add a custom CGSCC pass to this pass manager.
1065    ///
1066    /// The pass is adapted into the module pipeline and invoked for each
1067    /// function in each SCC.
1068    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        // SAFETY: self.raw is a valid PM handle. cgscc_pass_trampoline::<T> is the
1075        // correct monomorphized trampoline. The pass pointer is valid for the
1076        // lifetime of the PM because the Box is stored in _passes.
1077        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    /// Add a custom function pass adapted through the CGSCC level.
1084    ///
1085    /// The pass is wrapped with `Module → CGSCC → Function` adaptors, so it
1086    /// runs on each function within the CGSCC traversal order.
1087    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        // SAFETY: self.raw is a valid PM handle. function_pass_trampoline::<P> is the
1094        // correct monomorphized trampoline. The pass pointer is valid for the
1095        // lifetime of the PM because the Box is stored in _passes.
1096        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    /// Add a custom loop pass adapted through the CGSCC and function levels.
1107    ///
1108    /// The pass is wrapped with `Module → CGSCC → Function → Loop` adaptors.
1109    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        // SAFETY: self.raw is a valid PM handle. loop_pass_trampoline::<P> is the
1116        // correct monomorphized trampoline. The pass pointer is valid for the
1117        // lifetime of the PM because the Box is stored in _passes.
1118        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    /// Run the optimization passes on the given module.
1129    pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1130        // SAFETY: self.raw is a valid PM handle. module.as_mut_ptr() returns a valid
1131        // LLVMModuleRef. &mut self ensures exclusive access to stored passes.
1132        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            // SAFETY: On error, llvm_pm_run returns a valid malloc'd error string.
1137            Err(unsafe { consume_c_error(err) })
1138        }
1139    }
1140}
1141
1142impl<'a> Drop for ModulePassManager<'a> {
1143    fn drop(&mut self) {
1144        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1145        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1146        // dropped automatically afterward.
1147        unsafe {
1148            llvm_pm_sys::llvm_pm_dispose(self.raw);
1149        }
1150    }
1151}
1152
1153// SAFETY: `ModulePassManager` owns all its internal state exclusively:
1154// - `raw`: opaque C handle to a bundled C++ PM (PassBuilder, analysis managers,
1155//   StandardInstrumentations). No shared mutable aliases exist.
1156// - `_passes`: Vec of owned Boxes. Not Sync, but Send (owned data).
1157// All mutating operations (`run`, `add_pass`) require `&mut self`, so the type
1158// system prevents concurrent access. Moving between threads is safe because
1159// the C++ handle and Rust Boxes are self-contained.
1160unsafe impl<'a> Send for ModulePassManager<'a> {}
1161
1162// =========================================================================
1163// FunctionPassManager
1164// =========================================================================
1165
1166/// A configured LLVM function pass manager using the new PassManager infrastructure.
1167///
1168/// Similar to [`ModulePassManager`] but runs function-level passes on individual
1169/// functions rather than entire modules.
1170///
1171/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
1172/// ensuring the target machine outlives the pass manager.
1173pub 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    /// Create a function pass manager from a textual pipeline description.
1189    ///
1190    /// The pipeline should contain function-level passes, e.g. `"instcombine,dce"`.
1191    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        // SAFETY: tm is either null or valid. c_pipeline is a valid null-terminated string.
1204        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            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1215            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    /// Create an empty function pass manager with no built-in passes.
1226    ///
1227    /// Use [`add_pass()`](FunctionPassManager::add_pass) to add custom passes.
1228    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        // SAFETY: tm is either null or valid. opts is either null or valid.
1237        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_function(tm, opts, &mut err_msg) };
1238
1239        if raw.is_null() {
1240            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1241            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    /// Add a custom function pass to this pass manager.
1252    ///
1253    /// The pass is moved into the pass manager and kept alive until the pass
1254    /// manager is dropped. The pass is appended after any existing passes in
1255    /// the pipeline.
1256    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        // SAFETY: self.raw is a valid PM handle. function_pass_trampoline::<T> is the
1263        // correct monomorphized trampoline. The pass pointer is valid for the
1264        // lifetime of the PM because the Box is stored in _passes.
1265        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    /// Add a custom loop pass to this pass manager.
1276    ///
1277    /// The pass is adapted into the function pipeline and invoked with each
1278    /// loop header basic block.
1279    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        // SAFETY: self.raw is a valid PM handle. loop_pass_trampoline::<T> is the
1286        // correct monomorphized trampoline. The pass pointer is valid for the
1287        // lifetime of the PM because the Box is stored in _passes.
1288        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    /// Run the function passes on the given function.
1295    pub fn run(&mut self, function: inkwell::values::FunctionValue<'_>) -> Result<(), Error> {
1296        // SAFETY: self.raw is a valid PM handle. function.as_value_ref() returns a valid
1297        // LLVMValueRef. &mut self ensures exclusive access to stored passes.
1298        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            // SAFETY: On error, llvm_pm_run_on_function returns a valid malloc'd error string.
1304            Err(unsafe { consume_c_error(err) })
1305        }
1306    }
1307}
1308
1309impl<'a> Drop for FunctionPassManager<'a> {
1310    fn drop(&mut self) {
1311        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1312        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1313        // dropped automatically afterward.
1314        unsafe {
1315            llvm_pm_sys::llvm_pm_dispose(self.raw);
1316        }
1317    }
1318}
1319
1320// SAFETY: Same rationale as `ModulePassManager`: exclusively-owned C++ handle
1321// and Rust Boxes. All mutating operations require `&mut self`.
1322unsafe impl<'a> Send for FunctionPassManager<'a> {}
1323
1324// =========================================================================
1325// CGSCCPassManager
1326// =========================================================================
1327
1328/// A configured LLVM CGSCC pass manager using the new PassManager infrastructure.
1329///
1330/// Provides a type-level distinction for CGSCC-oriented pipelines. Internally
1331/// backed by a module-level pass manager where each pass is adapted through the
1332/// `Module → CGSCC` adaptor.
1333///
1334/// Supports adding CGSCC passes directly, as well as function and loop passes
1335/// which are adapted through the CGSCC level (`CGSCC → Function` and
1336/// `CGSCC → Function → Loop` respectively).
1337///
1338/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
1339/// ensuring the target machine outlives the pass manager.
1340pub 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    /// Create an empty CGSCC pass manager.
1356    ///
1357    /// Use [`add_pass()`](CGSCCPassManager::add_pass),
1358    /// [`add_function_pass()`](CGSCCPassManager::add_function_pass), or
1359    /// [`add_loop_pass()`](CGSCCPassManager::add_loop_pass) to add passes.
1360    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        // SAFETY: tm is either null or valid. opts is either null or valid.
1369        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1370
1371        if raw.is_null() {
1372            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1373            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    /// Add a custom CGSCC pass.
1384    ///
1385    /// The pass is adapted into the module pipeline via
1386    /// `createModuleToPostOrderCGSCCPassAdaptor` and invoked for each function
1387    /// in each SCC.
1388    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        // SAFETY: self.raw is a valid PM handle. cgscc_pass_trampoline::<P> is the
1395        // correct monomorphized trampoline. The pass pointer is valid for the
1396        // lifetime of the PM because the Box is stored in _passes.
1397        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    /// Add a custom function pass adapted through the CGSCC level.
1404    ///
1405    /// The pass is wrapped with `Module → CGSCC → Function` adaptors, so it
1406    /// runs on each function within the CGSCC traversal order.
1407    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        // SAFETY: self.raw is a valid PM handle. function_pass_trampoline::<P> is the
1414        // correct monomorphized trampoline. The pass pointer is valid for the
1415        // lifetime of the PM because the Box is stored in _passes.
1416        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    /// Add a custom loop pass adapted through the CGSCC and function levels.
1427    ///
1428    /// The pass is wrapped with `Module → CGSCC → Function → Loop` adaptors.
1429    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        // SAFETY: self.raw is a valid PM handle. loop_pass_trampoline::<P> is the
1436        // correct monomorphized trampoline. The pass pointer is valid for the
1437        // lifetime of the PM because the Box is stored in _passes.
1438        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    /// Run the CGSCC passes on the given module.
1449    pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1450        // SAFETY: self.raw is a valid PM handle. module.as_mut_ptr() returns a valid
1451        // LLVMModuleRef. &mut self ensures exclusive access to stored passes.
1452        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            // SAFETY: On error, llvm_pm_run returns a valid malloc'd error string.
1457            Err(unsafe { consume_c_error(err) })
1458        }
1459    }
1460}
1461
1462impl<'a> Drop for CGSCCPassManager<'a> {
1463    fn drop(&mut self) {
1464        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1465        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1466        // dropped automatically afterward.
1467        unsafe {
1468            llvm_pm_sys::llvm_pm_dispose(self.raw);
1469        }
1470    }
1471}
1472
1473// SAFETY: Same rationale as `ModulePassManager`: exclusively-owned C++ handle
1474// and Rust Boxes. All mutating operations require `&mut self`.
1475unsafe impl<'a> Send for CGSCCPassManager<'a> {}