2 use crate::builder::Builder;
3 use crate::context::CodegenCx;
4 use crate::llvm::{self, Attribute, AttributePlace};
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
9 use rustc_codegen_ssa::mir::operand::OperandValue;
10 use rustc_codegen_ssa::mir::place::PlaceRef;
11 use rustc_codegen_ssa::traits::*;
12 use rustc_codegen_ssa::MemFlags;
13 use rustc_middle::bug;
14 use rustc_middle::ty::layout::LayoutOf;
15 pub use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
16 use rustc_middle::ty::Ty;
17 use rustc_session::config;
18 use rustc_target::abi::call::ArgAbi;
19 pub use rustc_target::abi::call::*;
20 use rustc_target::abi::{self, HasDataLayout, Int};
21 pub use rustc_target::spec::abi::Abi;
22 use rustc_target::spec::SanitizerSet;
25 use smallvec::SmallVec;
27 pub trait ArgAttributesExt {
28 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
29 fn apply_attrs_to_callsite(
32 cx: &CodegenCx<'_, '_>,
37 fn should_use_mutable_noalias(cx: &CodegenCx<'_, '_>) -> bool {
38 // LLVM prior to version 12 had known miscompiles in the presence of
39 // noalias attributes (see #54878), but we don't support earlier
40 // versions at all anymore. We now enable mutable noalias by default.
41 cx.tcx.sess.opts.unstable_opts.mutable_noalias.unwrap_or(true)
44 const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
45 [(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
47 const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 5] = [
48 (ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
49 (ArgAttribute::NoCapture, llvm::AttributeKind::NoCapture),
50 (ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
51 (ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
52 (ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
55 fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 8]> {
56 let mut regular = this.regular;
58 let mut attrs = SmallVec::new();
60 // ABI-affecting attributes must always be applied
61 for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
62 if regular.contains(attr) {
63 attrs.push(llattr.create_attr(cx.llcx));
66 if let Some(align) = this.pointee_align {
67 attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
70 ArgExtension::None => {}
71 ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
72 ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
75 // Only apply remaining attributes when optimizing
76 if cx.sess().opts.optimize != config::OptLevel::No {
77 let deref = this.pointee_size.bytes();
79 if regular.contains(ArgAttribute::NonNull) {
80 attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
82 attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
84 regular -= ArgAttribute::NonNull;
86 for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
87 if regular.contains(attr) {
88 attrs.push(llattr.create_attr(cx.llcx));
91 if regular.contains(ArgAttribute::NoAliasMutRef) && should_use_mutable_noalias(cx) {
92 attrs.push(llvm::AttributeKind::NoAlias.create_attr(cx.llcx));
94 } else if cx.tcx.sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::MEMORY) {
95 // If we're not optimising, *but* memory sanitizer is on, emit noundef, since it affects
96 // memory sanitizer's behavior.
98 if regular.contains(ArgAttribute::NoUndef) {
99 attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
106 impl ArgAttributesExt for ArgAttributes {
107 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
108 let attrs = get_attrs(self, cx);
109 attributes::apply_to_llfn(llfn, idx, &attrs);
112 fn apply_attrs_to_callsite(
115 cx: &CodegenCx<'_, '_>,
118 let attrs = get_attrs(self, cx);
119 attributes::apply_to_callsite(callsite, idx, &attrs);
124 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
127 impl LlvmType for Reg {
128 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
130 RegKind::Integer => cx.type_ix(self.size.bits()),
131 RegKind::Float => match self.size.bits() {
134 _ => bug!("unsupported float: {:?}", self),
136 RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()),
141 impl LlvmType for CastTarget {
142 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
143 let rest_ll_unit = self.rest.unit.llvm_type(cx);
144 let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
148 self.rest.total.bytes() / self.rest.unit.size.bytes(),
149 self.rest.total.bytes() % self.rest.unit.size.bytes(),
153 if self.prefix.iter().all(|x| x.is_none()) {
154 // Simplify to a single unit when there is no prefix and size <= unit size
155 if self.rest.total <= self.rest.unit.size {
159 // Simplify to array when all chunks are the same size and type
161 return cx.type_array(rest_ll_unit, rest_count);
165 // Create list of fields in the main structure
166 let mut args: Vec<_> = self
169 .flat_map(|option_reg| option_reg.map(|reg| reg.llvm_type(cx)))
170 .chain((0..rest_count).map(|_| rest_ll_unit))
173 // Append final integer
175 // Only integers can be really split further.
176 assert_eq!(self.rest.unit.kind, RegKind::Integer);
177 args.push(cx.type_ix(rem_bytes * 8));
180 cx.type_struct(&args, false)
184 pub trait ArgAbiExt<'ll, 'tcx> {
185 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
188 bx: &mut Builder<'_, 'll, 'tcx>,
190 dst: PlaceRef<'tcx, &'ll Value>,
194 bx: &mut Builder<'_, 'll, 'tcx>,
196 dst: PlaceRef<'tcx, &'ll Value>,
200 impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
201 /// Gets the LLVM type for a place of the original Rust type of
202 /// this argument/return, i.e., the result of `type_of::type_of`.
203 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
204 self.layout.llvm_type(cx)
207 /// Stores a direct/indirect value described by this ArgAbi into a
208 /// place for the original Rust type of this argument/return.
209 /// Can be used for both storing formal arguments into Rust variables
210 /// or results of call/invoke instructions into their destinations.
213 bx: &mut Builder<'_, 'll, 'tcx>,
215 dst: PlaceRef<'tcx, &'ll Value>,
217 if self.is_ignore() {
220 if self.is_sized_indirect() {
221 OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
222 } else if self.is_unsized_indirect() {
223 bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
224 } else if let PassMode::Cast(cast, _) = &self.mode {
225 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
226 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
227 let can_store_through_cast_ptr = false;
228 if can_store_through_cast_ptr {
229 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
230 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
231 bx.store(val, cast_dst, self.layout.align.abi);
233 // The actual return type is a struct, but the ABI
234 // adaptation code has cast it into some scalar type. The
235 // code that follows is the only reliable way I have
236 // found to do a transform like i64 -> {i32,i32}.
237 // Basically we dump the data onto the stack then memcpy it.
239 // Other approaches I tried:
240 // - Casting rust ret pointer to the foreign type and using Store
241 // is (a) unsafe if size of foreign type > size of rust type and
242 // (b) runs afoul of strict aliasing rules, yielding invalid
243 // assembly under -O (specifically, the store gets removed).
244 // - Truncating foreign type to correct integral type and then
245 // bitcasting to the struct type yields invalid cast errors.
247 // We instead thus allocate some scratch space...
248 let scratch_size = cast.size(bx);
249 let scratch_align = cast.align(bx);
250 let llscratch = bx.alloca(cast.llvm_type(bx), scratch_align);
251 bx.lifetime_start(llscratch, scratch_size);
253 // ... where we first store the value...
254 bx.store(val, llscratch, scratch_align);
256 // ... and then memcpy it to the intended destination.
259 self.layout.align.abi,
262 bx.const_usize(self.layout.size.bytes()),
266 bx.lifetime_end(llscratch, scratch_size);
269 OperandValue::Immediate(val).store(bx, dst);
275 bx: &mut Builder<'_, 'll, 'tcx>,
277 dst: PlaceRef<'tcx, &'ll Value>,
280 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
285 PassMode::Ignore => {}
286 PassMode::Pair(..) => {
287 OperandValue::Pair(next(), next()).store(bx, dst);
289 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
290 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
293 | PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ }
294 | PassMode::Cast(..) => {
295 let next_arg = next();
296 self.store(bx, next_arg, dst);
302 impl<'ll, 'tcx> ArgAbiMethods<'tcx> for Builder<'_, 'll, 'tcx> {
305 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
307 dst: PlaceRef<'tcx, Self::Value>,
309 arg_abi.store_fn_arg(self, idx, dst)
313 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
315 dst: PlaceRef<'tcx, &'ll Value>,
317 arg_abi.store(self, val, dst)
319 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
320 arg_abi.memory_ty(self)
324 pub trait FnAbiLlvmExt<'ll, 'tcx> {
325 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
326 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
327 fn llvm_cconv(&self) -> llvm::CallConv;
328 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
329 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
332 impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
333 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
334 // Ignore "extra" args from the call site for C variadic functions.
335 // Only the "fixed" args are part of the LLVM function signature.
337 if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
339 // This capacity calculation is approximate.
340 let mut llargument_tys = Vec::with_capacity(
341 self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
344 let llreturn_ty = match &self.ret.mode {
345 PassMode::Ignore => cx.type_void(),
346 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
347 PassMode::Cast(cast, _) => cast.llvm_type(cx),
348 PassMode::Indirect { .. } => {
349 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
355 let llarg_ty = match &arg.mode {
356 PassMode::Ignore => continue,
357 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
358 PassMode::Pair(..) => {
359 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
360 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
363 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
364 let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
365 let ptr_layout = cx.layout_of(ptr_ty);
366 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
367 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
370 PassMode::Cast(cast, pad_i32) => {
373 llargument_tys.push(Reg::i32().llvm_type(cx));
377 PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ } => {
378 cx.type_ptr_to(arg.memory_ty(cx))
381 llargument_tys.push(llarg_ty);
385 cx.type_variadic_func(&llargument_tys, llreturn_ty)
387 cx.type_func(&llargument_tys, llreturn_ty)
391 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
393 llvm::LLVMPointerType(
395 cx.data_layout().instruction_address_space.0 as c_uint,
400 fn llvm_cconv(&self) -> llvm::CallConv {
402 Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
403 Conv::RustCold => llvm::ColdCallConv,
404 Conv::AmdGpuKernel => llvm::AmdGpuKernel,
405 Conv::AvrInterrupt => llvm::AvrInterrupt,
406 Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
407 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
408 Conv::Msp430Intr => llvm::Msp430Intr,
409 Conv::PtxKernel => llvm::PtxKernel,
410 Conv::X86Fastcall => llvm::X86FastcallCallConv,
411 Conv::X86Intr => llvm::X86_Intr,
412 Conv::X86Stdcall => llvm::X86StdcallCallConv,
413 Conv::X86ThisCall => llvm::X86_ThisCall,
414 Conv::X86VectorCall => llvm::X86_VectorCall,
415 Conv::X86_64SysV => llvm::X86_64_SysV,
416 Conv::X86_64Win64 => llvm::X86_64_Win64,
420 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
421 let mut func_attrs = SmallVec::<[_; 2]>::new();
422 if self.ret.layout.abi.is_uninhabited() {
423 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
425 if !self.can_unwind {
426 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
428 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
431 let mut apply = |attrs: &ArgAttributes| {
432 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
436 match &self.ret.mode {
437 PassMode::Direct(attrs) => {
438 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
440 PassMode::Indirect { attrs, extra_attrs: _, on_stack } => {
442 let i = apply(attrs);
443 let sret = llvm::CreateStructRetAttr(cx.llcx, self.ret.layout.llvm_type(cx));
444 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
446 PassMode::Cast(cast, _) => {
447 cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
451 for arg in self.args.iter() {
453 PassMode::Ignore => {}
454 PassMode::Indirect { attrs, extra_attrs: None, on_stack: true } => {
455 let i = apply(attrs);
456 let byval = llvm::CreateByValAttr(cx.llcx, arg.layout.llvm_type(cx));
457 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
459 PassMode::Direct(attrs)
460 | PassMode::Indirect { attrs, extra_attrs: None, on_stack: false } => {
463 PassMode::Indirect { attrs, extra_attrs: Some(extra_attrs), on_stack } => {
468 PassMode::Pair(a, b) => {
472 PassMode::Cast(cast, pad_i32) => {
474 apply(&ArgAttributes::new());
482 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
483 let mut func_attrs = SmallVec::<[_; 2]>::new();
484 if self.ret.layout.abi.is_uninhabited() {
485 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
487 if !self.can_unwind {
488 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
490 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
493 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
494 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
498 match &self.ret.mode {
499 PassMode::Direct(attrs) => {
500 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
502 PassMode::Indirect { attrs, extra_attrs: _, on_stack } => {
504 let i = apply(bx.cx, attrs);
505 let sret = llvm::CreateStructRetAttr(bx.cx.llcx, self.ret.layout.llvm_type(bx));
506 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
508 PassMode::Cast(cast, _) => {
509 cast.attrs.apply_attrs_to_callsite(
510 llvm::AttributePlace::ReturnValue,
517 if let abi::Abi::Scalar(scalar) = self.ret.layout.abi {
518 // If the value is a boolean, the range is 0..2 and that ultimately
519 // become 0..0 when the type becomes i1, which would be rejected
520 // by the LLVM verifier.
521 if let Int(..) = scalar.primitive() {
522 if !scalar.is_bool() && !scalar.is_always_valid(bx) {
523 bx.range_metadata(callsite, scalar.valid_range(bx));
527 for arg in self.args.iter() {
529 PassMode::Ignore => {}
530 PassMode::Indirect { attrs, extra_attrs: None, on_stack: true } => {
531 let i = apply(bx.cx, attrs);
532 let byval = llvm::CreateByValAttr(bx.cx.llcx, arg.layout.llvm_type(bx));
533 attributes::apply_to_callsite(
535 llvm::AttributePlace::Argument(i),
539 PassMode::Direct(attrs)
540 | PassMode::Indirect { attrs, extra_attrs: None, on_stack: false } => {
543 PassMode::Indirect { attrs, extra_attrs: Some(extra_attrs), on_stack: _ } => {
545 apply(bx.cx, extra_attrs);
547 PassMode::Pair(a, b) => {
551 PassMode::Cast(cast, pad_i32) => {
553 apply(bx.cx, &ArgAttributes::new());
555 apply(bx.cx, &cast.attrs);
560 let cconv = self.llvm_cconv();
561 if cconv != llvm::CCallConv {
562 llvm::SetInstructionCallConv(callsite, cconv);
565 if self.conv == Conv::CCmseNonSecureCall {
566 // This will probably get ignored on all targets but those supporting the TrustZone-M
567 // extension (thumbv8m targets).
568 let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
569 attributes::apply_to_callsite(
571 llvm::AttributePlace::Function,
572 &[cmse_nonsecure_call],
576 // Some intrinsics require that an elementtype attribute (with the pointee type of a
577 // pointer argument) is added to the callsite.
578 let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
579 if element_type_index >= 0 {
580 let arg_ty = self.args[element_type_index as usize].layout.ty;
581 let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument").ty;
582 let element_type_attr = unsafe {
583 llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
585 attributes::apply_to_callsite(
587 llvm::AttributePlace::Argument(element_type_index as u32),
588 &[element_type_attr],
594 impl<'tcx> AbiBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
595 fn apply_attrs_callsite(&mut self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, callsite: Self::Value) {
596 fn_abi.apply_attrs_callsite(self, callsite)
599 fn get_param(&mut self, index: usize) -> Self::Value {
600 llvm::get_param(self.llfn(), index as c_uint)