Skip to main content

rustc_codegen_llvm/llvm/
mod.rs

1#![allow(non_snake_case)]
2
3use std::ffi::{CStr, CString};
4use std::num::NonZero;
5use std::ptr;
6use std::string::FromUtf8Error;
7
8use libc::c_uint;
9use rustc_abi::{AddressSpace, Align, Size, WrappingRange};
10use rustc_llvm::RustString;
11
12pub(crate) use self::CallConv::*;
13pub(crate) use self::CodeGenOptSize::*;
14pub(crate) use self::conversions::*;
15pub(crate) use self::ffi::*;
16pub(crate) use self::metadata_kind::*;
17use crate::common::AsCCharPtr;
18
19mod conversions;
20pub(crate) mod diagnostic;
21pub(crate) mod enzyme_ffi;
22mod ffi;
23mod metadata_kind;
24pub(crate) mod offload_ffi;
25
26pub(crate) use self::enzyme_ffi::*;
27pub(crate) use self::offload_ffi::*;
28
29impl LLVMRustResult {
30    pub(crate) fn into_result(self) -> Result<(), ()> {
31        match self {
32            LLVMRustResult::Success => Ok(()),
33            LLVMRustResult::Failure => Err(()),
34        }
35    }
36}
37
38pub(crate) fn AddFunctionAttributes<'ll>(
39    llfn: &'ll Value,
40    idx: AttributePlace,
41    attrs: &[&'ll Attribute],
42) {
43    unsafe {
44        LLVMRustAddFunctionAttributes(llfn, idx.as_uint(), attrs.as_ptr(), attrs.len());
45    }
46}
47
48pub(crate) fn HasStringAttribute<'ll>(llfn: &'ll Value, name: &str) -> bool {
49    unsafe { LLVMRustHasFnAttribute(llfn, name.as_c_char_ptr(), name.len()) }
50}
51
52pub(crate) fn RemoveStringAttrFromFn<'ll>(llfn: &'ll Value, name: &str) {
53    unsafe { LLVMRustRemoveFnAttribute(llfn, name.as_c_char_ptr(), name.len()) }
54}
55
56pub(crate) fn AddCallSiteAttributes<'ll>(
57    callsite: &'ll Value,
58    idx: AttributePlace,
59    attrs: &[&'ll Attribute],
60) {
61    unsafe {
62        LLVMRustAddCallSiteAttributes(callsite, idx.as_uint(), attrs.as_ptr(), attrs.len());
63    }
64}
65
66pub(crate) fn CreateAttrStringValue<'ll>(
67    llcx: &'ll Context,
68    attr: &str,
69    value: &str,
70) -> &'ll Attribute {
71    unsafe {
72        LLVMCreateStringAttribute(
73            llcx,
74            attr.as_c_char_ptr(),
75            attr.len().try_into().unwrap(),
76            value.as_c_char_ptr(),
77            value.len().try_into().unwrap(),
78        )
79    }
80}
81pub(crate) fn CreateAttrStringValueFromCStr<'ll>(
82    llcx: &'ll Context,
83    attr: &std::ffi::CStr,
84    value: &std::ffi::CStr,
85) -> &'ll Attribute {
86    unsafe {
87        LLVMCreateStringAttribute(
88            llcx,
89            (*attr).as_ptr(),
90            (*attr).to_bytes().len() as c_uint,
91            (*value).as_ptr(),
92            (*value).to_bytes().len() as c_uint,
93        )
94    }
95}
96
97pub(crate) fn CreateAttrString<'ll>(llcx: &'ll Context, attr: &str) -> &'ll Attribute {
98    unsafe {
99        LLVMCreateStringAttribute(
100            llcx,
101            attr.as_c_char_ptr(),
102            attr.len().try_into().unwrap(),
103            std::ptr::null(),
104            0,
105        )
106    }
107}
108
109pub(crate) fn CreateAlignmentAttr(llcx: &Context, bytes: u64) -> &Attribute {
110    unsafe { LLVMRustCreateAlignmentAttr(llcx, bytes) }
111}
112
113pub(crate) fn CreateDereferenceableAttr(llcx: &Context, bytes: u64) -> &Attribute {
114    unsafe { LLVMRustCreateDereferenceableAttr(llcx, bytes) }
115}
116
117pub(crate) fn CreateDereferenceableOrNullAttr(llcx: &Context, bytes: u64) -> &Attribute {
118    unsafe { LLVMRustCreateDereferenceableOrNullAttr(llcx, bytes) }
119}
120
121pub(crate) fn CreateByValAttr<'ll>(llcx: &'ll Context, ty: &'ll Type) -> &'ll Attribute {
122    unsafe { LLVMRustCreateByValAttr(llcx, ty) }
123}
124
125pub(crate) fn CreateByRefAttr<'ll>(llcx: &'ll Context, ty: &'ll Type) -> &'ll Attribute {
126    unsafe { LLVMRustCreateByRefAttr(llcx, ty) }
127}
128
129pub(crate) fn CreateStructRetAttr<'ll>(llcx: &'ll Context, ty: &'ll Type) -> &'ll Attribute {
130    unsafe { LLVMRustCreateStructRetAttr(llcx, ty) }
131}
132
133pub(crate) fn CreateUWTableAttr(llcx: &Context, async_: bool) -> &Attribute {
134    unsafe { LLVMRustCreateUWTableAttr(llcx, async_) }
135}
136
137pub(crate) fn CreateAllocSizeAttr(llcx: &Context, size_arg: u32) -> &Attribute {
138    unsafe { LLVMRustCreateAllocSizeAttr(llcx, size_arg) }
139}
140
141pub(crate) fn CreateAllocKindAttr(llcx: &Context, kind_arg: AllocKindFlags) -> &Attribute {
142    unsafe { LLVMRustCreateAllocKindAttr(llcx, kind_arg.bits()) }
143}
144
145pub(crate) fn CreateRangeAttr(llcx: &Context, size: Size, range: WrappingRange) -> &Attribute {
146    let lower = range.start;
147    // LLVM treats the upper bound as exclusive, but allows wrapping.
148    let upper = range.end.wrapping_add(1);
149
150    // Pass each `u128` endpoint value as a `[u64; 2]` array, least-significant part first.
151    let as_u64_array = |x: u128| [x as u64, (x >> 64) as u64];
152    let lower_words: [u64; 2] = as_u64_array(lower);
153    let upper_words: [u64; 2] = as_u64_array(upper);
154
155    // To ensure that LLVM doesn't try to read beyond the `[u64; 2]` arrays,
156    // we must explicitly check that `size_bits` does not exceed 128.
157    let size_bits = size.bits();
158    if !(size_bits <= 128) {
    ::core::panicking::panic("assertion failed: size_bits <= 128")
};assert!(size_bits <= 128);
159    // More robust assertions that are redundant with `size_bits <= 128` and
160    // should be optimized away.
161    if !(size_bits.div_ceil(64) <= u64::try_from(lower_words.len()).unwrap()) {
    ::core::panicking::panic("assertion failed: size_bits.div_ceil(64) <= u64::try_from(lower_words.len()).unwrap()")
};assert!(size_bits.div_ceil(64) <= u64::try_from(lower_words.len()).unwrap());
162    if !(size_bits.div_ceil(64) <= u64::try_from(upper_words.len()).unwrap()) {
    ::core::panicking::panic("assertion failed: size_bits.div_ceil(64) <= u64::try_from(upper_words.len()).unwrap()")
};assert!(size_bits.div_ceil(64) <= u64::try_from(upper_words.len()).unwrap());
163    let size_bits = c_uint::try_from(size_bits).unwrap();
164
165    unsafe {
166        LLVMRustCreateRangeAttribute(llcx, size_bits, lower_words.as_ptr(), upper_words.as_ptr())
167    }
168}
169
170#[derive(#[automatically_derived]
impl ::core::marker::Copy for AttributePlace { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AttributePlace { }
#[automatically_derived]
impl ::core::clone::Clone for AttributePlace {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone)]
171pub(crate) enum AttributePlace {
172    ReturnValue,
173    Argument(u32),
174    Function,
175}
176
177impl AttributePlace {
178    pub(crate) fn as_uint(self) -> c_uint {
179        match self {
180            AttributePlace::ReturnValue => 0,
181            AttributePlace::Argument(i) => 1 + i,
182            AttributePlace::Function => !0,
183        }
184    }
185}
186
187#[derive(#[automatically_derived]
impl ::core::marker::Copy for CodeGenOptSize { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CodeGenOptSize { }
#[automatically_derived]
impl ::core::clone::Clone for CodeGenOptSize {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CodeGenOptSize { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CodeGenOptSize {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
188#[repr(C)]
189pub(crate) enum CodeGenOptSize {
190    CodeGenOptSizeNone = 0,
191    CodeGenOptSizeDefault = 1,
192    CodeGenOptSizeAggressive = 2,
193}
194
195pub(crate) fn SetInstructionCallConv(instr: &Value, cc: CallConv) {
196    unsafe {
197        LLVMSetInstructionCallConv(instr, cc as c_uint);
198    }
199}
200pub(crate) fn SetFunctionCallConv(fn_: &Value, cc: CallConv) {
201    unsafe {
202        LLVMSetFunctionCallConv(fn_, cc as c_uint);
203    }
204}
205
206// Externally visible symbols that might appear in multiple codegen units need to appear in
207// their own comdat section so that the duplicates can be discarded at link time. This can for
208// example happen for generics when using multiple codegen units. This function simply uses the
209// value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the
210// function.
211// For more details on COMDAT sections see e.g., https://www.airs.com/blog/archives/52
212pub(crate) fn SetUniqueComdat(llmod: &Module, val: &Value) {
213    let name_buf = get_value_name(val);
214    let name =
215        CString::from_vec_with_nul(name_buf).or_else(|buf| CString::new(buf.into_bytes())).unwrap();
216    set_comdat(llmod, val, &name);
217}
218
219pub(crate) fn set_unnamed_address(global: &Value, unnamed: UnnamedAddr) {
220    LLVMSetUnnamedAddress(global, unnamed);
221}
222
223pub(crate) fn set_thread_local_mode(global: &Value, mode: ThreadLocalMode) {
224    unsafe {
225        LLVMSetThreadLocalMode(global, mode);
226    }
227}
228
229impl AttributeKind {
230    /// Create an LLVM Attribute with no associated value.
231    pub(crate) fn create_attr(self, llcx: &Context) -> &Attribute {
232        unsafe { LLVMRustCreateAttrNoValue(llcx, self) }
233    }
234}
235
236impl MemoryEffects {
237    /// Create an LLVM Attribute with these memory effects.
238    pub(crate) fn create_attr(self, llcx: &Context) -> &Attribute {
239        unsafe { LLVMRustCreateMemoryEffectsAttr(llcx, self) }
240    }
241}
242
243pub(crate) fn set_section(llglobal: &Value, section_name: &CStr) {
244    unsafe {
245        LLVMSetSection(llglobal, section_name.as_ptr());
246    }
247}
248
249pub(crate) fn add_global<'a>(llmod: &'a Module, ty: &'a Type, name_cstr: &CStr) -> &'a Value {
250    unsafe { LLVMAddGlobal(llmod, ty, name_cstr.as_ptr()) }
251}
252
253pub(crate) fn set_initializer(llglobal: &Value, constant_val: &Value) {
254    unsafe {
255        LLVMSetInitializer(llglobal, constant_val);
256    }
257}
258
259pub(crate) fn set_global_constant(llglobal: &Value, is_constant: bool) {
260    LLVMSetGlobalConstant(llglobal, is_constant.to_llvm_bool());
261}
262
263pub(crate) fn get_linkage(llglobal: &Value) -> Linkage {
264    unsafe { LLVMGetLinkage(llglobal) }.to_rust()
265}
266
267pub(crate) fn set_linkage(llglobal: &Value, linkage: Linkage) {
268    unsafe {
269        LLVMSetLinkage(llglobal, linkage);
270    }
271}
272
273pub(crate) fn is_declaration(llglobal: &Value) -> bool {
274    unsafe { LLVMIsDeclaration(llglobal) }.is_true()
275}
276
277pub(crate) fn get_visibility(llglobal: &Value) -> Visibility {
278    unsafe { LLVMGetVisibility(llglobal) }.to_rust()
279}
280
281pub(crate) fn set_visibility(llglobal: &Value, visibility: Visibility) {
282    unsafe {
283        LLVMSetVisibility(llglobal, visibility);
284    }
285}
286
287pub(crate) fn set_alignment(llglobal: &Value, align: Align) {
288    unsafe {
289        ffi::LLVMSetAlignment(llglobal, align.bytes() as c_uint);
290    }
291}
292
293pub(crate) fn set_externally_initialized(llglobal: &Value, is_ext_init: bool) {
294    LLVMSetExternallyInitialized(llglobal, is_ext_init.to_llvm_bool());
295}
296
297/// Get the `name`d comdat from `llmod` and assign it to `llglobal`.
298///
299/// Inserts the comdat into `llmod` if it does not exist.
300/// It is an error to call this if the target does not support comdat.
301pub(crate) fn set_comdat(llmod: &Module, llglobal: &Value, name: &CStr) {
302    unsafe {
303        let comdat = LLVMGetOrInsertComdat(llmod, name.as_ptr());
304        LLVMSetComdat(llglobal, comdat);
305    }
306}
307
308pub(crate) fn count_params(llfn: &Value) -> c_uint {
309    LLVMCountParams(llfn)
310}
311
312/// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
313pub(crate) fn get_param(llfn: &Value, index: c_uint) -> &Value {
314    unsafe {
315        if !(index < LLVMCountParams(llfn)) {
    {
        ::core::panicking::panic_fmt(format_args!("out of bounds argument access: {0} out of {1} arguments",
                index, LLVMCountParams(llfn)));
    }
};assert!(
316            index < LLVMCountParams(llfn),
317            "out of bounds argument access: {} out of {} arguments",
318            index,
319            LLVMCountParams(llfn)
320        );
321        LLVMGetParam(llfn, index)
322    }
323}
324
325/// Safe wrapper for `LLVMGetValueName2`
326/// Needs to allocate the value, because `set_value_name` will invalidate
327/// the pointer.
328pub(crate) fn get_value_name(value: &Value) -> Vec<u8> {
329    unsafe {
330        let mut len = 0;
331        let data = LLVMGetValueName2(value, &mut len);
332        std::slice::from_raw_parts(data.cast(), len).to_vec()
333    }
334}
335
336#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Intrinsic {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "Intrinsic",
            "id", &&self.id)
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for Intrinsic { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Intrinsic { }
#[automatically_derived]
impl ::core::clone::Clone for Intrinsic {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<NonZero<c_uint>>;
        *self
    }
}Clone)]
337pub(crate) struct Intrinsic {
338    id: NonZero<c_uint>,
339}
340
341impl Intrinsic {
342    pub(crate) fn lookup(name: &[u8]) -> Option<Self> {
343        let id = unsafe { LLVMLookupIntrinsicID(name.as_c_char_ptr(), name.len()) };
344        NonZero::new(id).map(|id| Self { id })
345    }
346
347    pub(crate) fn is_overloaded(self) -> bool {
348        unsafe { LLVMIntrinsicIsOverloaded(self.id).is_true() }
349    }
350
351    pub(crate) fn is_target_specific(self) -> bool {
352        unsafe { LLVMRustIsTargetIntrinsic(self.id) }
353    }
354
355    pub(crate) fn get_declaration<'ll>(
356        self,
357        llmod: &'ll Module,
358        type_params: &[&'ll Type],
359    ) -> &'ll Value {
360        unsafe {
361            LLVMGetIntrinsicDeclaration(llmod, self.id, type_params.as_ptr(), type_params.len())
362        }
363    }
364}
365
366/// Safe wrapper for `LLVMSetValueName2` from a byte slice
367pub(crate) fn set_value_name(value: &Value, name: &[u8]) {
368    unsafe {
369        let data = name.as_c_char_ptr();
370        LLVMSetValueName2(value, data, name.len());
371    }
372}
373
374pub(crate) fn build_string(f: impl FnOnce(&RustString)) -> Result<String, FromUtf8Error> {
375    String::from_utf8(RustString::build_byte_buffer(f))
376}
377
378pub(crate) fn build_byte_buffer(f: impl FnOnce(&RustString)) -> Vec<u8> {
379    RustString::build_byte_buffer(f)
380}
381
382pub(crate) fn twine_to_string(tr: &Twine) -> String {
383    unsafe {
384        build_string(|s| LLVMRustWriteTwineToString(tr, s)).expect("got a non-UTF8 Twine from LLVM")
385    }
386}
387
388pub(crate) fn last_error() -> Option<String> {
389    unsafe {
390        let cstr = LLVMRustGetLastError();
391        if cstr.is_null() {
392            None
393        } else {
394            let err = CStr::from_ptr(cstr).to_bytes();
395            let err = String::from_utf8_lossy(err).to_string();
396            libc::free(cstr as *mut _);
397            Some(err)
398        }
399    }
400}
401
402/// Owning pointer to an [`OperandBundle`] that will dispose of the bundle
403/// when dropped.
404pub(crate) struct OperandBundleBox<'a> {
405    raw: ptr::NonNull<OperandBundle<'a>>,
406}
407
408impl<'a> OperandBundleBox<'a> {
409    pub(crate) fn new(name: &str, vals: &[&'a Value]) -> Self {
410        let raw = unsafe {
411            LLVMCreateOperandBundle(
412                name.as_c_char_ptr(),
413                name.len(),
414                vals.as_ptr(),
415                vals.len() as c_uint,
416            )
417        };
418        Self { raw: ptr::NonNull::new(raw).unwrap() }
419    }
420
421    /// Dereferences to the underlying `&OperandBundle`.
422    ///
423    /// This can't be a `Deref` implementation because `OperandBundle` transitively
424    /// contains an extern type, which is incompatible with `Deref::Target: ?Sized`.
425    pub(crate) fn as_ref(&self) -> &OperandBundle<'a> {
426        // SAFETY: The returned reference is opaque and can only used for FFI.
427        // It is valid for as long as `&self` is.
428        unsafe { self.raw.as_ref() }
429    }
430}
431
432impl Drop for OperandBundleBox<'_> {
433    fn drop(&mut self) {
434        unsafe {
435            LLVMDisposeOperandBundle(self.raw);
436        }
437    }
438}
439
440pub(crate) fn add_module_flag_u32(
441    module: &Module,
442    merge_behavior: ModuleFlagMergeBehavior,
443    key: &str,
444    value: u32,
445) {
446    unsafe {
447        LLVMRustAddModuleFlagU32(module, merge_behavior, key.as_c_char_ptr(), key.len(), value);
448    }
449}
450
451pub(crate) fn add_module_flag_str(
452    module: &Module,
453    merge_behavior: ModuleFlagMergeBehavior,
454    key: &str,
455    value: &str,
456) {
457    unsafe {
458        LLVMRustAddModuleFlagString(
459            module,
460            merge_behavior,
461            key.as_c_char_ptr(),
462            key.len(),
463            value.as_c_char_ptr(),
464            value.len(),
465        );
466    }
467}
468
469pub(crate) fn set_dllimport_storage_class<'ll>(v: &'ll Value) {
470    unsafe {
471        LLVMSetDLLStorageClass(v, DLLStorageClass::DllImport);
472    }
473}
474
475pub(crate) fn set_dso_local<'ll>(v: &'ll Value) {
476    unsafe {
477        LLVMRustSetDSOLocal(v, true);
478    }
479}
480
481/// Safe wrapper for `LLVMRustAppendModuleInlineAsm`, which delegates to
482/// `Module::appendModuleInlineAsm`.
483pub(crate) fn append_module_inline_asm<'ll>(
484    llmod: &'ll Module,
485    asm: &[u8],
486    target_features: &str,
487    target_cpu: &str,
488) {
489    unsafe {
490        LLVMRustAppendModuleInlineAsm(
491            llmod,
492            asm.as_ptr(),
493            asm.len(),
494            target_features.as_ptr(),
495            target_features.len(),
496            target_cpu.as_ptr(),
497            target_cpu.len(),
498        );
499    }
500}
501
502/// Safe wrapper for `LLVMAddAlias2`
503pub(crate) fn add_alias<'ll>(
504    module: &'ll Module,
505    ty: &Type,
506    address_space: AddressSpace,
507    aliasee: &Value,
508    name: &CStr,
509) -> &'ll Value {
510    unsafe { LLVMAddAlias2(module, ty, address_space.0, aliasee, name.as_ptr()) }
511}
512
513/// Safe wrapper for `LLVMRustConstPtrAuth`.
514pub(crate) fn const_ptr_auth<'ll>(
515    ptr: &'ll Value,
516    key: u32,
517    disc: u64,
518    addr_diversity: Option<&'ll Value>,
519) -> &'ll Value {
520    unsafe {
521        let addr_div_ptr = addr_diversity.map_or(std::ptr::null(), |v| v as *const Value);
522        let deactivation_symbol = std::ptr::null();
523        let result =
524            LLVMRustConstPtrAuth(ptr as *const Value, key, disc, addr_div_ptr, deactivation_symbol);
525        &*result
526    }
527}