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::MemFlags;
9 use rustc_codegen_ssa::mir::place::PlaceRef;
10 use rustc_codegen_ssa::mir::operand::OperandValue;
11 use rustc_codegen_ssa::traits::*;
12 use rustc_target::abi::call::ArgAbi;
13 use rustc_target::abi::{HasDataLayout, LayoutOf};
15 use rustc::ty::layout::{self};
19 pub use rustc_target::spec::abi::Abi;
20 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
21 pub use rustc_target::abi::call::*;
23 macro_rules! for_each_kind {
24 ($flags: ident, $f: ident, $($kind: ident),+) => ({
25 $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
29 trait ArgAttributeExt {
30 fn for_each_kind<F>(&self, f: F) where F: FnMut(llvm::Attribute);
33 impl ArgAttributeExt for ArgAttribute {
34 fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
35 for_each_kind!(self, f,
36 NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
40 pub trait ArgAttributesExt {
41 fn apply_llfn(&self, idx: AttributePlace, llfn: &Value, ty: Option<&Type>);
42 fn apply_callsite(&self, idx: AttributePlace, callsite: &Value, ty: Option<&Type>);
45 impl ArgAttributesExt for ArgAttributes {
46 fn apply_llfn(&self, idx: AttributePlace, llfn: &Value, ty: Option<&Type>) {
47 let mut regular = self.regular;
49 let deref = self.pointee_size.bytes();
51 if regular.contains(ArgAttribute::NonNull) {
52 llvm::LLVMRustAddDereferenceableAttr(llfn,
56 llvm::LLVMRustAddDereferenceableOrNullAttr(llfn,
60 regular -= ArgAttribute::NonNull;
62 if let Some(align) = self.pointee_align {
63 llvm::LLVMRustAddAlignmentAttr(llfn,
65 align.bytes() as u32);
67 if regular.contains(ArgAttribute::ByVal) {
68 llvm::LLVMRustAddByValAttr(llfn, idx.as_uint(), ty.unwrap());
70 regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
74 fn apply_callsite(&self, idx: AttributePlace, callsite: &Value, ty: Option<&Type>) {
75 let mut regular = self.regular;
77 let deref = self.pointee_size.bytes();
79 if regular.contains(ArgAttribute::NonNull) {
80 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
84 llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(callsite,
88 regular -= ArgAttribute::NonNull;
90 if let Some(align) = self.pointee_align {
91 llvm::LLVMRustAddAlignmentCallSiteAttr(callsite,
93 align.bytes() as u32);
95 if regular.contains(ArgAttribute::ByVal) {
96 llvm::LLVMRustAddByValCallSiteAttr(callsite, idx.as_uint(), ty.unwrap());
98 regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
104 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
107 impl LlvmType for Reg {
108 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
110 RegKind::Integer => cx.type_ix(self.size.bits()),
112 match self.size.bits() {
115 _ => bug!("unsupported float: {:?}", self)
119 cx.type_vector(cx.type_i8(), self.size.bytes())
125 impl LlvmType for CastTarget {
126 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
127 let rest_ll_unit = self.rest.unit.llvm_type(cx);
128 let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
131 (self.rest.total.bytes() / self.rest.unit.size.bytes(),
132 self.rest.total.bytes() % self.rest.unit.size.bytes())
135 if self.prefix.iter().all(|x| x.is_none()) {
136 // Simplify to a single unit when there is no prefix and size <= unit size
137 if self.rest.total <= self.rest.unit.size {
141 // Simplify to array when all chunks are the same size and type
143 return cx.type_array(rest_ll_unit, rest_count);
147 // Create list of fields in the main structure
148 let mut args: Vec<_> =
149 self.prefix.iter().flat_map(|option_kind| option_kind.map(
150 |kind| Reg { kind: 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>>,
285 idx: &mut usize, dst: PlaceRef<'tcx, Self::Value>
287 arg_abi.store_fn_arg(self, idx, dst)
291 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
293 dst: PlaceRef<'tcx, &'ll Value>
295 arg_abi.store(self, val, dst)
297 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
298 arg_abi.memory_ty(self)
302 pub trait FnAbiLlvmExt<'tcx> {
303 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
304 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
305 fn llvm_cconv(&self) -> llvm::CallConv;
306 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
307 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
310 impl<'tcx> FnAbiLlvmExt<'tcx> for FnAbi<'tcx, Ty<'tcx>> {
311 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
312 let args_capacity: usize = self.args.iter().map(|arg|
313 if arg.pad.is_some() { 1 } else { 0 } +
314 if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
316 let mut llargument_tys = Vec::with_capacity(
317 if let PassMode::Indirect(..) = self.ret.mode { 1 } else { 0 } + args_capacity
320 let llreturn_ty = match self.ret.mode {
321 PassMode::Ignore => cx.type_void(),
322 PassMode::Direct(_) | PassMode::Pair(..) => {
323 self.ret.layout.immediate_llvm_type(cx)
325 PassMode::Cast(cast) => cast.llvm_type(cx),
326 PassMode::Indirect(..) => {
327 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
332 for arg in &self.args {
334 if let Some(ty) = arg.pad {
335 llargument_tys.push(ty.llvm_type(cx));
338 let llarg_ty = match arg.mode {
339 PassMode::Ignore => continue,
340 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
341 PassMode::Pair(..) => {
342 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
343 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
346 PassMode::Indirect(_, Some(_)) => {
347 let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
348 let ptr_layout = cx.layout_of(ptr_ty);
349 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
350 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
353 PassMode::Cast(cast) => cast.llvm_type(cx),
354 PassMode::Indirect(_, None) => cx.type_ptr_to(arg.memory_ty(cx)),
356 llargument_tys.push(llarg_ty);
360 cx.type_variadic_func(&llargument_tys, llreturn_ty)
362 cx.type_func(&llargument_tys, llreturn_ty)
366 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
368 llvm::LLVMPointerType(self.llvm_type(cx),
369 cx.data_layout().instruction_address_space as c_uint)
373 fn llvm_cconv(&self) -> llvm::CallConv {
375 Conv::C => llvm::CCallConv,
376 Conv::AmdGpuKernel => llvm::AmdGpuKernel,
377 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
378 Conv::Msp430Intr => llvm::Msp430Intr,
379 Conv::PtxKernel => llvm::PtxKernel,
380 Conv::X86Fastcall => llvm::X86FastcallCallConv,
381 Conv::X86Intr => llvm::X86_Intr,
382 Conv::X86Stdcall => llvm::X86StdcallCallConv,
383 Conv::X86ThisCall => llvm::X86_ThisCall,
384 Conv::X86VectorCall => llvm::X86_VectorCall,
385 Conv::X86_64SysV => llvm::X86_64_SysV,
386 Conv::X86_64Win64 => llvm::X86_64_Win64,
390 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
392 let mut apply = |attrs: &ArgAttributes, ty: Option<&Type>| {
393 attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn, ty);
396 match self.ret.mode {
397 PassMode::Direct(ref attrs) => {
398 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn, None);
400 PassMode::Indirect(ref attrs, _) => apply(attrs, Some(self.ret.layout.llvm_type(cx))),
403 for arg in &self.args {
404 if arg.pad.is_some() {
405 apply(&ArgAttributes::new(), None);
408 PassMode::Ignore => {}
409 PassMode::Direct(ref attrs) |
410 PassMode::Indirect(ref attrs, None) => apply(attrs, Some(arg.layout.llvm_type(cx))),
411 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
413 apply(extra_attrs, None);
415 PassMode::Pair(ref a, ref b) => {
419 PassMode::Cast(_) => apply(&ArgAttributes::new(), None),
424 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
426 let mut apply = |attrs: &ArgAttributes, ty: Option<&Type>| {
427 attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite, ty);
430 match self.ret.mode {
431 PassMode::Direct(ref attrs) => {
432 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite, None);
434 PassMode::Indirect(ref attrs, _) => apply(attrs, Some(self.ret.layout.llvm_type(bx))),
437 if let layout::Abi::Scalar(ref scalar) = self.ret.layout.abi {
438 // If the value is a boolean, the range is 0..2 and that ultimately
439 // become 0..0 when the type becomes i1, which would be rejected
440 // by the LLVM verifier.
441 if let layout::Int(..) = scalar.value {
442 if !scalar.is_bool() {
443 let range = scalar.valid_range_exclusive(bx);
444 if range.start != range.end {
445 bx.range_metadata(callsite, range);
450 for arg in &self.args {
451 if arg.pad.is_some() {
452 apply(&ArgAttributes::new(), None);
455 PassMode::Ignore => {}
456 PassMode::Direct(ref attrs) |
457 PassMode::Indirect(ref attrs, None) => apply(attrs, Some(arg.layout.llvm_type(bx))),
458 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
460 apply(extra_attrs, None);
462 PassMode::Pair(ref a, ref b) => {
466 PassMode::Cast(_) => apply(&ArgAttributes::new(), None),
470 let cconv = self.llvm_cconv();
471 if cconv != llvm::CCallConv {
472 llvm::SetInstructionCallConv(callsite, cconv);
477 impl AbiBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
478 fn apply_attrs_callsite(
480 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
481 callsite: Self::Value
483 fn_abi.apply_attrs_callsite(self, callsite)
486 fn get_param(&self, index: usize) -> Self::Value {
487 llvm::get_param(self.llfn(), index as c_uint)