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 (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 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 if cx.sess().opts.optimize != config::OptLevel::No {
81 let deref = this.pointee_size.bytes();
82 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 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 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 if self.prefix.is_empty() {
197 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 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 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 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 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: _ } => {
253 let scratch_size = cast.size(bx);
257 let scratch_align = cast.align(bx);
258 let copy_bytes =
265 cmp::min(cast.unaligned_size(bx).bytes(), self.layout.size.bytes());
266 let llscratch = bx.alloca(scratch_size, scratch_align);
268 bx.lifetime_start(llscratch, scratch_size);
269 rustc_codegen_ssa::mir::store_cast(bx, cast, val, llscratch, scratch_align);
271 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 fn apply_attrs_llfn(
344 &self,
345 cx: &CodegenCx<'ll, 'tcx>,
346 llfn: &'ll Value,
347 instance: Option<ty::Instance<'tcx>>,
348 );
349
350 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 let args =
359 if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
360
361 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: _ } => 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 let llarg_ty = match &arg.mode {
381 PassMode::Ignore => continue,
382 PassMode::Direct(_) => {
383 arg.layout.immediate_llvm_type(cx)
387 }
388 PassMode::Pair(..) => {
389 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 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 } => {
409 if *pad_i32 {
411 llargument_tys.push(Reg::i32().llvm_type(cx));
412 }
413 cast.llvm_type(cx)
416 }
417 };
418 llargument_tys.push(llarg_ty);
419 }
420
421 if self.c_variadic {
422 cx.type_variadic_func(&llargument_tys, llreturn_ty)
423 } else {
424 cx.type_func(&llargument_tys, llreturn_ty)
425 }
426 }
427
428 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
429 cx.type_ptr_ext(cx.data_layout().instruction_address_space)
430 }
431
432 fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv {
433 to_llvm_calling_convention(cx.tcx.sess, self.conv)
434 }
435
436 fn apply_attrs_llfn(
437 &self,
438 cx: &CodegenCx<'ll, 'tcx>,
439 llfn: &'ll Value,
440 instance: Option<ty::Instance<'tcx>>,
441 ) {
442 let mut func_attrs = SmallVec::<[_; 3]>::new();
443 if self.ret.layout.is_uninhabited() {
444 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
445 }
446 if !self.can_unwind {
447 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
448 }
449 match self.conv {
450 CanonAbi::Interrupt(InterruptKind::RiscvMachine) => {
451 func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "machine"))
452 }
453 CanonAbi::Interrupt(InterruptKind::RiscvSupervisor) => {
454 func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "supervisor"))
455 }
456 CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) => {
457 func_attrs.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"))
458 }
459 _ => (),
460 }
461 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
462
463 let mut i = 0;
464 let mut apply = |attrs: &ArgAttributes| {
465 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
466 i += 1;
467 i - 1
468 };
469
470 let apply_range_attr = |idx: AttributePlace, scalar: rustc_abi::Scalar| {
471 if cx.sess().opts.optimize != config::OptLevel::No
472 && #[allow(non_exhaustive_omitted_patterns)] match scalar.primitive() {
Primitive::Int(..) => true,
_ => false,
}matches!(scalar.primitive(), Primitive::Int(..))
473 && !scalar.is_bool()
477 && !scalar.is_always_valid(cx)
479 {
480 attributes::apply_to_llfn(
481 llfn,
482 idx,
483 &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
484 );
485 }
486 };
487
488 match &self.ret.mode {
489 PassMode::Direct(attrs) => {
490 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
491 if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
492 apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
493 }
494 }
495 PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
496 if !!on_stack { ::core::panicking::panic("assertion failed: !on_stack") };assert!(!on_stack);
497 let i = apply(attrs);
498 let sret = llvm::CreateStructRetAttr(
499 cx.llcx,
500 cx.type_array(cx.type_i8(), self.ret.layout.size.bytes()),
501 );
502 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
503 if cx.sess().opts.optimize != config::OptLevel::No {
504 attributes::apply_to_llfn(
505 llfn,
506 llvm::AttributePlace::Argument(i),
507 &[
508 llvm::AttributeKind::Writable.create_attr(cx.llcx),
509 llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx),
510 ],
511 );
512 }
513 }
514 PassMode::Cast { cast, pad_i32: _ } => {
515 cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
516 }
517 _ => {}
518 }
519 for arg in self.args.iter() {
520 match &arg.mode {
521 PassMode::Ignore => {}
522 PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
523 let i = apply(attrs);
524 let byval = llvm::CreateByValAttr(
525 cx.llcx,
526 cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
527 );
528 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
529 }
530 PassMode::Direct(attrs) => {
531 let i = apply(attrs);
532 if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
533 apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
534 }
535 }
536 PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
537 let i = apply(attrs);
538 if cx.sess().opts.optimize != config::OptLevel::No {
539 attributes::apply_to_llfn(
540 llfn,
541 llvm::AttributePlace::Argument(i),
542 &[llvm::AttributeKind::DeadOnReturn.create_attr(cx.llcx)],
543 );
544 }
545 }
546 PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack } => {
547 if !!on_stack { ::core::panicking::panic("assertion failed: !on_stack") };assert!(!on_stack);
548 apply(attrs);
549 apply(meta_attrs);
550 }
551 PassMode::Pair(a, b) => {
552 let i = apply(a);
553 let ii = apply(b);
554 if let BackendRepr::ScalarPair(scalar_a, scalar_b) = arg.layout.backend_repr {
555 apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
556 let primitive_b = scalar_b.primitive();
557 let scalar_b = if let rustc_abi::Primitive::Int(int, false) = primitive_b
558 && let ty::Ref(_, pointee_ty, _) = *arg.layout.ty.kind()
559 && let ty::Slice(element_ty) = *pointee_ty.kind()
560 && let elem_size = cx.layout_of(element_ty).size
561 && elem_size != rustc_abi::Size::ZERO
562 {
563 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));
567 let isize_max = int.signed_max() as u64;
568 rustc_abi::Scalar::Initialized {
569 value: primitive_b,
570 valid_range: rustc_abi::WrappingRange {
571 start: 0,
572 end: u128::from(isize_max / elem_size.bytes()),
573 },
574 }
575 } else {
576 scalar_b
577 };
578 apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
579 }
580 }
581 PassMode::Cast { cast, pad_i32 } => {
582 if *pad_i32 {
583 apply(&ArgAttributes::new());
584 }
585 apply(&cast.attrs);
586 }
587 }
588 }
589
590 if let Some(instance) = instance {
592 llfn_attrs_from_instance(
593 cx,
594 cx.tcx,
595 llfn,
596 &cx.tcx.codegen_instance_attrs(instance.def),
597 Some(instance),
598 );
599 }
600 }
601
602 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
603 let mut func_attrs = SmallVec::<[_; 2]>::new();
604 if self.ret.layout.is_uninhabited() {
605 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
606 }
607 if !self.can_unwind {
608 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
609 }
610 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
611
612 let mut i = 0;
613 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
614 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
615 i += 1;
616 i - 1
617 };
618 match &self.ret.mode {
619 PassMode::Direct(attrs) => {
620 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
621 }
622 PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
623 if !!on_stack { ::core::panicking::panic("assertion failed: !on_stack") };assert!(!on_stack);
624 let i = apply(bx.cx, attrs);
625 let sret = llvm::CreateStructRetAttr(
626 bx.cx.llcx,
627 bx.cx.type_array(bx.cx.type_i8(), self.ret.layout.size.bytes()),
628 );
629 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
630 }
631 PassMode::Cast { cast, pad_i32: _ } => {
632 cast.attrs.apply_attrs_to_callsite(
633 llvm::AttributePlace::ReturnValue,
634 bx.cx,
635 callsite,
636 );
637 }
638 _ => {}
639 }
640 for arg in self.args.iter() {
641 match &arg.mode {
642 PassMode::Ignore => {}
643 PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
644 let i = apply(bx.cx, attrs);
645 let byval = llvm::CreateByValAttr(
646 bx.cx.llcx,
647 bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
648 );
649 attributes::apply_to_callsite(
650 callsite,
651 llvm::AttributePlace::Argument(i),
652 &[byval],
653 );
654 }
655 PassMode::Direct(attrs)
656 | PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
657 apply(bx.cx, attrs);
658 }
659 PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack: _ } => {
660 apply(bx.cx, attrs);
661 apply(bx.cx, meta_attrs);
662 }
663 PassMode::Pair(a, b) => {
664 apply(bx.cx, a);
665 apply(bx.cx, b);
666 }
667 PassMode::Cast { cast, pad_i32 } => {
668 if *pad_i32 {
669 apply(bx.cx, &ArgAttributes::new());
670 }
671 apply(bx.cx, &cast.attrs);
672 }
673 }
674 }
675
676 let cconv = self.llvm_cconv(&bx.cx);
677 if cconv != llvm::CCallConv {
678 llvm::SetInstructionCallConv(callsite, cconv);
679 }
680
681 if self.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
682 let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
685 attributes::apply_to_callsite(
686 callsite,
687 llvm::AttributePlace::Function,
688 &[cmse_nonsecure_call],
689 );
690 }
691
692 let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
695 if element_type_index >= 0 {
696 let arg_ty = self.args[element_type_index as usize].layout.ty;
697 let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument");
698 let element_type_attr = unsafe {
699 llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
700 };
701 attributes::apply_to_callsite(
702 callsite,
703 llvm::AttributePlace::Argument(element_type_index as u32),
704 &[element_type_attr],
705 );
706 }
707 }
708}
709
710impl AbiBuilderMethods for Builder<'_, '_, '_> {
711 fn get_param(&mut self, index: usize) -> Self::Value {
712 llvm::get_param(self.llfn(), index as c_uint)
713 }
714}
715
716pub(crate) fn to_llvm_calling_convention(sess: &Session, abi: CanonAbi) -> llvm::CallConv {
719 match abi {
720 CanonAbi::C | CanonAbi::Rust => llvm::CCallConv,
721 CanonAbi::RustCold => llvm::PreserveMost,
722 CanonAbi::RustPreserveNone => match &sess.target.arch {
723 Arch::X86_64 | Arch::AArch64 => llvm::PreserveNone,
724 _ => llvm::CCallConv,
725 },
726 CanonAbi::RustTail => match &sess.target.arch {
727 Arch::X86 | Arch::X86_64 | Arch::AArch64 => llvm::Tail,
728 _ => sess.dcx().fatal("extern \"tail\" is only supported on x86, x86_64 and aarch64"),
729 },
730 CanonAbi::Custom => llvm::CCallConv,
734 CanonAbi::Swift => llvm::SwiftCallConv,
735 CanonAbi::GpuKernel => match &sess.target.arch {
736 Arch::AmdGpu => llvm::AmdgpuKernel,
737 Arch::Nvptx64 => llvm::PtxKernel,
738 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"),
739 },
740 CanonAbi::Interrupt(interrupt_kind) => match interrupt_kind {
741 InterruptKind::Avr => llvm::AvrInterrupt,
742 InterruptKind::AvrNonBlocking => llvm::AvrNonBlockingInterrupt,
743 InterruptKind::Msp430 => llvm::Msp430Intr,
744 InterruptKind::RiscvMachine | InterruptKind::RiscvSupervisor => llvm::CCallConv,
745 InterruptKind::X86 => llvm::X86_Intr,
746 },
747 CanonAbi::Arm(arm_call) => match arm_call {
748 ArmCall::Aapcs => llvm::ArmAapcsCallConv,
749 ArmCall::CCmseNonSecureCall | ArmCall::CCmseNonSecureEntry => llvm::CCallConv,
750 },
751 CanonAbi::X86(x86_call) => match x86_call {
752 X86Call::Fastcall => llvm::X86FastcallCallConv,
753 X86Call::Stdcall => llvm::X86StdcallCallConv,
754 X86Call::SysV64 => llvm::X86_64_SysV,
755 X86Call::Thiscall => llvm::X86_ThisCall,
756 X86Call::Vectorcall => llvm::X86_VectorCall,
757 X86Call::Win64 => llvm::X86_64_Win64,
758 },
759 }
760}