rustc_codegen_llvm/llvm/
ffi.rs

1//! Bindings to the LLVM-C API (`LLVM*`), and to our own `extern "C"` wrapper
2//! functions around the unstable LLVM C++ API (`LLVMRust*`).
3//!
4//! ## Passing pointer/length strings as `*const c_uchar` (PTR_LEN_STR)
5//!
6//! Normally it's a good idea for Rust-side bindings to match the corresponding
7//! C-side function declarations as closely as possible. But when passing `&str`
8//! or `&[u8]` data as a pointer/length pair, it's more convenient to declare
9//! the Rust-side pointer as `*const c_uchar` instead of `*const c_char`.
10//! Both pointer types have the same ABI, and using `*const c_uchar` avoids
11//! the need for an extra cast from `*const u8` on the Rust side.
12
13#![allow(non_camel_case_types)]
14
15use std::fmt::{self, Debug};
16use std::marker::PhantomData;
17use std::num::NonZero;
18use std::ptr;
19
20use bitflags::bitflags;
21use libc::{c_char, c_int, c_uchar, c_uint, c_ulonglong, c_void, size_t};
22
23use super::RustString;
24use super::debuginfo::{
25    DIArray, DIBuilder, DIDerivedType, DIDescriptor, DIEnumerator, DIFile, DIFlags, DILocation,
26    DISPFlags, DIScope, DISubprogram, DITemplateTypeParameter, DIType, DebugEmissionKind,
27    DebugNameTableKind,
28};
29use crate::llvm::MetadataKindId;
30use crate::{TryFromU32, llvm};
31
32/// In the LLVM-C API, boolean values are passed as `typedef int LLVMBool`,
33/// which has a different ABI from Rust or C++ `bool`.
34///
35/// This wrapper does not implement `PartialEq`.
36/// To test the underlying boolean value, use [`Self::is_true`].
37#[derive(Clone, Copy)]
38#[repr(transparent)]
39pub(crate) struct Bool {
40    value: c_int,
41}
42
43pub(crate) const TRUE: Bool = Bool::TRUE;
44pub(crate) const FALSE: Bool = Bool::FALSE;
45
46impl Bool {
47    pub(crate) const TRUE: Self = Self { value: 1 };
48    pub(crate) const FALSE: Self = Self { value: 0 };
49
50    pub(crate) const fn from_bool(rust_bool: bool) -> Self {
51        if rust_bool { Self::TRUE } else { Self::FALSE }
52    }
53
54    /// Converts this LLVM-C boolean to a Rust `bool`
55    pub(crate) fn is_true(self) -> bool {
56        // Since we're interacting with a C API, follow the C convention of
57        // treating any nonzero value as true.
58        self.value != Self::FALSE.value
59    }
60}
61
62impl Debug for Bool {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        match self.value {
65            0 => f.write_str("FALSE"),
66            1 => f.write_str("TRUE"),
67            // As with `Self::is_true`, treat any nonzero value as true.
68            v => write!(f, "TRUE ({v})"),
69        }
70    }
71}
72
73/// Convenience trait to convert `bool` to `llvm::Bool` with an explicit method call.
74///
75/// Being able to write `b.to_llvm_bool()` is less noisy than `llvm::Bool::from(b)`,
76/// while being more explicit and less mistake-prone than something like `b.into()`.
77pub(crate) trait ToLlvmBool: Copy {
78    fn to_llvm_bool(self) -> llvm::Bool;
79}
80
81impl ToLlvmBool for bool {
82    #[inline(always)]
83    fn to_llvm_bool(self) -> llvm::Bool {
84        llvm::Bool::from_bool(self)
85    }
86}
87
88/// Wrapper for a raw enum value returned from LLVM's C APIs.
89///
90/// For C enums returned by LLVM, it's risky to use a Rust enum as the return
91/// type, because it would be UB if a later version of LLVM adds a new enum
92/// value and returns it. Instead, return this raw wrapper, then convert to the
93/// Rust-side enum explicitly.
94#[repr(transparent)]
95pub(crate) struct RawEnum<T> {
96    value: u32,
97    /// We don't own or consume a `T`, but we can produce one.
98    _rust_side_type: PhantomData<fn() -> T>,
99}
100
101impl<T: TryFrom<u32>> RawEnum<T> {
102    #[track_caller]
103    pub(crate) fn to_rust(self) -> T
104    where
105        T::Error: Debug,
106    {
107        // If this fails, the Rust-side enum is out of sync with LLVM's enum.
108        T::try_from(self.value).expect("enum value returned by LLVM should be known")
109    }
110}
111
112#[derive(Copy, Clone, PartialEq)]
113#[repr(C)]
114#[allow(dead_code)] // Variants constructed by C++.
115pub(crate) enum LLVMRustResult {
116    Success,
117    Failure,
118}
119
120/// Must match the layout of `LLVMRustModuleFlagMergeBehavior`.
121///
122/// When merging modules (e.g. during LTO), their metadata flags are combined. Conflicts are
123/// resolved according to the merge behaviors specified here. Flags differing only in merge
124/// behavior are still considered to be in conflict.
125///
126/// In order for Rust-C LTO to work, we must specify behaviors compatible with Clang. Notably,
127/// 'Error' and 'Warning' cannot be mixed for a given flag.
128///
129/// There is a stable LLVM-C version of this enum (`LLVMModuleFlagBehavior`),
130/// but as of LLVM 19 it does not support all of the enum values in the unstable
131/// C++ API.
132#[derive(Copy, Clone, PartialEq)]
133#[repr(C)]
134pub(crate) enum ModuleFlagMergeBehavior {
135    Error = 1,
136    Warning = 2,
137    Require = 3,
138    Override = 4,
139    Append = 5,
140    AppendUnique = 6,
141    Max = 7,
142    Min = 8,
143}
144
145// Consts for the LLVM CallConv type, pre-cast to usize.
146
147/// Must match the layout of `LLVMTailCallKind`.
148#[derive(Copy, Clone, PartialEq, Debug)]
149#[repr(C)]
150#[allow(dead_code)]
151pub(crate) enum TailCallKind {
152    None = 0,
153    Tail = 1,
154    MustTail = 2,
155    NoTail = 3,
156}
157
158/// LLVM CallingConv::ID. Should we wrap this?
159///
160/// See <https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/IR/CallingConv.h>
161#[derive(Copy, Clone, PartialEq, Debug, TryFromU32)]
162#[repr(C)]
163pub(crate) enum CallConv {
164    CCallConv = 0,
165    FastCallConv = 8,
166    ColdCallConv = 9,
167    PreserveMost = 14,
168    PreserveAll = 15,
169    Tail = 18,
170    X86StdcallCallConv = 64,
171    X86FastcallCallConv = 65,
172    ArmAapcsCallConv = 67,
173    Msp430Intr = 69,
174    X86_ThisCall = 70,
175    PtxKernel = 71,
176    X86_64_SysV = 78,
177    X86_64_Win64 = 79,
178    X86_VectorCall = 80,
179    X86_Intr = 83,
180    AvrNonBlockingInterrupt = 84,
181    AvrInterrupt = 85,
182    AmdgpuKernel = 91,
183}
184
185/// Must match the layout of `LLVMLinkage`.
186#[derive(Copy, Clone, PartialEq, TryFromU32)]
187#[repr(C)]
188pub(crate) enum Linkage {
189    ExternalLinkage = 0,
190    AvailableExternallyLinkage = 1,
191    LinkOnceAnyLinkage = 2,
192    LinkOnceODRLinkage = 3,
193    #[deprecated = "marked obsolete by LLVM"]
194    LinkOnceODRAutoHideLinkage = 4,
195    WeakAnyLinkage = 5,
196    WeakODRLinkage = 6,
197    AppendingLinkage = 7,
198    InternalLinkage = 8,
199    PrivateLinkage = 9,
200    #[deprecated = "marked obsolete by LLVM"]
201    DLLImportLinkage = 10,
202    #[deprecated = "marked obsolete by LLVM"]
203    DLLExportLinkage = 11,
204    ExternalWeakLinkage = 12,
205    #[deprecated = "marked obsolete by LLVM"]
206    GhostLinkage = 13,
207    CommonLinkage = 14,
208    LinkerPrivateLinkage = 15,
209    LinkerPrivateWeakLinkage = 16,
210}
211
212/// Must match the layout of `LLVMVisibility`.
213#[repr(C)]
214#[derive(Copy, Clone, PartialEq, TryFromU32)]
215pub(crate) enum Visibility {
216    Default = 0,
217    Hidden = 1,
218    Protected = 2,
219}
220
221/// LLVMUnnamedAddr
222#[repr(C)]
223pub(crate) enum UnnamedAddr {
224    No,
225    #[expect(dead_code)]
226    Local,
227    Global,
228}
229
230/// LLVMDLLStorageClass
231#[derive(Copy, Clone)]
232#[repr(C)]
233pub(crate) enum DLLStorageClass {
234    #[allow(dead_code)]
235    Default = 0,
236    DllImport = 1, // Function to be imported from DLL.
237    #[allow(dead_code)]
238    DllExport = 2, // Function to be accessible from DLL.
239}
240
241/// Must match the layout of `LLVMRustAttributeKind`.
242/// Semantically a subset of the C++ enum llvm::Attribute::AttrKind,
243/// though it is not ABI compatible (since it's a C++ enum)
244#[repr(C)]
245#[derive(Copy, Clone, Debug)]
246#[expect(dead_code, reason = "Some variants are unused, but are kept to match the C++")]
247pub(crate) enum AttributeKind {
248    AlwaysInline = 0,
249    ByVal = 1,
250    Cold = 2,
251    InlineHint = 3,
252    MinSize = 4,
253    Naked = 5,
254    NoAlias = 6,
255    CapturesAddress = 7,
256    NoInline = 8,
257    NonNull = 9,
258    NoRedZone = 10,
259    NoReturn = 11,
260    NoUnwind = 12,
261    OptimizeForSize = 13,
262    ReadOnly = 14,
263    SExt = 15,
264    StructRet = 16,
265    UWTable = 17,
266    ZExt = 18,
267    InReg = 19,
268    SanitizeThread = 20,
269    SanitizeAddress = 21,
270    SanitizeMemory = 22,
271    NonLazyBind = 23,
272    OptimizeNone = 24,
273    ReadNone = 26,
274    SanitizeHWAddress = 28,
275    WillReturn = 29,
276    StackProtectReq = 30,
277    StackProtectStrong = 31,
278    StackProtect = 32,
279    NoUndef = 33,
280    SanitizeMemTag = 34,
281    NoCfCheck = 35,
282    ShadowCallStack = 36,
283    AllocSize = 37,
284    AllocatedPointer = 38,
285    AllocAlign = 39,
286    SanitizeSafeStack = 40,
287    FnRetThunkExtern = 41,
288    Writable = 42,
289    DeadOnUnwind = 43,
290    DeadOnReturn = 44,
291    CapturesReadOnly = 45,
292}
293
294/// LLVMIntPredicate
295#[derive(Copy, Clone)]
296#[repr(C)]
297pub(crate) enum IntPredicate {
298    IntEQ = 32,
299    IntNE = 33,
300    IntUGT = 34,
301    IntUGE = 35,
302    IntULT = 36,
303    IntULE = 37,
304    IntSGT = 38,
305    IntSGE = 39,
306    IntSLT = 40,
307    IntSLE = 41,
308}
309
310/// LLVMRealPredicate
311#[derive(Copy, Clone)]
312#[repr(C)]
313pub(crate) enum RealPredicate {
314    RealPredicateFalse = 0,
315    RealOEQ = 1,
316    RealOGT = 2,
317    RealOGE = 3,
318    RealOLT = 4,
319    RealOLE = 5,
320    RealONE = 6,
321    RealORD = 7,
322    RealUNO = 8,
323    RealUEQ = 9,
324    RealUGT = 10,
325    RealUGE = 11,
326    RealULT = 12,
327    RealULE = 13,
328    RealUNE = 14,
329    RealPredicateTrue = 15,
330}
331
332/// Must match the layout of `LLVMTypeKind`.
333///
334/// Use [`RawEnum<TypeKind>`] for values of `LLVMTypeKind` returned from LLVM,
335/// to avoid risk of UB if LLVM adds new enum values.
336///
337/// All of LLVM's variants should be declared here, even if no Rust-side code refers
338/// to them, because unknown variants will cause [`RawEnum::to_rust`] to panic.
339#[derive(Copy, Clone, PartialEq, Debug, TryFromU32)]
340#[repr(C)]
341pub(crate) enum TypeKind {
342    Void = 0,
343    Half = 1,
344    Float = 2,
345    Double = 3,
346    X86_FP80 = 4,
347    FP128 = 5,
348    PPC_FP128 = 6,
349    Label = 7,
350    Integer = 8,
351    Function = 9,
352    Struct = 10,
353    Array = 11,
354    Pointer = 12,
355    Vector = 13,
356    Metadata = 14,
357    Token = 16,
358    ScalableVector = 17,
359    BFloat = 18,
360    X86_AMX = 19,
361}
362
363impl TypeKind {
364    pub(crate) fn to_generic(self) -> rustc_codegen_ssa::common::TypeKind {
365        use rustc_codegen_ssa::common::TypeKind as Common;
366        match self {
367            Self::Void => Common::Void,
368            Self::Half => Common::Half,
369            Self::Float => Common::Float,
370            Self::Double => Common::Double,
371            Self::X86_FP80 => Common::X86_FP80,
372            Self::FP128 => Common::FP128,
373            Self::PPC_FP128 => Common::PPC_FP128,
374            Self::Label => Common::Label,
375            Self::Integer => Common::Integer,
376            Self::Function => Common::Function,
377            Self::Struct => Common::Struct,
378            Self::Array => Common::Array,
379            Self::Pointer => Common::Pointer,
380            Self::Vector => Common::Vector,
381            Self::Metadata => Common::Metadata,
382            Self::Token => Common::Token,
383            Self::ScalableVector => Common::ScalableVector,
384            Self::BFloat => Common::BFloat,
385            Self::X86_AMX => Common::X86_AMX,
386        }
387    }
388}
389
390/// LLVMAtomicRmwBinOp
391#[derive(Copy, Clone)]
392#[repr(C)]
393pub(crate) enum AtomicRmwBinOp {
394    AtomicXchg = 0,
395    AtomicAdd = 1,
396    AtomicSub = 2,
397    AtomicAnd = 3,
398    AtomicNand = 4,
399    AtomicOr = 5,
400    AtomicXor = 6,
401    AtomicMax = 7,
402    AtomicMin = 8,
403    AtomicUMax = 9,
404    AtomicUMin = 10,
405}
406
407/// LLVMAtomicOrdering
408#[derive(Copy, Clone)]
409#[repr(C)]
410pub(crate) enum AtomicOrdering {
411    #[allow(dead_code)]
412    NotAtomic = 0,
413    #[allow(dead_code)]
414    Unordered = 1,
415    Monotonic = 2,
416    // Consume = 3,  // Not specified yet.
417    Acquire = 4,
418    Release = 5,
419    AcquireRelease = 6,
420    SequentiallyConsistent = 7,
421}
422
423/// LLVMRustFileType
424#[derive(Copy, Clone)]
425#[repr(C)]
426pub(crate) enum FileType {
427    AssemblyFile,
428    ObjectFile,
429}
430
431/// Must match the layout of `LLVMInlineAsmDialect`.
432#[derive(Copy, Clone, PartialEq)]
433#[repr(C)]
434pub(crate) enum AsmDialect {
435    Att,
436    Intel,
437}
438
439/// LLVMRustCodeGenOptLevel
440#[derive(Copy, Clone, PartialEq)]
441#[repr(C)]
442pub(crate) enum CodeGenOptLevel {
443    None,
444    Less,
445    Default,
446    Aggressive,
447}
448
449/// LLVMRustPassBuilderOptLevel
450#[repr(C)]
451pub(crate) enum PassBuilderOptLevel {
452    O0,
453    O1,
454    O2,
455    O3,
456    Os,
457    Oz,
458}
459
460/// LLVMRustOptStage
461#[derive(PartialEq)]
462#[repr(C)]
463pub(crate) enum OptStage {
464    PreLinkNoLTO,
465    PreLinkThinLTO,
466    PreLinkFatLTO,
467    ThinLTO,
468    FatLTO,
469}
470
471/// LLVMRustSanitizerOptions
472#[repr(C)]
473pub(crate) struct SanitizerOptions {
474    pub sanitize_address: bool,
475    pub sanitize_address_recover: bool,
476    pub sanitize_cfi: bool,
477    pub sanitize_dataflow: bool,
478    pub sanitize_dataflow_abilist: *const *const c_char,
479    pub sanitize_dataflow_abilist_len: size_t,
480    pub sanitize_kcfi: bool,
481    pub sanitize_memory: bool,
482    pub sanitize_memory_recover: bool,
483    pub sanitize_memory_track_origins: c_int,
484    pub sanitize_thread: bool,
485    pub sanitize_hwaddress: bool,
486    pub sanitize_hwaddress_recover: bool,
487    pub sanitize_kernel_address: bool,
488    pub sanitize_kernel_address_recover: bool,
489}
490
491/// LLVMRustRelocModel
492#[derive(Copy, Clone, PartialEq)]
493#[repr(C)]
494pub(crate) enum RelocModel {
495    Static,
496    PIC,
497    DynamicNoPic,
498    ROPI,
499    RWPI,
500    ROPI_RWPI,
501}
502
503/// LLVMRustFloatABI
504#[derive(Copy, Clone, PartialEq)]
505#[repr(C)]
506pub(crate) enum FloatAbi {
507    Default,
508    Soft,
509    Hard,
510}
511
512/// LLVMRustCodeModel
513#[derive(Copy, Clone)]
514#[repr(C)]
515pub(crate) enum CodeModel {
516    Tiny,
517    Small,
518    Kernel,
519    Medium,
520    Large,
521    None,
522}
523
524/// LLVMRustDiagnosticKind
525#[derive(Copy, Clone)]
526#[repr(C)]
527#[allow(dead_code)] // Variants constructed by C++.
528pub(crate) enum DiagnosticKind {
529    Other,
530    InlineAsm,
531    StackSize,
532    DebugMetadataVersion,
533    SampleProfile,
534    OptimizationRemark,
535    OptimizationRemarkMissed,
536    OptimizationRemarkAnalysis,
537    OptimizationRemarkAnalysisFPCommute,
538    OptimizationRemarkAnalysisAliasing,
539    OptimizationRemarkOther,
540    OptimizationFailure,
541    PGOProfile,
542    Linker,
543    Unsupported,
544    SrcMgr,
545}
546
547/// LLVMRustDiagnosticLevel
548#[derive(Copy, Clone)]
549#[repr(C)]
550#[allow(dead_code)] // Variants constructed by C++.
551pub(crate) enum DiagnosticLevel {
552    Error,
553    Warning,
554    Note,
555    Remark,
556}
557
558unsafe extern "C" {
559    // LLVMRustThinLTOData
560    pub(crate) type ThinLTOData;
561
562    // LLVMRustThinLTOBuffer
563    pub(crate) type ThinLTOBuffer;
564}
565
566/// LLVMRustThinLTOModule
567#[repr(C)]
568pub(crate) struct ThinLTOModule {
569    pub identifier: *const c_char,
570    pub data: *const u8,
571    pub len: usize,
572}
573
574/// LLVMThreadLocalMode
575#[derive(Copy, Clone)]
576#[repr(C)]
577pub(crate) enum ThreadLocalMode {
578    #[expect(dead_code)]
579    NotThreadLocal,
580    GeneralDynamic,
581    LocalDynamic,
582    InitialExec,
583    LocalExec,
584}
585
586/// LLVMRustChecksumKind
587#[derive(Copy, Clone)]
588#[repr(C)]
589pub(crate) enum ChecksumKind {
590    None,
591    MD5,
592    SHA1,
593    SHA256,
594}
595
596/// LLVMRustMemoryEffects
597#[derive(Copy, Clone)]
598#[repr(C)]
599pub(crate) enum MemoryEffects {
600    None,
601    ReadOnly,
602    InaccessibleMemOnly,
603    ReadOnlyNotPure,
604}
605
606/// LLVMOpcode
607#[derive(Copy, Clone, PartialEq, Eq)]
608#[repr(C)]
609#[expect(dead_code, reason = "Some variants are unused, but are kept to match LLVM-C")]
610pub(crate) enum Opcode {
611    Ret = 1,
612    Br = 2,
613    Switch = 3,
614    IndirectBr = 4,
615    Invoke = 5,
616    Unreachable = 7,
617    CallBr = 67,
618    FNeg = 66,
619    Add = 8,
620    FAdd = 9,
621    Sub = 10,
622    FSub = 11,
623    Mul = 12,
624    FMul = 13,
625    UDiv = 14,
626    SDiv = 15,
627    FDiv = 16,
628    URem = 17,
629    SRem = 18,
630    FRem = 19,
631    Shl = 20,
632    LShr = 21,
633    AShr = 22,
634    And = 23,
635    Or = 24,
636    Xor = 25,
637    Alloca = 26,
638    Load = 27,
639    Store = 28,
640    GetElementPtr = 29,
641    Trunc = 30,
642    ZExt = 31,
643    SExt = 32,
644    FPToUI = 33,
645    FPToSI = 34,
646    UIToFP = 35,
647    SIToFP = 36,
648    FPTrunc = 37,
649    FPExt = 38,
650    PtrToInt = 39,
651    IntToPtr = 40,
652    BitCast = 41,
653    AddrSpaceCast = 60,
654    ICmp = 42,
655    FCmp = 43,
656    PHI = 44,
657    Call = 45,
658    Select = 46,
659    UserOp1 = 47,
660    UserOp2 = 48,
661    VAArg = 49,
662    ExtractElement = 50,
663    InsertElement = 51,
664    ShuffleVector = 52,
665    ExtractValue = 53,
666    InsertValue = 54,
667    Freeze = 68,
668    Fence = 55,
669    AtomicCmpXchg = 56,
670    AtomicRMW = 57,
671    Resume = 58,
672    LandingPad = 59,
673    CleanupRet = 61,
674    CatchRet = 62,
675    CatchPad = 63,
676    CleanupPad = 64,
677    CatchSwitch = 65,
678}
679
680unsafe extern "C" {
681    type Opaque;
682}
683#[repr(C)]
684struct InvariantOpaque<'a> {
685    _marker: PhantomData<&'a mut &'a ()>,
686    _opaque: Opaque,
687}
688
689// Opaque pointer types
690unsafe extern "C" {
691    pub(crate) type Module;
692    pub(crate) type Context;
693    pub(crate) type Type;
694    pub(crate) type Value;
695    pub(crate) type ConstantInt;
696    pub(crate) type Attribute;
697    pub(crate) type Metadata;
698    pub(crate) type BasicBlock;
699    pub(crate) type Comdat;
700    /// `&'ll DbgRecord` represents `LLVMDbgRecordRef`.
701    pub(crate) type DbgRecord;
702}
703#[repr(C)]
704pub(crate) struct Builder<'a>(InvariantOpaque<'a>);
705#[repr(C)]
706pub(crate) struct PassManager<'a>(InvariantOpaque<'a>);
707unsafe extern "C" {
708    pub type TargetMachine;
709}
710unsafe extern "C" {
711    pub(crate) type Twine;
712    pub(crate) type DiagnosticInfo;
713    pub(crate) type SMDiagnostic;
714}
715/// Opaque pointee of `LLVMOperandBundleRef`.
716#[repr(C)]
717pub(crate) struct OperandBundle<'a>(InvariantOpaque<'a>);
718#[repr(C)]
719pub(crate) struct Linker<'a>(InvariantOpaque<'a>);
720
721unsafe extern "C" {
722    pub(crate) type DiagnosticHandler;
723}
724
725pub(crate) type DiagnosticHandlerTy = unsafe extern "C" fn(&DiagnosticInfo, *mut c_void);
726
727pub(crate) mod debuginfo {
728    use std::ptr;
729
730    use bitflags::bitflags;
731
732    use super::{InvariantOpaque, Metadata};
733    use crate::llvm::{self, Module};
734
735    /// Opaque target type for references to an LLVM debuginfo builder.
736    ///
737    /// `&'_ DIBuilder<'ll>` corresponds to `LLVMDIBuilderRef`, which is the
738    /// LLVM-C wrapper for `DIBuilder *`.
739    ///
740    /// Debuginfo builders are created and destroyed during codegen, so the
741    /// builder reference typically has a shorter lifetime than the LLVM
742    /// session (`'ll`) that it participates in.
743    #[repr(C)]
744    pub(crate) struct DIBuilder<'ll>(InvariantOpaque<'ll>);
745
746    /// Owning pointer to a `DIBuilder<'ll>` that will dispose of the builder
747    /// when dropped. Use `.as_ref()` to get the underlying `&DIBuilder`
748    /// needed for debuginfo FFI calls.
749    pub(crate) struct DIBuilderBox<'ll> {
750        raw: ptr::NonNull<DIBuilder<'ll>>,
751    }
752
753    impl<'ll> DIBuilderBox<'ll> {
754        pub(crate) fn new(llmod: &'ll Module) -> Self {
755            let raw = unsafe { llvm::LLVMCreateDIBuilder(llmod) };
756            let raw = ptr::NonNull::new(raw).unwrap();
757            Self { raw }
758        }
759
760        pub(crate) fn as_ref(&self) -> &DIBuilder<'ll> {
761            // SAFETY: This is an owning pointer, so `&DIBuilder` is valid
762            // for as long as `&self` is.
763            unsafe { self.raw.as_ref() }
764        }
765    }
766
767    impl<'ll> Drop for DIBuilderBox<'ll> {
768        fn drop(&mut self) {
769            unsafe { llvm::LLVMDisposeDIBuilder(self.raw) };
770        }
771    }
772
773    pub(crate) type DIDescriptor = Metadata;
774    pub(crate) type DILocation = Metadata;
775    pub(crate) type DIScope = DIDescriptor;
776    pub(crate) type DIFile = DIScope;
777    pub(crate) type DILexicalBlock = DIScope;
778    pub(crate) type DISubprogram = DIScope;
779    pub(crate) type DIType = DIDescriptor;
780    pub(crate) type DIBasicType = DIType;
781    pub(crate) type DIDerivedType = DIType;
782    pub(crate) type DICompositeType = DIDerivedType;
783    pub(crate) type DIVariable = DIDescriptor;
784    pub(crate) type DIArray = DIDescriptor;
785    pub(crate) type DIEnumerator = DIDescriptor;
786    pub(crate) type DITemplateTypeParameter = DIDescriptor;
787
788    bitflags! {
789        /// Must match the layout of `LLVMDIFlags` in the LLVM-C API.
790        ///
791        /// Each value declared here must also be covered by the static
792        /// assertions in `RustWrapper.cpp` used by `fromRust(LLVMDIFlags)`.
793        #[repr(transparent)]
794        #[derive(Clone, Copy, Default)]
795        pub(crate) struct DIFlags: u32 {
796            const FlagZero                = 0;
797            const FlagPrivate             = 1;
798            const FlagProtected           = 2;
799            const FlagPublic              = 3;
800            const FlagFwdDecl             = (1 << 2);
801            const FlagAppleBlock          = (1 << 3);
802            const FlagReservedBit4        = (1 << 4);
803            const FlagVirtual             = (1 << 5);
804            const FlagArtificial          = (1 << 6);
805            const FlagExplicit            = (1 << 7);
806            const FlagPrototyped          = (1 << 8);
807            const FlagObjcClassComplete   = (1 << 9);
808            const FlagObjectPointer       = (1 << 10);
809            const FlagVector              = (1 << 11);
810            const FlagStaticMember        = (1 << 12);
811            const FlagLValueReference     = (1 << 13);
812            const FlagRValueReference     = (1 << 14);
813            const FlagReserved            = (1 << 15);
814            const FlagSingleInheritance   = (1 << 16);
815            const FlagMultipleInheritance = (2 << 16);
816            const FlagVirtualInheritance  = (3 << 16);
817            const FlagIntroducedVirtual   = (1 << 18);
818            const FlagBitField            = (1 << 19);
819            const FlagNoReturn            = (1 << 20);
820            // The bit at (1 << 21) is unused, but was `LLVMDIFlagMainSubprogram`.
821            const FlagTypePassByValue     = (1 << 22);
822            const FlagTypePassByReference = (1 << 23);
823            const FlagEnumClass           = (1 << 24);
824            const FlagThunk               = (1 << 25);
825            const FlagNonTrivial          = (1 << 26);
826            const FlagBigEndian           = (1 << 27);
827            const FlagLittleEndian        = (1 << 28);
828        }
829    }
830
831    // These values **must** match with LLVMRustDISPFlags!!
832    bitflags! {
833        #[repr(transparent)]
834        #[derive(Clone, Copy, Default)]
835        pub(crate) struct DISPFlags: u32 {
836            const SPFlagZero              = 0;
837            const SPFlagVirtual           = 1;
838            const SPFlagPureVirtual       = 2;
839            const SPFlagLocalToUnit       = (1 << 2);
840            const SPFlagDefinition        = (1 << 3);
841            const SPFlagOptimized         = (1 << 4);
842            const SPFlagMainSubprogram    = (1 << 5);
843        }
844    }
845
846    /// LLVMRustDebugEmissionKind
847    #[derive(Copy, Clone)]
848    #[repr(C)]
849    pub(crate) enum DebugEmissionKind {
850        NoDebug,
851        FullDebug,
852        LineTablesOnly,
853        DebugDirectivesOnly,
854    }
855
856    /// LLVMRustDebugNameTableKind
857    #[derive(Clone, Copy)]
858    #[repr(C)]
859    pub(crate) enum DebugNameTableKind {
860        Default,
861        #[expect(dead_code)]
862        Gnu,
863        None,
864    }
865}
866
867// These values **must** match with LLVMRustAllocKindFlags
868bitflags! {
869    #[repr(transparent)]
870    #[derive(Default)]
871    pub(crate) struct AllocKindFlags : u64 {
872        const Unknown = 0;
873        const Alloc = 1;
874        const Realloc = 1 << 1;
875        const Free = 1 << 2;
876        const Uninitialized = 1 << 3;
877        const Zeroed = 1 << 4;
878        const Aligned = 1 << 5;
879    }
880}
881
882// These values **must** match with LLVMGEPNoWrapFlags
883bitflags! {
884    #[repr(transparent)]
885    #[derive(Default)]
886    pub struct GEPNoWrapFlags : c_uint {
887        const InBounds = 1 << 0;
888        const NUSW = 1 << 1;
889        const NUW = 1 << 2;
890    }
891}
892
893unsafe extern "C" {
894    pub(crate) type ModuleBuffer;
895}
896
897pub(crate) type SelfProfileBeforePassCallback =
898    unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char);
899pub(crate) type SelfProfileAfterPassCallback = unsafe extern "C" fn(*mut c_void);
900
901pub(crate) type GetSymbolsCallback =
902    unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void;
903pub(crate) type GetSymbolsErrorCallback = unsafe extern "C" fn(*const c_char) -> *mut c_void;
904
905unsafe extern "C" {
906    // Create and destroy contexts.
907    pub(crate) fn LLVMContextCreate() -> &'static mut Context;
908    pub(crate) fn LLVMContextDispose(C: &'static mut Context);
909    pub(crate) fn LLVMContextSetDiscardValueNames(C: &Context, Discard: Bool);
910    pub(crate) fn LLVMGetMDKindIDInContext(
911        C: &Context,
912        Name: *const c_char,
913        SLen: c_uint,
914    ) -> MetadataKindId;
915
916    pub(crate) fn LLVMDisposeTargetMachine(T: ptr::NonNull<TargetMachine>);
917
918    // Create modules.
919    pub(crate) fn LLVMModuleCreateWithNameInContext(
920        ModuleID: *const c_char,
921        C: &Context,
922    ) -> &Module;
923    pub(crate) safe fn LLVMCloneModule(M: &Module) -> &Module;
924
925    /// Data layout. See Module::getDataLayout.
926    pub(crate) fn LLVMGetDataLayoutStr(M: &Module) -> *const c_char;
927    pub(crate) fn LLVMSetDataLayout(M: &Module, Triple: *const c_char);
928
929    /// Append inline assembly to a module. See `Module::appendModuleInlineAsm`.
930    pub(crate) fn LLVMAppendModuleInlineAsm(
931        M: &Module,
932        Asm: *const c_uchar, // See "PTR_LEN_STR".
933        Len: size_t,
934    );
935
936    /// Create the specified uniqued inline asm string. See `InlineAsm::get()`.
937    pub(crate) fn LLVMGetInlineAsm<'ll>(
938        Ty: &'ll Type,
939        AsmString: *const c_uchar, // See "PTR_LEN_STR".
940        AsmStringSize: size_t,
941        Constraints: *const c_uchar, // See "PTR_LEN_STR".
942        ConstraintsSize: size_t,
943        HasSideEffects: llvm::Bool,
944        IsAlignStack: llvm::Bool,
945        Dialect: AsmDialect,
946        CanThrow: llvm::Bool,
947    ) -> &'ll Value;
948
949    pub(crate) safe fn LLVMGetTypeKind(Ty: &Type) -> RawEnum<TypeKind>;
950
951    // Operations on integer types
952    pub(crate) fn LLVMInt1TypeInContext(C: &Context) -> &Type;
953    pub(crate) fn LLVMInt8TypeInContext(C: &Context) -> &Type;
954    pub(crate) fn LLVMInt16TypeInContext(C: &Context) -> &Type;
955    pub(crate) fn LLVMInt32TypeInContext(C: &Context) -> &Type;
956    pub(crate) fn LLVMInt64TypeInContext(C: &Context) -> &Type;
957    pub(crate) safe fn LLVMIntTypeInContext(C: &Context, NumBits: c_uint) -> &Type;
958
959    pub(crate) fn LLVMGetIntTypeWidth(IntegerTy: &Type) -> c_uint;
960
961    // Operations on real types
962    pub(crate) fn LLVMHalfTypeInContext(C: &Context) -> &Type;
963    pub(crate) fn LLVMFloatTypeInContext(C: &Context) -> &Type;
964    pub(crate) fn LLVMDoubleTypeInContext(C: &Context) -> &Type;
965    pub(crate) fn LLVMFP128TypeInContext(C: &Context) -> &Type;
966
967    // Operations on function types
968    pub(crate) fn LLVMFunctionType<'a>(
969        ReturnType: &'a Type,
970        ParamTypes: *const &'a Type,
971        ParamCount: c_uint,
972        IsVarArg: Bool,
973    ) -> &'a Type;
974    pub(crate) fn LLVMCountParamTypes(FunctionTy: &Type) -> c_uint;
975    pub(crate) fn LLVMGetParamTypes<'a>(FunctionTy: &'a Type, Dest: *mut &'a Type);
976
977    // Operations on struct types
978    pub(crate) fn LLVMStructTypeInContext<'a>(
979        C: &'a Context,
980        ElementTypes: *const &'a Type,
981        ElementCount: c_uint,
982        Packed: Bool,
983    ) -> &'a Type;
984
985    // Operations on array, pointer, and vector types (sequence types)
986    pub(crate) safe fn LLVMPointerTypeInContext(C: &Context, AddressSpace: c_uint) -> &Type;
987    pub(crate) fn LLVMVectorType(ElementType: &Type, ElementCount: c_uint) -> &Type;
988
989    pub(crate) fn LLVMGetElementType(Ty: &Type) -> &Type;
990    pub(crate) fn LLVMGetVectorSize(VectorTy: &Type) -> c_uint;
991
992    // Operations on other types
993    pub(crate) fn LLVMVoidTypeInContext(C: &Context) -> &Type;
994
995    // Operations on all values
996    pub(crate) fn LLVMTypeOf(Val: &Value) -> &Type;
997    pub(crate) fn LLVMGetValueName2(Val: &Value, Length: *mut size_t) -> *const c_char;
998    pub(crate) fn LLVMSetValueName2(Val: &Value, Name: *const c_char, NameLen: size_t);
999    pub(crate) fn LLVMReplaceAllUsesWith<'a>(OldVal: &'a Value, NewVal: &'a Value);
1000    pub(crate) safe fn LLVMSetMetadata<'a>(Val: &'a Value, KindID: MetadataKindId, Node: &'a Value);
1001    pub(crate) fn LLVMGlobalSetMetadata<'a>(
1002        Val: &'a Value,
1003        KindID: MetadataKindId,
1004        Metadata: &'a Metadata,
1005    );
1006    pub(crate) safe fn LLVMValueAsMetadata(Node: &Value) -> &Metadata;
1007
1008    // Operations on constants of any type
1009    pub(crate) fn LLVMConstNull(Ty: &Type) -> &Value;
1010    pub(crate) fn LLVMGetUndef(Ty: &Type) -> &Value;
1011    pub(crate) fn LLVMGetPoison(Ty: &Type) -> &Value;
1012
1013    // Operations on metadata
1014    pub(crate) fn LLVMMDStringInContext2(
1015        C: &Context,
1016        Str: *const c_char,
1017        SLen: size_t,
1018    ) -> &Metadata;
1019    pub(crate) fn LLVMMDNodeInContext2<'a>(
1020        C: &'a Context,
1021        Vals: *const &'a Metadata,
1022        Count: size_t,
1023    ) -> &'a Metadata;
1024    pub(crate) fn LLVMAddNamedMetadataOperand<'a>(
1025        M: &'a Module,
1026        Name: *const c_char,
1027        Val: &'a Value,
1028    );
1029
1030    // Operations on scalar constants
1031    pub(crate) fn LLVMConstInt(IntTy: &Type, N: c_ulonglong, SignExtend: Bool) -> &Value;
1032    pub(crate) fn LLVMConstIntOfArbitraryPrecision(
1033        IntTy: &Type,
1034        Wn: c_uint,
1035        Ws: *const u64,
1036    ) -> &Value;
1037    pub(crate) fn LLVMConstReal(RealTy: &Type, N: f64) -> &Value;
1038
1039    // Operations on composite constants
1040    pub(crate) fn LLVMConstArray2<'a>(
1041        ElementTy: &'a Type,
1042        ConstantVals: *const &'a Value,
1043        Length: u64,
1044    ) -> &'a Value;
1045    pub(crate) fn LLVMArrayType2(ElementType: &Type, ElementCount: u64) -> &Type;
1046    pub(crate) fn LLVMConstStringInContext2(
1047        C: &Context,
1048        Str: *const c_char,
1049        Length: size_t,
1050        DontNullTerminate: Bool,
1051    ) -> &Value;
1052    pub(crate) fn LLVMConstStructInContext<'a>(
1053        C: &'a Context,
1054        ConstantVals: *const &'a Value,
1055        Count: c_uint,
1056        Packed: Bool,
1057    ) -> &'a Value;
1058    pub(crate) fn LLVMConstNamedStruct<'a>(
1059        StructTy: &'a Type,
1060        ConstantVals: *const &'a Value,
1061        Count: c_uint,
1062    ) -> &'a Value;
1063    pub(crate) fn LLVMConstVector(ScalarConstantVals: *const &Value, Size: c_uint) -> &Value;
1064
1065    // Constant expressions
1066    pub(crate) fn LLVMConstInBoundsGEP2<'a>(
1067        ty: &'a Type,
1068        ConstantVal: &'a Value,
1069        ConstantIndices: *const &'a Value,
1070        NumIndices: c_uint,
1071    ) -> &'a Value;
1072    pub(crate) fn LLVMConstPtrToInt<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1073    pub(crate) fn LLVMConstIntToPtr<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1074    pub(crate) fn LLVMConstBitCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1075    pub(crate) fn LLVMConstPointerCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1076    pub(crate) fn LLVMGetAggregateElement(ConstantVal: &Value, Idx: c_uint) -> Option<&Value>;
1077    pub(crate) fn LLVMGetConstOpcode(ConstantVal: &Value) -> Opcode;
1078    pub(crate) fn LLVMIsAConstantExpr(Val: &Value) -> Option<&Value>;
1079
1080    // Operations on global variables, functions, and aliases (globals)
1081    pub(crate) fn LLVMIsDeclaration(Global: &Value) -> Bool;
1082    pub(crate) fn LLVMGetLinkage(Global: &Value) -> RawEnum<Linkage>;
1083    pub(crate) fn LLVMSetLinkage(Global: &Value, RustLinkage: Linkage);
1084    pub(crate) fn LLVMSetSection(Global: &Value, Section: *const c_char);
1085    pub(crate) fn LLVMGetVisibility(Global: &Value) -> RawEnum<Visibility>;
1086    pub(crate) fn LLVMSetVisibility(Global: &Value, Viz: Visibility);
1087    pub(crate) fn LLVMGetAlignment(Global: &Value) -> c_uint;
1088    pub(crate) fn LLVMSetAlignment(Global: &Value, Bytes: c_uint);
1089    pub(crate) fn LLVMSetDLLStorageClass(V: &Value, C: DLLStorageClass);
1090    pub(crate) fn LLVMGlobalGetValueType(Global: &Value) -> &Type;
1091
1092    // Operations on global variables
1093    pub(crate) safe fn LLVMIsAGlobalVariable(GlobalVar: &Value) -> Option<&Value>;
1094    pub(crate) fn LLVMAddGlobal<'a>(M: &'a Module, Ty: &'a Type, Name: *const c_char) -> &'a Value;
1095    pub(crate) fn LLVMGetNamedGlobal(M: &Module, Name: *const c_char) -> Option<&Value>;
1096    pub(crate) fn LLVMGetFirstGlobal(M: &Module) -> Option<&Value>;
1097    pub(crate) fn LLVMGetNextGlobal(GlobalVar: &Value) -> Option<&Value>;
1098    pub(crate) fn LLVMDeleteGlobal(GlobalVar: &Value);
1099    pub(crate) safe fn LLVMGetInitializer(GlobalVar: &Value) -> Option<&Value>;
1100    pub(crate) fn LLVMSetInitializer<'a>(GlobalVar: &'a Value, ConstantVal: &'a Value);
1101    pub(crate) safe fn LLVMIsThreadLocal(GlobalVar: &Value) -> Bool;
1102    pub(crate) fn LLVMSetThreadLocalMode(GlobalVar: &Value, Mode: ThreadLocalMode);
1103    pub(crate) safe fn LLVMIsGlobalConstant(GlobalVar: &Value) -> Bool;
1104    pub(crate) safe fn LLVMSetGlobalConstant(GlobalVar: &Value, IsConstant: Bool);
1105    pub(crate) safe fn LLVMSetTailCall(CallInst: &Value, IsTailCall: Bool);
1106    pub(crate) safe fn LLVMSetTailCallKind(CallInst: &Value, kind: TailCallKind);
1107    pub(crate) safe fn LLVMSetExternallyInitialized(GlobalVar: &Value, IsExtInit: Bool);
1108
1109    // Operations on attributes
1110    pub(crate) fn LLVMCreateStringAttribute(
1111        C: &Context,
1112        Name: *const c_char,
1113        NameLen: c_uint,
1114        Value: *const c_char,
1115        ValueLen: c_uint,
1116    ) -> &Attribute;
1117
1118    // Operations on functions
1119    pub(crate) fn LLVMSetFunctionCallConv(Fn: &Value, CC: c_uint);
1120    pub(crate) fn LLVMDeleteFunction(Fn: &Value);
1121
1122    // Operations about llvm intrinsics
1123    pub(crate) fn LLVMLookupIntrinsicID(Name: *const c_char, NameLen: size_t) -> c_uint;
1124    pub(crate) fn LLVMGetIntrinsicDeclaration<'a>(
1125        Mod: &'a Module,
1126        ID: NonZero<c_uint>,
1127        ParamTypes: *const &'a Type,
1128        ParamCount: size_t,
1129    ) -> &'a Value;
1130
1131    // Operations on parameters
1132    pub(crate) fn LLVMIsAArgument(Val: &Value) -> Option<&Value>;
1133    pub(crate) safe fn LLVMCountParams(Fn: &Value) -> c_uint;
1134    pub(crate) fn LLVMGetParam(Fn: &Value, Index: c_uint) -> &Value;
1135
1136    // Operations on basic blocks
1137    pub(crate) fn LLVMGetBasicBlockParent(BB: &BasicBlock) -> &Value;
1138    pub(crate) fn LLVMAppendBasicBlockInContext<'a>(
1139        C: &'a Context,
1140        Fn: &'a Value,
1141        Name: *const c_char,
1142    ) -> &'a BasicBlock;
1143
1144    // Operations on instructions
1145    pub(crate) fn LLVMGetInstructionParent(Inst: &Value) -> &BasicBlock;
1146    pub(crate) fn LLVMGetCalledValue(CallInst: &Value) -> Option<&Value>;
1147    pub(crate) fn LLVMIsAInstruction(Val: &Value) -> Option<&Value>;
1148    pub(crate) fn LLVMGetFirstBasicBlock(Fn: &Value) -> &BasicBlock;
1149    pub(crate) fn LLVMGetOperand(Val: &Value, Index: c_uint) -> Option<&Value>;
1150    pub(crate) fn LLVMGetNextInstruction(Val: &Value) -> Option<&Value>;
1151    pub(crate) fn LLVMInstructionEraseFromParent(Val: &Value);
1152
1153    // Operations on call sites
1154    pub(crate) fn LLVMSetInstructionCallConv(Instr: &Value, CC: c_uint);
1155
1156    // Operations on load/store instructions (only)
1157    pub(crate) fn LLVMSetVolatile(MemoryAccessInst: &Value, volatile: Bool);
1158    pub(crate) fn LLVMSetOrdering(MemoryAccessInst: &Value, Ordering: AtomicOrdering);
1159
1160    // Operations on phi nodes
1161    pub(crate) fn LLVMAddIncoming<'a>(
1162        PhiNode: &'a Value,
1163        IncomingValues: *const &'a Value,
1164        IncomingBlocks: *const &'a BasicBlock,
1165        Count: c_uint,
1166    );
1167
1168    // Instruction builders
1169    pub(crate) fn LLVMCreateBuilderInContext(C: &Context) -> &mut Builder<'_>;
1170    pub(crate) fn LLVMPositionBuilderAtEnd<'a>(Builder: &Builder<'a>, Block: &'a BasicBlock);
1171    pub(crate) fn LLVMGetInsertBlock<'a>(Builder: &Builder<'a>) -> &'a BasicBlock;
1172    pub(crate) fn LLVMDisposeBuilder<'a>(Builder: &'a mut Builder<'a>);
1173
1174    // Metadata
1175    pub(crate) fn LLVMSetCurrentDebugLocation2<'a>(Builder: &Builder<'a>, Loc: *const Metadata);
1176    pub(crate) fn LLVMGetCurrentDebugLocation2<'a>(Builder: &Builder<'a>) -> Option<&'a Metadata>;
1177
1178    // Terminators
1179    pub(crate) safe fn LLVMBuildRetVoid<'a>(B: &Builder<'a>) -> &'a Value;
1180    pub(crate) fn LLVMBuildRet<'a>(B: &Builder<'a>, V: &'a Value) -> &'a Value;
1181    pub(crate) fn LLVMBuildBr<'a>(B: &Builder<'a>, Dest: &'a BasicBlock) -> &'a Value;
1182    pub(crate) fn LLVMBuildCondBr<'a>(
1183        B: &Builder<'a>,
1184        If: &'a Value,
1185        Then: &'a BasicBlock,
1186        Else: &'a BasicBlock,
1187    ) -> &'a Value;
1188    pub(crate) fn LLVMBuildSwitch<'a>(
1189        B: &Builder<'a>,
1190        V: &'a Value,
1191        Else: &'a BasicBlock,
1192        NumCases: c_uint,
1193    ) -> &'a Value;
1194    pub(crate) fn LLVMBuildLandingPad<'a>(
1195        B: &Builder<'a>,
1196        Ty: &'a Type,
1197        PersFn: Option<&'a Value>,
1198        NumClauses: c_uint,
1199        Name: *const c_char,
1200    ) -> &'a Value;
1201    pub(crate) fn LLVMBuildResume<'a>(B: &Builder<'a>, Exn: &'a Value) -> &'a Value;
1202    pub(crate) fn LLVMBuildUnreachable<'a>(B: &Builder<'a>) -> &'a Value;
1203
1204    pub(crate) fn LLVMBuildCleanupPad<'a>(
1205        B: &Builder<'a>,
1206        ParentPad: Option<&'a Value>,
1207        Args: *const &'a Value,
1208        NumArgs: c_uint,
1209        Name: *const c_char,
1210    ) -> Option<&'a Value>;
1211    pub(crate) fn LLVMBuildCleanupRet<'a>(
1212        B: &Builder<'a>,
1213        CleanupPad: &'a Value,
1214        BB: Option<&'a BasicBlock>,
1215    ) -> Option<&'a Value>;
1216    pub(crate) fn LLVMBuildCatchPad<'a>(
1217        B: &Builder<'a>,
1218        ParentPad: &'a Value,
1219        Args: *const &'a Value,
1220        NumArgs: c_uint,
1221        Name: *const c_char,
1222    ) -> Option<&'a Value>;
1223    pub(crate) fn LLVMBuildCatchRet<'a>(
1224        B: &Builder<'a>,
1225        CatchPad: &'a Value,
1226        BB: &'a BasicBlock,
1227    ) -> Option<&'a Value>;
1228    pub(crate) fn LLVMBuildCatchSwitch<'a>(
1229        Builder: &Builder<'a>,
1230        ParentPad: Option<&'a Value>,
1231        UnwindBB: Option<&'a BasicBlock>,
1232        NumHandlers: c_uint,
1233        Name: *const c_char,
1234    ) -> Option<&'a Value>;
1235    pub(crate) fn LLVMAddHandler<'a>(CatchSwitch: &'a Value, Dest: &'a BasicBlock);
1236    pub(crate) fn LLVMSetPersonalityFn<'a>(Func: &'a Value, Pers: &'a Value);
1237
1238    // Add a case to the switch instruction
1239    pub(crate) fn LLVMAddCase<'a>(Switch: &'a Value, OnVal: &'a Value, Dest: &'a BasicBlock);
1240
1241    // Add a clause to the landing pad instruction
1242    pub(crate) fn LLVMAddClause<'a>(LandingPad: &'a Value, ClauseVal: &'a Value);
1243
1244    // Set the cleanup on a landing pad instruction
1245    pub(crate) fn LLVMSetCleanup(LandingPad: &Value, Val: Bool);
1246
1247    // Arithmetic
1248    pub(crate) fn LLVMBuildAdd<'a>(
1249        B: &Builder<'a>,
1250        LHS: &'a Value,
1251        RHS: &'a Value,
1252        Name: *const c_char,
1253    ) -> &'a Value;
1254    pub(crate) fn LLVMBuildFAdd<'a>(
1255        B: &Builder<'a>,
1256        LHS: &'a Value,
1257        RHS: &'a Value,
1258        Name: *const c_char,
1259    ) -> &'a Value;
1260    pub(crate) fn LLVMBuildSub<'a>(
1261        B: &Builder<'a>,
1262        LHS: &'a Value,
1263        RHS: &'a Value,
1264        Name: *const c_char,
1265    ) -> &'a Value;
1266    pub(crate) fn LLVMBuildFSub<'a>(
1267        B: &Builder<'a>,
1268        LHS: &'a Value,
1269        RHS: &'a Value,
1270        Name: *const c_char,
1271    ) -> &'a Value;
1272    pub(crate) fn LLVMBuildMul<'a>(
1273        B: &Builder<'a>,
1274        LHS: &'a Value,
1275        RHS: &'a Value,
1276        Name: *const c_char,
1277    ) -> &'a Value;
1278    pub(crate) fn LLVMBuildFMul<'a>(
1279        B: &Builder<'a>,
1280        LHS: &'a Value,
1281        RHS: &'a Value,
1282        Name: *const c_char,
1283    ) -> &'a Value;
1284    pub(crate) fn LLVMBuildUDiv<'a>(
1285        B: &Builder<'a>,
1286        LHS: &'a Value,
1287        RHS: &'a Value,
1288        Name: *const c_char,
1289    ) -> &'a Value;
1290    pub(crate) fn LLVMBuildExactUDiv<'a>(
1291        B: &Builder<'a>,
1292        LHS: &'a Value,
1293        RHS: &'a Value,
1294        Name: *const c_char,
1295    ) -> &'a Value;
1296    pub(crate) fn LLVMBuildSDiv<'a>(
1297        B: &Builder<'a>,
1298        LHS: &'a Value,
1299        RHS: &'a Value,
1300        Name: *const c_char,
1301    ) -> &'a Value;
1302    pub(crate) fn LLVMBuildExactSDiv<'a>(
1303        B: &Builder<'a>,
1304        LHS: &'a Value,
1305        RHS: &'a Value,
1306        Name: *const c_char,
1307    ) -> &'a Value;
1308    pub(crate) fn LLVMBuildFDiv<'a>(
1309        B: &Builder<'a>,
1310        LHS: &'a Value,
1311        RHS: &'a Value,
1312        Name: *const c_char,
1313    ) -> &'a Value;
1314    pub(crate) fn LLVMBuildURem<'a>(
1315        B: &Builder<'a>,
1316        LHS: &'a Value,
1317        RHS: &'a Value,
1318        Name: *const c_char,
1319    ) -> &'a Value;
1320    pub(crate) fn LLVMBuildSRem<'a>(
1321        B: &Builder<'a>,
1322        LHS: &'a Value,
1323        RHS: &'a Value,
1324        Name: *const c_char,
1325    ) -> &'a Value;
1326    pub(crate) fn LLVMBuildFRem<'a>(
1327        B: &Builder<'a>,
1328        LHS: &'a Value,
1329        RHS: &'a Value,
1330        Name: *const c_char,
1331    ) -> &'a Value;
1332    pub(crate) fn LLVMBuildShl<'a>(
1333        B: &Builder<'a>,
1334        LHS: &'a Value,
1335        RHS: &'a Value,
1336        Name: *const c_char,
1337    ) -> &'a Value;
1338    pub(crate) fn LLVMBuildLShr<'a>(
1339        B: &Builder<'a>,
1340        LHS: &'a Value,
1341        RHS: &'a Value,
1342        Name: *const c_char,
1343    ) -> &'a Value;
1344    pub(crate) fn LLVMBuildAShr<'a>(
1345        B: &Builder<'a>,
1346        LHS: &'a Value,
1347        RHS: &'a Value,
1348        Name: *const c_char,
1349    ) -> &'a Value;
1350    pub(crate) fn LLVMBuildNSWAdd<'a>(
1351        B: &Builder<'a>,
1352        LHS: &'a Value,
1353        RHS: &'a Value,
1354        Name: *const c_char,
1355    ) -> &'a Value;
1356    pub(crate) fn LLVMBuildNUWAdd<'a>(
1357        B: &Builder<'a>,
1358        LHS: &'a Value,
1359        RHS: &'a Value,
1360        Name: *const c_char,
1361    ) -> &'a Value;
1362    pub(crate) fn LLVMBuildNSWSub<'a>(
1363        B: &Builder<'a>,
1364        LHS: &'a Value,
1365        RHS: &'a Value,
1366        Name: *const c_char,
1367    ) -> &'a Value;
1368    pub(crate) fn LLVMBuildNUWSub<'a>(
1369        B: &Builder<'a>,
1370        LHS: &'a Value,
1371        RHS: &'a Value,
1372        Name: *const c_char,
1373    ) -> &'a Value;
1374    pub(crate) fn LLVMBuildNSWMul<'a>(
1375        B: &Builder<'a>,
1376        LHS: &'a Value,
1377        RHS: &'a Value,
1378        Name: *const c_char,
1379    ) -> &'a Value;
1380    pub(crate) fn LLVMBuildNUWMul<'a>(
1381        B: &Builder<'a>,
1382        LHS: &'a Value,
1383        RHS: &'a Value,
1384        Name: *const c_char,
1385    ) -> &'a Value;
1386    pub(crate) fn LLVMBuildAnd<'a>(
1387        B: &Builder<'a>,
1388        LHS: &'a Value,
1389        RHS: &'a Value,
1390        Name: *const c_char,
1391    ) -> &'a Value;
1392    pub(crate) fn LLVMBuildOr<'a>(
1393        B: &Builder<'a>,
1394        LHS: &'a Value,
1395        RHS: &'a Value,
1396        Name: *const c_char,
1397    ) -> &'a Value;
1398    pub(crate) fn LLVMBuildXor<'a>(
1399        B: &Builder<'a>,
1400        LHS: &'a Value,
1401        RHS: &'a Value,
1402        Name: *const c_char,
1403    ) -> &'a Value;
1404    pub(crate) fn LLVMBuildNeg<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char)
1405    -> &'a Value;
1406    pub(crate) fn LLVMBuildFNeg<'a>(
1407        B: &Builder<'a>,
1408        V: &'a Value,
1409        Name: *const c_char,
1410    ) -> &'a Value;
1411    pub(crate) fn LLVMBuildNot<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char)
1412    -> &'a Value;
1413
1414    // Extra flags on arithmetic
1415    pub(crate) fn LLVMSetIsDisjoint(Instr: &Value, IsDisjoint: Bool);
1416    pub(crate) fn LLVMSetNUW(ArithInst: &Value, HasNUW: Bool);
1417    pub(crate) fn LLVMSetNSW(ArithInst: &Value, HasNSW: Bool);
1418
1419    // Memory
1420    pub(crate) fn LLVMBuildAlloca<'a>(
1421        B: &Builder<'a>,
1422        Ty: &'a Type,
1423        Name: *const c_char,
1424    ) -> &'a Value;
1425    pub(crate) fn LLVMBuildLoad2<'a>(
1426        B: &Builder<'a>,
1427        Ty: &'a Type,
1428        PointerVal: &'a Value,
1429        Name: *const c_char,
1430    ) -> &'a Value;
1431
1432    pub(crate) fn LLVMBuildStore<'a>(B: &Builder<'a>, Val: &'a Value, Ptr: &'a Value) -> &'a Value;
1433
1434    pub(crate) fn LLVMBuildGEPWithNoWrapFlags<'a>(
1435        B: &Builder<'a>,
1436        Ty: &'a Type,
1437        Pointer: &'a Value,
1438        Indices: *const &'a Value,
1439        NumIndices: c_uint,
1440        Name: *const c_char,
1441        Flags: GEPNoWrapFlags,
1442    ) -> &'a Value;
1443
1444    // Casts
1445    pub(crate) fn LLVMBuildTrunc<'a>(
1446        B: &Builder<'a>,
1447        Val: &'a Value,
1448        DestTy: &'a Type,
1449        Name: *const c_char,
1450    ) -> &'a Value;
1451    pub(crate) fn LLVMBuildZExt<'a>(
1452        B: &Builder<'a>,
1453        Val: &'a Value,
1454        DestTy: &'a Type,
1455        Name: *const c_char,
1456    ) -> &'a Value;
1457    pub(crate) fn LLVMBuildSExt<'a>(
1458        B: &Builder<'a>,
1459        Val: &'a Value,
1460        DestTy: &'a Type,
1461        Name: *const c_char,
1462    ) -> &'a Value;
1463    pub(crate) fn LLVMBuildFPToUI<'a>(
1464        B: &Builder<'a>,
1465        Val: &'a Value,
1466        DestTy: &'a Type,
1467        Name: *const c_char,
1468    ) -> &'a Value;
1469    pub(crate) fn LLVMBuildFPToSI<'a>(
1470        B: &Builder<'a>,
1471        Val: &'a Value,
1472        DestTy: &'a Type,
1473        Name: *const c_char,
1474    ) -> &'a Value;
1475    pub(crate) fn LLVMBuildUIToFP<'a>(
1476        B: &Builder<'a>,
1477        Val: &'a Value,
1478        DestTy: &'a Type,
1479        Name: *const c_char,
1480    ) -> &'a Value;
1481    pub(crate) fn LLVMBuildSIToFP<'a>(
1482        B: &Builder<'a>,
1483        Val: &'a Value,
1484        DestTy: &'a Type,
1485        Name: *const c_char,
1486    ) -> &'a Value;
1487    pub(crate) fn LLVMBuildFPTrunc<'a>(
1488        B: &Builder<'a>,
1489        Val: &'a Value,
1490        DestTy: &'a Type,
1491        Name: *const c_char,
1492    ) -> &'a Value;
1493    pub(crate) fn LLVMBuildFPExt<'a>(
1494        B: &Builder<'a>,
1495        Val: &'a Value,
1496        DestTy: &'a Type,
1497        Name: *const c_char,
1498    ) -> &'a Value;
1499    pub(crate) fn LLVMBuildPtrToInt<'a>(
1500        B: &Builder<'a>,
1501        Val: &'a Value,
1502        DestTy: &'a Type,
1503        Name: *const c_char,
1504    ) -> &'a Value;
1505    pub(crate) fn LLVMBuildIntToPtr<'a>(
1506        B: &Builder<'a>,
1507        Val: &'a Value,
1508        DestTy: &'a Type,
1509        Name: *const c_char,
1510    ) -> &'a Value;
1511    pub(crate) fn LLVMBuildBitCast<'a>(
1512        B: &Builder<'a>,
1513        Val: &'a Value,
1514        DestTy: &'a Type,
1515        Name: *const c_char,
1516    ) -> &'a Value;
1517    pub(crate) fn LLVMBuildPointerCast<'a>(
1518        B: &Builder<'a>,
1519        Val: &'a Value,
1520        DestTy: &'a Type,
1521        Name: *const c_char,
1522    ) -> &'a Value;
1523    pub(crate) fn LLVMBuildIntCast2<'a>(
1524        B: &Builder<'a>,
1525        Val: &'a Value,
1526        DestTy: &'a Type,
1527        IsSigned: Bool,
1528        Name: *const c_char,
1529    ) -> &'a Value;
1530
1531    // Comparisons
1532    pub(crate) fn LLVMBuildICmp<'a>(
1533        B: &Builder<'a>,
1534        Op: c_uint,
1535        LHS: &'a Value,
1536        RHS: &'a Value,
1537        Name: *const c_char,
1538    ) -> &'a Value;
1539    pub(crate) fn LLVMBuildFCmp<'a>(
1540        B: &Builder<'a>,
1541        Op: c_uint,
1542        LHS: &'a Value,
1543        RHS: &'a Value,
1544        Name: *const c_char,
1545    ) -> &'a Value;
1546
1547    // Miscellaneous instructions
1548    pub(crate) fn LLVMBuildPhi<'a>(B: &Builder<'a>, Ty: &'a Type, Name: *const c_char)
1549    -> &'a Value;
1550    pub(crate) fn LLVMBuildSelect<'a>(
1551        B: &Builder<'a>,
1552        If: &'a Value,
1553        Then: &'a Value,
1554        Else: &'a Value,
1555        Name: *const c_char,
1556    ) -> &'a Value;
1557    pub(crate) fn LLVMBuildVAArg<'a>(
1558        B: &Builder<'a>,
1559        list: &'a Value,
1560        Ty: &'a Type,
1561        Name: *const c_char,
1562    ) -> &'a Value;
1563    pub(crate) fn LLVMBuildExtractElement<'a>(
1564        B: &Builder<'a>,
1565        VecVal: &'a Value,
1566        Index: &'a Value,
1567        Name: *const c_char,
1568    ) -> &'a Value;
1569    pub(crate) fn LLVMBuildInsertElement<'a>(
1570        B: &Builder<'a>,
1571        VecVal: &'a Value,
1572        EltVal: &'a Value,
1573        Index: &'a Value,
1574        Name: *const c_char,
1575    ) -> &'a Value;
1576    pub(crate) fn LLVMBuildShuffleVector<'a>(
1577        B: &Builder<'a>,
1578        V1: &'a Value,
1579        V2: &'a Value,
1580        Mask: &'a Value,
1581        Name: *const c_char,
1582    ) -> &'a Value;
1583    pub(crate) fn LLVMBuildExtractValue<'a>(
1584        B: &Builder<'a>,
1585        AggVal: &'a Value,
1586        Index: c_uint,
1587        Name: *const c_char,
1588    ) -> &'a Value;
1589    pub(crate) fn LLVMBuildInsertValue<'a>(
1590        B: &Builder<'a>,
1591        AggVal: &'a Value,
1592        EltVal: &'a Value,
1593        Index: c_uint,
1594        Name: *const c_char,
1595    ) -> &'a Value;
1596
1597    // Atomic Operations
1598    pub(crate) fn LLVMBuildAtomicCmpXchg<'a>(
1599        B: &Builder<'a>,
1600        LHS: &'a Value,
1601        CMP: &'a Value,
1602        RHS: &'a Value,
1603        Order: AtomicOrdering,
1604        FailureOrder: AtomicOrdering,
1605        SingleThreaded: Bool,
1606    ) -> &'a Value;
1607
1608    pub(crate) fn LLVMSetWeak(CmpXchgInst: &Value, IsWeak: Bool);
1609
1610    pub(crate) fn LLVMBuildAtomicRMW<'a>(
1611        B: &Builder<'a>,
1612        Op: AtomicRmwBinOp,
1613        LHS: &'a Value,
1614        RHS: &'a Value,
1615        Order: AtomicOrdering,
1616        SingleThreaded: Bool,
1617    ) -> &'a Value;
1618
1619    pub(crate) fn LLVMBuildFence<'a>(
1620        B: &Builder<'a>,
1621        Order: AtomicOrdering,
1622        SingleThreaded: Bool,
1623        Name: *const c_char,
1624    ) -> &'a Value;
1625
1626    /// Writes a module to the specified path. Returns 0 on success.
1627    pub(crate) fn LLVMWriteBitcodeToFile(M: &Module, Path: *const c_char) -> c_int;
1628
1629    /// Creates a legacy pass manager -- only used for final codegen.
1630    pub(crate) fn LLVMCreatePassManager<'a>() -> &'a mut PassManager<'a>;
1631
1632    pub(crate) fn LLVMAddAnalysisPasses<'a>(T: &'a TargetMachine, PM: &PassManager<'a>);
1633
1634    pub(crate) fn LLVMGetHostCPUFeatures() -> *mut c_char;
1635
1636    pub(crate) fn LLVMDisposeMessage(message: *mut c_char);
1637
1638    pub(crate) fn LLVMIsMultithreaded() -> Bool;
1639
1640    pub(crate) fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type;
1641
1642    pub(crate) fn LLVMStructSetBody<'a>(
1643        StructTy: &'a Type,
1644        ElementTypes: *const &'a Type,
1645        ElementCount: c_uint,
1646        Packed: Bool,
1647    );
1648
1649    pub(crate) safe fn LLVMMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value;
1650
1651    pub(crate) safe fn LLVMSetUnnamedAddress(Global: &Value, UnnamedAddr: UnnamedAddr);
1652
1653    pub(crate) fn LLVMIsAConstantInt(value_ref: &Value) -> Option<&ConstantInt>;
1654
1655    pub(crate) fn LLVMGetOrInsertComdat(M: &Module, Name: *const c_char) -> &Comdat;
1656    pub(crate) fn LLVMSetComdat(V: &Value, C: &Comdat);
1657
1658    pub(crate) fn LLVMCreateOperandBundle(
1659        Tag: *const c_char,
1660        TagLen: size_t,
1661        Args: *const &'_ Value,
1662        NumArgs: c_uint,
1663    ) -> *mut OperandBundle<'_>;
1664    pub(crate) fn LLVMDisposeOperandBundle(Bundle: ptr::NonNull<OperandBundle<'_>>);
1665
1666    pub(crate) fn LLVMBuildCallWithOperandBundles<'a>(
1667        B: &Builder<'a>,
1668        Ty: &'a Type,
1669        Fn: &'a Value,
1670        Args: *const &'a Value,
1671        NumArgs: c_uint,
1672        Bundles: *const &OperandBundle<'a>,
1673        NumBundles: c_uint,
1674        Name: *const c_char,
1675    ) -> &'a Value;
1676    pub(crate) fn LLVMBuildInvokeWithOperandBundles<'a>(
1677        B: &Builder<'a>,
1678        Ty: &'a Type,
1679        Fn: &'a Value,
1680        Args: *const &'a Value,
1681        NumArgs: c_uint,
1682        Then: &'a BasicBlock,
1683        Catch: &'a BasicBlock,
1684        Bundles: *const &OperandBundle<'a>,
1685        NumBundles: c_uint,
1686        Name: *const c_char,
1687    ) -> &'a Value;
1688    pub(crate) fn LLVMBuildCallBr<'a>(
1689        B: &Builder<'a>,
1690        Ty: &'a Type,
1691        Fn: &'a Value,
1692        DefaultDest: &'a BasicBlock,
1693        IndirectDests: *const &'a BasicBlock,
1694        NumIndirectDests: c_uint,
1695        Args: *const &'a Value,
1696        NumArgs: c_uint,
1697        Bundles: *const &OperandBundle<'a>,
1698        NumBundles: c_uint,
1699        Name: *const c_char,
1700    ) -> &'a Value;
1701}
1702
1703// FFI bindings for `DIBuilder` functions in the LLVM-C API.
1704// Try to keep these in the same order as in `llvm/include/llvm-c/DebugInfo.h`.
1705//
1706// FIXME(#134001): Audit all `Option` parameters, especially in lists, to check
1707// that they really are nullable on the C/C++ side. LLVM doesn't appear to
1708// actually document which ones are nullable.
1709unsafe extern "C" {
1710    pub(crate) fn LLVMCreateDIBuilder<'ll>(M: &'ll Module) -> *mut DIBuilder<'ll>;
1711    pub(crate) fn LLVMDisposeDIBuilder<'ll>(Builder: ptr::NonNull<DIBuilder<'ll>>);
1712
1713    pub(crate) fn LLVMDIBuilderFinalize<'ll>(Builder: &DIBuilder<'ll>);
1714
1715    pub(crate) fn LLVMDIBuilderCreateNameSpace<'ll>(
1716        Builder: &DIBuilder<'ll>,
1717        ParentScope: Option<&'ll Metadata>,
1718        Name: *const c_uchar, // See "PTR_LEN_STR".
1719        NameLen: size_t,
1720        ExportSymbols: llvm::Bool,
1721    ) -> &'ll Metadata;
1722
1723    pub(crate) fn LLVMDIBuilderCreateLexicalBlock<'ll>(
1724        Builder: &DIBuilder<'ll>,
1725        Scope: &'ll Metadata,
1726        File: &'ll Metadata,
1727        Line: c_uint,
1728        Column: c_uint,
1729    ) -> &'ll Metadata;
1730
1731    pub(crate) fn LLVMDIBuilderCreateLexicalBlockFile<'ll>(
1732        Builder: &DIBuilder<'ll>,
1733        Scope: &'ll Metadata,
1734        File: &'ll Metadata,
1735        Discriminator: c_uint, // (optional "DWARF path discriminator"; default is 0)
1736    ) -> &'ll Metadata;
1737
1738    pub(crate) fn LLVMDIBuilderCreateDebugLocation<'ll>(
1739        Ctx: &'ll Context,
1740        Line: c_uint,
1741        Column: c_uint,
1742        Scope: &'ll Metadata,
1743        InlinedAt: Option<&'ll Metadata>,
1744    ) -> &'ll Metadata;
1745
1746    pub(crate) fn LLVMDIBuilderCreateSubroutineType<'ll>(
1747        Builder: &DIBuilder<'ll>,
1748        File: Option<&'ll Metadata>, // (ignored and has no effect)
1749        ParameterTypes: *const Option<&'ll Metadata>,
1750        NumParameterTypes: c_uint,
1751        Flags: DIFlags, // (default is `DIFlags::DIFlagZero`)
1752    ) -> &'ll Metadata;
1753
1754    pub(crate) fn LLVMDIBuilderCreateUnionType<'ll>(
1755        Builder: &DIBuilder<'ll>,
1756        Scope: Option<&'ll Metadata>,
1757        Name: *const c_uchar, // See "PTR_LEN_STR".
1758        NameLen: size_t,
1759        File: &'ll Metadata,
1760        LineNumber: c_uint,
1761        SizeInBits: u64,
1762        AlignInBits: u32,
1763        Flags: DIFlags,
1764        Elements: *const Option<&'ll Metadata>,
1765        NumElements: c_uint,
1766        RunTimeLang: c_uint, // (optional Objective-C runtime version; default is 0)
1767        UniqueId: *const c_uchar, // See "PTR_LEN_STR".
1768        UniqueIdLen: size_t,
1769    ) -> &'ll Metadata;
1770
1771    pub(crate) fn LLVMDIBuilderCreateArrayType<'ll>(
1772        Builder: &DIBuilder<'ll>,
1773        Size: u64,
1774        Align: u32,
1775        Ty: &'ll Metadata,
1776        Subscripts: *const &'ll Metadata,
1777        NumSubscripts: c_uint,
1778    ) -> &'ll Metadata;
1779
1780    pub(crate) fn LLVMDIBuilderCreateBasicType<'ll>(
1781        Builder: &DIBuilder<'ll>,
1782        Name: *const c_uchar, // See "PTR_LEN_STR".
1783        NameLen: size_t,
1784        SizeInBits: u64,
1785        Encoding: c_uint, // (`LLVMDWARFTypeEncoding`)
1786        Flags: DIFlags,   // (default is `DIFlags::DIFlagZero`)
1787    ) -> &'ll Metadata;
1788
1789    pub(crate) fn LLVMDIBuilderCreatePointerType<'ll>(
1790        Builder: &DIBuilder<'ll>,
1791        PointeeTy: &'ll Metadata,
1792        SizeInBits: u64,
1793        AlignInBits: u32,
1794        AddressSpace: c_uint, // (optional DWARF address space; default is 0)
1795        Name: *const c_uchar, // See "PTR_LEN_STR".
1796        NameLen: size_t,
1797    ) -> &'ll Metadata;
1798
1799    pub(crate) fn LLVMDIBuilderCreateStructType<'ll>(
1800        Builder: &DIBuilder<'ll>,
1801        Scope: Option<&'ll Metadata>,
1802        Name: *const c_uchar, // See "PTR_LEN_STR".
1803        NameLen: size_t,
1804        File: &'ll Metadata,
1805        LineNumber: c_uint,
1806        SizeInBits: u64,
1807        AlignInBits: u32,
1808        Flags: DIFlags,
1809        DerivedFrom: Option<&'ll Metadata>,
1810        Elements: *const Option<&'ll Metadata>,
1811        NumElements: c_uint,
1812        RunTimeLang: c_uint, // (optional Objective-C runtime version; default is 0)
1813        VTableHolder: Option<&'ll Metadata>,
1814        UniqueId: *const c_uchar, // See "PTR_LEN_STR".
1815        UniqueIdLen: size_t,
1816    ) -> &'ll Metadata;
1817
1818    pub(crate) fn LLVMDIBuilderCreateMemberType<'ll>(
1819        Builder: &DIBuilder<'ll>,
1820        Scope: &'ll Metadata,
1821        Name: *const c_uchar, // See "PTR_LEN_STR".
1822        NameLen: size_t,
1823        File: &'ll Metadata,
1824        LineNo: c_uint,
1825        SizeInBits: u64,
1826        AlignInBits: u32,
1827        OffsetInBits: u64,
1828        Flags: DIFlags,
1829        Ty: &'ll Metadata,
1830    ) -> &'ll Metadata;
1831
1832    pub(crate) fn LLVMDIBuilderCreateStaticMemberType<'ll>(
1833        Builder: &DIBuilder<'ll>,
1834        Scope: &'ll Metadata,
1835        Name: *const c_uchar, // See "PTR_LEN_STR".
1836        NameLen: size_t,
1837        File: &'ll Metadata,
1838        LineNumber: c_uint,
1839        Type: &'ll Metadata,
1840        Flags: DIFlags,
1841        ConstantVal: Option<&'ll Value>,
1842        AlignInBits: u32,
1843    ) -> &'ll Metadata;
1844
1845    /// Creates a "qualified type" in the C/C++ sense, by adding modifiers
1846    /// like `const` or `volatile`.
1847    pub(crate) fn LLVMDIBuilderCreateQualifiedType<'ll>(
1848        Builder: &DIBuilder<'ll>,
1849        Tag: c_uint, // (DWARF tag, e.g. `DW_TAG_const_type`)
1850        Type: &'ll Metadata,
1851    ) -> &'ll Metadata;
1852
1853    pub(crate) fn LLVMDIBuilderCreateTypedef<'ll>(
1854        Builder: &DIBuilder<'ll>,
1855        Type: &'ll Metadata,
1856        Name: *const c_uchar, // See "PTR_LEN_STR".
1857        NameLen: size_t,
1858        File: &'ll Metadata,
1859        LineNo: c_uint,
1860        Scope: Option<&'ll Metadata>,
1861        AlignInBits: u32, // (optional; default is 0)
1862    ) -> &'ll Metadata;
1863
1864    pub(crate) fn LLVMDIBuilderGetOrCreateSubrange<'ll>(
1865        Builder: &DIBuilder<'ll>,
1866        LowerBound: i64,
1867        Count: i64,
1868    ) -> &'ll Metadata;
1869
1870    pub(crate) fn LLVMDIBuilderGetOrCreateArray<'ll>(
1871        Builder: &DIBuilder<'ll>,
1872        Data: *const Option<&'ll Metadata>,
1873        NumElements: size_t,
1874    ) -> &'ll Metadata;
1875
1876    pub(crate) fn LLVMDIBuilderCreateExpression<'ll>(
1877        Builder: &DIBuilder<'ll>,
1878        Addr: *const u64,
1879        Length: size_t,
1880    ) -> &'ll Metadata;
1881
1882    pub(crate) fn LLVMDIBuilderCreateGlobalVariableExpression<'ll>(
1883        Builder: &DIBuilder<'ll>,
1884        Scope: Option<&'ll Metadata>,
1885        Name: *const c_uchar, // See "PTR_LEN_STR".
1886        NameLen: size_t,
1887        Linkage: *const c_uchar, // See "PTR_LEN_STR".
1888        LinkLen: size_t,
1889        File: &'ll Metadata,
1890        LineNo: c_uint,
1891        Ty: &'ll Metadata,
1892        LocalToUnit: llvm::Bool,
1893        Expr: &'ll Metadata,
1894        Decl: Option<&'ll Metadata>,
1895        AlignInBits: u32,
1896    ) -> &'ll Metadata;
1897
1898    pub(crate) fn LLVMDIBuilderInsertDeclareRecordAtEnd<'ll>(
1899        Builder: &DIBuilder<'ll>,
1900        Storage: &'ll Value,
1901        VarInfo: &'ll Metadata,
1902        Expr: &'ll Metadata,
1903        DebugLoc: &'ll Metadata,
1904        Block: &'ll BasicBlock,
1905    ) -> &'ll DbgRecord;
1906
1907    pub(crate) fn LLVMDIBuilderInsertDbgValueRecordAtEnd<'ll>(
1908        Builder: &DIBuilder<'ll>,
1909        Val: &'ll Value,
1910        VarInfo: &'ll Metadata,
1911        Expr: &'ll Metadata,
1912        DebugLoc: &'ll Metadata,
1913        Block: &'ll BasicBlock,
1914    ) -> &'ll DbgRecord;
1915
1916    pub(crate) fn LLVMDIBuilderCreateAutoVariable<'ll>(
1917        Builder: &DIBuilder<'ll>,
1918        Scope: &'ll Metadata,
1919        Name: *const c_uchar, // See "PTR_LEN_STR".
1920        NameLen: size_t,
1921        File: &'ll Metadata,
1922        LineNo: c_uint,
1923        Ty: &'ll Metadata,
1924        AlwaysPreserve: llvm::Bool, // "If true, this descriptor will survive optimizations."
1925        Flags: DIFlags,
1926        AlignInBits: u32,
1927    ) -> &'ll Metadata;
1928
1929    pub(crate) fn LLVMDIBuilderCreateParameterVariable<'ll>(
1930        Builder: &DIBuilder<'ll>,
1931        Scope: &'ll Metadata,
1932        Name: *const c_uchar, // See "PTR_LEN_STR".
1933        NameLen: size_t,
1934        ArgNo: c_uint,
1935        File: &'ll Metadata,
1936        LineNo: c_uint,
1937        Ty: &'ll Metadata,
1938        AlwaysPreserve: llvm::Bool, // "If true, this descriptor will survive optimizations."
1939        Flags: DIFlags,
1940    ) -> &'ll Metadata;
1941}
1942
1943#[link(name = "llvm-wrapper", kind = "static")]
1944unsafe extern "C" {
1945    pub(crate) fn LLVMRustInstallErrorHandlers();
1946    pub(crate) fn LLVMRustDisableSystemDialogsOnCrash();
1947
1948    // Operations on all values
1949    pub(crate) fn LLVMRustGlobalAddMetadata<'a>(
1950        Val: &'a Value,
1951        KindID: MetadataKindId,
1952        Metadata: &'a Metadata,
1953    );
1954    pub(crate) fn LLVMRustIsNonGVFunctionPointerTy(Val: &Value) -> bool;
1955
1956    // Operations on scalar constants
1957    pub(crate) fn LLVMRustConstIntGetZExtValue(ConstantVal: &ConstantInt, Value: &mut u64) -> bool;
1958    pub(crate) fn LLVMRustConstInt128Get(
1959        ConstantVal: &ConstantInt,
1960        SExt: bool,
1961        high: &mut u64,
1962        low: &mut u64,
1963    ) -> bool;
1964
1965    // Operations on global variables, functions, and aliases (globals)
1966    pub(crate) fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool);
1967
1968    // Operations on global variables
1969    pub(crate) fn LLVMRustGetOrInsertGlobal<'a>(
1970        M: &'a Module,
1971        Name: *const c_char,
1972        NameLen: size_t,
1973        T: &'a Type,
1974    ) -> &'a Value;
1975    pub(crate) fn LLVMRustGetNamedValue(
1976        M: &Module,
1977        Name: *const c_char,
1978        NameLen: size_t,
1979    ) -> Option<&Value>;
1980
1981    // Operations on attributes
1982    pub(crate) fn LLVMRustCreateAttrNoValue(C: &Context, attr: AttributeKind) -> &Attribute;
1983    pub(crate) fn LLVMRustCreateAlignmentAttr(C: &Context, bytes: u64) -> &Attribute;
1984    pub(crate) fn LLVMRustCreateDereferenceableAttr(C: &Context, bytes: u64) -> &Attribute;
1985    pub(crate) fn LLVMRustCreateDereferenceableOrNullAttr(C: &Context, bytes: u64) -> &Attribute;
1986    pub(crate) fn LLVMRustCreateByValAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
1987    pub(crate) fn LLVMRustCreateStructRetAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
1988    pub(crate) fn LLVMRustCreateElementTypeAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
1989    pub(crate) fn LLVMRustCreateUWTableAttr(C: &Context, async_: bool) -> &Attribute;
1990    pub(crate) fn LLVMRustCreateAllocSizeAttr(C: &Context, size_arg: u32) -> &Attribute;
1991    pub(crate) fn LLVMRustCreateAllocKindAttr(C: &Context, size_arg: u64) -> &Attribute;
1992    pub(crate) fn LLVMRustCreateMemoryEffectsAttr(
1993        C: &Context,
1994        effects: MemoryEffects,
1995    ) -> &Attribute;
1996    /// ## Safety
1997    /// - Each of `LowerWords` and `UpperWords` must point to an array that is
1998    ///   long enough to fully define an integer of size `NumBits`, i.e. each
1999    ///   pointer must point to `NumBits.div_ceil(64)` elements or more.
2000    /// - The implementation will make its own copy of the pointed-to `u64`
2001    ///   values, so the pointers only need to outlive this function call.
2002    pub(crate) fn LLVMRustCreateRangeAttribute(
2003        C: &Context,
2004        NumBits: c_uint,
2005        LowerWords: *const u64,
2006        UpperWords: *const u64,
2007    ) -> &Attribute;
2008
2009    // Operations on functions
2010    pub(crate) fn LLVMRustGetOrInsertFunction<'a>(
2011        M: &'a Module,
2012        Name: *const c_char,
2013        NameLen: size_t,
2014        FunctionTy: &'a Type,
2015    ) -> &'a Value;
2016    pub(crate) fn LLVMRustAddFunctionAttributes<'a>(
2017        Fn: &'a Value,
2018        index: c_uint,
2019        Attrs: *const &'a Attribute,
2020        AttrsLen: size_t,
2021    );
2022
2023    // Operations on call sites
2024    pub(crate) fn LLVMRustAddCallSiteAttributes<'a>(
2025        Instr: &'a Value,
2026        index: c_uint,
2027        Attrs: *const &'a Attribute,
2028        AttrsLen: size_t,
2029    );
2030
2031    pub(crate) fn LLVMRustSetFastMath(Instr: &Value);
2032    pub(crate) fn LLVMRustSetAlgebraicMath(Instr: &Value);
2033    pub(crate) fn LLVMRustSetAllowReassoc(Instr: &Value);
2034
2035    // Miscellaneous instructions
2036    pub(crate) fn LLVMRustBuildMemCpy<'a>(
2037        B: &Builder<'a>,
2038        Dst: &'a Value,
2039        DstAlign: c_uint,
2040        Src: &'a Value,
2041        SrcAlign: c_uint,
2042        Size: &'a Value,
2043        IsVolatile: bool,
2044    ) -> &'a Value;
2045    pub(crate) fn LLVMRustBuildMemMove<'a>(
2046        B: &Builder<'a>,
2047        Dst: &'a Value,
2048        DstAlign: c_uint,
2049        Src: &'a Value,
2050        SrcAlign: c_uint,
2051        Size: &'a Value,
2052        IsVolatile: bool,
2053    ) -> &'a Value;
2054    pub(crate) fn LLVMRustBuildMemSet<'a>(
2055        B: &Builder<'a>,
2056        Dst: &'a Value,
2057        DstAlign: c_uint,
2058        Val: &'a Value,
2059        Size: &'a Value,
2060        IsVolatile: bool,
2061    ) -> &'a Value;
2062
2063    pub(crate) fn LLVMRustTimeTraceProfilerInitialize();
2064
2065    pub(crate) fn LLVMRustTimeTraceProfilerFinishThread();
2066
2067    pub(crate) fn LLVMRustTimeTraceProfilerFinish(FileName: *const c_char);
2068
2069    /// Returns a string describing the last error caused by an LLVMRust* call.
2070    pub(crate) fn LLVMRustGetLastError() -> *const c_char;
2071
2072    /// Prints the timing information collected by `-Ztime-llvm-passes`.
2073    pub(crate) fn LLVMRustPrintPassTimings(OutStr: &RustString);
2074
2075    /// Prints the statistics collected by `-Zprint-codegen-stats`.
2076    pub(crate) fn LLVMRustPrintStatistics(OutStr: &RustString);
2077
2078    pub(crate) fn LLVMRustInlineAsmVerify(
2079        Ty: &Type,
2080        Constraints: *const c_uchar, // See "PTR_LEN_STR".
2081        ConstraintsLen: size_t,
2082    ) -> bool;
2083
2084    /// A list of pointer-length strings is passed as two pointer-length slices,
2085    /// one slice containing pointers and one slice containing their corresponding
2086    /// lengths. The implementation will check that both slices have the same length.
2087    pub(crate) fn LLVMRustCoverageWriteFilenamesToBuffer(
2088        Filenames: *const *const c_uchar, // See "PTR_LEN_STR".
2089        FilenamesLen: size_t,
2090        Lengths: *const size_t,
2091        LengthsLen: size_t,
2092        BufferOut: &RustString,
2093    );
2094
2095    pub(crate) fn LLVMRustCoverageWriteFunctionMappingsToBuffer(
2096        VirtualFileMappingIDs: *const c_uint,
2097        NumVirtualFileMappingIDs: size_t,
2098        Expressions: *const crate::coverageinfo::ffi::CounterExpression,
2099        NumExpressions: size_t,
2100        CodeRegions: *const crate::coverageinfo::ffi::CodeRegion,
2101        NumCodeRegions: size_t,
2102        ExpansionRegions: *const crate::coverageinfo::ffi::ExpansionRegion,
2103        NumExpansionRegions: size_t,
2104        BranchRegions: *const crate::coverageinfo::ffi::BranchRegion,
2105        NumBranchRegions: size_t,
2106        BufferOut: &RustString,
2107    );
2108
2109    pub(crate) fn LLVMRustCoverageCreatePGOFuncNameVar(
2110        F: &Value,
2111        FuncName: *const c_uchar, // See "PTR_LEN_STR".
2112        FuncNameLen: size_t,
2113    ) -> &Value;
2114    pub(crate) fn LLVMRustCoverageHashBytes(
2115        Bytes: *const c_uchar, // See "PTR_LEN_STR".
2116        NumBytes: size_t,
2117    ) -> u64;
2118
2119    pub(crate) safe fn LLVMRustCoverageWriteCovmapSectionNameToString(
2120        M: &Module,
2121        OutStr: &RustString,
2122    );
2123    pub(crate) safe fn LLVMRustCoverageWriteCovfunSectionNameToString(
2124        M: &Module,
2125        OutStr: &RustString,
2126    );
2127    pub(crate) safe fn LLVMRustCoverageWriteCovmapVarNameToString(OutStr: &RustString);
2128
2129    pub(crate) safe fn LLVMRustCoverageMappingVersion() -> u32;
2130    pub(crate) fn LLVMRustDebugMetadataVersion() -> u32;
2131    pub(crate) fn LLVMRustVersionMajor() -> u32;
2132    pub(crate) fn LLVMRustVersionMinor() -> u32;
2133    pub(crate) fn LLVMRustVersionPatch() -> u32;
2134
2135    /// Add LLVM module flags.
2136    ///
2137    /// In order for Rust-C LTO to work, module flags must be compatible with Clang. What
2138    /// "compatible" means depends on the merge behaviors involved.
2139    pub(crate) fn LLVMRustAddModuleFlagU32(
2140        M: &Module,
2141        MergeBehavior: ModuleFlagMergeBehavior,
2142        Name: *const c_char,
2143        NameLen: size_t,
2144        Value: u32,
2145    );
2146
2147    pub(crate) fn LLVMRustAddModuleFlagString(
2148        M: &Module,
2149        MergeBehavior: ModuleFlagMergeBehavior,
2150        Name: *const c_char,
2151        NameLen: size_t,
2152        Value: *const c_char,
2153        ValueLen: size_t,
2154    );
2155
2156    pub(crate) fn LLVMRustDIBuilderCreateCompileUnit<'a>(
2157        Builder: &DIBuilder<'a>,
2158        Lang: c_uint,
2159        File: &'a DIFile,
2160        Producer: *const c_char,
2161        ProducerLen: size_t,
2162        isOptimized: bool,
2163        Flags: *const c_char,
2164        RuntimeVer: c_uint,
2165        SplitName: *const c_char,
2166        SplitNameLen: size_t,
2167        kind: DebugEmissionKind,
2168        DWOId: u64,
2169        SplitDebugInlining: bool,
2170        DebugNameTableKind: DebugNameTableKind,
2171    ) -> &'a DIDescriptor;
2172
2173    pub(crate) fn LLVMRustDIBuilderCreateFile<'a>(
2174        Builder: &DIBuilder<'a>,
2175        Filename: *const c_char,
2176        FilenameLen: size_t,
2177        Directory: *const c_char,
2178        DirectoryLen: size_t,
2179        CSKind: ChecksumKind,
2180        Checksum: *const c_char,
2181        ChecksumLen: size_t,
2182        Source: *const c_char,
2183        SourceLen: size_t,
2184    ) -> &'a DIFile;
2185
2186    pub(crate) fn LLVMRustDIBuilderCreateFunction<'a>(
2187        Builder: &DIBuilder<'a>,
2188        Scope: &'a DIDescriptor,
2189        Name: *const c_char,
2190        NameLen: size_t,
2191        LinkageName: *const c_char,
2192        LinkageNameLen: size_t,
2193        File: &'a DIFile,
2194        LineNo: c_uint,
2195        Ty: &'a DIType,
2196        ScopeLine: c_uint,
2197        Flags: DIFlags,
2198        SPFlags: DISPFlags,
2199        MaybeFn: Option<&'a Value>,
2200        TParam: &'a DIArray,
2201        Decl: Option<&'a DIDescriptor>,
2202    ) -> &'a DISubprogram;
2203
2204    pub(crate) fn LLVMRustDIBuilderCreateMethod<'a>(
2205        Builder: &DIBuilder<'a>,
2206        Scope: &'a DIDescriptor,
2207        Name: *const c_char,
2208        NameLen: size_t,
2209        LinkageName: *const c_char,
2210        LinkageNameLen: size_t,
2211        File: &'a DIFile,
2212        LineNo: c_uint,
2213        Ty: &'a DIType,
2214        Flags: DIFlags,
2215        SPFlags: DISPFlags,
2216        TParam: &'a DIArray,
2217    ) -> &'a DISubprogram;
2218
2219    pub(crate) fn LLVMRustDIBuilderCreateVariantMemberType<'a>(
2220        Builder: &DIBuilder<'a>,
2221        Scope: &'a DIScope,
2222        Name: *const c_char,
2223        NameLen: size_t,
2224        File: &'a DIFile,
2225        LineNumber: c_uint,
2226        SizeInBits: u64,
2227        AlignInBits: u32,
2228        OffsetInBits: u64,
2229        Discriminant: Option<&'a Value>,
2230        Flags: DIFlags,
2231        Ty: &'a DIType,
2232    ) -> &'a DIType;
2233
2234    pub(crate) fn LLVMRustDIBuilderCreateEnumerator<'a>(
2235        Builder: &DIBuilder<'a>,
2236        Name: *const c_char,
2237        NameLen: size_t,
2238        Value: *const u64,
2239        SizeInBits: c_uint,
2240        IsUnsigned: bool,
2241    ) -> &'a DIEnumerator;
2242
2243    pub(crate) fn LLVMRustDIBuilderCreateEnumerationType<'a>(
2244        Builder: &DIBuilder<'a>,
2245        Scope: &'a DIScope,
2246        Name: *const c_char,
2247        NameLen: size_t,
2248        File: &'a DIFile,
2249        LineNumber: c_uint,
2250        SizeInBits: u64,
2251        AlignInBits: u32,
2252        Elements: &'a DIArray,
2253        ClassType: &'a DIType,
2254        IsScoped: bool,
2255    ) -> &'a DIType;
2256
2257    pub(crate) fn LLVMRustDIBuilderCreateVariantPart<'a>(
2258        Builder: &DIBuilder<'a>,
2259        Scope: &'a DIScope,
2260        Name: *const c_char,
2261        NameLen: size_t,
2262        File: &'a DIFile,
2263        LineNo: c_uint,
2264        SizeInBits: u64,
2265        AlignInBits: u32,
2266        Flags: DIFlags,
2267        Discriminator: Option<&'a DIDerivedType>,
2268        Elements: &'a DIArray,
2269        UniqueId: *const c_char,
2270        UniqueIdLen: size_t,
2271    ) -> &'a DIDerivedType;
2272
2273    pub(crate) fn LLVMRustDIBuilderCreateTemplateTypeParameter<'a>(
2274        Builder: &DIBuilder<'a>,
2275        Scope: Option<&'a DIScope>,
2276        Name: *const c_char,
2277        NameLen: size_t,
2278        Ty: &'a DIType,
2279    ) -> &'a DITemplateTypeParameter;
2280
2281    pub(crate) fn LLVMRustDICompositeTypeReplaceArrays<'a>(
2282        Builder: &DIBuilder<'a>,
2283        CompositeType: &'a DIType,
2284        Elements: Option<&'a DIArray>,
2285        Params: Option<&'a DIArray>,
2286    );
2287
2288    pub(crate) fn LLVMRustDILocationCloneWithBaseDiscriminator<'a>(
2289        Location: &'a DILocation,
2290        BD: c_uint,
2291    ) -> Option<&'a DILocation>;
2292
2293    pub(crate) fn LLVMRustWriteTypeToString(Type: &Type, s: &RustString);
2294    pub(crate) fn LLVMRustWriteValueToString(value_ref: &Value, s: &RustString);
2295
2296    pub(crate) fn LLVMRustHasFeature(T: &TargetMachine, s: *const c_char) -> bool;
2297
2298    pub(crate) fn LLVMRustPrintTargetCPUs(TM: &TargetMachine, OutStr: &RustString);
2299    pub(crate) fn LLVMRustGetTargetFeaturesCount(T: &TargetMachine) -> size_t;
2300    pub(crate) fn LLVMRustGetTargetFeature(
2301        T: &TargetMachine,
2302        Index: size_t,
2303        Feature: &mut *const c_char,
2304        Desc: &mut *const c_char,
2305    );
2306
2307    pub(crate) fn LLVMRustGetHostCPUName(LenOut: &mut size_t) -> *const u8;
2308
2309    // This function makes copies of pointed to data, so the data's lifetime may end after this
2310    // function returns.
2311    pub(crate) fn LLVMRustCreateTargetMachine(
2312        Triple: *const c_char,
2313        CPU: *const c_char,
2314        Features: *const c_char,
2315        Abi: *const c_char,
2316        Model: CodeModel,
2317        Reloc: RelocModel,
2318        Level: CodeGenOptLevel,
2319        FloatABIType: FloatAbi,
2320        FunctionSections: bool,
2321        DataSections: bool,
2322        UniqueSectionNames: bool,
2323        TrapUnreachable: bool,
2324        Singlethread: bool,
2325        VerboseAsm: bool,
2326        EmitStackSizeSection: bool,
2327        RelaxELFRelocations: bool,
2328        UseInitArray: bool,
2329        SplitDwarfFile: *const c_char,
2330        OutputObjFile: *const c_char,
2331        DebugInfoCompression: *const c_char,
2332        UseEmulatedTls: bool,
2333        UseWasmEH: bool,
2334    ) -> *mut TargetMachine;
2335
2336    pub(crate) fn LLVMRustAddLibraryInfo<'a>(
2337        PM: &PassManager<'a>,
2338        M: &'a Module,
2339        DisableSimplifyLibCalls: bool,
2340    );
2341    pub(crate) fn LLVMRustWriteOutputFile<'a>(
2342        T: &'a TargetMachine,
2343        PM: *mut PassManager<'a>,
2344        M: &'a Module,
2345        Output: *const c_char,
2346        DwoOutput: *const c_char,
2347        FileType: FileType,
2348        VerifyIR: bool,
2349    ) -> LLVMRustResult;
2350    pub(crate) fn LLVMRustOptimize<'a>(
2351        M: &'a Module,
2352        TM: &'a TargetMachine,
2353        OptLevel: PassBuilderOptLevel,
2354        OptStage: OptStage,
2355        IsLinkerPluginLTO: bool,
2356        NoPrepopulatePasses: bool,
2357        VerifyIR: bool,
2358        LintIR: bool,
2359        ThinLTOBuffer: Option<&mut *mut ThinLTOBuffer>,
2360        EmitThinLTO: bool,
2361        EmitThinLTOSummary: bool,
2362        MergeFunctions: bool,
2363        UnrollLoops: bool,
2364        SLPVectorize: bool,
2365        LoopVectorize: bool,
2366        DisableSimplifyLibCalls: bool,
2367        EmitLifetimeMarkers: bool,
2368        RunEnzyme: bool,
2369        PrintBeforeEnzyme: bool,
2370        PrintAfterEnzyme: bool,
2371        PrintPasses: bool,
2372        SanitizerOptions: Option<&SanitizerOptions>,
2373        PGOGenPath: *const c_char,
2374        PGOUsePath: *const c_char,
2375        InstrumentCoverage: bool,
2376        InstrProfileOutput: *const c_char,
2377        PGOSampleUsePath: *const c_char,
2378        DebugInfoForProfiling: bool,
2379        llvm_selfprofiler: *mut c_void,
2380        begin_callback: SelfProfileBeforePassCallback,
2381        end_callback: SelfProfileAfterPassCallback,
2382        ExtraPasses: *const c_char,
2383        ExtraPassesLen: size_t,
2384        LLVMPlugins: *const c_char,
2385        LLVMPluginsLen: size_t,
2386    ) -> LLVMRustResult;
2387    pub(crate) fn LLVMRustPrintModule(
2388        M: &Module,
2389        Output: *const c_char,
2390        Demangle: extern "C" fn(*const c_char, size_t, *mut c_char, size_t) -> size_t,
2391    ) -> LLVMRustResult;
2392    pub(crate) fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: *const *const c_char);
2393    pub(crate) fn LLVMRustPrintPasses();
2394    pub(crate) fn LLVMRustSetNormalizedTarget(M: &Module, triple: *const c_char);
2395    pub(crate) fn LLVMRustRunRestrictionPass(M: &Module, syms: *const *const c_char, len: size_t);
2396
2397    pub(crate) fn LLVMRustWriteTwineToString(T: &Twine, s: &RustString);
2398
2399    pub(crate) fn LLVMRustUnpackOptimizationDiagnostic<'a>(
2400        DI: &'a DiagnosticInfo,
2401        pass_name_out: &RustString,
2402        function_out: &mut Option<&'a Value>,
2403        loc_line_out: &mut c_uint,
2404        loc_column_out: &mut c_uint,
2405        loc_filename_out: &RustString,
2406        message_out: &RustString,
2407    );
2408
2409    pub(crate) fn LLVMRustUnpackInlineAsmDiagnostic<'a>(
2410        DI: &'a DiagnosticInfo,
2411        level_out: &mut DiagnosticLevel,
2412        cookie_out: &mut u64,
2413        message_out: &mut Option<&'a Twine>,
2414    );
2415
2416    pub(crate) fn LLVMRustWriteDiagnosticInfoToString(DI: &DiagnosticInfo, s: &RustString);
2417    pub(crate) fn LLVMRustGetDiagInfoKind(DI: &DiagnosticInfo) -> DiagnosticKind;
2418
2419    pub(crate) fn LLVMRustGetSMDiagnostic<'a>(
2420        DI: &'a DiagnosticInfo,
2421        cookie_out: &mut u64,
2422    ) -> &'a SMDiagnostic;
2423
2424    pub(crate) fn LLVMRustUnpackSMDiagnostic(
2425        d: &SMDiagnostic,
2426        message_out: &RustString,
2427        buffer_out: &RustString,
2428        level_out: &mut DiagnosticLevel,
2429        loc_out: &mut c_uint,
2430        ranges_out: *mut c_uint,
2431        num_ranges: &mut usize,
2432    ) -> bool;
2433
2434    pub(crate) fn LLVMRustSetDataLayoutFromTargetMachine<'a>(M: &'a Module, TM: &'a TargetMachine);
2435
2436    pub(crate) fn LLVMRustPositionBuilderPastAllocas<'a>(B: &Builder<'a>, Fn: &'a Value);
2437    pub(crate) fn LLVMRustPositionBuilderAtStart<'a>(B: &Builder<'a>, BB: &'a BasicBlock);
2438
2439    pub(crate) fn LLVMRustSetModulePICLevel(M: &Module);
2440    pub(crate) fn LLVMRustSetModulePIELevel(M: &Module);
2441    pub(crate) fn LLVMRustSetModuleCodeModel(M: &Module, Model: CodeModel);
2442    pub(crate) fn LLVMRustModuleBufferCreate(M: &Module) -> &'static mut ModuleBuffer;
2443    pub(crate) fn LLVMRustModuleBufferPtr(p: &ModuleBuffer) -> *const u8;
2444    pub(crate) fn LLVMRustModuleBufferLen(p: &ModuleBuffer) -> usize;
2445    pub(crate) fn LLVMRustModuleBufferFree(p: &'static mut ModuleBuffer);
2446    pub(crate) fn LLVMRustModuleCost(M: &Module) -> u64;
2447    pub(crate) fn LLVMRustModuleInstructionStats(M: &Module, Str: &RustString);
2448
2449    pub(crate) fn LLVMRustThinLTOBufferCreate(
2450        M: &Module,
2451        is_thin: bool,
2452    ) -> &'static mut ThinLTOBuffer;
2453    pub(crate) fn LLVMRustThinLTOBufferFree(M: &'static mut ThinLTOBuffer);
2454    pub(crate) fn LLVMRustThinLTOBufferPtr(M: &ThinLTOBuffer) -> *const c_char;
2455    pub(crate) fn LLVMRustThinLTOBufferLen(M: &ThinLTOBuffer) -> size_t;
2456    pub(crate) fn LLVMRustThinLTOBufferThinLinkDataPtr(M: &ThinLTOBuffer) -> *const c_char;
2457    pub(crate) fn LLVMRustThinLTOBufferThinLinkDataLen(M: &ThinLTOBuffer) -> size_t;
2458    pub(crate) fn LLVMRustCreateThinLTOData(
2459        Modules: *const ThinLTOModule,
2460        NumModules: size_t,
2461        PreservedSymbols: *const *const c_char,
2462        PreservedSymbolsLen: size_t,
2463    ) -> Option<&'static mut ThinLTOData>;
2464    pub(crate) fn LLVMRustPrepareThinLTORename(
2465        Data: &ThinLTOData,
2466        Module: &Module,
2467        Target: &TargetMachine,
2468    );
2469    pub(crate) fn LLVMRustPrepareThinLTOResolveWeak(Data: &ThinLTOData, Module: &Module) -> bool;
2470    pub(crate) fn LLVMRustPrepareThinLTOInternalize(Data: &ThinLTOData, Module: &Module) -> bool;
2471    pub(crate) fn LLVMRustPrepareThinLTOImport(
2472        Data: &ThinLTOData,
2473        Module: &Module,
2474        Target: &TargetMachine,
2475    ) -> bool;
2476    pub(crate) fn LLVMRustFreeThinLTOData(Data: &'static mut ThinLTOData);
2477    pub(crate) fn LLVMRustParseBitcodeForLTO(
2478        Context: &Context,
2479        Data: *const u8,
2480        len: usize,
2481        Identifier: *const c_char,
2482    ) -> Option<&Module>;
2483
2484    pub(crate) fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>;
2485    pub(crate) fn LLVMRustLinkerAdd(
2486        linker: &Linker<'_>,
2487        bytecode: *const c_char,
2488        bytecode_len: usize,
2489    ) -> bool;
2490    pub(crate) fn LLVMRustLinkerFree<'a>(linker: &'a mut Linker<'a>);
2491    pub(crate) fn LLVMRustComputeLTOCacheKey(
2492        key_out: &RustString,
2493        mod_id: *const c_char,
2494        data: &ThinLTOData,
2495    );
2496
2497    pub(crate) fn LLVMRustContextGetDiagnosticHandler(
2498        Context: &Context,
2499    ) -> Option<&DiagnosticHandler>;
2500    pub(crate) fn LLVMRustContextSetDiagnosticHandler(
2501        context: &Context,
2502        diagnostic_handler: Option<&DiagnosticHandler>,
2503    );
2504    pub(crate) fn LLVMRustContextConfigureDiagnosticHandler(
2505        context: &Context,
2506        diagnostic_handler_callback: DiagnosticHandlerTy,
2507        diagnostic_handler_context: *mut c_void,
2508        remark_all_passes: bool,
2509        remark_passes: *const *const c_char,
2510        remark_passes_len: usize,
2511        remark_file: *const c_char,
2512        pgo_available: bool,
2513    );
2514
2515    pub(crate) fn LLVMRustGetMangledName(V: &Value, out: &RustString);
2516
2517    pub(crate) fn LLVMRustGetElementTypeArgIndex(CallSite: &Value) -> i32;
2518
2519    pub(crate) fn LLVMRustLLVMHasZlibCompressionForDebugSymbols() -> bool;
2520
2521    pub(crate) fn LLVMRustLLVMHasZstdCompressionForDebugSymbols() -> bool;
2522
2523    pub(crate) fn LLVMRustGetSymbols(
2524        buf_ptr: *const u8,
2525        buf_len: usize,
2526        state: *mut c_void,
2527        callback: GetSymbolsCallback,
2528        error_callback: GetSymbolsErrorCallback,
2529    ) -> *mut c_void;
2530
2531    pub(crate) fn LLVMRustIs64BitSymbolicFile(buf_ptr: *const u8, buf_len: usize) -> bool;
2532
2533    pub(crate) fn LLVMRustIsECObject(buf_ptr: *const u8, buf_len: usize) -> bool;
2534
2535    pub(crate) fn LLVMRustIsAnyArm64Coff(buf_ptr: *const u8, buf_len: usize) -> bool;
2536
2537    pub(crate) fn LLVMRustSetNoSanitizeAddress(Global: &Value);
2538    pub(crate) fn LLVMRustSetNoSanitizeHWAddress(Global: &Value);
2539}