1 use crate::builder::Builder;
2 use crate::context::CodegenCx;
3 use crate::llvm::{self, AttributePlace};
4 use crate::type_::Type;
5 use crate::type_of::LayoutLlvmExt;
6 use crate::value::Value;
8 use rustc_codegen_ssa::mir::operand::OperandValue;
9 use rustc_codegen_ssa::mir::place::PlaceRef;
10 use rustc_codegen_ssa::traits::*;
11 use rustc_codegen_ssa::MemFlags;
12 use rustc_middle::bug;
13 pub use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
14 use rustc_middle::ty::Ty;
15 use rustc_target::abi::call::ArgAbi;
16 pub use rustc_target::abi::call::*;
17 use rustc_target::abi::{self, HasDataLayout, Int, LayoutOf};
18 pub use rustc_target::spec::abi::Abi;
22 macro_rules! for_each_kind {
23 ($flags: ident, $f: ident, $($kind: ident),+) => ({
24 $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
28 trait ArgAttributeExt {
29 fn for_each_kind<F>(&self, f: F)
31 F: FnMut(llvm::Attribute);
34 impl ArgAttributeExt for ArgAttribute {
35 fn for_each_kind<F>(&self, mut f: F)
37 F: FnMut(llvm::Attribute),
39 for_each_kind!(self, f, NoAlias, NoCapture, NonNull, ReadOnly, InReg)
43 pub trait ArgAttributesExt {
44 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
45 fn apply_attrs_to_callsite(
48 cx: &CodegenCx<'_, '_>,
53 fn should_use_mutable_noalias(cx: &CodegenCx<'_, '_>) -> bool {
54 // Previously we would only emit noalias annotations for LLVM >= 6 or in
55 // panic=abort mode. That was deemed right, as prior versions had many bugs
56 // in conjunction with unwinding, but later versions didn’t seem to have
57 // said issues. See issue #31681.
59 // Alas, later on we encountered a case where noalias would generate wrong
60 // code altogether even with recent versions of LLVM in *safe* code with no
61 // unwinding involved. See #54462.
63 // For now, do not enable mutable_noalias by default at all, while the
64 // issue is being figured out.
65 cx.tcx.sess.opts.debugging_opts.mutable_noalias
68 impl ArgAttributesExt for ArgAttributes {
69 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
70 let mut regular = self.regular;
72 let deref = self.pointee_size.bytes();
74 if regular.contains(ArgAttribute::NonNull) {
75 llvm::LLVMRustAddDereferenceableAttr(llfn, idx.as_uint(), deref);
77 llvm::LLVMRustAddDereferenceableOrNullAttr(llfn, idx.as_uint(), deref);
79 regular -= ArgAttribute::NonNull;
81 if let Some(align) = self.pointee_align {
82 llvm::LLVMRustAddAlignmentAttr(llfn, idx.as_uint(), align.bytes() as u32);
84 regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
85 if regular.contains(ArgAttribute::NoAliasMutRef) && should_use_mutable_noalias(cx) {
86 llvm::Attribute::NoAlias.apply_llfn(idx, llfn);
89 ArgExtension::None => {}
90 ArgExtension::Zext => {
91 llvm::Attribute::ZExt.apply_llfn(idx, llfn);
93 ArgExtension::Sext => {
94 llvm::Attribute::SExt.apply_llfn(idx, llfn);
100 fn apply_attrs_to_callsite(
103 cx: &CodegenCx<'_, '_>,
106 let mut regular = self.regular;
108 let deref = self.pointee_size.bytes();
110 if regular.contains(ArgAttribute::NonNull) {
111 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite, idx.as_uint(), deref);
113 llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(
119 regular -= ArgAttribute::NonNull;
121 if let Some(align) = self.pointee_align {
122 llvm::LLVMRustAddAlignmentCallSiteAttr(
125 align.bytes() as u32,
128 regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
129 if regular.contains(ArgAttribute::NoAliasMutRef) && should_use_mutable_noalias(cx) {
130 llvm::Attribute::NoAlias.apply_callsite(idx, callsite);
133 ArgExtension::None => {}
134 ArgExtension::Zext => {
135 llvm::Attribute::ZExt.apply_callsite(idx, callsite);
137 ArgExtension::Sext => {
138 llvm::Attribute::SExt.apply_callsite(idx, callsite);
146 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
149 impl LlvmType for Reg {
150 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
152 RegKind::Integer => cx.type_ix(self.size.bits()),
153 RegKind::Float => match self.size.bits() {
156 _ => bug!("unsupported float: {:?}", self),
158 RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()),
163 impl LlvmType for CastTarget {
164 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
165 let rest_ll_unit = self.rest.unit.llvm_type(cx);
166 let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
170 self.rest.total.bytes() / self.rest.unit.size.bytes(),
171 self.rest.total.bytes() % self.rest.unit.size.bytes(),
175 if self.prefix.iter().all(|x| x.is_none()) {
176 // Simplify to a single unit when there is no prefix and size <= unit size
177 if self.rest.total <= self.rest.unit.size {
181 // Simplify to array when all chunks are the same size and type
183 return cx.type_array(rest_ll_unit, rest_count);
187 // Create list of fields in the main structure
188 let mut args: Vec<_> = self
191 .flat_map(|option_kind| {
192 option_kind.map(|kind| Reg { kind, size: self.prefix_chunk_size }.llvm_type(cx))
194 .chain((0..rest_count).map(|_| rest_ll_unit))
197 // Append final integer
199 // Only integers can be really split further.
200 assert_eq!(self.rest.unit.kind, RegKind::Integer);
201 args.push(cx.type_ix(rem_bytes * 8));
204 cx.type_struct(&args, false)
208 pub trait ArgAbiExt<'ll, 'tcx> {
209 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
212 bx: &mut Builder<'_, 'll, 'tcx>,
214 dst: PlaceRef<'tcx, &'ll Value>,
218 bx: &mut Builder<'_, 'll, 'tcx>,
220 dst: PlaceRef<'tcx, &'ll Value>,
224 impl ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
225 /// Gets the LLVM type for a place of the original Rust type of
226 /// this argument/return, i.e., the result of `type_of::type_of`.
227 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
228 self.layout.llvm_type(cx)
231 /// Stores a direct/indirect value described by this ArgAbi into a
232 /// place for the original Rust type of this argument/return.
233 /// Can be used for both storing formal arguments into Rust variables
234 /// or results of call/invoke instructions into their destinations.
237 bx: &mut Builder<'_, 'll, 'tcx>,
239 dst: PlaceRef<'tcx, &'ll Value>,
241 if self.is_ignore() {
244 if self.is_sized_indirect() {
245 OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
246 } else if self.is_unsized_indirect() {
247 bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
248 } else if let PassMode::Cast(cast) = self.mode {
249 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
250 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
251 let can_store_through_cast_ptr = false;
252 if can_store_through_cast_ptr {
253 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
254 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
255 bx.store(val, cast_dst, self.layout.align.abi);
257 // The actual return type is a struct, but the ABI
258 // adaptation code has cast it into some scalar type. The
259 // code that follows is the only reliable way I have
260 // found to do a transform like i64 -> {i32,i32}.
261 // Basically we dump the data onto the stack then memcpy it.
263 // Other approaches I tried:
264 // - Casting rust ret pointer to the foreign type and using Store
265 // is (a) unsafe if size of foreign type > size of rust type and
266 // (b) runs afoul of strict aliasing rules, yielding invalid
267 // assembly under -O (specifically, the store gets removed).
268 // - Truncating foreign type to correct integral type and then
269 // bitcasting to the struct type yields invalid cast errors.
271 // We instead thus allocate some scratch space...
272 let scratch_size = cast.size(bx);
273 let scratch_align = cast.align(bx);
274 let llscratch = bx.alloca(cast.llvm_type(bx), scratch_align);
275 bx.lifetime_start(llscratch, scratch_size);
277 // ... where we first store the value...
278 bx.store(val, llscratch, scratch_align);
280 // ... and then memcpy it to the intended destination.
283 self.layout.align.abi,
286 bx.const_usize(self.layout.size.bytes()),
290 bx.lifetime_end(llscratch, scratch_size);
293 OperandValue::Immediate(val).store(bx, dst);
299 bx: &mut Builder<'a, 'll, 'tcx>,
301 dst: PlaceRef<'tcx, &'ll Value>,
304 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
309 PassMode::Ignore => {}
310 PassMode::Pair(..) => {
311 OperandValue::Pair(next(), next()).store(bx, dst);
313 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
314 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
317 | PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ }
318 | PassMode::Cast(_) => {
319 let next_arg = next();
320 self.store(bx, next_arg, dst);
326 impl ArgAbiMethods<'tcx> for Builder<'a, 'll, 'tcx> {
329 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
331 dst: PlaceRef<'tcx, Self::Value>,
333 arg_abi.store_fn_arg(self, idx, dst)
337 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
339 dst: PlaceRef<'tcx, &'ll Value>,
341 arg_abi.store(self, val, dst)
343 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
344 arg_abi.memory_ty(self)
348 pub trait FnAbiLlvmExt<'tcx> {
349 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
350 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
351 fn llvm_cconv(&self) -> llvm::CallConv;
352 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
353 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
356 impl<'tcx> FnAbiLlvmExt<'tcx> for FnAbi<'tcx, Ty<'tcx>> {
357 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
358 let args_capacity: usize = self.args.iter().map(|arg|
359 if arg.pad.is_some() { 1 } else { 0 } +
360 if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
362 let mut llargument_tys = Vec::with_capacity(
363 if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 } + args_capacity,
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) => cast.llvm_type(cx),
370 PassMode::Indirect { .. } => {
371 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
376 for arg in &self.args {
378 if let Some(ty) = arg.pad {
379 llargument_tys.push(ty.llvm_type(cx));
382 let llarg_ty = match arg.mode {
383 PassMode::Ignore => continue,
384 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
385 PassMode::Pair(..) => {
386 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
387 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
390 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
391 let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
392 let ptr_layout = cx.layout_of(ptr_ty);
393 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
394 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
397 PassMode::Cast(cast) => cast.llvm_type(cx),
398 PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ } => {
399 cx.type_ptr_to(arg.memory_ty(cx))
402 llargument_tys.push(llarg_ty);
406 cx.type_variadic_func(&llargument_tys, llreturn_ty)
408 cx.type_func(&llargument_tys, llreturn_ty)
412 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
414 llvm::LLVMPointerType(
416 cx.data_layout().instruction_address_space.0 as c_uint,
421 fn llvm_cconv(&self) -> llvm::CallConv {
423 Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
424 Conv::AmdGpuKernel => llvm::AmdGpuKernel,
425 Conv::AvrInterrupt => llvm::AvrInterrupt,
426 Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
427 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
428 Conv::Msp430Intr => llvm::Msp430Intr,
429 Conv::PtxKernel => llvm::PtxKernel,
430 Conv::X86Fastcall => llvm::X86FastcallCallConv,
431 Conv::X86Intr => llvm::X86_Intr,
432 Conv::X86Stdcall => llvm::X86StdcallCallConv,
433 Conv::X86ThisCall => llvm::X86_ThisCall,
434 Conv::X86VectorCall => llvm::X86_VectorCall,
435 Conv::X86_64SysV => llvm::X86_64_SysV,
436 Conv::X86_64Win64 => llvm::X86_64_Win64,
440 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
441 // FIXME(eddyb) can this also be applied to callsites?
442 if self.ret.layout.abi.is_uninhabited() {
443 llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn);
446 // FIXME(eddyb, wesleywiser): apply this to callsites as well?
447 if !self.can_unwind {
448 llvm::Attribute::NoUnwind.apply_llfn(llvm::AttributePlace::Function, llfn);
452 let mut apply = |attrs: &ArgAttributes| {
453 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
457 match self.ret.mode {
458 PassMode::Direct(ref attrs) => {
459 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
461 PassMode::Indirect { ref attrs, extra_attrs: _, on_stack } => {
463 let i = apply(attrs);
465 llvm::LLVMRustAddStructRetAttr(
467 llvm::AttributePlace::Argument(i).as_uint(),
468 self.ret.layout.llvm_type(cx),
474 for arg in &self.args {
475 if arg.pad.is_some() {
476 apply(&ArgAttributes::new());
479 PassMode::Ignore => {}
480 PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: true } => {
481 let i = apply(attrs);
483 llvm::LLVMRustAddByValAttr(
485 llvm::AttributePlace::Argument(i).as_uint(),
486 arg.layout.llvm_type(cx),
490 PassMode::Direct(ref attrs)
491 | PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: false } => {
494 PassMode::Indirect { ref attrs, extra_attrs: Some(ref extra_attrs), on_stack } => {
499 PassMode::Pair(ref a, ref b) => {
503 PassMode::Cast(_) => {
504 apply(&ArgAttributes::new());
510 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
511 // FIXME(wesleywiser, eddyb): We should apply `nounwind` and `noreturn` as appropriate to this callsite.
514 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
515 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
519 match self.ret.mode {
520 PassMode::Direct(ref attrs) => {
521 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, &bx.cx, callsite);
523 PassMode::Indirect { ref attrs, extra_attrs: _, on_stack } => {
525 let i = apply(bx.cx, attrs);
527 llvm::LLVMRustAddStructRetCallSiteAttr(
529 llvm::AttributePlace::Argument(i).as_uint(),
530 self.ret.layout.llvm_type(bx),
536 if let abi::Abi::Scalar(ref scalar) = self.ret.layout.abi {
537 // If the value is a boolean, the range is 0..2 and that ultimately
538 // become 0..0 when the type becomes i1, which would be rejected
539 // by the LLVM verifier.
540 if let Int(..) = scalar.value {
541 if !scalar.is_bool() {
542 let range = scalar.valid_range_exclusive(bx);
543 if range.start != range.end {
544 bx.range_metadata(callsite, range);
549 for arg in &self.args {
550 if arg.pad.is_some() {
551 apply(bx.cx, &ArgAttributes::new());
554 PassMode::Ignore => {}
555 PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: true } => {
556 let i = apply(bx.cx, attrs);
558 llvm::LLVMRustAddByValCallSiteAttr(
560 llvm::AttributePlace::Argument(i).as_uint(),
561 arg.layout.llvm_type(bx),
565 PassMode::Direct(ref attrs)
566 | PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: false } => {
571 extra_attrs: Some(ref extra_attrs),
575 apply(bx.cx, extra_attrs);
577 PassMode::Pair(ref a, ref b) => {
581 PassMode::Cast(_) => {
582 apply(bx.cx, &ArgAttributes::new());
587 let cconv = self.llvm_cconv();
588 if cconv != llvm::CCallConv {
589 llvm::SetInstructionCallConv(callsite, cconv);
592 if self.conv == Conv::CCmseNonSecureCall {
593 // This will probably get ignored on all targets but those supporting the TrustZone-M
594 // extension (thumbv8m targets).
596 llvm::AddCallSiteAttrString(
598 llvm::AttributePlace::Function,
599 cstr::cstr!("cmse_nonsecure_call"),
606 impl AbiBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
607 fn apply_attrs_callsite(&mut self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, callsite: Self::Value) {
608 fn_abi.apply_attrs_callsite(self, callsite)
611 fn get_param(&self, index: usize) -> Self::Value {
612 llvm::get_param(self.llfn(), index as c_uint)