rustc_codegen_llvm/
abi.rs

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