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,
26    DIGlobalVariableExpression, DILocation, DISPFlags, DIScope, DISubprogram,
27    DITemplateTypeParameter, DIType, DebugEmissionKind, 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 DIGlobalVariableExpression = DIDescriptor;
785    pub(crate) type DIArray = DIDescriptor;
786    pub(crate) type DIEnumerator = DIDescriptor;
787    pub(crate) type DITemplateTypeParameter = DIDescriptor;
788
789    bitflags! {
790        /// Must match the layout of `LLVMDIFlags` in the LLVM-C API.
791        ///
792        /// Each value declared here must also be covered by the static
793        /// assertions in `RustWrapper.cpp` used by `fromRust(LLVMDIFlags)`.
794        #[repr(transparent)]
795        #[derive(Clone, Copy, Default)]
796        pub(crate) struct DIFlags: u32 {
797            const FlagZero                = 0;
798            const FlagPrivate             = 1;
799            const FlagProtected           = 2;
800            const FlagPublic              = 3;
801            const FlagFwdDecl             = (1 << 2);
802            const FlagAppleBlock          = (1 << 3);
803            const FlagReservedBit4        = (1 << 4);
804            const FlagVirtual             = (1 << 5);
805            const FlagArtificial          = (1 << 6);
806            const FlagExplicit            = (1 << 7);
807            const FlagPrototyped          = (1 << 8);
808            const FlagObjcClassComplete   = (1 << 9);
809            const FlagObjectPointer       = (1 << 10);
810            const FlagVector              = (1 << 11);
811            const FlagStaticMember        = (1 << 12);
812            const FlagLValueReference     = (1 << 13);
813            const FlagRValueReference     = (1 << 14);
814            const FlagReserved            = (1 << 15);
815            const FlagSingleInheritance   = (1 << 16);
816            const FlagMultipleInheritance = (2 << 16);
817            const FlagVirtualInheritance  = (3 << 16);
818            const FlagIntroducedVirtual   = (1 << 18);
819            const FlagBitField            = (1 << 19);
820            const FlagNoReturn            = (1 << 20);
821            // The bit at (1 << 21) is unused, but was `LLVMDIFlagMainSubprogram`.
822            const FlagTypePassByValue     = (1 << 22);
823            const FlagTypePassByReference = (1 << 23);
824            const FlagEnumClass           = (1 << 24);
825            const FlagThunk               = (1 << 25);
826            const FlagNonTrivial          = (1 << 26);
827            const FlagBigEndian           = (1 << 27);
828            const FlagLittleEndian        = (1 << 28);
829        }
830    }
831
832    // These values **must** match with LLVMRustDISPFlags!!
833    bitflags! {
834        #[repr(transparent)]
835        #[derive(Clone, Copy, Default)]
836        pub(crate) struct DISPFlags: u32 {
837            const SPFlagZero              = 0;
838            const SPFlagVirtual           = 1;
839            const SPFlagPureVirtual       = 2;
840            const SPFlagLocalToUnit       = (1 << 2);
841            const SPFlagDefinition        = (1 << 3);
842            const SPFlagOptimized         = (1 << 4);
843            const SPFlagMainSubprogram    = (1 << 5);
844        }
845    }
846
847    /// LLVMRustDebugEmissionKind
848    #[derive(Copy, Clone)]
849    #[repr(C)]
850    pub(crate) enum DebugEmissionKind {
851        NoDebug,
852        FullDebug,
853        LineTablesOnly,
854        DebugDirectivesOnly,
855    }
856
857    /// LLVMRustDebugNameTableKind
858    #[derive(Clone, Copy)]
859    #[repr(C)]
860    pub(crate) enum DebugNameTableKind {
861        Default,
862        #[expect(dead_code)]
863        Gnu,
864        None,
865    }
866}
867
868// These values **must** match with LLVMRustAllocKindFlags
869bitflags! {
870    #[repr(transparent)]
871    #[derive(Default)]
872    pub(crate) struct AllocKindFlags : u64 {
873        const Unknown = 0;
874        const Alloc = 1;
875        const Realloc = 1 << 1;
876        const Free = 1 << 2;
877        const Uninitialized = 1 << 3;
878        const Zeroed = 1 << 4;
879        const Aligned = 1 << 5;
880    }
881}
882
883// These values **must** match with LLVMGEPNoWrapFlags
884bitflags! {
885    #[repr(transparent)]
886    #[derive(Default)]
887    pub struct GEPNoWrapFlags : c_uint {
888        const InBounds = 1 << 0;
889        const NUSW = 1 << 1;
890        const NUW = 1 << 2;
891    }
892}
893
894unsafe extern "C" {
895    pub(crate) type ModuleBuffer;
896}
897
898pub(crate) type SelfProfileBeforePassCallback =
899    unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char);
900pub(crate) type SelfProfileAfterPassCallback = unsafe extern "C" fn(*mut c_void);
901
902pub(crate) type GetSymbolsCallback =
903    unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void;
904pub(crate) type GetSymbolsErrorCallback = unsafe extern "C" fn(*const c_char) -> *mut c_void;
905
906unsafe extern "C" {
907    // Create and destroy contexts.
908    pub(crate) fn LLVMContextDispose(C: &'static mut Context);
909    pub(crate) fn LLVMGetMDKindIDInContext(
910        C: &Context,
911        Name: *const c_char,
912        SLen: c_uint,
913    ) -> MetadataKindId;
914
915    pub(crate) fn LLVMDisposeTargetMachine(T: ptr::NonNull<TargetMachine>);
916
917    // Create modules.
918    pub(crate) fn LLVMModuleCreateWithNameInContext(
919        ModuleID: *const c_char,
920        C: &Context,
921    ) -> &Module;
922    pub(crate) safe fn LLVMCloneModule(M: &Module) -> &Module;
923
924    /// Data layout. See Module::getDataLayout.
925    pub(crate) fn LLVMGetDataLayoutStr(M: &Module) -> *const c_char;
926    pub(crate) fn LLVMSetDataLayout(M: &Module, Triple: *const c_char);
927
928    /// Append inline assembly to a module. See `Module::appendModuleInlineAsm`.
929    pub(crate) fn LLVMAppendModuleInlineAsm(
930        M: &Module,
931        Asm: *const c_uchar, // See "PTR_LEN_STR".
932        Len: size_t,
933    );
934
935    /// Create the specified uniqued inline asm string. See `InlineAsm::get()`.
936    pub(crate) fn LLVMGetInlineAsm<'ll>(
937        Ty: &'ll Type,
938        AsmString: *const c_uchar, // See "PTR_LEN_STR".
939        AsmStringSize: size_t,
940        Constraints: *const c_uchar, // See "PTR_LEN_STR".
941        ConstraintsSize: size_t,
942        HasSideEffects: llvm::Bool,
943        IsAlignStack: llvm::Bool,
944        Dialect: AsmDialect,
945        CanThrow: llvm::Bool,
946    ) -> &'ll Value;
947
948    pub(crate) safe fn LLVMGetTypeKind(Ty: &Type) -> RawEnum<TypeKind>;
949
950    // Operations on integer types
951    pub(crate) fn LLVMInt1TypeInContext(C: &Context) -> &Type;
952    pub(crate) fn LLVMInt8TypeInContext(C: &Context) -> &Type;
953    pub(crate) fn LLVMInt16TypeInContext(C: &Context) -> &Type;
954    pub(crate) fn LLVMInt32TypeInContext(C: &Context) -> &Type;
955    pub(crate) fn LLVMInt64TypeInContext(C: &Context) -> &Type;
956    pub(crate) safe fn LLVMIntTypeInContext(C: &Context, NumBits: c_uint) -> &Type;
957
958    pub(crate) fn LLVMGetIntTypeWidth(IntegerTy: &Type) -> c_uint;
959
960    // Operations on real types
961    pub(crate) fn LLVMHalfTypeInContext(C: &Context) -> &Type;
962    pub(crate) fn LLVMFloatTypeInContext(C: &Context) -> &Type;
963    pub(crate) fn LLVMDoubleTypeInContext(C: &Context) -> &Type;
964    pub(crate) fn LLVMFP128TypeInContext(C: &Context) -> &Type;
965
966    // Operations on function types
967    pub(crate) fn LLVMFunctionType<'a>(
968        ReturnType: &'a Type,
969        ParamTypes: *const &'a Type,
970        ParamCount: c_uint,
971        IsVarArg: Bool,
972    ) -> &'a Type;
973    pub(crate) fn LLVMCountParamTypes(FunctionTy: &Type) -> c_uint;
974    pub(crate) fn LLVMGetParamTypes<'a>(FunctionTy: &'a Type, Dest: *mut &'a Type);
975
976    // Operations on struct types
977    pub(crate) fn LLVMStructTypeInContext<'a>(
978        C: &'a Context,
979        ElementTypes: *const &'a Type,
980        ElementCount: c_uint,
981        Packed: Bool,
982    ) -> &'a Type;
983
984    // Operations on array, pointer, and vector types (sequence types)
985    pub(crate) safe fn LLVMPointerTypeInContext(C: &Context, AddressSpace: c_uint) -> &Type;
986    pub(crate) fn LLVMVectorType(ElementType: &Type, ElementCount: c_uint) -> &Type;
987
988    pub(crate) fn LLVMGetElementType(Ty: &Type) -> &Type;
989    pub(crate) fn LLVMGetVectorSize(VectorTy: &Type) -> c_uint;
990
991    // Operations on other types
992    pub(crate) fn LLVMVoidTypeInContext(C: &Context) -> &Type;
993
994    // Operations on all values
995    pub(crate) fn LLVMTypeOf(Val: &Value) -> &Type;
996    pub(crate) fn LLVMGetValueName2(Val: &Value, Length: *mut size_t) -> *const c_char;
997    pub(crate) fn LLVMSetValueName2(Val: &Value, Name: *const c_char, NameLen: size_t);
998    pub(crate) fn LLVMReplaceAllUsesWith<'a>(OldVal: &'a Value, NewVal: &'a Value);
999    pub(crate) safe fn LLVMSetMetadata<'a>(Val: &'a Value, KindID: MetadataKindId, Node: &'a Value);
1000    pub(crate) fn LLVMGlobalSetMetadata<'a>(
1001        Val: &'a Value,
1002        KindID: MetadataKindId,
1003        Metadata: &'a Metadata,
1004    );
1005    pub(crate) safe fn LLVMValueAsMetadata(Node: &Value) -> &Metadata;
1006
1007    // Operations on constants of any type
1008    pub(crate) fn LLVMConstNull(Ty: &Type) -> &Value;
1009    pub(crate) fn LLVMGetUndef(Ty: &Type) -> &Value;
1010    pub(crate) fn LLVMGetPoison(Ty: &Type) -> &Value;
1011
1012    // Operations on metadata
1013    pub(crate) fn LLVMMDStringInContext2(
1014        C: &Context,
1015        Str: *const c_char,
1016        SLen: size_t,
1017    ) -> &Metadata;
1018    pub(crate) fn LLVMMDNodeInContext2<'a>(
1019        C: &'a Context,
1020        Vals: *const &'a Metadata,
1021        Count: size_t,
1022    ) -> &'a Metadata;
1023    pub(crate) fn LLVMAddNamedMetadataOperand<'a>(
1024        M: &'a Module,
1025        Name: *const c_char,
1026        Val: &'a Value,
1027    );
1028
1029    // Operations on scalar constants
1030    pub(crate) fn LLVMConstInt(IntTy: &Type, N: c_ulonglong, SignExtend: Bool) -> &Value;
1031    pub(crate) fn LLVMConstIntOfArbitraryPrecision(
1032        IntTy: &Type,
1033        Wn: c_uint,
1034        Ws: *const u64,
1035    ) -> &Value;
1036    pub(crate) fn LLVMConstReal(RealTy: &Type, N: f64) -> &Value;
1037
1038    // Operations on composite constants
1039    pub(crate) fn LLVMConstArray2<'a>(
1040        ElementTy: &'a Type,
1041        ConstantVals: *const &'a Value,
1042        Length: u64,
1043    ) -> &'a Value;
1044    pub(crate) fn LLVMArrayType2(ElementType: &Type, ElementCount: u64) -> &Type;
1045    pub(crate) fn LLVMConstStringInContext2(
1046        C: &Context,
1047        Str: *const c_char,
1048        Length: size_t,
1049        DontNullTerminate: Bool,
1050    ) -> &Value;
1051    pub(crate) fn LLVMConstStructInContext<'a>(
1052        C: &'a Context,
1053        ConstantVals: *const &'a Value,
1054        Count: c_uint,
1055        Packed: Bool,
1056    ) -> &'a Value;
1057    pub(crate) fn LLVMConstNamedStruct<'a>(
1058        StructTy: &'a Type,
1059        ConstantVals: *const &'a Value,
1060        Count: c_uint,
1061    ) -> &'a Value;
1062    pub(crate) fn LLVMConstVector(ScalarConstantVals: *const &Value, Size: c_uint) -> &Value;
1063
1064    // Constant expressions
1065    pub(crate) fn LLVMConstInBoundsGEP2<'a>(
1066        ty: &'a Type,
1067        ConstantVal: &'a Value,
1068        ConstantIndices: *const &'a Value,
1069        NumIndices: c_uint,
1070    ) -> &'a Value;
1071    pub(crate) fn LLVMConstPtrToInt<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1072    pub(crate) fn LLVMConstIntToPtr<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1073    pub(crate) fn LLVMConstBitCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1074    pub(crate) fn LLVMConstPointerCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1075    pub(crate) fn LLVMGetAggregateElement(ConstantVal: &Value, Idx: c_uint) -> Option<&Value>;
1076    pub(crate) fn LLVMGetConstOpcode(ConstantVal: &Value) -> Opcode;
1077    pub(crate) fn LLVMIsAConstantExpr(Val: &Value) -> Option<&Value>;
1078
1079    // Operations on global variables, functions, and aliases (globals)
1080    pub(crate) fn LLVMIsDeclaration(Global: &Value) -> Bool;
1081    pub(crate) fn LLVMGetLinkage(Global: &Value) -> RawEnum<Linkage>;
1082    pub(crate) fn LLVMSetLinkage(Global: &Value, RustLinkage: Linkage);
1083    pub(crate) fn LLVMSetSection(Global: &Value, Section: *const c_char);
1084    pub(crate) fn LLVMGetVisibility(Global: &Value) -> RawEnum<Visibility>;
1085    pub(crate) fn LLVMSetVisibility(Global: &Value, Viz: Visibility);
1086    pub(crate) fn LLVMGetAlignment(Global: &Value) -> c_uint;
1087    pub(crate) fn LLVMSetAlignment(Global: &Value, Bytes: c_uint);
1088    pub(crate) fn LLVMSetDLLStorageClass(V: &Value, C: DLLStorageClass);
1089    pub(crate) fn LLVMGlobalGetValueType(Global: &Value) -> &Type;
1090
1091    // Operations on global variables
1092    pub(crate) safe fn LLVMIsAGlobalVariable(GlobalVar: &Value) -> Option<&Value>;
1093    pub(crate) fn LLVMAddGlobal<'a>(M: &'a Module, Ty: &'a Type, Name: *const c_char) -> &'a Value;
1094    pub(crate) fn LLVMGetNamedGlobal(M: &Module, Name: *const c_char) -> Option<&Value>;
1095    pub(crate) fn LLVMGetFirstGlobal(M: &Module) -> Option<&Value>;
1096    pub(crate) fn LLVMGetNextGlobal(GlobalVar: &Value) -> Option<&Value>;
1097    pub(crate) fn LLVMDeleteGlobal(GlobalVar: &Value);
1098    pub(crate) safe fn LLVMGetInitializer(GlobalVar: &Value) -> Option<&Value>;
1099    pub(crate) fn LLVMSetInitializer<'a>(GlobalVar: &'a Value, ConstantVal: &'a Value);
1100    pub(crate) safe fn LLVMIsThreadLocal(GlobalVar: &Value) -> Bool;
1101    pub(crate) fn LLVMSetThreadLocalMode(GlobalVar: &Value, Mode: ThreadLocalMode);
1102    pub(crate) safe fn LLVMIsGlobalConstant(GlobalVar: &Value) -> Bool;
1103    pub(crate) safe fn LLVMSetGlobalConstant(GlobalVar: &Value, IsConstant: Bool);
1104    pub(crate) safe fn LLVMSetTailCall(CallInst: &Value, IsTailCall: Bool);
1105    pub(crate) safe fn LLVMSetTailCallKind(CallInst: &Value, kind: TailCallKind);
1106    pub(crate) safe fn LLVMSetExternallyInitialized(GlobalVar: &Value, IsExtInit: Bool);
1107
1108    // Operations on attributes
1109    pub(crate) fn LLVMCreateStringAttribute(
1110        C: &Context,
1111        Name: *const c_char,
1112        NameLen: c_uint,
1113        Value: *const c_char,
1114        ValueLen: c_uint,
1115    ) -> &Attribute;
1116
1117    // Operations on functions
1118    pub(crate) fn LLVMSetFunctionCallConv(Fn: &Value, CC: c_uint);
1119
1120    // Operations about llvm intrinsics
1121    pub(crate) fn LLVMLookupIntrinsicID(Name: *const c_char, NameLen: size_t) -> c_uint;
1122    pub(crate) fn LLVMGetIntrinsicDeclaration<'a>(
1123        Mod: &'a Module,
1124        ID: NonZero<c_uint>,
1125        ParamTypes: *const &'a Type,
1126        ParamCount: size_t,
1127    ) -> &'a Value;
1128
1129    // Operations on parameters
1130    pub(crate) fn LLVMIsAArgument(Val: &Value) -> Option<&Value>;
1131    pub(crate) safe fn LLVMCountParams(Fn: &Value) -> c_uint;
1132    pub(crate) fn LLVMGetParam(Fn: &Value, Index: c_uint) -> &Value;
1133
1134    // Operations on basic blocks
1135    pub(crate) fn LLVMGetBasicBlockParent(BB: &BasicBlock) -> &Value;
1136    pub(crate) fn LLVMAppendBasicBlockInContext<'a>(
1137        C: &'a Context,
1138        Fn: &'a Value,
1139        Name: *const c_char,
1140    ) -> &'a BasicBlock;
1141
1142    // Operations on instructions
1143    pub(crate) fn LLVMGetInstructionParent(Inst: &Value) -> &BasicBlock;
1144    pub(crate) fn LLVMGetCalledValue(CallInst: &Value) -> Option<&Value>;
1145    pub(crate) fn LLVMIsAInstruction(Val: &Value) -> Option<&Value>;
1146    pub(crate) fn LLVMGetFirstBasicBlock(Fn: &Value) -> &BasicBlock;
1147    pub(crate) fn LLVMGetOperand(Val: &Value, Index: c_uint) -> Option<&Value>;
1148
1149    // Operations on call sites
1150    pub(crate) fn LLVMSetInstructionCallConv(Instr: &Value, CC: c_uint);
1151
1152    // Operations on load/store instructions (only)
1153    pub(crate) fn LLVMSetVolatile(MemoryAccessInst: &Value, volatile: Bool);
1154    pub(crate) fn LLVMSetOrdering(MemoryAccessInst: &Value, Ordering: AtomicOrdering);
1155
1156    // Operations on phi nodes
1157    pub(crate) fn LLVMAddIncoming<'a>(
1158        PhiNode: &'a Value,
1159        IncomingValues: *const &'a Value,
1160        IncomingBlocks: *const &'a BasicBlock,
1161        Count: c_uint,
1162    );
1163
1164    // Instruction builders
1165    pub(crate) fn LLVMCreateBuilderInContext(C: &Context) -> &mut Builder<'_>;
1166    pub(crate) fn LLVMPositionBuilderAtEnd<'a>(Builder: &Builder<'a>, Block: &'a BasicBlock);
1167    pub(crate) fn LLVMGetInsertBlock<'a>(Builder: &Builder<'a>) -> &'a BasicBlock;
1168    pub(crate) fn LLVMDisposeBuilder<'a>(Builder: &'a mut Builder<'a>);
1169
1170    // Metadata
1171    pub(crate) fn LLVMSetCurrentDebugLocation2<'a>(Builder: &Builder<'a>, Loc: *const Metadata);
1172    pub(crate) fn LLVMGetCurrentDebugLocation2<'a>(Builder: &Builder<'a>) -> Option<&'a Metadata>;
1173
1174    // Terminators
1175    pub(crate) safe fn LLVMBuildRetVoid<'a>(B: &Builder<'a>) -> &'a Value;
1176    pub(crate) fn LLVMBuildRet<'a>(B: &Builder<'a>, V: &'a Value) -> &'a Value;
1177    pub(crate) fn LLVMBuildBr<'a>(B: &Builder<'a>, Dest: &'a BasicBlock) -> &'a Value;
1178    pub(crate) fn LLVMBuildCondBr<'a>(
1179        B: &Builder<'a>,
1180        If: &'a Value,
1181        Then: &'a BasicBlock,
1182        Else: &'a BasicBlock,
1183    ) -> &'a Value;
1184    pub(crate) fn LLVMBuildSwitch<'a>(
1185        B: &Builder<'a>,
1186        V: &'a Value,
1187        Else: &'a BasicBlock,
1188        NumCases: c_uint,
1189    ) -> &'a Value;
1190    pub(crate) fn LLVMBuildLandingPad<'a>(
1191        B: &Builder<'a>,
1192        Ty: &'a Type,
1193        PersFn: Option<&'a Value>,
1194        NumClauses: c_uint,
1195        Name: *const c_char,
1196    ) -> &'a Value;
1197    pub(crate) fn LLVMBuildResume<'a>(B: &Builder<'a>, Exn: &'a Value) -> &'a Value;
1198    pub(crate) fn LLVMBuildUnreachable<'a>(B: &Builder<'a>) -> &'a Value;
1199
1200    pub(crate) fn LLVMBuildCleanupPad<'a>(
1201        B: &Builder<'a>,
1202        ParentPad: Option<&'a Value>,
1203        Args: *const &'a Value,
1204        NumArgs: c_uint,
1205        Name: *const c_char,
1206    ) -> Option<&'a Value>;
1207    pub(crate) fn LLVMBuildCleanupRet<'a>(
1208        B: &Builder<'a>,
1209        CleanupPad: &'a Value,
1210        BB: Option<&'a BasicBlock>,
1211    ) -> Option<&'a Value>;
1212    pub(crate) fn LLVMBuildCatchPad<'a>(
1213        B: &Builder<'a>,
1214        ParentPad: &'a Value,
1215        Args: *const &'a Value,
1216        NumArgs: c_uint,
1217        Name: *const c_char,
1218    ) -> Option<&'a Value>;
1219    pub(crate) fn LLVMBuildCatchRet<'a>(
1220        B: &Builder<'a>,
1221        CatchPad: &'a Value,
1222        BB: &'a BasicBlock,
1223    ) -> Option<&'a Value>;
1224    pub(crate) fn LLVMBuildCatchSwitch<'a>(
1225        Builder: &Builder<'a>,
1226        ParentPad: Option<&'a Value>,
1227        UnwindBB: Option<&'a BasicBlock>,
1228        NumHandlers: c_uint,
1229        Name: *const c_char,
1230    ) -> Option<&'a Value>;
1231    pub(crate) fn LLVMAddHandler<'a>(CatchSwitch: &'a Value, Dest: &'a BasicBlock);
1232    pub(crate) fn LLVMSetPersonalityFn<'a>(Func: &'a Value, Pers: &'a Value);
1233
1234    // Add a case to the switch instruction
1235    pub(crate) fn LLVMAddCase<'a>(Switch: &'a Value, OnVal: &'a Value, Dest: &'a BasicBlock);
1236
1237    // Add a clause to the landing pad instruction
1238    pub(crate) fn LLVMAddClause<'a>(LandingPad: &'a Value, ClauseVal: &'a Value);
1239
1240    // Set the cleanup on a landing pad instruction
1241    pub(crate) fn LLVMSetCleanup(LandingPad: &Value, Val: Bool);
1242
1243    // Arithmetic
1244    pub(crate) fn LLVMBuildAdd<'a>(
1245        B: &Builder<'a>,
1246        LHS: &'a Value,
1247        RHS: &'a Value,
1248        Name: *const c_char,
1249    ) -> &'a Value;
1250    pub(crate) fn LLVMBuildFAdd<'a>(
1251        B: &Builder<'a>,
1252        LHS: &'a Value,
1253        RHS: &'a Value,
1254        Name: *const c_char,
1255    ) -> &'a Value;
1256    pub(crate) fn LLVMBuildSub<'a>(
1257        B: &Builder<'a>,
1258        LHS: &'a Value,
1259        RHS: &'a Value,
1260        Name: *const c_char,
1261    ) -> &'a Value;
1262    pub(crate) fn LLVMBuildFSub<'a>(
1263        B: &Builder<'a>,
1264        LHS: &'a Value,
1265        RHS: &'a Value,
1266        Name: *const c_char,
1267    ) -> &'a Value;
1268    pub(crate) fn LLVMBuildMul<'a>(
1269        B: &Builder<'a>,
1270        LHS: &'a Value,
1271        RHS: &'a Value,
1272        Name: *const c_char,
1273    ) -> &'a Value;
1274    pub(crate) fn LLVMBuildFMul<'a>(
1275        B: &Builder<'a>,
1276        LHS: &'a Value,
1277        RHS: &'a Value,
1278        Name: *const c_char,
1279    ) -> &'a Value;
1280    pub(crate) fn LLVMBuildUDiv<'a>(
1281        B: &Builder<'a>,
1282        LHS: &'a Value,
1283        RHS: &'a Value,
1284        Name: *const c_char,
1285    ) -> &'a Value;
1286    pub(crate) fn LLVMBuildExactUDiv<'a>(
1287        B: &Builder<'a>,
1288        LHS: &'a Value,
1289        RHS: &'a Value,
1290        Name: *const c_char,
1291    ) -> &'a Value;
1292    pub(crate) fn LLVMBuildSDiv<'a>(
1293        B: &Builder<'a>,
1294        LHS: &'a Value,
1295        RHS: &'a Value,
1296        Name: *const c_char,
1297    ) -> &'a Value;
1298    pub(crate) fn LLVMBuildExactSDiv<'a>(
1299        B: &Builder<'a>,
1300        LHS: &'a Value,
1301        RHS: &'a Value,
1302        Name: *const c_char,
1303    ) -> &'a Value;
1304    pub(crate) fn LLVMBuildFDiv<'a>(
1305        B: &Builder<'a>,
1306        LHS: &'a Value,
1307        RHS: &'a Value,
1308        Name: *const c_char,
1309    ) -> &'a Value;
1310    pub(crate) fn LLVMBuildURem<'a>(
1311        B: &Builder<'a>,
1312        LHS: &'a Value,
1313        RHS: &'a Value,
1314        Name: *const c_char,
1315    ) -> &'a Value;
1316    pub(crate) fn LLVMBuildSRem<'a>(
1317        B: &Builder<'a>,
1318        LHS: &'a Value,
1319        RHS: &'a Value,
1320        Name: *const c_char,
1321    ) -> &'a Value;
1322    pub(crate) fn LLVMBuildFRem<'a>(
1323        B: &Builder<'a>,
1324        LHS: &'a Value,
1325        RHS: &'a Value,
1326        Name: *const c_char,
1327    ) -> &'a Value;
1328    pub(crate) fn LLVMBuildShl<'a>(
1329        B: &Builder<'a>,
1330        LHS: &'a Value,
1331        RHS: &'a Value,
1332        Name: *const c_char,
1333    ) -> &'a Value;
1334    pub(crate) fn LLVMBuildLShr<'a>(
1335        B: &Builder<'a>,
1336        LHS: &'a Value,
1337        RHS: &'a Value,
1338        Name: *const c_char,
1339    ) -> &'a Value;
1340    pub(crate) fn LLVMBuildAShr<'a>(
1341        B: &Builder<'a>,
1342        LHS: &'a Value,
1343        RHS: &'a Value,
1344        Name: *const c_char,
1345    ) -> &'a Value;
1346    pub(crate) fn LLVMBuildNSWAdd<'a>(
1347        B: &Builder<'a>,
1348        LHS: &'a Value,
1349        RHS: &'a Value,
1350        Name: *const c_char,
1351    ) -> &'a Value;
1352    pub(crate) fn LLVMBuildNUWAdd<'a>(
1353        B: &Builder<'a>,
1354        LHS: &'a Value,
1355        RHS: &'a Value,
1356        Name: *const c_char,
1357    ) -> &'a Value;
1358    pub(crate) fn LLVMBuildNSWSub<'a>(
1359        B: &Builder<'a>,
1360        LHS: &'a Value,
1361        RHS: &'a Value,
1362        Name: *const c_char,
1363    ) -> &'a Value;
1364    pub(crate) fn LLVMBuildNUWSub<'a>(
1365        B: &Builder<'a>,
1366        LHS: &'a Value,
1367        RHS: &'a Value,
1368        Name: *const c_char,
1369    ) -> &'a Value;
1370    pub(crate) fn LLVMBuildNSWMul<'a>(
1371        B: &Builder<'a>,
1372        LHS: &'a Value,
1373        RHS: &'a Value,
1374        Name: *const c_char,
1375    ) -> &'a Value;
1376    pub(crate) fn LLVMBuildNUWMul<'a>(
1377        B: &Builder<'a>,
1378        LHS: &'a Value,
1379        RHS: &'a Value,
1380        Name: *const c_char,
1381    ) -> &'a Value;
1382    pub(crate) fn LLVMBuildAnd<'a>(
1383        B: &Builder<'a>,
1384        LHS: &'a Value,
1385        RHS: &'a Value,
1386        Name: *const c_char,
1387    ) -> &'a Value;
1388    pub(crate) fn LLVMBuildOr<'a>(
1389        B: &Builder<'a>,
1390        LHS: &'a Value,
1391        RHS: &'a Value,
1392        Name: *const c_char,
1393    ) -> &'a Value;
1394    pub(crate) fn LLVMBuildXor<'a>(
1395        B: &Builder<'a>,
1396        LHS: &'a Value,
1397        RHS: &'a Value,
1398        Name: *const c_char,
1399    ) -> &'a Value;
1400    pub(crate) fn LLVMBuildNeg<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char)
1401    -> &'a Value;
1402    pub(crate) fn LLVMBuildFNeg<'a>(
1403        B: &Builder<'a>,
1404        V: &'a Value,
1405        Name: *const c_char,
1406    ) -> &'a Value;
1407    pub(crate) fn LLVMBuildNot<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char)
1408    -> &'a Value;
1409
1410    // Extra flags on arithmetic
1411    pub(crate) fn LLVMSetIsDisjoint(Instr: &Value, IsDisjoint: Bool);
1412    pub(crate) fn LLVMSetNUW(ArithInst: &Value, HasNUW: Bool);
1413    pub(crate) fn LLVMSetNSW(ArithInst: &Value, HasNSW: Bool);
1414
1415    // Memory
1416    pub(crate) fn LLVMBuildAlloca<'a>(
1417        B: &Builder<'a>,
1418        Ty: &'a Type,
1419        Name: *const c_char,
1420    ) -> &'a Value;
1421    pub(crate) fn LLVMBuildLoad2<'a>(
1422        B: &Builder<'a>,
1423        Ty: &'a Type,
1424        PointerVal: &'a Value,
1425        Name: *const c_char,
1426    ) -> &'a Value;
1427
1428    pub(crate) fn LLVMBuildStore<'a>(B: &Builder<'a>, Val: &'a Value, Ptr: &'a Value) -> &'a Value;
1429
1430    pub(crate) fn LLVMBuildGEPWithNoWrapFlags<'a>(
1431        B: &Builder<'a>,
1432        Ty: &'a Type,
1433        Pointer: &'a Value,
1434        Indices: *const &'a Value,
1435        NumIndices: c_uint,
1436        Name: *const c_char,
1437        Flags: GEPNoWrapFlags,
1438    ) -> &'a Value;
1439
1440    // Casts
1441    pub(crate) fn LLVMBuildTrunc<'a>(
1442        B: &Builder<'a>,
1443        Val: &'a Value,
1444        DestTy: &'a Type,
1445        Name: *const c_char,
1446    ) -> &'a Value;
1447    pub(crate) fn LLVMBuildZExt<'a>(
1448        B: &Builder<'a>,
1449        Val: &'a Value,
1450        DestTy: &'a Type,
1451        Name: *const c_char,
1452    ) -> &'a Value;
1453    pub(crate) fn LLVMBuildSExt<'a>(
1454        B: &Builder<'a>,
1455        Val: &'a Value,
1456        DestTy: &'a Type,
1457        Name: *const c_char,
1458    ) -> &'a Value;
1459    pub(crate) fn LLVMBuildFPToUI<'a>(
1460        B: &Builder<'a>,
1461        Val: &'a Value,
1462        DestTy: &'a Type,
1463        Name: *const c_char,
1464    ) -> &'a Value;
1465    pub(crate) fn LLVMBuildFPToSI<'a>(
1466        B: &Builder<'a>,
1467        Val: &'a Value,
1468        DestTy: &'a Type,
1469        Name: *const c_char,
1470    ) -> &'a Value;
1471    pub(crate) fn LLVMBuildUIToFP<'a>(
1472        B: &Builder<'a>,
1473        Val: &'a Value,
1474        DestTy: &'a Type,
1475        Name: *const c_char,
1476    ) -> &'a Value;
1477    pub(crate) fn LLVMBuildSIToFP<'a>(
1478        B: &Builder<'a>,
1479        Val: &'a Value,
1480        DestTy: &'a Type,
1481        Name: *const c_char,
1482    ) -> &'a Value;
1483    pub(crate) fn LLVMBuildFPTrunc<'a>(
1484        B: &Builder<'a>,
1485        Val: &'a Value,
1486        DestTy: &'a Type,
1487        Name: *const c_char,
1488    ) -> &'a Value;
1489    pub(crate) fn LLVMBuildFPExt<'a>(
1490        B: &Builder<'a>,
1491        Val: &'a Value,
1492        DestTy: &'a Type,
1493        Name: *const c_char,
1494    ) -> &'a Value;
1495    pub(crate) fn LLVMBuildPtrToInt<'a>(
1496        B: &Builder<'a>,
1497        Val: &'a Value,
1498        DestTy: &'a Type,
1499        Name: *const c_char,
1500    ) -> &'a Value;
1501    pub(crate) fn LLVMBuildIntToPtr<'a>(
1502        B: &Builder<'a>,
1503        Val: &'a Value,
1504        DestTy: &'a Type,
1505        Name: *const c_char,
1506    ) -> &'a Value;
1507    pub(crate) fn LLVMBuildBitCast<'a>(
1508        B: &Builder<'a>,
1509        Val: &'a Value,
1510        DestTy: &'a Type,
1511        Name: *const c_char,
1512    ) -> &'a Value;
1513    pub(crate) fn LLVMBuildPointerCast<'a>(
1514        B: &Builder<'a>,
1515        Val: &'a Value,
1516        DestTy: &'a Type,
1517        Name: *const c_char,
1518    ) -> &'a Value;
1519    pub(crate) fn LLVMBuildIntCast2<'a>(
1520        B: &Builder<'a>,
1521        Val: &'a Value,
1522        DestTy: &'a Type,
1523        IsSigned: Bool,
1524        Name: *const c_char,
1525    ) -> &'a Value;
1526
1527    // Comparisons
1528    pub(crate) fn LLVMBuildICmp<'a>(
1529        B: &Builder<'a>,
1530        Op: c_uint,
1531        LHS: &'a Value,
1532        RHS: &'a Value,
1533        Name: *const c_char,
1534    ) -> &'a Value;
1535    pub(crate) fn LLVMBuildFCmp<'a>(
1536        B: &Builder<'a>,
1537        Op: c_uint,
1538        LHS: &'a Value,
1539        RHS: &'a Value,
1540        Name: *const c_char,
1541    ) -> &'a Value;
1542
1543    // Miscellaneous instructions
1544    pub(crate) fn LLVMBuildPhi<'a>(B: &Builder<'a>, Ty: &'a Type, Name: *const c_char)
1545    -> &'a Value;
1546    pub(crate) fn LLVMBuildSelect<'a>(
1547        B: &Builder<'a>,
1548        If: &'a Value,
1549        Then: &'a Value,
1550        Else: &'a Value,
1551        Name: *const c_char,
1552    ) -> &'a Value;
1553    pub(crate) fn LLVMBuildVAArg<'a>(
1554        B: &Builder<'a>,
1555        list: &'a Value,
1556        Ty: &'a Type,
1557        Name: *const c_char,
1558    ) -> &'a Value;
1559    pub(crate) fn LLVMBuildExtractElement<'a>(
1560        B: &Builder<'a>,
1561        VecVal: &'a Value,
1562        Index: &'a Value,
1563        Name: *const c_char,
1564    ) -> &'a Value;
1565    pub(crate) fn LLVMBuildInsertElement<'a>(
1566        B: &Builder<'a>,
1567        VecVal: &'a Value,
1568        EltVal: &'a Value,
1569        Index: &'a Value,
1570        Name: *const c_char,
1571    ) -> &'a Value;
1572    pub(crate) fn LLVMBuildShuffleVector<'a>(
1573        B: &Builder<'a>,
1574        V1: &'a Value,
1575        V2: &'a Value,
1576        Mask: &'a Value,
1577        Name: *const c_char,
1578    ) -> &'a Value;
1579    pub(crate) fn LLVMBuildExtractValue<'a>(
1580        B: &Builder<'a>,
1581        AggVal: &'a Value,
1582        Index: c_uint,
1583        Name: *const c_char,
1584    ) -> &'a Value;
1585    pub(crate) fn LLVMBuildInsertValue<'a>(
1586        B: &Builder<'a>,
1587        AggVal: &'a Value,
1588        EltVal: &'a Value,
1589        Index: c_uint,
1590        Name: *const c_char,
1591    ) -> &'a Value;
1592
1593    // Atomic Operations
1594    pub(crate) fn LLVMBuildAtomicCmpXchg<'a>(
1595        B: &Builder<'a>,
1596        LHS: &'a Value,
1597        CMP: &'a Value,
1598        RHS: &'a Value,
1599        Order: AtomicOrdering,
1600        FailureOrder: AtomicOrdering,
1601        SingleThreaded: Bool,
1602    ) -> &'a Value;
1603
1604    pub(crate) fn LLVMSetWeak(CmpXchgInst: &Value, IsWeak: Bool);
1605
1606    pub(crate) fn LLVMBuildAtomicRMW<'a>(
1607        B: &Builder<'a>,
1608        Op: AtomicRmwBinOp,
1609        LHS: &'a Value,
1610        RHS: &'a Value,
1611        Order: AtomicOrdering,
1612        SingleThreaded: Bool,
1613    ) -> &'a Value;
1614
1615    pub(crate) fn LLVMBuildFence<'a>(
1616        B: &Builder<'a>,
1617        Order: AtomicOrdering,
1618        SingleThreaded: Bool,
1619        Name: *const c_char,
1620    ) -> &'a Value;
1621
1622    /// Writes a module to the specified path. Returns 0 on success.
1623    pub(crate) fn LLVMWriteBitcodeToFile(M: &Module, Path: *const c_char) -> c_int;
1624
1625    /// Creates a legacy pass manager -- only used for final codegen.
1626    pub(crate) fn LLVMCreatePassManager<'a>() -> &'a mut PassManager<'a>;
1627
1628    pub(crate) fn LLVMAddAnalysisPasses<'a>(T: &'a TargetMachine, PM: &PassManager<'a>);
1629
1630    pub(crate) fn LLVMGetHostCPUFeatures() -> *mut c_char;
1631
1632    pub(crate) fn LLVMDisposeMessage(message: *mut c_char);
1633
1634    pub(crate) fn LLVMIsMultithreaded() -> Bool;
1635
1636    pub(crate) fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type;
1637
1638    pub(crate) fn LLVMStructSetBody<'a>(
1639        StructTy: &'a Type,
1640        ElementTypes: *const &'a Type,
1641        ElementCount: c_uint,
1642        Packed: Bool,
1643    );
1644
1645    pub(crate) safe fn LLVMMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value;
1646
1647    pub(crate) safe fn LLVMSetUnnamedAddress(Global: &Value, UnnamedAddr: UnnamedAddr);
1648
1649    pub(crate) fn LLVMIsAConstantInt(value_ref: &Value) -> Option<&ConstantInt>;
1650
1651    pub(crate) fn LLVMGetOrInsertComdat(M: &Module, Name: *const c_char) -> &Comdat;
1652    pub(crate) fn LLVMSetComdat(V: &Value, C: &Comdat);
1653
1654    pub(crate) fn LLVMCreateOperandBundle(
1655        Tag: *const c_char,
1656        TagLen: size_t,
1657        Args: *const &'_ Value,
1658        NumArgs: c_uint,
1659    ) -> *mut OperandBundle<'_>;
1660    pub(crate) fn LLVMDisposeOperandBundle(Bundle: ptr::NonNull<OperandBundle<'_>>);
1661
1662    pub(crate) fn LLVMBuildCallWithOperandBundles<'a>(
1663        B: &Builder<'a>,
1664        Ty: &'a Type,
1665        Fn: &'a Value,
1666        Args: *const &'a Value,
1667        NumArgs: c_uint,
1668        Bundles: *const &OperandBundle<'a>,
1669        NumBundles: c_uint,
1670        Name: *const c_char,
1671    ) -> &'a Value;
1672    pub(crate) fn LLVMBuildInvokeWithOperandBundles<'a>(
1673        B: &Builder<'a>,
1674        Ty: &'a Type,
1675        Fn: &'a Value,
1676        Args: *const &'a Value,
1677        NumArgs: c_uint,
1678        Then: &'a BasicBlock,
1679        Catch: &'a BasicBlock,
1680        Bundles: *const &OperandBundle<'a>,
1681        NumBundles: c_uint,
1682        Name: *const c_char,
1683    ) -> &'a Value;
1684    pub(crate) fn LLVMBuildCallBr<'a>(
1685        B: &Builder<'a>,
1686        Ty: &'a Type,
1687        Fn: &'a Value,
1688        DefaultDest: &'a BasicBlock,
1689        IndirectDests: *const &'a BasicBlock,
1690        NumIndirectDests: c_uint,
1691        Args: *const &'a Value,
1692        NumArgs: c_uint,
1693        Bundles: *const &OperandBundle<'a>,
1694        NumBundles: c_uint,
1695        Name: *const c_char,
1696    ) -> &'a Value;
1697}
1698
1699// FFI bindings for `DIBuilder` functions in the LLVM-C API.
1700// Try to keep these in the same order as in `llvm/include/llvm-c/DebugInfo.h`.
1701//
1702// FIXME(#134001): Audit all `Option` parameters, especially in lists, to check
1703// that they really are nullable on the C/C++ side. LLVM doesn't appear to
1704// actually document which ones are nullable.
1705unsafe extern "C" {
1706    pub(crate) fn LLVMCreateDIBuilder<'ll>(M: &'ll Module) -> *mut DIBuilder<'ll>;
1707    pub(crate) fn LLVMDisposeDIBuilder<'ll>(Builder: ptr::NonNull<DIBuilder<'ll>>);
1708
1709    pub(crate) fn LLVMDIBuilderFinalize<'ll>(Builder: &DIBuilder<'ll>);
1710
1711    pub(crate) fn LLVMDIBuilderCreateNameSpace<'ll>(
1712        Builder: &DIBuilder<'ll>,
1713        ParentScope: Option<&'ll Metadata>,
1714        Name: *const c_uchar, // See "PTR_LEN_STR".
1715        NameLen: size_t,
1716        ExportSymbols: llvm::Bool,
1717    ) -> &'ll Metadata;
1718
1719    pub(crate) fn LLVMDIBuilderCreateLexicalBlock<'ll>(
1720        Builder: &DIBuilder<'ll>,
1721        Scope: &'ll Metadata,
1722        File: &'ll Metadata,
1723        Line: c_uint,
1724        Column: c_uint,
1725    ) -> &'ll Metadata;
1726
1727    pub(crate) fn LLVMDIBuilderCreateLexicalBlockFile<'ll>(
1728        Builder: &DIBuilder<'ll>,
1729        Scope: &'ll Metadata,
1730        File: &'ll Metadata,
1731        Discriminator: c_uint, // (optional "DWARF path discriminator"; default is 0)
1732    ) -> &'ll Metadata;
1733
1734    pub(crate) fn LLVMDIBuilderCreateDebugLocation<'ll>(
1735        Ctx: &'ll Context,
1736        Line: c_uint,
1737        Column: c_uint,
1738        Scope: &'ll Metadata,
1739        InlinedAt: Option<&'ll Metadata>,
1740    ) -> &'ll Metadata;
1741
1742    pub(crate) fn LLVMDIBuilderCreateSubroutineType<'ll>(
1743        Builder: &DIBuilder<'ll>,
1744        File: Option<&'ll Metadata>, // (ignored and has no effect)
1745        ParameterTypes: *const Option<&'ll Metadata>,
1746        NumParameterTypes: c_uint,
1747        Flags: DIFlags, // (default is `DIFlags::DIFlagZero`)
1748    ) -> &'ll Metadata;
1749
1750    pub(crate) fn LLVMDIBuilderCreateUnionType<'ll>(
1751        Builder: &DIBuilder<'ll>,
1752        Scope: Option<&'ll Metadata>,
1753        Name: *const c_uchar, // See "PTR_LEN_STR".
1754        NameLen: size_t,
1755        File: &'ll Metadata,
1756        LineNumber: c_uint,
1757        SizeInBits: u64,
1758        AlignInBits: u32,
1759        Flags: DIFlags,
1760        Elements: *const Option<&'ll Metadata>,
1761        NumElements: c_uint,
1762        RunTimeLang: c_uint, // (optional Objective-C runtime version; default is 0)
1763        UniqueId: *const c_uchar, // See "PTR_LEN_STR".
1764        UniqueIdLen: size_t,
1765    ) -> &'ll Metadata;
1766
1767    pub(crate) fn LLVMDIBuilderCreateArrayType<'ll>(
1768        Builder: &DIBuilder<'ll>,
1769        Size: u64,
1770        Align: u32,
1771        Ty: &'ll Metadata,
1772        Subscripts: *const &'ll Metadata,
1773        NumSubscripts: c_uint,
1774    ) -> &'ll Metadata;
1775
1776    pub(crate) fn LLVMDIBuilderCreateBasicType<'ll>(
1777        Builder: &DIBuilder<'ll>,
1778        Name: *const c_uchar, // See "PTR_LEN_STR".
1779        NameLen: size_t,
1780        SizeInBits: u64,
1781        Encoding: c_uint, // (`LLVMDWARFTypeEncoding`)
1782        Flags: DIFlags,   // (default is `DIFlags::DIFlagZero`)
1783    ) -> &'ll Metadata;
1784
1785    pub(crate) fn LLVMDIBuilderCreatePointerType<'ll>(
1786        Builder: &DIBuilder<'ll>,
1787        PointeeTy: &'ll Metadata,
1788        SizeInBits: u64,
1789        AlignInBits: u32,
1790        AddressSpace: c_uint, // (optional DWARF address space; default is 0)
1791        Name: *const c_uchar, // See "PTR_LEN_STR".
1792        NameLen: size_t,
1793    ) -> &'ll Metadata;
1794
1795    pub(crate) fn LLVMDIBuilderCreateStructType<'ll>(
1796        Builder: &DIBuilder<'ll>,
1797        Scope: Option<&'ll Metadata>,
1798        Name: *const c_uchar, // See "PTR_LEN_STR".
1799        NameLen: size_t,
1800        File: &'ll Metadata,
1801        LineNumber: c_uint,
1802        SizeInBits: u64,
1803        AlignInBits: u32,
1804        Flags: DIFlags,
1805        DerivedFrom: Option<&'ll Metadata>,
1806        Elements: *const Option<&'ll Metadata>,
1807        NumElements: c_uint,
1808        RunTimeLang: c_uint, // (optional Objective-C runtime version; default is 0)
1809        VTableHolder: Option<&'ll Metadata>,
1810        UniqueId: *const c_uchar, // See "PTR_LEN_STR".
1811        UniqueIdLen: size_t,
1812    ) -> &'ll Metadata;
1813
1814    pub(crate) fn LLVMDIBuilderCreateMemberType<'ll>(
1815        Builder: &DIBuilder<'ll>,
1816        Scope: &'ll Metadata,
1817        Name: *const c_uchar, // See "PTR_LEN_STR".
1818        NameLen: size_t,
1819        File: &'ll Metadata,
1820        LineNo: c_uint,
1821        SizeInBits: u64,
1822        AlignInBits: u32,
1823        OffsetInBits: u64,
1824        Flags: DIFlags,
1825        Ty: &'ll Metadata,
1826    ) -> &'ll Metadata;
1827
1828    pub(crate) fn LLVMDIBuilderCreateStaticMemberType<'ll>(
1829        Builder: &DIBuilder<'ll>,
1830        Scope: &'ll Metadata,
1831        Name: *const c_uchar, // See "PTR_LEN_STR".
1832        NameLen: size_t,
1833        File: &'ll Metadata,
1834        LineNumber: c_uint,
1835        Type: &'ll Metadata,
1836        Flags: DIFlags,
1837        ConstantVal: Option<&'ll Value>,
1838        AlignInBits: u32,
1839    ) -> &'ll Metadata;
1840
1841    /// Creates a "qualified type" in the C/C++ sense, by adding modifiers
1842    /// like `const` or `volatile`.
1843    pub(crate) fn LLVMDIBuilderCreateQualifiedType<'ll>(
1844        Builder: &DIBuilder<'ll>,
1845        Tag: c_uint, // (DWARF tag, e.g. `DW_TAG_const_type`)
1846        Type: &'ll Metadata,
1847    ) -> &'ll Metadata;
1848
1849    pub(crate) fn LLVMDIBuilderCreateTypedef<'ll>(
1850        Builder: &DIBuilder<'ll>,
1851        Type: &'ll Metadata,
1852        Name: *const c_uchar, // See "PTR_LEN_STR".
1853        NameLen: size_t,
1854        File: &'ll Metadata,
1855        LineNo: c_uint,
1856        Scope: Option<&'ll Metadata>,
1857        AlignInBits: u32, // (optional; default is 0)
1858    ) -> &'ll Metadata;
1859
1860    pub(crate) fn LLVMDIBuilderGetOrCreateSubrange<'ll>(
1861        Builder: &DIBuilder<'ll>,
1862        LowerBound: i64,
1863        Count: i64,
1864    ) -> &'ll Metadata;
1865
1866    pub(crate) fn LLVMDIBuilderGetOrCreateArray<'ll>(
1867        Builder: &DIBuilder<'ll>,
1868        Data: *const Option<&'ll Metadata>,
1869        NumElements: size_t,
1870    ) -> &'ll Metadata;
1871
1872    pub(crate) fn LLVMDIBuilderCreateExpression<'ll>(
1873        Builder: &DIBuilder<'ll>,
1874        Addr: *const u64,
1875        Length: size_t,
1876    ) -> &'ll Metadata;
1877
1878    pub(crate) fn LLVMDIBuilderInsertDeclareRecordAtEnd<'ll>(
1879        Builder: &DIBuilder<'ll>,
1880        Storage: &'ll Value,
1881        VarInfo: &'ll Metadata,
1882        Expr: &'ll Metadata,
1883        DebugLoc: &'ll Metadata,
1884        Block: &'ll BasicBlock,
1885    ) -> &'ll DbgRecord;
1886
1887    pub(crate) fn LLVMDIBuilderInsertDbgValueRecordAtEnd<'ll>(
1888        Builder: &DIBuilder<'ll>,
1889        Val: &'ll Value,
1890        VarInfo: &'ll Metadata,
1891        Expr: &'ll Metadata,
1892        DebugLoc: &'ll Metadata,
1893        Block: &'ll BasicBlock,
1894    ) -> &'ll DbgRecord;
1895
1896    pub(crate) fn LLVMDIBuilderCreateAutoVariable<'ll>(
1897        Builder: &DIBuilder<'ll>,
1898        Scope: &'ll Metadata,
1899        Name: *const c_uchar, // See "PTR_LEN_STR".
1900        NameLen: size_t,
1901        File: &'ll Metadata,
1902        LineNo: c_uint,
1903        Ty: &'ll Metadata,
1904        AlwaysPreserve: llvm::Bool, // "If true, this descriptor will survive optimizations."
1905        Flags: DIFlags,
1906        AlignInBits: u32,
1907    ) -> &'ll Metadata;
1908
1909    pub(crate) fn LLVMDIBuilderCreateParameterVariable<'ll>(
1910        Builder: &DIBuilder<'ll>,
1911        Scope: &'ll Metadata,
1912        Name: *const c_uchar, // See "PTR_LEN_STR".
1913        NameLen: size_t,
1914        ArgNo: c_uint,
1915        File: &'ll Metadata,
1916        LineNo: c_uint,
1917        Ty: &'ll Metadata,
1918        AlwaysPreserve: llvm::Bool, // "If true, this descriptor will survive optimizations."
1919        Flags: DIFlags,
1920    ) -> &'ll Metadata;
1921}
1922
1923#[link(name = "llvm-wrapper", kind = "static")]
1924unsafe extern "C" {
1925    pub(crate) fn LLVMRustInstallErrorHandlers();
1926    pub(crate) fn LLVMRustDisableSystemDialogsOnCrash();
1927
1928    // Create and destroy contexts.
1929    pub(crate) fn LLVMRustContextCreate(shouldDiscardNames: bool) -> &'static mut Context;
1930
1931    // Operations on all values
1932    pub(crate) fn LLVMRustGlobalAddMetadata<'a>(
1933        Val: &'a Value,
1934        KindID: MetadataKindId,
1935        Metadata: &'a Metadata,
1936    );
1937    pub(crate) fn LLVMRustIsNonGVFunctionPointerTy(Val: &Value) -> bool;
1938
1939    // Operations on scalar constants
1940    pub(crate) fn LLVMRustConstIntGetZExtValue(ConstantVal: &ConstantInt, Value: &mut u64) -> bool;
1941    pub(crate) fn LLVMRustConstInt128Get(
1942        ConstantVal: &ConstantInt,
1943        SExt: bool,
1944        high: &mut u64,
1945        low: &mut u64,
1946    ) -> bool;
1947
1948    // Operations on global variables, functions, and aliases (globals)
1949    pub(crate) fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool);
1950
1951    // Operations on global variables
1952    pub(crate) fn LLVMRustGetOrInsertGlobal<'a>(
1953        M: &'a Module,
1954        Name: *const c_char,
1955        NameLen: size_t,
1956        T: &'a Type,
1957    ) -> &'a Value;
1958    pub(crate) fn LLVMRustInsertPrivateGlobal<'a>(M: &'a Module, T: &'a Type) -> &'a Value;
1959    pub(crate) fn LLVMRustGetNamedValue(
1960        M: &Module,
1961        Name: *const c_char,
1962        NameLen: size_t,
1963    ) -> Option<&Value>;
1964
1965    // Operations on attributes
1966    pub(crate) fn LLVMRustCreateAttrNoValue(C: &Context, attr: AttributeKind) -> &Attribute;
1967    pub(crate) fn LLVMRustCreateAlignmentAttr(C: &Context, bytes: u64) -> &Attribute;
1968    pub(crate) fn LLVMRustCreateDereferenceableAttr(C: &Context, bytes: u64) -> &Attribute;
1969    pub(crate) fn LLVMRustCreateDereferenceableOrNullAttr(C: &Context, bytes: u64) -> &Attribute;
1970    pub(crate) fn LLVMRustCreateByValAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
1971    pub(crate) fn LLVMRustCreateStructRetAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
1972    pub(crate) fn LLVMRustCreateElementTypeAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
1973    pub(crate) fn LLVMRustCreateUWTableAttr(C: &Context, async_: bool) -> &Attribute;
1974    pub(crate) fn LLVMRustCreateAllocSizeAttr(C: &Context, size_arg: u32) -> &Attribute;
1975    pub(crate) fn LLVMRustCreateAllocKindAttr(C: &Context, size_arg: u64) -> &Attribute;
1976    pub(crate) fn LLVMRustCreateMemoryEffectsAttr(
1977        C: &Context,
1978        effects: MemoryEffects,
1979    ) -> &Attribute;
1980    /// ## Safety
1981    /// - Each of `LowerWords` and `UpperWords` must point to an array that is
1982    ///   long enough to fully define an integer of size `NumBits`, i.e. each
1983    ///   pointer must point to `NumBits.div_ceil(64)` elements or more.
1984    /// - The implementation will make its own copy of the pointed-to `u64`
1985    ///   values, so the pointers only need to outlive this function call.
1986    pub(crate) fn LLVMRustCreateRangeAttribute(
1987        C: &Context,
1988        NumBits: c_uint,
1989        LowerWords: *const u64,
1990        UpperWords: *const u64,
1991    ) -> &Attribute;
1992
1993    // Operations on functions
1994    pub(crate) fn LLVMRustGetOrInsertFunction<'a>(
1995        M: &'a Module,
1996        Name: *const c_char,
1997        NameLen: size_t,
1998        FunctionTy: &'a Type,
1999    ) -> &'a Value;
2000    pub(crate) fn LLVMRustAddFunctionAttributes<'a>(
2001        Fn: &'a Value,
2002        index: c_uint,
2003        Attrs: *const &'a Attribute,
2004        AttrsLen: size_t,
2005    );
2006
2007    // Operations on call sites
2008    pub(crate) fn LLVMRustAddCallSiteAttributes<'a>(
2009        Instr: &'a Value,
2010        index: c_uint,
2011        Attrs: *const &'a Attribute,
2012        AttrsLen: size_t,
2013    );
2014
2015    pub(crate) fn LLVMRustSetFastMath(Instr: &Value);
2016    pub(crate) fn LLVMRustSetAlgebraicMath(Instr: &Value);
2017    pub(crate) fn LLVMRustSetAllowReassoc(Instr: &Value);
2018
2019    // Miscellaneous instructions
2020    pub(crate) fn LLVMRustBuildMemCpy<'a>(
2021        B: &Builder<'a>,
2022        Dst: &'a Value,
2023        DstAlign: c_uint,
2024        Src: &'a Value,
2025        SrcAlign: c_uint,
2026        Size: &'a Value,
2027        IsVolatile: bool,
2028    ) -> &'a Value;
2029    pub(crate) fn LLVMRustBuildMemMove<'a>(
2030        B: &Builder<'a>,
2031        Dst: &'a Value,
2032        DstAlign: c_uint,
2033        Src: &'a Value,
2034        SrcAlign: c_uint,
2035        Size: &'a Value,
2036        IsVolatile: bool,
2037    ) -> &'a Value;
2038    pub(crate) fn LLVMRustBuildMemSet<'a>(
2039        B: &Builder<'a>,
2040        Dst: &'a Value,
2041        DstAlign: c_uint,
2042        Val: &'a Value,
2043        Size: &'a Value,
2044        IsVolatile: bool,
2045    ) -> &'a Value;
2046
2047    pub(crate) fn LLVMRustBuildVectorReduceFAdd<'a>(
2048        B: &Builder<'a>,
2049        Acc: &'a Value,
2050        Src: &'a Value,
2051    ) -> &'a Value;
2052    pub(crate) fn LLVMRustBuildVectorReduceFMul<'a>(
2053        B: &Builder<'a>,
2054        Acc: &'a Value,
2055        Src: &'a Value,
2056    ) -> &'a Value;
2057    pub(crate) fn LLVMRustBuildVectorReduceAdd<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
2058    pub(crate) fn LLVMRustBuildVectorReduceMul<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
2059    pub(crate) fn LLVMRustBuildVectorReduceAnd<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
2060    pub(crate) fn LLVMRustBuildVectorReduceOr<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
2061    pub(crate) fn LLVMRustBuildVectorReduceXor<'a>(B: &Builder<'a>, Src: &'a Value) -> &'a Value;
2062    pub(crate) fn LLVMRustBuildVectorReduceMin<'a>(
2063        B: &Builder<'a>,
2064        Src: &'a Value,
2065        IsSigned: bool,
2066    ) -> &'a Value;
2067    pub(crate) fn LLVMRustBuildVectorReduceMax<'a>(
2068        B: &Builder<'a>,
2069        Src: &'a Value,
2070        IsSigned: bool,
2071    ) -> &'a Value;
2072    pub(crate) fn LLVMRustBuildVectorReduceFMin<'a>(
2073        B: &Builder<'a>,
2074        Src: &'a Value,
2075        IsNaN: bool,
2076    ) -> &'a Value;
2077    pub(crate) fn LLVMRustBuildVectorReduceFMax<'a>(
2078        B: &Builder<'a>,
2079        Src: &'a Value,
2080        IsNaN: bool,
2081    ) -> &'a Value;
2082
2083    pub(crate) fn LLVMRustBuildMinNum<'a>(
2084        B: &Builder<'a>,
2085        LHS: &'a Value,
2086        RHS: &'a Value,
2087    ) -> &'a Value;
2088    pub(crate) fn LLVMRustBuildMaxNum<'a>(
2089        B: &Builder<'a>,
2090        LHS: &'a Value,
2091        RHS: &'a Value,
2092    ) -> &'a Value;
2093
2094    pub(crate) fn LLVMRustTimeTraceProfilerInitialize();
2095
2096    pub(crate) fn LLVMRustTimeTraceProfilerFinishThread();
2097
2098    pub(crate) fn LLVMRustTimeTraceProfilerFinish(FileName: *const c_char);
2099
2100    /// Returns a string describing the last error caused by an LLVMRust* call.
2101    pub(crate) fn LLVMRustGetLastError() -> *const c_char;
2102
2103    /// Prints the timing information collected by `-Ztime-llvm-passes`.
2104    pub(crate) fn LLVMRustPrintPassTimings(OutStr: &RustString);
2105
2106    /// Prints the statistics collected by `-Zprint-codegen-stats`.
2107    pub(crate) fn LLVMRustPrintStatistics(OutStr: &RustString);
2108
2109    pub(crate) fn LLVMRustInlineAsmVerify(
2110        Ty: &Type,
2111        Constraints: *const c_uchar, // See "PTR_LEN_STR".
2112        ConstraintsLen: size_t,
2113    ) -> bool;
2114
2115    /// A list of pointer-length strings is passed as two pointer-length slices,
2116    /// one slice containing pointers and one slice containing their corresponding
2117    /// lengths. The implementation will check that both slices have the same length.
2118    pub(crate) fn LLVMRustCoverageWriteFilenamesToBuffer(
2119        Filenames: *const *const c_uchar, // See "PTR_LEN_STR".
2120        FilenamesLen: size_t,
2121        Lengths: *const size_t,
2122        LengthsLen: size_t,
2123        BufferOut: &RustString,
2124    );
2125
2126    pub(crate) fn LLVMRustCoverageWriteFunctionMappingsToBuffer(
2127        VirtualFileMappingIDs: *const c_uint,
2128        NumVirtualFileMappingIDs: size_t,
2129        Expressions: *const crate::coverageinfo::ffi::CounterExpression,
2130        NumExpressions: size_t,
2131        CodeRegions: *const crate::coverageinfo::ffi::CodeRegion,
2132        NumCodeRegions: size_t,
2133        ExpansionRegions: *const crate::coverageinfo::ffi::ExpansionRegion,
2134        NumExpansionRegions: size_t,
2135        BranchRegions: *const crate::coverageinfo::ffi::BranchRegion,
2136        NumBranchRegions: size_t,
2137        BufferOut: &RustString,
2138    );
2139
2140    pub(crate) fn LLVMRustCoverageCreatePGOFuncNameVar(
2141        F: &Value,
2142        FuncName: *const c_uchar, // See "PTR_LEN_STR".
2143        FuncNameLen: size_t,
2144    ) -> &Value;
2145    pub(crate) fn LLVMRustCoverageHashBytes(
2146        Bytes: *const c_uchar, // See "PTR_LEN_STR".
2147        NumBytes: size_t,
2148    ) -> u64;
2149
2150    pub(crate) safe fn LLVMRustCoverageWriteCovmapSectionNameToString(
2151        M: &Module,
2152        OutStr: &RustString,
2153    );
2154    pub(crate) safe fn LLVMRustCoverageWriteCovfunSectionNameToString(
2155        M: &Module,
2156        OutStr: &RustString,
2157    );
2158    pub(crate) safe fn LLVMRustCoverageWriteCovmapVarNameToString(OutStr: &RustString);
2159
2160    pub(crate) safe fn LLVMRustCoverageMappingVersion() -> u32;
2161    pub(crate) fn LLVMRustDebugMetadataVersion() -> u32;
2162    pub(crate) fn LLVMRustVersionMajor() -> u32;
2163    pub(crate) fn LLVMRustVersionMinor() -> u32;
2164    pub(crate) fn LLVMRustVersionPatch() -> u32;
2165
2166    /// Add LLVM module flags.
2167    ///
2168    /// In order for Rust-C LTO to work, module flags must be compatible with Clang. What
2169    /// "compatible" means depends on the merge behaviors involved.
2170    pub(crate) fn LLVMRustAddModuleFlagU32(
2171        M: &Module,
2172        MergeBehavior: ModuleFlagMergeBehavior,
2173        Name: *const c_char,
2174        NameLen: size_t,
2175        Value: u32,
2176    );
2177
2178    pub(crate) fn LLVMRustAddModuleFlagString(
2179        M: &Module,
2180        MergeBehavior: ModuleFlagMergeBehavior,
2181        Name: *const c_char,
2182        NameLen: size_t,
2183        Value: *const c_char,
2184        ValueLen: size_t,
2185    );
2186
2187    pub(crate) fn LLVMRustDIBuilderCreateCompileUnit<'a>(
2188        Builder: &DIBuilder<'a>,
2189        Lang: c_uint,
2190        File: &'a DIFile,
2191        Producer: *const c_char,
2192        ProducerLen: size_t,
2193        isOptimized: bool,
2194        Flags: *const c_char,
2195        RuntimeVer: c_uint,
2196        SplitName: *const c_char,
2197        SplitNameLen: size_t,
2198        kind: DebugEmissionKind,
2199        DWOId: u64,
2200        SplitDebugInlining: bool,
2201        DebugNameTableKind: DebugNameTableKind,
2202    ) -> &'a DIDescriptor;
2203
2204    pub(crate) fn LLVMRustDIBuilderCreateFile<'a>(
2205        Builder: &DIBuilder<'a>,
2206        Filename: *const c_char,
2207        FilenameLen: size_t,
2208        Directory: *const c_char,
2209        DirectoryLen: size_t,
2210        CSKind: ChecksumKind,
2211        Checksum: *const c_char,
2212        ChecksumLen: size_t,
2213        Source: *const c_char,
2214        SourceLen: size_t,
2215    ) -> &'a DIFile;
2216
2217    pub(crate) fn LLVMRustDIBuilderCreateFunction<'a>(
2218        Builder: &DIBuilder<'a>,
2219        Scope: &'a DIDescriptor,
2220        Name: *const c_char,
2221        NameLen: size_t,
2222        LinkageName: *const c_char,
2223        LinkageNameLen: size_t,
2224        File: &'a DIFile,
2225        LineNo: c_uint,
2226        Ty: &'a DIType,
2227        ScopeLine: c_uint,
2228        Flags: DIFlags,
2229        SPFlags: DISPFlags,
2230        MaybeFn: Option<&'a Value>,
2231        TParam: &'a DIArray,
2232        Decl: Option<&'a DIDescriptor>,
2233    ) -> &'a DISubprogram;
2234
2235    pub(crate) fn LLVMRustDIBuilderCreateMethod<'a>(
2236        Builder: &DIBuilder<'a>,
2237        Scope: &'a DIDescriptor,
2238        Name: *const c_char,
2239        NameLen: size_t,
2240        LinkageName: *const c_char,
2241        LinkageNameLen: size_t,
2242        File: &'a DIFile,
2243        LineNo: c_uint,
2244        Ty: &'a DIType,
2245        Flags: DIFlags,
2246        SPFlags: DISPFlags,
2247        TParam: &'a DIArray,
2248    ) -> &'a DISubprogram;
2249
2250    pub(crate) fn LLVMRustDIBuilderCreateVariantMemberType<'a>(
2251        Builder: &DIBuilder<'a>,
2252        Scope: &'a DIScope,
2253        Name: *const c_char,
2254        NameLen: size_t,
2255        File: &'a DIFile,
2256        LineNumber: c_uint,
2257        SizeInBits: u64,
2258        AlignInBits: u32,
2259        OffsetInBits: u64,
2260        Discriminant: Option<&'a Value>,
2261        Flags: DIFlags,
2262        Ty: &'a DIType,
2263    ) -> &'a DIType;
2264
2265    pub(crate) fn LLVMRustDIBuilderCreateStaticVariable<'a>(
2266        Builder: &DIBuilder<'a>,
2267        Context: Option<&'a DIScope>,
2268        Name: *const c_char,
2269        NameLen: size_t,
2270        LinkageName: *const c_char,
2271        LinkageNameLen: size_t,
2272        File: &'a DIFile,
2273        LineNo: c_uint,
2274        Ty: &'a DIType,
2275        isLocalToUnit: bool,
2276        Val: &'a Value,
2277        Decl: Option<&'a DIDescriptor>,
2278        AlignInBits: u32,
2279    ) -> &'a DIGlobalVariableExpression;
2280
2281    pub(crate) fn LLVMRustDIBuilderCreateEnumerator<'a>(
2282        Builder: &DIBuilder<'a>,
2283        Name: *const c_char,
2284        NameLen: size_t,
2285        Value: *const u64,
2286        SizeInBits: c_uint,
2287        IsUnsigned: bool,
2288    ) -> &'a DIEnumerator;
2289
2290    pub(crate) fn LLVMRustDIBuilderCreateEnumerationType<'a>(
2291        Builder: &DIBuilder<'a>,
2292        Scope: &'a DIScope,
2293        Name: *const c_char,
2294        NameLen: size_t,
2295        File: &'a DIFile,
2296        LineNumber: c_uint,
2297        SizeInBits: u64,
2298        AlignInBits: u32,
2299        Elements: &'a DIArray,
2300        ClassType: &'a DIType,
2301        IsScoped: bool,
2302    ) -> &'a DIType;
2303
2304    pub(crate) fn LLVMRustDIBuilderCreateVariantPart<'a>(
2305        Builder: &DIBuilder<'a>,
2306        Scope: &'a DIScope,
2307        Name: *const c_char,
2308        NameLen: size_t,
2309        File: &'a DIFile,
2310        LineNo: c_uint,
2311        SizeInBits: u64,
2312        AlignInBits: u32,
2313        Flags: DIFlags,
2314        Discriminator: Option<&'a DIDerivedType>,
2315        Elements: &'a DIArray,
2316        UniqueId: *const c_char,
2317        UniqueIdLen: size_t,
2318    ) -> &'a DIDerivedType;
2319
2320    pub(crate) fn LLVMRustDIBuilderCreateTemplateTypeParameter<'a>(
2321        Builder: &DIBuilder<'a>,
2322        Scope: Option<&'a DIScope>,
2323        Name: *const c_char,
2324        NameLen: size_t,
2325        Ty: &'a DIType,
2326    ) -> &'a DITemplateTypeParameter;
2327
2328    pub(crate) fn LLVMRustDICompositeTypeReplaceArrays<'a>(
2329        Builder: &DIBuilder<'a>,
2330        CompositeType: &'a DIType,
2331        Elements: Option<&'a DIArray>,
2332        Params: Option<&'a DIArray>,
2333    );
2334
2335    pub(crate) fn LLVMRustDILocationCloneWithBaseDiscriminator<'a>(
2336        Location: &'a DILocation,
2337        BD: c_uint,
2338    ) -> Option<&'a DILocation>;
2339
2340    pub(crate) fn LLVMRustWriteTypeToString(Type: &Type, s: &RustString);
2341    pub(crate) fn LLVMRustWriteValueToString(value_ref: &Value, s: &RustString);
2342
2343    pub(crate) fn LLVMRustHasFeature(T: &TargetMachine, s: *const c_char) -> bool;
2344
2345    pub(crate) fn LLVMRustPrintTargetCPUs(TM: &TargetMachine, OutStr: &RustString);
2346    pub(crate) fn LLVMRustGetTargetFeaturesCount(T: &TargetMachine) -> size_t;
2347    pub(crate) fn LLVMRustGetTargetFeature(
2348        T: &TargetMachine,
2349        Index: size_t,
2350        Feature: &mut *const c_char,
2351        Desc: &mut *const c_char,
2352    );
2353
2354    pub(crate) fn LLVMRustGetHostCPUName(LenOut: &mut size_t) -> *const u8;
2355
2356    // This function makes copies of pointed to data, so the data's lifetime may end after this
2357    // function returns.
2358    pub(crate) fn LLVMRustCreateTargetMachine(
2359        Triple: *const c_char,
2360        CPU: *const c_char,
2361        Features: *const c_char,
2362        Abi: *const c_char,
2363        Model: CodeModel,
2364        Reloc: RelocModel,
2365        Level: CodeGenOptLevel,
2366        FloatABIType: FloatAbi,
2367        FunctionSections: bool,
2368        DataSections: bool,
2369        UniqueSectionNames: bool,
2370        TrapUnreachable: bool,
2371        Singlethread: bool,
2372        VerboseAsm: bool,
2373        EmitStackSizeSection: bool,
2374        RelaxELFRelocations: bool,
2375        UseInitArray: bool,
2376        SplitDwarfFile: *const c_char,
2377        OutputObjFile: *const c_char,
2378        DebugInfoCompression: *const c_char,
2379        UseEmulatedTls: bool,
2380        Argv0: *const c_uchar, // See "PTR_LEN_STR".
2381        Argv0Len: size_t,
2382        CommandLineArgs: *const c_uchar, // See "PTR_LEN_STR".
2383        CommandLineArgsLen: size_t,
2384        UseWasmEH: bool,
2385    ) -> *mut TargetMachine;
2386
2387    pub(crate) fn LLVMRustAddLibraryInfo<'a>(
2388        PM: &PassManager<'a>,
2389        M: &'a Module,
2390        DisableSimplifyLibCalls: bool,
2391    );
2392    pub(crate) fn LLVMRustWriteOutputFile<'a>(
2393        T: &'a TargetMachine,
2394        PM: *mut PassManager<'a>,
2395        M: &'a Module,
2396        Output: *const c_char,
2397        DwoOutput: *const c_char,
2398        FileType: FileType,
2399        VerifyIR: bool,
2400    ) -> LLVMRustResult;
2401    pub(crate) fn LLVMRustOptimize<'a>(
2402        M: &'a Module,
2403        TM: &'a TargetMachine,
2404        OptLevel: PassBuilderOptLevel,
2405        OptStage: OptStage,
2406        IsLinkerPluginLTO: bool,
2407        NoPrepopulatePasses: bool,
2408        VerifyIR: bool,
2409        LintIR: bool,
2410        ThinLTOBuffer: Option<&mut *mut ThinLTOBuffer>,
2411        EmitThinLTO: bool,
2412        EmitThinLTOSummary: bool,
2413        MergeFunctions: bool,
2414        UnrollLoops: bool,
2415        SLPVectorize: bool,
2416        LoopVectorize: bool,
2417        DisableSimplifyLibCalls: bool,
2418        EmitLifetimeMarkers: bool,
2419        RunEnzyme: bool,
2420        PrintBeforeEnzyme: bool,
2421        PrintAfterEnzyme: bool,
2422        PrintPasses: bool,
2423        SanitizerOptions: Option<&SanitizerOptions>,
2424        PGOGenPath: *const c_char,
2425        PGOUsePath: *const c_char,
2426        InstrumentCoverage: bool,
2427        InstrProfileOutput: *const c_char,
2428        PGOSampleUsePath: *const c_char,
2429        DebugInfoForProfiling: bool,
2430        llvm_selfprofiler: *mut c_void,
2431        begin_callback: SelfProfileBeforePassCallback,
2432        end_callback: SelfProfileAfterPassCallback,
2433        ExtraPasses: *const c_char,
2434        ExtraPassesLen: size_t,
2435        LLVMPlugins: *const c_char,
2436        LLVMPluginsLen: size_t,
2437    ) -> LLVMRustResult;
2438    pub(crate) fn LLVMRustPrintModule(
2439        M: &Module,
2440        Output: *const c_char,
2441        Demangle: extern "C" fn(*const c_char, size_t, *mut c_char, size_t) -> size_t,
2442    ) -> LLVMRustResult;
2443    pub(crate) fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: *const *const c_char);
2444    pub(crate) fn LLVMRustPrintPasses();
2445    pub(crate) fn LLVMRustSetNormalizedTarget(M: &Module, triple: *const c_char);
2446    pub(crate) fn LLVMRustRunRestrictionPass(M: &Module, syms: *const *const c_char, len: size_t);
2447
2448    pub(crate) fn LLVMRustWriteTwineToString(T: &Twine, s: &RustString);
2449
2450    pub(crate) fn LLVMRustUnpackOptimizationDiagnostic<'a>(
2451        DI: &'a DiagnosticInfo,
2452        pass_name_out: &RustString,
2453        function_out: &mut Option<&'a Value>,
2454        loc_line_out: &mut c_uint,
2455        loc_column_out: &mut c_uint,
2456        loc_filename_out: &RustString,
2457        message_out: &RustString,
2458    );
2459
2460    pub(crate) fn LLVMRustUnpackInlineAsmDiagnostic<'a>(
2461        DI: &'a DiagnosticInfo,
2462        level_out: &mut DiagnosticLevel,
2463        cookie_out: &mut u64,
2464        message_out: &mut Option<&'a Twine>,
2465    );
2466
2467    pub(crate) fn LLVMRustWriteDiagnosticInfoToString(DI: &DiagnosticInfo, s: &RustString);
2468    pub(crate) fn LLVMRustGetDiagInfoKind(DI: &DiagnosticInfo) -> DiagnosticKind;
2469
2470    pub(crate) fn LLVMRustGetSMDiagnostic<'a>(
2471        DI: &'a DiagnosticInfo,
2472        cookie_out: &mut u64,
2473    ) -> &'a SMDiagnostic;
2474
2475    pub(crate) fn LLVMRustUnpackSMDiagnostic(
2476        d: &SMDiagnostic,
2477        message_out: &RustString,
2478        buffer_out: &RustString,
2479        level_out: &mut DiagnosticLevel,
2480        loc_out: &mut c_uint,
2481        ranges_out: *mut c_uint,
2482        num_ranges: &mut usize,
2483    ) -> bool;
2484
2485    pub(crate) fn LLVMRustSetDataLayoutFromTargetMachine<'a>(M: &'a Module, TM: &'a TargetMachine);
2486
2487    pub(crate) fn LLVMRustPositionBuilderPastAllocas<'a>(B: &Builder<'a>, Fn: &'a Value);
2488    pub(crate) fn LLVMRustPositionBuilderAtStart<'a>(B: &Builder<'a>, BB: &'a BasicBlock);
2489
2490    pub(crate) fn LLVMRustSetModulePICLevel(M: &Module);
2491    pub(crate) fn LLVMRustSetModulePIELevel(M: &Module);
2492    pub(crate) fn LLVMRustSetModuleCodeModel(M: &Module, Model: CodeModel);
2493    pub(crate) fn LLVMRustModuleBufferCreate(M: &Module) -> &'static mut ModuleBuffer;
2494    pub(crate) fn LLVMRustModuleBufferPtr(p: &ModuleBuffer) -> *const u8;
2495    pub(crate) fn LLVMRustModuleBufferLen(p: &ModuleBuffer) -> usize;
2496    pub(crate) fn LLVMRustModuleBufferFree(p: &'static mut ModuleBuffer);
2497    pub(crate) fn LLVMRustModuleCost(M: &Module) -> u64;
2498    pub(crate) fn LLVMRustModuleInstructionStats(M: &Module, Str: &RustString);
2499
2500    pub(crate) fn LLVMRustThinLTOBufferCreate(
2501        M: &Module,
2502        is_thin: bool,
2503    ) -> &'static mut ThinLTOBuffer;
2504    pub(crate) fn LLVMRustThinLTOBufferFree(M: &'static mut ThinLTOBuffer);
2505    pub(crate) fn LLVMRustThinLTOBufferPtr(M: &ThinLTOBuffer) -> *const c_char;
2506    pub(crate) fn LLVMRustThinLTOBufferLen(M: &ThinLTOBuffer) -> size_t;
2507    pub(crate) fn LLVMRustThinLTOBufferThinLinkDataPtr(M: &ThinLTOBuffer) -> *const c_char;
2508    pub(crate) fn LLVMRustThinLTOBufferThinLinkDataLen(M: &ThinLTOBuffer) -> size_t;
2509    pub(crate) fn LLVMRustCreateThinLTOData(
2510        Modules: *const ThinLTOModule,
2511        NumModules: size_t,
2512        PreservedSymbols: *const *const c_char,
2513        PreservedSymbolsLen: size_t,
2514    ) -> Option<&'static mut ThinLTOData>;
2515    pub(crate) fn LLVMRustPrepareThinLTORename(
2516        Data: &ThinLTOData,
2517        Module: &Module,
2518        Target: &TargetMachine,
2519    );
2520    pub(crate) fn LLVMRustPrepareThinLTOResolveWeak(Data: &ThinLTOData, Module: &Module) -> bool;
2521    pub(crate) fn LLVMRustPrepareThinLTOInternalize(Data: &ThinLTOData, Module: &Module) -> bool;
2522    pub(crate) fn LLVMRustPrepareThinLTOImport(
2523        Data: &ThinLTOData,
2524        Module: &Module,
2525        Target: &TargetMachine,
2526    ) -> bool;
2527    pub(crate) fn LLVMRustFreeThinLTOData(Data: &'static mut ThinLTOData);
2528    pub(crate) fn LLVMRustParseBitcodeForLTO(
2529        Context: &Context,
2530        Data: *const u8,
2531        len: usize,
2532        Identifier: *const c_char,
2533    ) -> Option<&Module>;
2534
2535    pub(crate) fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>;
2536    pub(crate) fn LLVMRustLinkerAdd(
2537        linker: &Linker<'_>,
2538        bytecode: *const c_char,
2539        bytecode_len: usize,
2540    ) -> bool;
2541    pub(crate) fn LLVMRustLinkerFree<'a>(linker: &'a mut Linker<'a>);
2542    pub(crate) fn LLVMRustComputeLTOCacheKey(
2543        key_out: &RustString,
2544        mod_id: *const c_char,
2545        data: &ThinLTOData,
2546    );
2547
2548    pub(crate) fn LLVMRustContextGetDiagnosticHandler(
2549        Context: &Context,
2550    ) -> Option<&DiagnosticHandler>;
2551    pub(crate) fn LLVMRustContextSetDiagnosticHandler(
2552        context: &Context,
2553        diagnostic_handler: Option<&DiagnosticHandler>,
2554    );
2555    pub(crate) fn LLVMRustContextConfigureDiagnosticHandler(
2556        context: &Context,
2557        diagnostic_handler_callback: DiagnosticHandlerTy,
2558        diagnostic_handler_context: *mut c_void,
2559        remark_all_passes: bool,
2560        remark_passes: *const *const c_char,
2561        remark_passes_len: usize,
2562        remark_file: *const c_char,
2563        pgo_available: bool,
2564    );
2565
2566    pub(crate) fn LLVMRustGetMangledName(V: &Value, out: &RustString);
2567
2568    pub(crate) fn LLVMRustGetElementTypeArgIndex(CallSite: &Value) -> i32;
2569
2570    pub(crate) fn LLVMRustLLVMHasZlibCompressionForDebugSymbols() -> bool;
2571
2572    pub(crate) fn LLVMRustLLVMHasZstdCompressionForDebugSymbols() -> bool;
2573
2574    pub(crate) fn LLVMRustGetSymbols(
2575        buf_ptr: *const u8,
2576        buf_len: usize,
2577        state: *mut c_void,
2578        callback: GetSymbolsCallback,
2579        error_callback: GetSymbolsErrorCallback,
2580    ) -> *mut c_void;
2581
2582    pub(crate) fn LLVMRustIs64BitSymbolicFile(buf_ptr: *const u8, buf_len: usize) -> bool;
2583
2584    pub(crate) fn LLVMRustIsECObject(buf_ptr: *const u8, buf_len: usize) -> bool;
2585
2586    pub(crate) fn LLVMRustIsAnyArm64Coff(buf_ptr: *const u8, buf_len: usize) -> bool;
2587
2588    pub(crate) fn LLVMRustSetNoSanitizeAddress(Global: &Value);
2589    pub(crate) fn LLVMRustSetNoSanitizeHWAddress(Global: &Value);
2590}