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, 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                _ => 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::F32 => cx.type_f32(),
163                        Float::F64 => cx.type_f64(),
164                        Float::F128 => cx.type_f128(),
165                    },
166                    Primitive::Pointer(_) => cx.type_ptr(),
167                };
168
169                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()));
170                let len = self.size.bytes() / hint_vector_elem.size(cx).bytes();
171                cx.type_vector(ty, len)
172            }
173        }
174    }
175}
176
177impl LlvmType for CastTarget {
178    fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
179        let rest_ll_unit = self.rest.unit.llvm_type(cx);
180        let rest_count = if self.rest.total == Size::ZERO {
181            0
182        } else {
183            {
    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!(
184                self.rest.unit.size,
185                Size::ZERO,
186                "total size {:?} cannot be divided into units of zero size",
187                self.rest.total
188            );
189            if !self.rest.total.bytes().is_multiple_of(self.rest.unit.size.bytes()) {
190                {
    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");
191            }
192            self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes())
193        };
194
195        // Simplify to a single unit or an array if there's no prefix.
196        // This produces the same layout, but using a simpler type.
197        if self.prefix.is_empty() {
198            // We can't do this if is_consecutive is set and the unit would get
199            // split on the target. Currently, this is only relevant for i128
200            // registers.
201            if rest_count == 1 && (!self.rest.is_consecutive || self.rest.unit != Reg::i128()) {
202                return rest_ll_unit;
203            }
204
205            return cx.type_array(rest_ll_unit, rest_count);
206        }
207
208        // Generate a struct type with the prefix and the "rest" arguments.
209        let prefix_args = self.prefix.iter().map(|reg| reg.llvm_type(cx));
210        let rest_args = (0..rest_count).map(|_| rest_ll_unit);
211        let args: Vec<_> = prefix_args.chain(rest_args).collect();
212        cx.type_struct(&args, false)
213    }
214}
215
216trait ArgAbiExt<'ll, 'tcx> {
217    fn store(
218        &self,
219        bx: &mut Builder<'_, 'll, 'tcx>,
220        val: &'ll Value,
221        dst: PlaceRef<'tcx, &'ll Value>,
222    );
223    fn store_fn_arg(
224        &self,
225        bx: &mut Builder<'_, 'll, 'tcx>,
226        idx: &mut usize,
227        dst: PlaceRef<'tcx, &'ll Value>,
228    );
229}
230
231impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
232    /// Stores a direct/indirect value described by this ArgAbi into a
233    /// place for the original Rust type of this argument/return.
234    /// Can be used for both storing formal arguments into Rust variables
235    /// or results of call/invoke instructions into their destinations.
236    fn store(
237        &self,
238        bx: &mut Builder<'_, 'll, 'tcx>,
239        val: &'ll Value,
240        dst: PlaceRef<'tcx, &'ll Value>,
241    ) {
242        match &self.mode {
243            PassMode::Ignore => {}
244            // Sized indirect arguments
245            PassMode::Indirect { attrs, meta_attrs: None, on_stack: _ } => {
246                let align = attrs.pointee_align.unwrap_or(self.layout.align.abi);
247                OperandValue::Ref(PlaceValue::new_sized(val, align)).store(bx, dst);
248            }
249            // Unsized indirect arguments cannot be stored
250            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
251                bug_impl(None, format_args!("unsized `ArgAbi` cannot be stored"),
    Location::caller());bug!("unsized `ArgAbi` cannot be stored");
252            }
253            PassMode::Cast { cast, pad_i32_count: _ } => {
254                // The ABI mandates that the value is passed as a different struct representation.
255                // Spill and reload it from the stack to convert from the ABI representation to
256                // the Rust representation.
257                let scratch_size = cast.size(bx);
258                let scratch_align = cast.align(bx);
259                // Note that the ABI type may be either larger or smaller than the Rust type,
260                // due to the presence or absence of trailing padding. For example:
261                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
262                //   when passed by value, making it smaller.
263                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
264                //   when passed by value, making it larger.
265                let copy_bytes =
266                    cmp::min(cast.unaligned_size(bx).bytes(), self.layout.size.bytes());
267                // Allocate some scratch space...
268                let llscratch = bx.alloca(scratch_size, scratch_align);
269                bx.lifetime_start(llscratch, scratch_size);
270                // ...store the value...
271                rustc_codegen_ssa::mir::store_cast(bx, cast, val, llscratch, scratch_align);
272                // ... and then memcpy it to the intended destination.
273                bx.memcpy(
274                    dst.val.llval,
275                    self.layout.align.abi,
276                    llscratch,
277                    scratch_align,
278                    bx.const_usize(copy_bytes),
279                    MemFlags::empty(),
280                    None,
281                );
282                bx.lifetime_end(llscratch, scratch_size);
283            }
284            PassMode::Pair(..) | PassMode::Direct { .. } => {
285                OperandRef::from_immediate_or_packed_pair(bx, val, self.layout).val.store(bx, dst);
286            }
287        }
288    }
289
290    fn store_fn_arg(
291        &self,
292        bx: &mut Builder<'_, 'll, 'tcx>,
293        idx: &mut usize,
294        dst: PlaceRef<'tcx, &'ll Value>,
295    ) {
296        let mut next = || {
297            let val = llvm::get_param(bx.llfn(), *idx as c_uint);
298            *idx += 1;
299            val
300        };
301        match self.mode {
302            PassMode::Ignore => {}
303            PassMode::Pair(..) => {
304                OperandValue::Pair(next(), next()).store(bx, dst);
305            }
306            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
307                bug_impl(None, format_args!("unsized `ArgAbi` cannot be stored"),
    Location::caller());bug!("unsized `ArgAbi` cannot be stored");
308            }
309            PassMode::Direct(_)
310            | PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ }
311            | PassMode::Cast { .. } => {
312                let next_arg = next();
313                self.store(bx, next_arg, dst);
314            }
315        }
316    }
317}
318
319impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
320    fn store_fn_arg(
321        &mut self,
322        arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
323        idx: &mut usize,
324        dst: PlaceRef<'tcx, Self::Value>,
325    ) {
326        arg_abi.store_fn_arg(self, idx, dst)
327    }
328    fn store_arg(
329        &mut self,
330        arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
331        val: &'ll Value,
332        dst: PlaceRef<'tcx, &'ll Value>,
333    ) {
334        arg_abi.store(self, val, dst)
335    }
336}
337
338pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
339    fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
340    fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
341    fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv;
342
343    /// Apply attributes to a function declaration/definition.
344    fn apply_attrs_llfn(
345        &self,
346        cx: &CodegenCx<'ll, 'tcx>,
347        llfn: &'ll Value,
348        instance: Option<ty::Instance<'tcx>>,
349    );
350
351    /// Apply attributes to a function call.
352    fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
353}
354
355impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
356    fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
357        // Ignore "extra" args from the call site for C variadic functions.
358        // Only the "fixed" args are part of the LLVM function signature.
359        let args =
360            if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
361
362        // This capacity calculation is approximate.
363        let mut llargument_tys = Vec::with_capacity(
364            self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
365        );
366
367        let llreturn_ty = match &self.ret.mode {
368            PassMode::Ignore => cx.type_void(),
369            PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
370            PassMode::Cast { cast, pad_i32_count: _ } => cast.llvm_type(cx),
371            PassMode::Indirect { .. } => {
372                llargument_tys.push(cx.type_ptr());
373                cx.type_void()
374            }
375        };
376
377        for arg in args {
378            // Note that the exact number of arguments pushed here is carefully synchronized with
379            // code all over the place, both in the codegen_llvm and codegen_ssa crates. That's how
380            // other code then knows which LLVM argument(s) correspond to the n-th Rust argument.
381            let llarg_ty = match &arg.mode {
382                PassMode::Ignore => continue,
383                PassMode::Direct(_) => {
384                    // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
385                    // and for Scalar ABIs the LLVM type is fully determined by `layout.abi`,
386                    // guaranteeing that we generate ABI-compatible LLVM IR.
387                    arg.layout.immediate_llvm_type(cx)
388                }
389                PassMode::Pair(..) => {
390                    // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
391                    // so for ScalarPair we can easily be sure that we are generating ABI-compatible
392                    // LLVM IR.
393                    llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
394                    llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
395                    continue;
396                }
397                PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
398                    // Construct the type of a (wide) pointer to `ty`, and pass its two fields.
399                    // Any two ABI-compatible unsized types have the same metadata type and
400                    // moreover the same metadata value leads to the same dynamic size and
401                    // alignment, so this respects ABI compatibility.
402                    let ptr_ty = Ty::new_mut_ptr(cx.tcx, arg.layout.ty);
403                    let ptr_layout = cx.layout_of(ptr_ty);
404                    llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
405                    llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
406                    continue;
407                }
408                PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ } => cx.type_ptr(),
409                PassMode::Cast { cast, pad_i32_count } => {
410                    // Add padding.
411                    llargument_tys.extend(std::iter::repeat_n(
412                        Reg::i32().llvm_type(cx),
413                        usize::from(*pad_i32_count),
414                    ));
415
416                    // Compute the LLVM type we use for this function from the cast type.
417                    // We assume here that ABI-compatible Rust types have the same cast type.
418                    cast.llvm_type(cx)
419                }
420            };
421            llargument_tys.push(llarg_ty);
422        }
423
424        if self.c_variadic {
425            cx.type_variadic_func(&llargument_tys, llreturn_ty)
426        } else {
427            cx.type_func(&llargument_tys, llreturn_ty)
428        }
429    }
430
431    fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
432        cx.type_ptr_ext(cx.data_layout().instruction_address_space)
433    }
434
435    fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv {
436        to_llvm_calling_convention(cx.tcx.sess, self.conv)
437    }
438
439    fn apply_attrs_llfn(
440        &self,
441        cx: &CodegenCx<'ll, 'tcx>,
442        llfn: &'ll Value,
443        instance: Option<ty::Instance<'tcx>>,
444    ) {
445        let mut func_attrs = SmallVec::<[_; 3]>::new();
446        if self.ret.layout.is_uninhabited() {
447            func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
448        }
449        if !self.can_unwind {
450            func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
451        }
452        match self.conv {
453            CanonAbi::Interrupt(InterruptKind::RiscvMachine) => {
454                func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "machine"))
455            }
456            CanonAbi::Interrupt(InterruptKind::RiscvSupervisor) => {
457                func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "supervisor"))
458            }
459            CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) => {
460                func_attrs.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"))
461            }
462            _ => (),
463        }
464        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
465
466        let mut i = 0;
467        let mut apply = |attrs: &ArgAttributes| {
468            attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
469            i += 1;
470            i - 1
471        };
472
473        let apply_range_attr = |idx: AttributePlace, scalar: rustc_abi::Scalar| {
474            if cx.sess().opts.optimize != config::OptLevel::No
475                && #[allow(non_exhaustive_omitted_patterns)] match scalar.primitive() {
    Primitive::Int(..) => true,
    _ => false,
}matches!(scalar.primitive(), Primitive::Int(..))
476                // If the value is a boolean, the range is 0..2 and that ultimately
477                // become 0..0 when the type becomes i1, which would be rejected
478                // by the LLVM verifier.
479                && !scalar.is_bool()
480                // LLVM also rejects full range.
481                && !scalar.is_always_valid(cx)
482            {
483                attributes::apply_to_llfn(
484                    llfn,
485                    idx,
486                    &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
487                );
488            }
489        };
490
491        match &self.ret.mode {
492            PassMode::Direct(attrs) => {
493                attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
494                if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
495                    apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
496                }
497            }
498            PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
499                if !!on_stack { ::core::panicking::panic("assertion failed: !on_stack") };assert!(!on_stack);
500                let i = apply(attrs);
501                let sret = llvm::CreateStructRetAttr(
502                    cx.llcx,
503                    cx.type_array(cx.type_i8(), self.ret.layout.size.bytes()),
504                );
505                attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
506                if cx.sess().opts.optimize != config::OptLevel::No {
507                    attributes::apply_to_llfn(
508                        llfn,
509                        llvm::AttributePlace::Argument(i),
510                        &[
511                            llvm::AttributeKind::Writable.create_attr(cx.llcx),
512                            llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx),
513                        ],
514                    );
515                }
516            }
517            PassMode::Cast { cast, pad_i32_count: _ } => {
518                cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
519            }
520            _ => {}
521        }
522        for arg in self.args.iter() {
523            match &arg.mode {
524                PassMode::Ignore => {}
525                PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
526                    let i = apply(attrs);
527                    let byval = llvm::CreateByValAttr(
528                        cx.llcx,
529                        cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
530                    );
531                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
532                }
533                PassMode::Direct(attrs) => {
534                    let i = apply(attrs);
535                    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
536                        apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
537                    }
538                }
539                PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
540                    let i = apply(attrs);
541                    if cx.sess().opts.optimize != config::OptLevel::No {
542                        attributes::apply_to_llfn(
543                            llfn,
544                            llvm::AttributePlace::Argument(i),
545                            &[llvm::AttributeKind::DeadOnReturn.create_attr(cx.llcx)],
546                        );
547                    }
548                }
549                PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack } => {
550                    if !!on_stack { ::core::panicking::panic("assertion failed: !on_stack") };assert!(!on_stack);
551                    apply(attrs);
552                    apply(meta_attrs);
553                }
554                PassMode::Pair(a, b) => {
555                    let i = apply(a);
556                    let ii = apply(b);
557                    if let BackendRepr::ScalarPair { a: scalar_a, b: scalar_b, b_offset: _ } =
558                        arg.layout.backend_repr
559                    {
560                        apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
561                        let primitive_b = scalar_b.primitive();
562                        let scalar_b = if let rustc_abi::Primitive::Int(int, false) = primitive_b
563                            && let ty::Ref(_, pointee_ty, _) = *arg.layout.ty.kind()
564                            && let ty::Slice(element_ty) = *pointee_ty.kind()
565                            && let elem_size = cx.layout_of(element_ty).size
566                            && elem_size != rustc_abi::Size::ZERO
567                        {
568                            // Ideally the layout calculations would have set the range,
569                            // but that's complicated due to cycles, so in the mean time
570                            // we calculate and apply it here.
571                            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));
572                            let isize_max = int.signed_max() as u64;
573                            rustc_abi::Scalar::Initialized {
574                                value: primitive_b,
575                                valid_range: rustc_abi::WrappingRange {
576                                    start: 0,
577                                    end: u128::from(isize_max / elem_size.bytes()),
578                                },
579                            }
580                        } else {
581                            scalar_b
582                        };
583                        apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
584                    }
585                }
586                PassMode::Cast { cast, pad_i32_count } => {
587                    for _ in 0..*pad_i32_count {
588                        apply(&ArgAttributes::new());
589                    }
590                    apply(&cast.attrs);
591                }
592            }
593        }
594
595        // If the declaration has an associated instance, compute extra attributes based on that.
596        if let Some(instance) = instance {
597            llfn_attrs_from_instance(
598                cx,
599                cx.tcx,
600                llfn,
601                &cx.tcx.codegen_instance_attrs(instance.def),
602                Some(instance),
603                cx.sanitizer_ignorelist.as_ref(),
604            );
605        }
606    }
607
608    fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
609        let mut func_attrs = SmallVec::<[_; 2]>::new();
610        if self.ret.layout.is_uninhabited() {
611            func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
612        }
613        if !self.can_unwind {
614            func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
615        }
616        attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
617
618        let mut i = 0;
619        let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
620            attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
621            i += 1;
622            i - 1
623        };
624        match &self.ret.mode {
625            PassMode::Direct(attrs) => {
626                attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
627            }
628            PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
629                if !!on_stack { ::core::panicking::panic("assertion failed: !on_stack") };assert!(!on_stack);
630                let i = apply(bx.cx, attrs);
631                let sret = llvm::CreateStructRetAttr(
632                    bx.cx.llcx,
633                    bx.cx.type_array(bx.cx.type_i8(), self.ret.layout.size.bytes()),
634                );
635                attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
636            }
637            PassMode::Cast { cast, pad_i32_count: _ } => {
638                cast.attrs.apply_attrs_to_callsite(
639                    llvm::AttributePlace::ReturnValue,
640                    bx.cx,
641                    callsite,
642                );
643            }
644            _ => {}
645        }
646        for arg in self.args.iter() {
647            match &arg.mode {
648                PassMode::Ignore => {}
649                PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
650                    let i = apply(bx.cx, attrs);
651                    let byval = llvm::CreateByValAttr(
652                        bx.cx.llcx,
653                        bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
654                    );
655                    attributes::apply_to_callsite(
656                        callsite,
657                        llvm::AttributePlace::Argument(i),
658                        &[byval],
659                    );
660                }
661                PassMode::Direct(attrs)
662                | PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
663                    apply(bx.cx, attrs);
664                }
665                PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack: _ } => {
666                    apply(bx.cx, attrs);
667                    apply(bx.cx, meta_attrs);
668                }
669                PassMode::Pair(a, b) => {
670                    apply(bx.cx, a);
671                    apply(bx.cx, b);
672                }
673                PassMode::Cast { cast, pad_i32_count } => {
674                    for _ in 0..*pad_i32_count {
675                        apply(bx.cx, &ArgAttributes::new());
676                    }
677                    apply(bx.cx, &cast.attrs);
678                }
679            }
680        }
681
682        let cconv = self.llvm_cconv(&bx.cx);
683        if cconv != llvm::CCallConv {
684            llvm::SetInstructionCallConv(callsite, cconv);
685        }
686
687        if self.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
688            // This will probably get ignored on all targets but those supporting the TrustZone-M
689            // extension (thumbv8m targets).
690            let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
691            attributes::apply_to_callsite(
692                callsite,
693                llvm::AttributePlace::Function,
694                &[cmse_nonsecure_call],
695            );
696        }
697
698        // Some intrinsics require that an elementtype attribute (with the pointee type of a
699        // pointer argument) is added to the callsite.
700        let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
701        if element_type_index >= 0 {
702            let arg_ty = self.args[element_type_index as usize].layout.ty;
703            let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument");
704            let element_type_attr = unsafe {
705                llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
706            };
707            attributes::apply_to_callsite(
708                callsite,
709                llvm::AttributePlace::Argument(element_type_index as u32),
710                &[element_type_attr],
711            );
712        }
713    }
714}
715
716impl AbiBuilderMethods for Builder<'_, '_, '_> {
717    fn get_param(&mut self, index: usize) -> Self::Value {
718        llvm::get_param(self.llfn(), index as c_uint)
719    }
720}
721
722/// Determines the appropriate [`llvm::CallConv`] to use for a given function
723/// ABI, for the current target.
724pub(crate) fn to_llvm_calling_convention(sess: &Session, abi: CanonAbi) -> llvm::CallConv {
725    match abi {
726        CanonAbi::C | CanonAbi::Rust => llvm::CCallConv,
727        CanonAbi::RustCold => llvm::PreserveMost,
728        CanonAbi::RustPreserveNone => match &sess.target.arch {
729            Arch::X86_64 | Arch::AArch64 => llvm::PreserveNone,
730            _ => llvm::CCallConv,
731        },
732        CanonAbi::RustTail => match &sess.target.arch {
733            Arch::X86 | Arch::X86_64 | Arch::AArch64 => llvm::Tail,
734            _ => sess.dcx().fatal("extern \"tail\" is only supported on x86, x86_64 and aarch64"),
735        },
736        // Functions with this calling convention can only be called from assembly, but it is
737        // possible to declare an `extern "custom"` block, so the backend still needs a calling
738        // convention for declaring foreign functions.
739        CanonAbi::Custom => llvm::CCallConv,
740        CanonAbi::Swift => llvm::SwiftCallConv,
741        CanonAbi::GpuKernel => match &sess.target.arch {
742            Arch::AmdGpu => llvm::AmdgpuKernel,
743            Arch::Nvptx64 => llvm::PtxKernel,
744            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"),
745        },
746        CanonAbi::Interrupt(interrupt_kind) => match interrupt_kind {
747            InterruptKind::Avr => llvm::AvrInterrupt,
748            InterruptKind::AvrNonBlocking => llvm::AvrNonBlockingInterrupt,
749            InterruptKind::Msp430 => llvm::Msp430Intr,
750            InterruptKind::RiscvMachine | InterruptKind::RiscvSupervisor => llvm::CCallConv,
751            InterruptKind::X86 => llvm::X86_Intr,
752        },
753        CanonAbi::Arm(arm_call) => match arm_call {
754            ArmCall::Aapcs => llvm::ArmAapcsCallConv,
755            ArmCall::CCmseNonSecureCall | ArmCall::CCmseNonSecureEntry => llvm::CCallConv,
756        },
757        CanonAbi::X86(x86_call) => match x86_call {
758            X86Call::Fastcall => llvm::X86FastcallCallConv,
759            X86Call::Stdcall => llvm::X86StdcallCallConv,
760            X86Call::SysV64 => llvm::X86_64_SysV,
761            X86Call::Thiscall => llvm::X86_ThisCall,
762            X86Call::Vectorcall => llvm::X86_VectorCall,
763            X86Call::Win64 => llvm::X86_64_Win64,
764        },
765    }
766}