rustc_codegen_llvm/
abi.rs

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