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