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, SExt, StructRet, ZExt, InReg)
43 pub trait ArgAttributesExt {
44 fn apply_llfn(&self, idx: AttributePlace, llfn: &Value, ty: Option<&Type>);
45 fn apply_callsite(&self, idx: AttributePlace, callsite: &Value, ty: Option<&Type>);
48 impl ArgAttributesExt for ArgAttributes {
49 fn apply_llfn(&self, idx: AttributePlace, llfn: &Value, ty: Option<&Type>) {
50 let mut regular = self.regular;
52 let deref = self.pointee_size.bytes();
54 if regular.contains(ArgAttribute::NonNull) {
55 llvm::LLVMRustAddDereferenceableAttr(llfn, idx.as_uint(), deref);
57 llvm::LLVMRustAddDereferenceableOrNullAttr(llfn, idx.as_uint(), deref);
59 regular -= ArgAttribute::NonNull;
61 if let Some(align) = self.pointee_align {
62 llvm::LLVMRustAddAlignmentAttr(llfn, idx.as_uint(), align.bytes() as u32);
64 if regular.contains(ArgAttribute::ByVal) {
65 llvm::LLVMRustAddByValAttr(llfn, idx.as_uint(), ty.unwrap());
67 regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
71 fn apply_callsite(&self, idx: AttributePlace, callsite: &Value, ty: Option<&Type>) {
72 let mut regular = self.regular;
74 let deref = self.pointee_size.bytes();
76 if regular.contains(ArgAttribute::NonNull) {
77 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite, idx.as_uint(), deref);
79 llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(
85 regular -= ArgAttribute::NonNull;
87 if let Some(align) = self.pointee_align {
88 llvm::LLVMRustAddAlignmentCallSiteAttr(
94 if regular.contains(ArgAttribute::ByVal) {
95 llvm::LLVMRustAddByValCallSiteAttr(callsite, idx.as_uint(), ty.unwrap());
97 regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
103 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
106 impl LlvmType for Reg {
107 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
109 RegKind::Integer => cx.type_ix(self.size.bits()),
110 RegKind::Float => match self.size.bits() {
113 _ => bug!("unsupported float: {:?}", self),
115 RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()),
120 impl LlvmType for CastTarget {
121 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
122 let rest_ll_unit = self.rest.unit.llvm_type(cx);
123 let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
127 self.rest.total.bytes() / self.rest.unit.size.bytes(),
128 self.rest.total.bytes() % self.rest.unit.size.bytes(),
132 if self.prefix.iter().all(|x| x.is_none()) {
133 // Simplify to a single unit when there is no prefix and size <= unit size
134 if self.rest.total <= self.rest.unit.size {
138 // Simplify to array when all chunks are the same size and type
140 return cx.type_array(rest_ll_unit, rest_count);
144 // Create list of fields in the main structure
145 let mut args: Vec<_> = self
148 .flat_map(|option_kind| {
149 option_kind.map(|kind| Reg { kind, size: self.prefix_chunk }.llvm_type(cx))
151 .chain((0..rest_count).map(|_| rest_ll_unit))
154 // Append final integer
156 // Only integers can be really split further.
157 assert_eq!(self.rest.unit.kind, RegKind::Integer);
158 args.push(cx.type_ix(rem_bytes * 8));
161 cx.type_struct(&args, false)
165 pub trait ArgAbiExt<'ll, 'tcx> {
166 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
169 bx: &mut Builder<'_, 'll, 'tcx>,
171 dst: PlaceRef<'tcx, &'ll Value>,
175 bx: &mut Builder<'_, 'll, 'tcx>,
177 dst: PlaceRef<'tcx, &'ll Value>,
181 impl ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
182 /// Gets the LLVM type for a place of the original Rust type of
183 /// this argument/return, i.e., the result of `type_of::type_of`.
184 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
185 self.layout.llvm_type(cx)
188 /// Stores a direct/indirect value described by this ArgAbi into a
189 /// place for the original Rust type of this argument/return.
190 /// Can be used for both storing formal arguments into Rust variables
191 /// or results of call/invoke instructions into their destinations.
194 bx: &mut Builder<'_, 'll, 'tcx>,
196 dst: PlaceRef<'tcx, &'ll Value>,
198 if self.is_ignore() {
201 if self.is_sized_indirect() {
202 OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
203 } else if self.is_unsized_indirect() {
204 bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
205 } else if let PassMode::Cast(cast) = self.mode {
206 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
207 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
208 let can_store_through_cast_ptr = false;
209 if can_store_through_cast_ptr {
210 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
211 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
212 bx.store(val, cast_dst, self.layout.align.abi);
214 // The actual return type is a struct, but the ABI
215 // adaptation code has cast it into some scalar type. The
216 // code that follows is the only reliable way I have
217 // found to do a transform like i64 -> {i32,i32}.
218 // Basically we dump the data onto the stack then memcpy it.
220 // Other approaches I tried:
221 // - Casting rust ret pointer to the foreign type and using Store
222 // is (a) unsafe if size of foreign type > size of rust type and
223 // (b) runs afoul of strict aliasing rules, yielding invalid
224 // assembly under -O (specifically, the store gets removed).
225 // - Truncating foreign type to correct integral type and then
226 // bitcasting to the struct type yields invalid cast errors.
228 // We instead thus allocate some scratch space...
229 let scratch_size = cast.size(bx);
230 let scratch_align = cast.align(bx);
231 let llscratch = bx.alloca(cast.llvm_type(bx), scratch_align);
232 bx.lifetime_start(llscratch, scratch_size);
234 // ... where we first store the value...
235 bx.store(val, llscratch, scratch_align);
237 // ... and then memcpy it to the intended destination.
240 self.layout.align.abi,
243 bx.const_usize(self.layout.size.bytes()),
247 bx.lifetime_end(llscratch, scratch_size);
250 OperandValue::Immediate(val).store(bx, dst);
256 bx: &mut Builder<'a, 'll, 'tcx>,
258 dst: PlaceRef<'tcx, &'ll Value>,
261 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
266 PassMode::Ignore => {}
267 PassMode::Pair(..) => {
268 OperandValue::Pair(next(), next()).store(bx, dst);
270 PassMode::Indirect(_, Some(_)) => {
271 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
273 PassMode::Direct(_) | PassMode::Indirect(_, None) | PassMode::Cast(_) => {
274 let next_arg = next();
275 self.store(bx, next_arg, dst);
281 impl ArgAbiMethods<'tcx> for Builder<'a, 'll, 'tcx> {
284 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
286 dst: PlaceRef<'tcx, Self::Value>,
288 arg_abi.store_fn_arg(self, idx, dst)
292 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
294 dst: PlaceRef<'tcx, &'ll Value>,
296 arg_abi.store(self, val, dst)
298 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
299 arg_abi.memory_ty(self)
303 pub trait FnAbiLlvmExt<'tcx> {
304 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
305 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
306 fn llvm_cconv(&self) -> llvm::CallConv;
307 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
308 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
311 impl<'tcx> FnAbiLlvmExt<'tcx> for FnAbi<'tcx, Ty<'tcx>> {
312 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
313 let args_capacity: usize = self.args.iter().map(|arg|
314 if arg.pad.is_some() { 1 } else { 0 } +
315 if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
317 let mut llargument_tys = Vec::with_capacity(
318 if let PassMode::Indirect(..) = self.ret.mode { 1 } else { 0 } + args_capacity,
321 let llreturn_ty = match self.ret.mode {
322 PassMode::Ignore => cx.type_void(),
323 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
324 PassMode::Cast(cast) => cast.llvm_type(cx),
325 PassMode::Indirect(..) => {
326 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
331 for arg in &self.args {
333 if let Some(ty) = arg.pad {
334 llargument_tys.push(ty.llvm_type(cx));
337 let llarg_ty = match arg.mode {
338 PassMode::Ignore => continue,
339 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
340 PassMode::Pair(..) => {
341 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
342 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
345 PassMode::Indirect(_, Some(_)) => {
346 let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
347 let ptr_layout = cx.layout_of(ptr_ty);
348 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
349 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
352 PassMode::Cast(cast) => cast.llvm_type(cx),
353 PassMode::Indirect(_, None) => cx.type_ptr_to(arg.memory_ty(cx)),
355 llargument_tys.push(llarg_ty);
359 cx.type_variadic_func(&llargument_tys, llreturn_ty)
361 cx.type_func(&llargument_tys, llreturn_ty)
365 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
367 llvm::LLVMPointerType(
369 cx.data_layout().instruction_address_space as c_uint,
374 fn llvm_cconv(&self) -> llvm::CallConv {
376 Conv::C | Conv::Rust => llvm::CCallConv,
377 Conv::AmdGpuKernel => llvm::AmdGpuKernel,
378 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
379 Conv::Msp430Intr => llvm::Msp430Intr,
380 Conv::PtxKernel => llvm::PtxKernel,
381 Conv::X86Fastcall => llvm::X86FastcallCallConv,
382 Conv::X86Intr => llvm::X86_Intr,
383 Conv::X86Stdcall => llvm::X86StdcallCallConv,
384 Conv::X86ThisCall => llvm::X86_ThisCall,
385 Conv::X86VectorCall => llvm::X86_VectorCall,
386 Conv::X86_64SysV => llvm::X86_64_SysV,
387 Conv::X86_64Win64 => llvm::X86_64_Win64,
391 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
392 // FIXME(eddyb) can this also be applied to callsites?
393 if self.ret.layout.abi.is_uninhabited() {
394 llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn);
397 // FIXME(eddyb, wesleywiser): apply this to callsites as well?
398 if !self.can_unwind {
399 llvm::Attribute::NoUnwind.apply_llfn(llvm::AttributePlace::Function, llfn);
403 let mut apply = |attrs: &ArgAttributes, ty: Option<&Type>| {
404 attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn, ty);
407 match self.ret.mode {
408 PassMode::Direct(ref attrs) => {
409 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn, None);
411 PassMode::Indirect(ref attrs, _) => apply(attrs, Some(self.ret.layout.llvm_type(cx))),
414 for arg in &self.args {
415 if arg.pad.is_some() {
416 apply(&ArgAttributes::new(), None);
419 PassMode::Ignore => {}
420 PassMode::Direct(ref attrs) | PassMode::Indirect(ref attrs, None) => {
421 apply(attrs, Some(arg.layout.llvm_type(cx)))
423 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
425 apply(extra_attrs, None);
427 PassMode::Pair(ref a, ref b) => {
431 PassMode::Cast(_) => apply(&ArgAttributes::new(), None),
436 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
437 // FIXME(wesleywiser, eddyb): We should apply `nounwind` and `noreturn` as appropriate to this callsite.
440 let mut apply = |attrs: &ArgAttributes, ty: Option<&Type>| {
441 attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite, ty);
444 match self.ret.mode {
445 PassMode::Direct(ref attrs) => {
446 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite, None);
448 PassMode::Indirect(ref attrs, _) => apply(attrs, Some(self.ret.layout.llvm_type(bx))),
451 if let abi::Abi::Scalar(ref scalar) = self.ret.layout.abi {
452 // If the value is a boolean, the range is 0..2 and that ultimately
453 // become 0..0 when the type becomes i1, which would be rejected
454 // by the LLVM verifier.
455 if let Int(..) = scalar.value {
456 if !scalar.is_bool() {
457 let range = scalar.valid_range_exclusive(bx);
458 if range.start != range.end {
459 bx.range_metadata(callsite, range);
464 for arg in &self.args {
465 if arg.pad.is_some() {
466 apply(&ArgAttributes::new(), None);
469 PassMode::Ignore => {}
470 PassMode::Direct(ref attrs) | PassMode::Indirect(ref attrs, None) => {
471 apply(attrs, Some(arg.layout.llvm_type(bx)))
473 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
475 apply(extra_attrs, None);
477 PassMode::Pair(ref a, ref b) => {
481 PassMode::Cast(_) => apply(&ArgAttributes::new(), None),
485 let cconv = self.llvm_cconv();
486 if cconv != llvm::CCallConv {
487 llvm::SetInstructionCallConv(callsite, cconv);
492 impl AbiBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
493 fn apply_attrs_callsite(&mut self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, callsite: Self::Value) {
494 fn_abi.apply_attrs_callsite(self, callsite)
497 fn get_param(&self, index: usize) -> Self::Value {
498 llvm::get_param(self.llfn(), index as c_uint)