1use std::cmp;
2
3use libc::c_uint;
4use rustc_abi::{
5 ArmCall, BackendRepr, CanonAbi, Float, HasDataLayout, Integer, InterruptKind, Primitive, Reg,
6 RegKind, Size, X86Call,
7};
8use rustc_codegen_ssa::MemFlags;
9use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
10use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
11use rustc_codegen_ssa::traits::*;
12use rustc_middle::ty;
13use rustc_middle::ty::Ty;
14use rustc_middle::ty::layout::LayoutOf;
15use rustc_session::{Session, config};
16use rustc_span::bug;
17use rustc_target::callconv::{
18 ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, CastTarget, FnAbi, IndirectMode, PassMode,
19};
20use rustc_target::spec::{Arch, SanitizerSet};
21use smallvec::SmallVec;
22
23use crate::attributes::{self, llfn_attrs_from_instance};
24use crate::builder::Builder;
25use crate::context::CodegenCx;
26use crate::llvm::{self, Attribute, AttributePlace, Type, Value};
27use crate::type_of::LayoutLlvmExt;
28
29trait ArgAttributesExt {
30 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
31 fn apply_attrs_to_callsite(
32 &self,
33 idx: AttributePlace,
34 cx: &CodegenCx<'_, '_>,
35 callsite: &Value,
36 );
37}
38
39const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
40 [(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
41
42const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 6] = [
43 (ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
44 (ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
45 (ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
46 (ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
47 (ArgAttribute::Writable, llvm::AttributeKind::Writable),
48 (ArgAttribute::NoFree, llvm::AttributeKind::NoFree),
52];
53
54const CAPTURES_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 3] = [
55 (ArgAttribute::CapturesNone, llvm::AttributeKind::CapturesNone),
56 (ArgAttribute::CapturesAddress, llvm::AttributeKind::CapturesAddress),
57 (ArgAttribute::CapturesReadOnly, llvm::AttributeKind::CapturesReadOnly),
58];
59
60fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 8]> {
61 let mut regular = this.regular;
62
63 let mut attrs = SmallVec::new();
64
65 for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
67 if regular.contains(attr) {
68 attrs.push(llattr.create_attr(cx.llcx));
69 }
70 }
71 if let Some(align) = this.pointee_align {
72 attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
73 }
74 match this.arg_ext {
75 ArgExtension::None => {}
76 ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
77 ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
78 }
79
80 if cx.sess().opts.optimize != config::OptLevel::No {
82 let deref = this.pointee_size.bytes();
83 let llvm_version = crate::llvm_util::get_version();
87 if deref != 0 && (llvm_version >= (23, 0, 0) || regular.contains(ArgAttribute::NoFree)) {
88 if regular.contains(ArgAttribute::NonNull) {
89 attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
90 } else {
91 attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
92 }
93 regular -= ArgAttribute::NonNull;
94 }
95 for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
96 if regular.contains(attr) {
97 attrs.push(llattr.create_attr(cx.llcx));
98 }
99 }
100 for (attr, llattr) in CAPTURES_ATTRIBUTES {
101 if regular.contains(attr) {
102 attrs.push(llattr.create_attr(cx.llcx));
103 break;
104 }
105 }
106 } else if cx.tcx.sess.sanitizers().contains(SanitizerSet::MEMORY) {
107 if regular.contains(ArgAttribute::NoUndef) {
111 attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
112 }
113 }
114
115 attrs
116}
117
118impl ArgAttributesExt for ArgAttributes {
119 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
120 let attrs = get_attrs(self, cx);
121 attributes::apply_to_llfn(llfn, idx, &attrs);
122 }
123
124 fn apply_attrs_to_callsite(
125 &self,
126 idx: AttributePlace,
127 cx: &CodegenCx<'_, '_>,
128 callsite: &Value,
129 ) {
130 let attrs = get_attrs(self, cx);
131 attributes::apply_to_callsite(callsite, idx, &attrs);
132 }
133}
134
135pub(crate) trait LlvmType {
136 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
137}
138
139impl LlvmType for Reg {
140 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
141 match self.kind {
142 RegKind::Integer => cx.type_ix(self.size.bits()),
143 RegKind::Float => match self.size.bits() {
144 16 => cx.type_f16(),
145 32 => cx.type_f32(),
146 64 => cx.type_f64(),
147 128 => cx.type_f128(),
148 _ => ::rustc_span::macros::bug_impl(None,
format_args!("unsupported float: {0:?}", self), Location::caller())bug!("unsupported float: {:?}", self),
149 },
150 RegKind::Vector { hint_vector_elem } => {
151 let ty = match hint_vector_elem {
155 Primitive::Int(integer, _) => match integer {
156 Integer::I8 => cx.type_ix(8),
157 Integer::I16 => cx.type_ix(16),
158 Integer::I32 => cx.type_ix(32),
159 Integer::I64 => cx.type_ix(64),
160 Integer::I128 => cx.type_ix(128),
161 },
162 Primitive::Float(float) => match float {
163 Float::F16 => cx.type_f16(),
164 Float::F16B => cx.type_f16b(),
165 Float::F32 => cx.type_f32(),
166 Float::F64 => cx.type_f64(),
167 Float::F128 => cx.type_f128(),
168 },
169 Primitive::Pointer(_) => cx.type_ptr(),
170 };
171
172 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()));
173 let len = self.size.bytes() / hint_vector_elem.size(cx).bytes();
174 cx.type_vector(ty, len)
175 }
176 }
177 }
178}
179
180impl LlvmType for CastTarget {
181 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
182 let rest_ll_unit = self.rest.unit.llvm_type(cx);
183 let rest_count = if self.rest.total == Size::ZERO {
184 0
185 } else {
186 {
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!(
187 self.rest.unit.size,
188 Size::ZERO,
189 "total size {:?} cannot be divided into units of zero size",
190 self.rest.total
191 );
192 if !self.rest.total.bytes().is_multiple_of(self.rest.unit.size.bytes()) {
193 {
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");
194 }
195 self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes())
196 };
197
198 if self.prefix.is_empty() {
201 if rest_count == 1 && (!self.rest.is_consecutive || self.rest.unit != Reg::i128()) {
205 return rest_ll_unit;
206 }
207
208 return cx.type_array(rest_ll_unit, rest_count);
209 }
210
211 let prefix_args = self.prefix.iter().map(|reg| reg.llvm_type(cx));
213 let rest_args = (0..rest_count).map(|_| rest_ll_unit);
214 let args: Vec<_> = prefix_args.chain(rest_args).collect();
215 cx.type_struct(&args, false)
216 }
217}
218
219trait ArgAbiExt<'ll, 'tcx> {
220 fn store(
221 &self,
222 bx: &mut Builder<'_, 'll, 'tcx>,
223 val: &'ll Value,
224 dst: PlaceRef<'tcx, &'ll Value>,
225 );
226 fn store_fn_arg(
227 &self,
228 bx: &mut Builder<'_, 'll, 'tcx>,
229 idx: &mut usize,
230 dst: PlaceRef<'tcx, &'ll Value>,
231 );
232}
233
234impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
235 fn store(
240 &self,
241 bx: &mut Builder<'_, 'll, 'tcx>,
242 val: &'ll Value,
243 dst: PlaceRef<'tcx, &'ll Value>,
244 ) {
245 match &self.mode {
246 PassMode::Ignore => {}
247 PassMode::Indirect { attrs, meta_attrs: None, address_space: _, mode: _ } => {
249 let align = attrs.pointee_align.unwrap_or(self.layout.align.abi);
250 OperandValue::Ref(PlaceValue::new_sized(val, align)).store(bx, dst);
251 }
252 PassMode::Indirect { attrs: _, meta_attrs: Some(_), address_space: _, mode: _ } => {
254 ::rustc_span::macros::bug_impl(None,
format_args!("unsized `ArgAbi` cannot be stored"), Location::caller());bug!("unsized `ArgAbi` cannot be stored");
255 }
256 PassMode::Cast { cast, pad_i32_count: _ } => {
257 let scratch_size = cast.size(bx);
261 let scratch_align = cast.align(bx);
262 let copy_bytes =
269 cmp::min(cast.unaligned_size(bx).bytes(), self.layout.size.bytes());
270 let llscratch = bx.alloca(scratch_size, scratch_align);
272 bx.lifetime_start(llscratch, scratch_size);
273 rustc_codegen_ssa::mir::store_cast(bx, cast, val, llscratch, scratch_align);
275 bx.memcpy(
277 dst.val.llval,
278 self.layout.align.abi,
279 llscratch,
280 scratch_align,
281 bx.const_usize(copy_bytes),
282 MemFlags::empty(),
283 None,
284 );
285 bx.lifetime_end(llscratch, scratch_size);
286 }
287 PassMode::Pair(..) | PassMode::Direct { .. } => {
288 OperandRef::from_immediate_or_packed_pair(bx, val, self.layout).val.store(bx, dst);
289 }
290 }
291 }
292
293 fn store_fn_arg(
294 &self,
295 bx: &mut Builder<'_, 'll, 'tcx>,
296 idx: &mut usize,
297 dst: PlaceRef<'tcx, &'ll Value>,
298 ) {
299 let mut next = || {
300 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
301 *idx += 1;
302 val
303 };
304 match self.mode {
305 PassMode::Ignore => {}
306 PassMode::Pair(..) => {
307 OperandValue::Pair(next(), next()).store(bx, dst);
308 }
309 PassMode::Indirect { attrs: _, meta_attrs: Some(_), address_space: _, mode: _ } => {
310 ::rustc_span::macros::bug_impl(None,
format_args!("unsized `ArgAbi` cannot be stored"), Location::caller());bug!("unsized `ArgAbi` cannot be stored");
311 }
312 PassMode::Direct(_)
313 | PassMode::Indirect { attrs: _, meta_attrs: None, address_space: _, mode: _ }
314 | PassMode::Cast { .. } => {
315 let next_arg = next();
316 self.store(bx, next_arg, dst);
317 }
318 }
319 }
320}
321
322impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
323 fn store_fn_arg(
324 &mut self,
325 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
326 idx: &mut usize,
327 dst: PlaceRef<'tcx, Self::Value>,
328 ) {
329 arg_abi.store_fn_arg(self, idx, dst)
330 }
331 fn store_arg(
332 &mut self,
333 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
334 val: &'ll Value,
335 dst: PlaceRef<'tcx, &'ll Value>,
336 ) {
337 arg_abi.store(self, val, dst)
338 }
339}
340
341pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
342 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
343 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
344 fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv;
345
346 fn apply_attrs_llfn(
348 &self,
349 cx: &CodegenCx<'ll, 'tcx>,
350 llfn: &'ll Value,
351 instance: Option<ty::Instance<'tcx>>,
352 );
353
354 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
356}
357
358impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
359 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
360 let args =
363 if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
364
365 let mut llargument_tys = Vec::with_capacity(
367 self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
368 );
369
370 let llreturn_ty = match &self.ret.mode {
371 PassMode::Ignore => cx.type_void(),
372 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
373 PassMode::Cast { cast, pad_i32_count: _ } => cast.llvm_type(cx),
374 PassMode::Indirect { address_space, .. } => {
375 let ty = if let Some(address_space) = address_space {
376 cx.type_ptr_ext(*address_space)
377 } else {
378 cx.type_ptr()
379 };
380 llargument_tys.push(ty);
381 cx.type_void()
382 }
383 };
384
385 for arg in args {
386 let llarg_ty = match &arg.mode {
390 PassMode::Ignore => continue,
391 PassMode::Direct(_) => {
392 arg.layout.immediate_llvm_type(cx)
396 }
397 PassMode::Pair(..) => {
398 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
402 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
403 continue;
404 }
405 PassMode::Indirect { attrs: _, meta_attrs: Some(_), address_space: _, mode: _ } => {
406 let ptr_ty = Ty::new_mut_ptr(cx.tcx, arg.layout.ty);
411 let ptr_layout = cx.layout_of(ptr_ty);
412 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
413 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
414 continue;
415 }
416 PassMode::Indirect { attrs: _, meta_attrs: None, address_space, mode: _ } => {
417 if let Some(address_space) = address_space {
418 cx.type_ptr_ext(*address_space)
419 } else {
420 cx.type_ptr()
421 }
422 }
423 PassMode::Cast { cast, pad_i32_count } => {
424 llargument_tys.extend(std::iter::repeat_n(
426 Reg::i32().llvm_type(cx),
427 usize::from(*pad_i32_count),
428 ));
429
430 cast.llvm_type(cx)
433 }
434 };
435 llargument_tys.push(llarg_ty);
436 }
437
438 if self.c_variadic {
439 cx.type_variadic_func(&llargument_tys, llreturn_ty)
440 } else {
441 cx.type_func(&llargument_tys, llreturn_ty)
442 }
443 }
444
445 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
446 cx.type_ptr_ext(cx.data_layout().instruction_address_space)
447 }
448
449 fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv {
450 to_llvm_calling_convention(cx.tcx.sess, self.conv)
451 }
452
453 fn apply_attrs_llfn(
454 &self,
455 cx: &CodegenCx<'ll, 'tcx>,
456 llfn: &'ll Value,
457 instance: Option<ty::Instance<'tcx>>,
458 ) {
459 let mut func_attrs = SmallVec::<[_; 3]>::new();
460 if self.ret.layout.is_uninhabited() {
461 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
462 }
463 if !self.can_unwind {
464 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
465 }
466 match self.conv {
467 CanonAbi::Interrupt(InterruptKind::RiscvMachine) => {
468 func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "machine"))
469 }
470 CanonAbi::Interrupt(InterruptKind::RiscvSupervisor) => {
471 func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "supervisor"))
472 }
473 CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) => {
474 func_attrs.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"))
475 }
476 _ => (),
477 }
478 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
479
480 let mut i = 0;
481 let mut apply = |attrs: &ArgAttributes| {
482 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
483 i += 1;
484 i - 1
485 };
486
487 let apply_range_attr = |idx: AttributePlace, scalar: rustc_abi::Scalar| {
488 if cx.sess().opts.optimize != config::OptLevel::No
489 && #[allow(non_exhaustive_omitted_patterns)] match scalar.primitive() {
Primitive::Int(..) => true,
_ => false,
}matches!(scalar.primitive(), Primitive::Int(..))
490 && !scalar.is_bool()
494 && !scalar.is_always_valid(cx)
496 {
497 attributes::apply_to_llfn(
498 llfn,
499 idx,
500 &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
501 );
502 }
503 };
504
505 match &self.ret.mode {
506 PassMode::Direct(attrs) => {
507 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
508 if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
509 apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
510 }
511 }
512 PassMode::Indirect { attrs, meta_attrs: _, address_space: _, mode } => {
513 if !(*mode == IndirectMode::Pointer) {
::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
514 let i = apply(attrs);
515 let sret = llvm::CreateStructRetAttr(
516 cx.llcx,
517 cx.type_array(cx.type_i8(), self.ret.layout.size.bytes()),
518 );
519 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
520 if cx.sess().opts.optimize != config::OptLevel::No {
521 attributes::apply_to_llfn(
522 llfn,
523 llvm::AttributePlace::Argument(i),
524 &[
525 llvm::AttributeKind::Writable.create_attr(cx.llcx),
526 llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx),
527 ],
528 );
529 }
530 }
531 PassMode::Cast { cast, pad_i32_count: _ } => {
532 cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
533 }
534 _ => {}
535 }
536 for arg in self.args.iter() {
537 match &arg.mode {
538 PassMode::Ignore => {}
539 PassMode::Indirect {
540 attrs,
541 meta_attrs: None,
542 address_space: _,
543 mode: IndirectMode::OnStack,
544 } => {
545 let i = apply(attrs);
546 let byval = llvm::CreateByValAttr(
547 cx.llcx,
548 cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
549 );
550 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
551 }
552 PassMode::Indirect {
553 attrs,
554 meta_attrs: None,
555 address_space: _,
556 mode: IndirectMode::AmdgpuKernelArg,
557 } => {
558 let i = apply(attrs);
559 let byref = llvm::CreateByRefAttr(
560 cx.llcx,
561 cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
562 );
563 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byref]);
564 }
565 PassMode::Direct(attrs) => {
566 let i = apply(attrs);
567 if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
568 apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
569 }
570 }
571 PassMode::Indirect {
572 attrs,
573 meta_attrs: None,
574 address_space: _,
575 mode: IndirectMode::Pointer,
576 } => {
577 let i = apply(attrs);
578 if cx.sess().opts.optimize != config::OptLevel::No {
579 attributes::apply_to_llfn(
580 llfn,
581 llvm::AttributePlace::Argument(i),
582 &[llvm::AttributeKind::DeadOnReturn.create_attr(cx.llcx)],
583 );
584 }
585 }
586 PassMode::Indirect {
587 attrs,
588 meta_attrs: Some(meta_attrs),
589 address_space: _,
590 mode,
591 } => {
592 if !(*mode == IndirectMode::Pointer) {
::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
593 apply(attrs);
594 apply(meta_attrs);
595 }
596 PassMode::Pair(a, b) => {
597 let i = apply(a);
598 let ii = apply(b);
599 if let BackendRepr::ScalarPair { a: scalar_a, b: scalar_b, b_offset: _ } =
600 arg.layout.backend_repr
601 {
602 apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
603 let primitive_b = scalar_b.primitive();
604 let scalar_b = if let rustc_abi::Primitive::Int(int, false) = primitive_b
605 && let ty::Ref(_, pointee_ty, _) = *arg.layout.ty.kind()
606 && let ty::Slice(element_ty) = *pointee_ty.kind()
607 && let elem_size = cx.layout_of(element_ty).size
608 && elem_size != rustc_abi::Size::ZERO
609 {
610 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));
614 let isize_max = int.signed_max() as u64;
615 rustc_abi::Scalar::Initialized {
616 value: primitive_b,
617 valid_range: rustc_abi::WrappingRange {
618 start: 0,
619 end: u128::from(isize_max / elem_size.bytes()),
620 },
621 }
622 } else {
623 scalar_b
624 };
625 apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
626 }
627 }
628 PassMode::Cast { cast, pad_i32_count } => {
629 for _ in 0..*pad_i32_count {
630 apply(&ArgAttributes::new());
631 }
632 apply(&cast.attrs);
633 }
634 }
635 }
636
637 if let Some(instance) = instance {
639 llfn_attrs_from_instance(
640 cx,
641 cx.tcx,
642 llfn,
643 &cx.tcx.codegen_instance_attrs(instance.def),
644 Some(instance),
645 cx.sanitizer_ignorelist.as_ref(),
646 );
647 }
648 }
649
650 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
651 let mut func_attrs = SmallVec::<[_; 2]>::new();
652 if self.ret.layout.is_uninhabited() {
653 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
654 }
655 if !self.can_unwind {
656 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
657 }
658 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
659
660 let mut i = 0;
661 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
662 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
663 i += 1;
664 i - 1
665 };
666 match &self.ret.mode {
667 PassMode::Direct(attrs) => {
668 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
669 }
670 PassMode::Indirect { attrs, meta_attrs: _, address_space: _, mode } => {
671 if !(*mode == IndirectMode::Pointer) {
::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
672 let i = apply(bx.cx, attrs);
673 let sret = llvm::CreateStructRetAttr(
674 bx.cx.llcx,
675 bx.cx.type_array(bx.cx.type_i8(), self.ret.layout.size.bytes()),
676 );
677 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
678 }
679 PassMode::Cast { cast, pad_i32_count: _ } => {
680 cast.attrs.apply_attrs_to_callsite(
681 llvm::AttributePlace::ReturnValue,
682 bx.cx,
683 callsite,
684 );
685 }
686 _ => {}
687 }
688 for arg in self.args.iter() {
689 match &arg.mode {
690 PassMode::Ignore => {}
691 PassMode::Indirect {
692 attrs,
693 meta_attrs: None,
694 address_space: _,
695 mode: IndirectMode::OnStack,
696 } => {
697 let i = apply(bx.cx, attrs);
698 let byval = llvm::CreateByValAttr(
699 bx.cx.llcx,
700 bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
701 );
702 attributes::apply_to_callsite(
703 callsite,
704 llvm::AttributePlace::Argument(i),
705 &[byval],
706 );
707 }
708 PassMode::Indirect {
709 attrs,
710 meta_attrs: None,
711 address_space: _,
712 mode: IndirectMode::AmdgpuKernelArg,
713 } => {
714 let i = apply(bx.cx, attrs);
715 let byref = llvm::CreateByRefAttr(
716 bx.cx.llcx,
717 bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
718 );
719 attributes::apply_to_callsite(
720 callsite,
721 llvm::AttributePlace::Argument(i),
722 &[byref],
723 );
724 }
725 PassMode::Direct(attrs)
726 | PassMode::Indirect {
727 attrs,
728 meta_attrs: None,
729 address_space: _,
730 mode: IndirectMode::Pointer,
731 } => {
732 apply(bx.cx, attrs);
733 }
734 PassMode::Indirect {
735 attrs,
736 meta_attrs: Some(meta_attrs),
737 address_space: _,
738 mode: _,
739 } => {
740 apply(bx.cx, attrs);
741 apply(bx.cx, meta_attrs);
742 }
743 PassMode::Pair(a, b) => {
744 apply(bx.cx, a);
745 apply(bx.cx, b);
746 }
747 PassMode::Cast { cast, pad_i32_count } => {
748 for _ in 0..*pad_i32_count {
749 apply(bx.cx, &ArgAttributes::new());
750 }
751 apply(bx.cx, &cast.attrs);
752 }
753 }
754 }
755
756 let cconv = self.llvm_cconv(&bx.cx);
757 if cconv != llvm::CCallConv {
758 llvm::SetInstructionCallConv(callsite, cconv);
759 }
760
761 if self.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
762 let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
765 attributes::apply_to_callsite(
766 callsite,
767 llvm::AttributePlace::Function,
768 &[cmse_nonsecure_call],
769 );
770 }
771
772 let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
775 if element_type_index >= 0 {
776 let arg_ty = self.args[element_type_index as usize].layout.ty;
777 let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument");
778 let element_type_attr = unsafe {
779 llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
780 };
781 attributes::apply_to_callsite(
782 callsite,
783 llvm::AttributePlace::Argument(element_type_index as u32),
784 &[element_type_attr],
785 );
786 }
787 }
788}
789
790impl AbiBuilderMethods for Builder<'_, '_, '_> {
791 fn get_param(&mut self, index: usize) -> Self::Value {
792 llvm::get_param(self.llfn(), index as c_uint)
793 }
794}
795
796pub(crate) fn to_llvm_calling_convention(sess: &Session, abi: CanonAbi) -> llvm::CallConv {
799 match abi {
800 CanonAbi::C | CanonAbi::Rust => llvm::CCallConv,
801 CanonAbi::RustCold => llvm::PreserveMost,
802 CanonAbi::RustPreserveNone => match &sess.target.arch {
803 Arch::X86_64 | Arch::AArch64 => llvm::PreserveNone,
804 _ => llvm::CCallConv,
805 },
806 CanonAbi::RustTail => match &sess.target.arch {
807 Arch::X86 | Arch::X86_64 | Arch::AArch64 => llvm::Tail,
808 _ => sess.dcx().fatal("extern \"tail\" is only supported on x86, x86_64 and aarch64"),
809 },
810 CanonAbi::Custom => llvm::CCallConv,
814 CanonAbi::Swift => llvm::SwiftCallConv,
815 CanonAbi::GpuKernel => match &sess.target.arch {
816 Arch::AmdGpu => llvm::AmdgpuKernel,
817 Arch::Nvptx64 => llvm::PtxKernel,
818 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"),
819 },
820 CanonAbi::Interrupt(interrupt_kind) => match interrupt_kind {
821 InterruptKind::Avr => llvm::AvrInterrupt,
822 InterruptKind::AvrNonBlocking => llvm::AvrNonBlockingInterrupt,
823 InterruptKind::Msp430 => llvm::Msp430Intr,
824 InterruptKind::RiscvMachine | InterruptKind::RiscvSupervisor => llvm::CCallConv,
825 InterruptKind::X86 => llvm::X86_Intr,
826 },
827 CanonAbi::Arm(arm_call) => match arm_call {
828 ArmCall::Aapcs => llvm::ArmAapcsCallConv,
829 ArmCall::CCmseNonSecureCall | ArmCall::CCmseNonSecureEntry => llvm::CCallConv,
830 },
831 CanonAbi::X86(x86_call) => match x86_call {
832 X86Call::Fastcall => llvm::X86FastcallCallConv,
833 X86Call::Stdcall => llvm::X86StdcallCallConv,
834 X86Call::SysV64 => llvm::X86_64_SysV,
835 X86Call::Thiscall => llvm::X86_ThisCall,
836 X86Call::Vectorcall => llvm::X86_VectorCall,
837 X86Call::Win64 => llvm::X86_64_Win64,
838 },
839 }
840}