Skip to main content

rustc_codegen_llvm/
abi.rs

1use std::cmp;
2
3use libc::c_uint;
4use rustc_abi::{
5    ArmCall, BackendRepr, CanonAbi, Float, HasDataLayout, Integer, InterruptKind, Primitive, Reg,
6    RegKind, Size, X86Call,
7};
8use rustc_codegen_ssa::MemFlags;
9use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
10use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
11use rustc_codegen_ssa::traits::*;
12use rustc_middle::ty;
13use rustc_middle::ty::Ty;
14use rustc_middle::ty::layout::LayoutOf;
15use rustc_session::{Session, config};
16use rustc_span::bug;
17use rustc_target::callconv::{
18    ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, CastTarget, FnAbi, IndirectMode, PassMode,
19};
20use rustc_target::spec::{Arch, SanitizerSet};
21use smallvec::SmallVec;
22
23use crate::attributes::{self, llfn_attrs_from_instance};
24use crate::builder::Builder;
25use crate::context::CodegenCx;
26use crate::llvm::{self, Attribute, AttributePlace, Type, Value};
27use crate::type_of::LayoutLlvmExt;
28
29trait ArgAttributesExt {
30    fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
31    fn apply_attrs_to_callsite(
32        &self,
33        idx: AttributePlace,
34        cx: &CodegenCx<'_, '_>,
35        callsite: &Value,
36    );
37}
38
39const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
40    [(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
41
42const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 6] = [
43    (ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
44    (ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
45    (ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
46    (ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
47    (ArgAttribute::Writable, llvm::AttributeKind::Writable),
48    // Our internal NoFree attribute still allows deallocation of zero-size allocations. However,
49    // these don't render any bytes non-dereferenceable, so it's still fine to apply LLVM NoFree
50    // for them.
51    (ArgAttribute::NoFree, llvm::AttributeKind::NoFree),
52];
53
54const CAPTURES_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 3] = [
55    (ArgAttribute::CapturesNone, llvm::AttributeKind::CapturesNone),
56    (ArgAttribute::CapturesAddress, llvm::AttributeKind::CapturesAddress),
57    (ArgAttribute::CapturesReadOnly, llvm::AttributeKind::CapturesReadOnly),
58];
59
60fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 8]> {
61    let mut regular = this.regular;
62
63    let mut attrs = SmallVec::new();
64
65    // ABI-affecting attributes must always be applied
66    for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
67        if regular.contains(attr) {
68            attrs.push(llattr.create_attr(cx.llcx));
69        }
70    }
71    if let Some(align) = this.pointee_align {
72        attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
73    }
74    match this.arg_ext {
75        ArgExtension::None => {}
76        ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
77        ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
78    }
79
80    // Only apply remaining attributes when optimizing
81    if cx.sess().opts.optimize != config::OptLevel::No {
82        let deref = this.pointee_size.bytes();
83        // dereferenceable in LLVM currently implies nofree, so only emit dereferenceable if nofree
84        // is also set.
85        if deref != 0 && regular.contains(ArgAttribute::NoFree) {
86            if regular.contains(ArgAttribute::NonNull) {
87                attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
88            } else {
89                attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
90            }
91            regular -= ArgAttribute::NonNull;
92        }
93        for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
94            if regular.contains(attr) {
95                attrs.push(llattr.create_attr(cx.llcx));
96            }
97        }
98        for (attr, llattr) in CAPTURES_ATTRIBUTES {
99            if regular.contains(attr) {
100                attrs.push(llattr.create_attr(cx.llcx));
101                break;
102            }
103        }
104    } else if cx.tcx.sess.sanitizers().contains(SanitizerSet::MEMORY) {
105        // If we're not optimising, *but* memory sanitizer is on, emit noundef, since it affects
106        // memory sanitizer's behavior.
107
108        if regular.contains(ArgAttribute::NoUndef) {
109            attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
110        }
111    }
112
113    attrs
114}
115
116impl ArgAttributesExt for ArgAttributes {
117    fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
118        let attrs = get_attrs(self, cx);
119        attributes::apply_to_llfn(llfn, idx, &attrs);
120    }
121
122    fn apply_attrs_to_callsite(
123        &self,
124        idx: AttributePlace,
125        cx: &CodegenCx<'_, '_>,
126        callsite: &Value,
127    ) {
128        let attrs = get_attrs(self, cx);
129        attributes::apply_to_callsite(callsite, idx, &attrs);
130    }
131}
132
133pub(crate) trait LlvmType {
134    fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
135}
136
137impl LlvmType for Reg {
138    fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
139        match self.kind {
140            RegKind::Integer => cx.type_ix(self.size.bits()),
141            RegKind::Float => match self.size.bits() {
142                16 => cx.type_f16(),
143                32 => cx.type_f32(),
144                64 => cx.type_f64(),
145                128 => cx.type_f128(),
146                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unsupported float: {0:?}", self), Location::caller())bug!("unsupported float: {:?}", self),
147            },
148            RegKind::Vector { hint_vector_elem } => {
149                // NOTE: it is valid to ignore the element type hint (and always pick i8).
150                // But providing a more accurate type means fewer casts in LLVM IR,
151                // which helps with optimization.
152                let ty = match hint_vector_elem {
153                    Primitive::Int(integer, _) => match integer {
154                        Integer::I8 => cx.type_ix(8),
155                        Integer::I16 => cx.type_ix(16),
156                        Integer::I32 => cx.type_ix(32),
157                        Integer::I64 => cx.type_ix(64),
158                        Integer::I128 => cx.type_ix(128),
159                    },
160                    Primitive::Float(float) => match float {
161                        Float::F16 => cx.type_f16(),
162                        Float::F16B => cx.type_f16b(),
163                        Float::F32 => cx.type_f32(),
164                        Float::F64 => cx.type_f64(),
165                        Float::F128 => cx.type_f128(),
166                    },
167                    Primitive::Pointer(_) => cx.type_ptr(),
168                };
169
170                if !self.size.bytes().is_multiple_of(hint_vector_elem.size(cx).bytes()) {
    ::core::panicking::panic("assertion failed: self.size.bytes().is_multiple_of(hint_vector_elem.size(cx).bytes())")
};assert!(self.size.bytes().is_multiple_of(hint_vector_elem.size(cx).bytes()));
171                let len = self.size.bytes() / hint_vector_elem.size(cx).bytes();
172                cx.type_vector(ty, len)
173            }
174        }
175    }
176}
177
178impl LlvmType for CastTarget {
179    fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
180        let rest_ll_unit = self.rest.unit.llvm_type(cx);
181        let rest_count = if self.rest.total == Size::ZERO {
182            0
183        } else {
184            {
    match (&(self.rest.unit.size), &(Size::ZERO)) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("total size {0:?} cannot be divided into units of zero size",
                            self.rest.total)));
            }
        }
    }
};assert_ne!(
185                self.rest.unit.size,
186                Size::ZERO,
187                "total size {:?} cannot be divided into units of zero size",
188                self.rest.total
189            );
190            if !self.rest.total.bytes().is_multiple_of(self.rest.unit.size.bytes()) {
191                {
    match (&self.rest.unit.kind, &RegKind::Integer) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("only int regs can be split")));
            }
        }
    }
};assert_eq!(self.rest.unit.kind, RegKind::Integer, "only int regs can be split");
192            }
193            self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes())
194        };
195
196        // Simplify to a single unit or an array if there's no prefix.
197        // This produces the same layout, but using a simpler type.
198        if self.prefix.is_empty() {
199            // We can't do this if is_consecutive is set and the unit would get
200            // split on the target. Currently, this is only relevant for i128
201            // registers.
202            if rest_count == 1 && (!self.rest.is_consecutive || self.rest.unit != Reg::i128()) {
203                return rest_ll_unit;
204            }
205
206            return cx.type_array(rest_ll_unit, rest_count);
207        }
208
209        // Generate a struct type with the prefix and the "rest" arguments.
210        let prefix_args = self.prefix.iter().map(|reg| reg.llvm_type(cx));
211        let rest_args = (0..rest_count).map(|_| rest_ll_unit);
212        let args: Vec<_> = prefix_args.chain(rest_args).collect();
213        cx.type_struct(&args, false)
214    }
215}
216
217trait ArgAbiExt<'ll, 'tcx> {
218    fn store(
219        &self,
220        bx: &mut Builder<'_, 'll, 'tcx>,
221        val: &'ll Value,
222        dst: PlaceRef<'tcx, &'ll Value>,
223    );
224    fn store_fn_arg(
225        &self,
226        bx: &mut Builder<'_, 'll, 'tcx>,
227        idx: &mut usize,
228        dst: PlaceRef<'tcx, &'ll Value>,
229    );
230}
231
232impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
233    /// Stores a direct/indirect value described by this ArgAbi into a
234    /// place for the original Rust type of this argument/return.
235    /// Can be used for both storing formal arguments into Rust variables
236    /// or results of call/invoke instructions into their destinations.
237    fn store(
238        &self,
239        bx: &mut Builder<'_, 'll, 'tcx>,
240        val: &'ll Value,
241        dst: PlaceRef<'tcx, &'ll Value>,
242    ) {
243        match &self.mode {
244            PassMode::Ignore => {}
245            // Sized indirect arguments
246            PassMode::Indirect { attrs, meta_attrs: None, address_space: _, mode: _ } => {
247                let align = attrs.pointee_align.unwrap_or(self.layout.align.abi);
248                OperandValue::Ref(PlaceValue::new_sized(val, align)).store(bx, dst);
249            }
250            // Unsized indirect arguments cannot be stored
251            PassMode::Indirect { attrs: _, meta_attrs: Some(_), address_space: _, mode: _ } => {
252                ::rustc_span::macros::bug_impl(None,
    format_args!("unsized `ArgAbi` cannot be stored"), Location::caller());bug!("unsized `ArgAbi` cannot be stored");
253            }
254            PassMode::Cast { cast, pad_i32_count: _ } => {
255                // The ABI mandates that the value is passed as a different struct representation.
256                // Spill and reload it from the stack to convert from the ABI representation to
257                // the Rust representation.
258                let scratch_size = cast.size(bx);
259                let scratch_align = cast.align(bx);
260                // Note that the ABI type may be either larger or smaller than the Rust type,
261                // due to the presence or absence of trailing padding. For example:
262                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
263                //   when passed by value, making it smaller.
264                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
265                //   when passed by value, making it larger.
266                let copy_bytes =
267                    cmp::min(cast.unaligned_size(bx).bytes(), self.layout.size.bytes());
268                // Allocate some scratch space...
269                let llscratch = bx.alloca(scratch_size, scratch_align);
270                bx.lifetime_start(llscratch, scratch_size);
271                // ...store the value...
272                rustc_codegen_ssa::mir::store_cast(bx, cast, val, llscratch, scratch_align);
273                // ... and then memcpy it to the intended destination.
274                bx.memcpy(
275                    dst.val.llval,
276                    self.layout.align.abi,
277                    llscratch,
278                    scratch_align,
279                    bx.const_usize(copy_bytes),
280                    MemFlags::empty(),
281                    None,
282                );
283                bx.lifetime_end(llscratch, scratch_size);
284            }
285            PassMode::Pair(..) | PassMode::Direct { .. } => {
286                OperandRef::from_immediate_or_packed_pair(bx, val, self.layout).val.store(bx, dst);
287            }
288        }
289    }
290
291    fn store_fn_arg(
292        &self,
293        bx: &mut Builder<'_, 'll, 'tcx>,
294        idx: &mut usize,
295        dst: PlaceRef<'tcx, &'ll Value>,
296    ) {
297        let mut next = || {
298            let val = llvm::get_param(bx.llfn(), *idx as c_uint);
299            *idx += 1;
300            val
301        };
302        match self.mode {
303            PassMode::Ignore => {}
304            PassMode::Pair(..) => {
305                OperandValue::Pair(next(), next()).store(bx, dst);
306            }
307            PassMode::Indirect { attrs: _, meta_attrs: Some(_), address_space: _, mode: _ } => {
308                ::rustc_span::macros::bug_impl(None,
    format_args!("unsized `ArgAbi` cannot be stored"), Location::caller());bug!("unsized `ArgAbi` cannot be stored");
309            }
310            PassMode::Direct(_)
311            | PassMode::Indirect { attrs: _, meta_attrs: None, address_space: _, mode: _ }
312            | PassMode::Cast { .. } => {
313                let next_arg = next();
314                self.store(bx, next_arg, dst);
315            }
316        }
317    }
318}
319
320impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
321    fn store_fn_arg(
322        &mut self,
323        arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
324        idx: &mut usize,
325        dst: PlaceRef<'tcx, Self::Value>,
326    ) {
327        arg_abi.store_fn_arg(self, idx, dst)
328    }
329    fn store_arg(
330        &mut self,
331        arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
332        val: &'ll Value,
333        dst: PlaceRef<'tcx, &'ll Value>,
334    ) {
335        arg_abi.store(self, val, dst)
336    }
337}
338
339pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
340    fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
341    fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
342    fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv;
343
344    /// Apply attributes to a function declaration/definition.
345    fn apply_attrs_llfn(
346        &self,
347        cx: &CodegenCx<'ll, 'tcx>,
348        llfn: &'ll Value,
349        instance: Option<ty::Instance<'tcx>>,
350    );
351
352    /// Apply attributes to a function call.
353    fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
354}
355
356impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
357    fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
358        // Ignore "extra" args from the call site for C variadic functions.
359        // Only the "fixed" args are part of the LLVM function signature.
360        let args =
361            if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
362
363        // This capacity calculation is approximate.
364        let mut llargument_tys = Vec::with_capacity(
365            self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
366        );
367
368        let llreturn_ty = match &self.ret.mode {
369            PassMode::Ignore => cx.type_void(),
370            PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
371            PassMode::Cast { cast, pad_i32_count: _ } => cast.llvm_type(cx),
372            PassMode::Indirect { address_space, .. } => {
373                let ty = if let Some(address_space) = address_space {
374                    cx.type_ptr_ext(*address_space)
375                } else {
376                    cx.type_ptr()
377                };
378                llargument_tys.push(ty);
379                cx.type_void()
380            }
381        };
382
383        for arg in args {
384            // Note that the exact number of arguments pushed here is carefully synchronized with
385            // code all over the place, both in the codegen_llvm and codegen_ssa crates. That's how
386            // other code then knows which LLVM argument(s) correspond to the n-th Rust argument.
387            let llarg_ty = match &arg.mode {
388                PassMode::Ignore => continue,
389                PassMode::Direct(_) => {
390                    // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
391                    // and for Scalar ABIs the LLVM type is fully determined by `layout.abi`,
392                    // guaranteeing that we generate ABI-compatible LLVM IR.
393                    arg.layout.immediate_llvm_type(cx)
394                }
395                PassMode::Pair(..) => {
396                    // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
397                    // so for ScalarPair we can easily be sure that we are generating ABI-compatible
398                    // LLVM IR.
399                    llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
400                    llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
401                    continue;
402                }
403                PassMode::Indirect { attrs: _, meta_attrs: Some(_), address_space: _, mode: _ } => {
404                    // Construct the type of a (wide) pointer to `ty`, and pass its two fields.
405                    // Any two ABI-compatible unsized types have the same metadata type and
406                    // moreover the same metadata value leads to the same dynamic size and
407                    // alignment, so this respects ABI compatibility.
408                    let ptr_ty = Ty::new_mut_ptr(cx.tcx, arg.layout.ty);
409                    let ptr_layout = cx.layout_of(ptr_ty);
410                    llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
411                    llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
412                    continue;
413                }
414                PassMode::Indirect { attrs: _, meta_attrs: None, address_space, mode: _ } => {
415                    if let Some(address_space) = address_space {
416                        cx.type_ptr_ext(*address_space)
417                    } else {
418                        cx.type_ptr()
419                    }
420                }
421                PassMode::Cast { cast, pad_i32_count } => {
422                    // Add padding.
423                    llargument_tys.extend(std::iter::repeat_n(
424                        Reg::i32().llvm_type(cx),
425                        usize::from(*pad_i32_count),
426                    ));
427
428                    // Compute the LLVM type we use for this function from the cast type.
429                    // We assume here that ABI-compatible Rust types have the same cast type.
430                    cast.llvm_type(cx)
431                }
432            };
433            llargument_tys.push(llarg_ty);
434        }
435
436        if self.c_variadic {
437            cx.type_variadic_func(&llargument_tys, llreturn_ty)
438        } else {
439            cx.type_func(&llargument_tys, llreturn_ty)
440        }
441    }
442
443    fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
444        cx.type_ptr_ext(cx.data_layout().instruction_address_space)
445    }
446
447    fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv {
448        to_llvm_calling_convention(cx.tcx.sess, self.conv)
449    }
450
451    fn apply_attrs_llfn(
452        &self,
453        cx: &CodegenCx<'ll, 'tcx>,
454        llfn: &'ll Value,
455        instance: Option<ty::Instance<'tcx>>,
456    ) {
457        let mut func_attrs = SmallVec::<[_; 3]>::new();
458        if self.ret.layout.is_uninhabited() {
459            func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
460        }
461        if !self.can_unwind {
462            func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
463        }
464        match self.conv {
465            CanonAbi::Interrupt(InterruptKind::RiscvMachine) => {
466                func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "machine"))
467            }
468            CanonAbi::Interrupt(InterruptKind::RiscvSupervisor) => {
469                func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "supervisor"))
470            }
471            CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) => {
472                func_attrs.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"))
473            }
474            _ => (),
475        }
476        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
477
478        let mut i = 0;
479        let mut apply = |attrs: &ArgAttributes| {
480            attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
481            i += 1;
482            i - 1
483        };
484
485        let apply_range_attr = |idx: AttributePlace, scalar: rustc_abi::Scalar| {
486            if cx.sess().opts.optimize != config::OptLevel::No
487                && #[allow(non_exhaustive_omitted_patterns)] match scalar.primitive() {
    Primitive::Int(..) => true,
    _ => false,
}matches!(scalar.primitive(), Primitive::Int(..))
488                // If the value is a boolean, the range is 0..2 and that ultimately
489                // become 0..0 when the type becomes i1, which would be rejected
490                // by the LLVM verifier.
491                && !scalar.is_bool()
492                // LLVM also rejects full range.
493                && !scalar.is_always_valid(cx)
494            {
495                attributes::apply_to_llfn(
496                    llfn,
497                    idx,
498                    &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
499                );
500            }
501        };
502
503        match &self.ret.mode {
504            PassMode::Direct(attrs) => {
505                attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
506                if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
507                    apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
508                }
509            }
510            PassMode::Indirect { attrs, meta_attrs: _, address_space: _, mode } => {
511                if !(*mode == IndirectMode::Pointer) {
    ::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
512                let i = apply(attrs);
513                let sret = llvm::CreateStructRetAttr(
514                    cx.llcx,
515                    cx.type_array(cx.type_i8(), self.ret.layout.size.bytes()),
516                );
517                attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
518                if cx.sess().opts.optimize != config::OptLevel::No {
519                    attributes::apply_to_llfn(
520                        llfn,
521                        llvm::AttributePlace::Argument(i),
522                        &[
523                            llvm::AttributeKind::Writable.create_attr(cx.llcx),
524                            llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx),
525                        ],
526                    );
527                }
528            }
529            PassMode::Cast { cast, pad_i32_count: _ } => {
530                cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
531            }
532            _ => {}
533        }
534        for arg in self.args.iter() {
535            match &arg.mode {
536                PassMode::Ignore => {}
537                PassMode::Indirect {
538                    attrs,
539                    meta_attrs: None,
540                    address_space: _,
541                    mode: IndirectMode::OnStack,
542                } => {
543                    let i = apply(attrs);
544                    let byval = llvm::CreateByValAttr(
545                        cx.llcx,
546                        cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
547                    );
548                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
549                }
550                PassMode::Indirect {
551                    attrs,
552                    meta_attrs: None,
553                    address_space: _,
554                    mode: IndirectMode::AmdgpuKernelArg,
555                } => {
556                    let i = apply(attrs);
557                    let byref = llvm::CreateByRefAttr(
558                        cx.llcx,
559                        cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
560                    );
561                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byref]);
562                }
563                PassMode::Direct(attrs) => {
564                    let i = apply(attrs);
565                    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
566                        apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
567                    }
568                }
569                PassMode::Indirect {
570                    attrs,
571                    meta_attrs: None,
572                    address_space: _,
573                    mode: IndirectMode::Pointer,
574                } => {
575                    let i = apply(attrs);
576                    if cx.sess().opts.optimize != config::OptLevel::No {
577                        attributes::apply_to_llfn(
578                            llfn,
579                            llvm::AttributePlace::Argument(i),
580                            &[llvm::AttributeKind::DeadOnReturn.create_attr(cx.llcx)],
581                        );
582                    }
583                }
584                PassMode::Indirect {
585                    attrs,
586                    meta_attrs: Some(meta_attrs),
587                    address_space: _,
588                    mode,
589                } => {
590                    if !(*mode == IndirectMode::Pointer) {
    ::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
591                    apply(attrs);
592                    apply(meta_attrs);
593                }
594                PassMode::Pair(a, b) => {
595                    let i = apply(a);
596                    let ii = apply(b);
597                    if let BackendRepr::ScalarPair { a: scalar_a, b: scalar_b, b_offset: _ } =
598                        arg.layout.backend_repr
599                    {
600                        apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
601                        let primitive_b = scalar_b.primitive();
602                        let scalar_b = if let rustc_abi::Primitive::Int(int, false) = primitive_b
603                            && let ty::Ref(_, pointee_ty, _) = *arg.layout.ty.kind()
604                            && let ty::Slice(element_ty) = *pointee_ty.kind()
605                            && let elem_size = cx.layout_of(element_ty).size
606                            && elem_size != rustc_abi::Size::ZERO
607                        {
608                            // Ideally the layout calculations would have set the range,
609                            // but that's complicated due to cycles, so in the mean time
610                            // we calculate and apply it here.
611                            if true {
    if !scalar_b.is_always_valid(cx) {
        ::core::panicking::panic("assertion failed: scalar_b.is_always_valid(cx)")
    };
};debug_assert!(scalar_b.is_always_valid(cx));
612                            let isize_max = int.signed_max() as u64;
613                            rustc_abi::Scalar::Initialized {
614                                value: primitive_b,
615                                valid_range: rustc_abi::WrappingRange {
616                                    start: 0,
617                                    end: u128::from(isize_max / elem_size.bytes()),
618                                },
619                            }
620                        } else {
621                            scalar_b
622                        };
623                        apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
624                    }
625                }
626                PassMode::Cast { cast, pad_i32_count } => {
627                    for _ in 0..*pad_i32_count {
628                        apply(&ArgAttributes::new());
629                    }
630                    apply(&cast.attrs);
631                }
632            }
633        }
634
635        // If the declaration has an associated instance, compute extra attributes based on that.
636        if let Some(instance) = instance {
637            llfn_attrs_from_instance(
638                cx,
639                cx.tcx,
640                llfn,
641                &cx.tcx.codegen_instance_attrs(instance.def),
642                Some(instance),
643                cx.sanitizer_ignorelist.as_ref(),
644            );
645        }
646    }
647
648    fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
649        let mut func_attrs = SmallVec::<[_; 2]>::new();
650        if self.ret.layout.is_uninhabited() {
651            func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
652        }
653        if !self.can_unwind {
654            func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
655        }
656        attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
657
658        let mut i = 0;
659        let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
660            attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
661            i += 1;
662            i - 1
663        };
664        match &self.ret.mode {
665            PassMode::Direct(attrs) => {
666                attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
667            }
668            PassMode::Indirect { attrs, meta_attrs: _, address_space: _, mode } => {
669                if !(*mode == IndirectMode::Pointer) {
    ::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
670                let i = apply(bx.cx, attrs);
671                let sret = llvm::CreateStructRetAttr(
672                    bx.cx.llcx,
673                    bx.cx.type_array(bx.cx.type_i8(), self.ret.layout.size.bytes()),
674                );
675                attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
676            }
677            PassMode::Cast { cast, pad_i32_count: _ } => {
678                cast.attrs.apply_attrs_to_callsite(
679                    llvm::AttributePlace::ReturnValue,
680                    bx.cx,
681                    callsite,
682                );
683            }
684            _ => {}
685        }
686        for arg in self.args.iter() {
687            match &arg.mode {
688                PassMode::Ignore => {}
689                PassMode::Indirect {
690                    attrs,
691                    meta_attrs: None,
692                    address_space: _,
693                    mode: IndirectMode::OnStack,
694                } => {
695                    let i = apply(bx.cx, attrs);
696                    let byval = llvm::CreateByValAttr(
697                        bx.cx.llcx,
698                        bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
699                    );
700                    attributes::apply_to_callsite(
701                        callsite,
702                        llvm::AttributePlace::Argument(i),
703                        &[byval],
704                    );
705                }
706                PassMode::Indirect {
707                    attrs,
708                    meta_attrs: None,
709                    address_space: _,
710                    mode: IndirectMode::AmdgpuKernelArg,
711                } => {
712                    let i = apply(bx.cx, attrs);
713                    let byref = llvm::CreateByRefAttr(
714                        bx.cx.llcx,
715                        bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
716                    );
717                    attributes::apply_to_callsite(
718                        callsite,
719                        llvm::AttributePlace::Argument(i),
720                        &[byref],
721                    );
722                }
723                PassMode::Direct(attrs)
724                | PassMode::Indirect {
725                    attrs,
726                    meta_attrs: None,
727                    address_space: _,
728                    mode: IndirectMode::Pointer,
729                } => {
730                    apply(bx.cx, attrs);
731                }
732                PassMode::Indirect {
733                    attrs,
734                    meta_attrs: Some(meta_attrs),
735                    address_space: _,
736                    mode: _,
737                } => {
738                    apply(bx.cx, attrs);
739                    apply(bx.cx, meta_attrs);
740                }
741                PassMode::Pair(a, b) => {
742                    apply(bx.cx, a);
743                    apply(bx.cx, b);
744                }
745                PassMode::Cast { cast, pad_i32_count } => {
746                    for _ in 0..*pad_i32_count {
747                        apply(bx.cx, &ArgAttributes::new());
748                    }
749                    apply(bx.cx, &cast.attrs);
750                }
751            }
752        }
753
754        let cconv = self.llvm_cconv(&bx.cx);
755        if cconv != llvm::CCallConv {
756            llvm::SetInstructionCallConv(callsite, cconv);
757        }
758
759        if self.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
760            // This will probably get ignored on all targets but those supporting the TrustZone-M
761            // extension (thumbv8m targets).
762            let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
763            attributes::apply_to_callsite(
764                callsite,
765                llvm::AttributePlace::Function,
766                &[cmse_nonsecure_call],
767            );
768        }
769
770        // Some intrinsics require that an elementtype attribute (with the pointee type of a
771        // pointer argument) is added to the callsite.
772        let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
773        if element_type_index >= 0 {
774            let arg_ty = self.args[element_type_index as usize].layout.ty;
775            let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument");
776            let element_type_attr = unsafe {
777                llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
778            };
779            attributes::apply_to_callsite(
780                callsite,
781                llvm::AttributePlace::Argument(element_type_index as u32),
782                &[element_type_attr],
783            );
784        }
785    }
786}
787
788impl AbiBuilderMethods for Builder<'_, '_, '_> {
789    fn get_param(&mut self, index: usize) -> Self::Value {
790        llvm::get_param(self.llfn(), index as c_uint)
791    }
792}
793
794/// Determines the appropriate [`llvm::CallConv`] to use for a given function
795/// ABI, for the current target.
796pub(crate) fn to_llvm_calling_convention(sess: &Session, abi: CanonAbi) -> llvm::CallConv {
797    match abi {
798        CanonAbi::C | CanonAbi::Rust => llvm::CCallConv,
799        CanonAbi::RustCold => llvm::PreserveMost,
800        CanonAbi::RustPreserveNone => match &sess.target.arch {
801            Arch::X86_64 | Arch::AArch64 => llvm::PreserveNone,
802            _ => llvm::CCallConv,
803        },
804        CanonAbi::RustTail => match &sess.target.arch {
805            Arch::X86 | Arch::X86_64 | Arch::AArch64 => llvm::Tail,
806            _ => sess.dcx().fatal("extern \"tail\" is only supported on x86, x86_64 and aarch64"),
807        },
808        // Functions with this calling convention can only be called from assembly, but it is
809        // possible to declare an `extern "custom"` block, so the backend still needs a calling
810        // convention for declaring foreign functions.
811        CanonAbi::Custom => llvm::CCallConv,
812        CanonAbi::Swift => llvm::SwiftCallConv,
813        CanonAbi::GpuKernel => match &sess.target.arch {
814            Arch::AmdGpu => llvm::AmdgpuKernel,
815            Arch::Nvptx64 => llvm::PtxKernel,
816            arch => {
    ::core::panicking::panic_fmt(format_args!("Architecture {0} does not support GpuKernel calling convention",
            arch));
}panic!("Architecture {arch} does not support GpuKernel calling convention"),
817        },
818        CanonAbi::Interrupt(interrupt_kind) => match interrupt_kind {
819            InterruptKind::Avr => llvm::AvrInterrupt,
820            InterruptKind::AvrNonBlocking => llvm::AvrNonBlockingInterrupt,
821            InterruptKind::Msp430 => llvm::Msp430Intr,
822            InterruptKind::RiscvMachine | InterruptKind::RiscvSupervisor => llvm::CCallConv,
823            InterruptKind::X86 => llvm::X86_Intr,
824        },
825        CanonAbi::Arm(arm_call) => match arm_call {
826            ArmCall::Aapcs => llvm::ArmAapcsCallConv,
827            ArmCall::CCmseNonSecureCall | ArmCall::CCmseNonSecureEntry => llvm::CCallConv,
828        },
829        CanonAbi::X86(x86_call) => match x86_call {
830            X86Call::Fastcall => llvm::X86FastcallCallConv,
831            X86Call::Stdcall => llvm::X86StdcallCallConv,
832            X86Call::SysV64 => llvm::X86_64_SysV,
833            X86Call::Thiscall => llvm::X86_ThisCall,
834            X86Call::Vectorcall => llvm::X86_VectorCall,
835            X86Call::Win64 => llvm::X86_64_Win64,
836        },
837    }
838}