1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use llvm::{self, ValueRef, Integer, Pointer, Float, Double, Struct, Array, Vector, AttributePlace};
14 use common::{type_is_fat_ptr, C_uint};
15 use context::CrateContext;
32 use machine::{llalign_of_min, llsize_of, llsize_of_alloc};
37 use rustc::ty::{self, Ty};
38 use rustc::ty::layout::{Layout, LayoutTyper};
43 pub use syntax::abi::Abi;
44 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
46 #[derive(Clone, Copy, PartialEq, Debug)]
48 /// Pass the argument directly using the normal converted
49 /// LLVM type or by coercing to another specified type
51 /// Pass the argument indirectly via a hidden pointer
53 /// Ignore the argument (useful for empty struct)
57 // Hack to disable non_upper_case_globals only for the bitflags! and not for the rest
59 pub use self::attr_impl::ArgAttribute;
61 #[allow(non_upper_case_globals)]
64 // The subset of llvm::Attribute needed for arguments, packed into a bitfield.
66 #[derive(Default, Debug)]
67 flags ArgAttribute : u16 {
69 const NoAlias = 1 << 1,
70 const NoCapture = 1 << 2,
71 const NonNull = 1 << 3,
72 const ReadOnly = 1 << 4,
74 const StructRet = 1 << 6,
81 macro_rules! for_each_kind {
82 ($flags: ident, $f: ident, $($kind: ident),+) => ({
83 $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
88 fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
89 for_each_kind!(self, f,
90 ByVal, NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
94 /// A compact representation of LLVM attributes (at least those relevant for this module)
95 /// that can be manipulated without interacting with LLVM's Attribute machinery.
96 #[derive(Copy, Clone, Debug, Default)]
97 pub struct ArgAttributes {
98 regular: ArgAttribute,
99 dereferenceable_bytes: u64,
103 pub fn set(&mut self, attr: ArgAttribute) -> &mut Self {
104 self.regular = self.regular | attr;
108 pub fn set_dereferenceable(&mut self, bytes: u64) -> &mut Self {
109 self.dereferenceable_bytes = bytes;
113 pub fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) {
115 self.regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
116 if self.dereferenceable_bytes != 0 {
117 llvm::LLVMRustAddDereferenceableAttr(llfn,
119 self.dereferenceable_bytes);
124 pub fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) {
126 self.regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
127 if self.dereferenceable_bytes != 0 {
128 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
130 self.dereferenceable_bytes);
136 /// Information about how a specific C type
137 /// should be passed to or returned from a function
139 /// This is borrowed from clang's ABIInfo.h
140 #[derive(Clone, Copy, Debug)]
143 /// Original LLVM type
144 pub original_ty: Type,
145 /// Sizing LLVM type (pointers are opaque).
146 /// Unlike original_ty, this is guaranteed to be complete.
148 /// For example, while we're computing the function pointer type in
149 /// `struct Foo(fn(Foo));`, `original_ty` is still LLVM's `%Foo = {}`.
150 /// The field type will likely end up being `void(%Foo)*`, but we cannot
151 /// use `%Foo` to compute properties (e.g. size and alignment) of `Foo`,
152 /// until `%Foo` is completed by having all of its field types inserted,
153 /// so `ty` holds the "sizing type" of `Foo`, which replaces all pointers
154 /// with opaque ones, resulting in `{i8*}` for `Foo`.
155 /// ABI-specific logic can then look at the size, alignment and fields of
156 /// `{i8*}` in order to determine how the argument will be passed.
157 /// Only later will `original_ty` aka `%Foo` be used in the LLVM function
158 /// pointer type, without ever having introspected it.
160 /// Signedness for integer types, None for other types
161 pub signedness: Option<bool>,
162 /// Coerced LLVM Type
163 pub cast: Option<Type>,
164 /// Dummy argument, which is emitted before the real argument
165 pub pad: Option<Type>,
166 /// LLVM attributes of argument
167 pub attrs: ArgAttributes
171 fn new(original_ty: Type, ty: Type) -> ArgType {
173 kind: ArgKind::Direct,
174 original_ty: original_ty,
179 attrs: ArgAttributes::default()
183 pub fn make_indirect(&mut self, ccx: &CrateContext) {
184 assert_eq!(self.kind, ArgKind::Direct);
186 // Wipe old attributes, likely not valid through indirection.
187 self.attrs = ArgAttributes::default();
189 let llarg_sz = llsize_of_alloc(ccx, self.ty);
191 // For non-immediate arguments the callee gets its own copy of
192 // the value on the stack, so there are no aliases. It's also
193 // program-invisible so can't possibly capture
194 self.attrs.set(ArgAttribute::NoAlias)
195 .set(ArgAttribute::NoCapture)
196 .set_dereferenceable(llarg_sz);
198 self.kind = ArgKind::Indirect;
201 pub fn ignore(&mut self) {
202 assert_eq!(self.kind, ArgKind::Direct);
203 self.kind = ArgKind::Ignore;
206 pub fn extend_integer_width_to(&mut self, bits: u64) {
207 // Only integers have signedness
208 if let Some(signed) = self.signedness {
209 if self.ty.int_width() < bits {
210 self.attrs.set(if signed {
219 pub fn is_indirect(&self) -> bool {
220 self.kind == ArgKind::Indirect
223 pub fn is_ignore(&self) -> bool {
224 self.kind == ArgKind::Ignore
227 /// Store a direct/indirect value described by this ArgType into a
228 /// lvalue for the original Rust type of this argument/return.
229 /// Can be used for both storing formal arguments into Rust variables
230 /// or results of call/invoke instructions into their destinations.
231 pub fn store(&self, bcx: &Builder, mut val: ValueRef, dst: ValueRef) {
232 if self.is_ignore() {
236 if self.is_indirect() {
237 let llsz = llsize_of(ccx, self.ty);
238 let llalign = llalign_of_min(ccx, self.ty);
239 base::call_memcpy(bcx, dst, val, llsz, llalign as u32);
240 } else if let Some(ty) = self.cast {
241 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
242 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
243 let can_store_through_cast_ptr = false;
244 if can_store_through_cast_ptr {
245 let cast_dst = bcx.pointercast(dst, ty.ptr_to());
246 let llalign = llalign_of_min(ccx, self.ty);
247 bcx.store(val, cast_dst, Some(llalign));
249 // The actual return type is a struct, but the ABI
250 // adaptation code has cast it into some scalar type. The
251 // code that follows is the only reliable way I have
252 // found to do a transform like i64 -> {i32,i32}.
253 // Basically we dump the data onto the stack then memcpy it.
255 // Other approaches I tried:
256 // - Casting rust ret pointer to the foreign type and using Store
257 // is (a) unsafe if size of foreign type > size of rust type and
258 // (b) runs afoul of strict aliasing rules, yielding invalid
259 // assembly under -O (specifically, the store gets removed).
260 // - Truncating foreign type to correct integral type and then
261 // bitcasting to the struct type yields invalid cast errors.
263 // We instead thus allocate some scratch space...
264 let llscratch = bcx.alloca(ty, "abi_cast");
265 base::Lifetime::Start.call(bcx, llscratch);
267 // ...where we first store the value...
268 bcx.store(val, llscratch, None);
270 // ...and then memcpy it to the intended destination.
271 base::call_memcpy(bcx,
272 bcx.pointercast(dst, Type::i8p(ccx)),
273 bcx.pointercast(llscratch, Type::i8p(ccx)),
274 C_uint(ccx, llsize_of_alloc(ccx, self.ty)),
275 cmp::min(llalign_of_min(ccx, self.ty),
276 llalign_of_min(ccx, ty)) as u32);
278 base::Lifetime::End.call(bcx, llscratch);
281 if self.original_ty == Type::i1(ccx) {
282 val = bcx.zext(val, Type::i8(ccx));
284 bcx.store(val, dst, None);
288 pub fn store_fn_arg(&self, bcx: &Builder, idx: &mut usize, dst: ValueRef) {
289 if self.pad.is_some() {
292 if self.is_ignore() {
295 let val = llvm::get_param(bcx.llfn(), *idx as c_uint);
297 self.store(bcx, val, dst);
301 /// Metadata describing how the arguments to a native function
302 /// should be passed in order to respect the native ABI.
304 /// I will do my best to describe this structure, but these
305 /// comments are reverse-engineered and may be inaccurate. -NDM
306 #[derive(Clone, Debug)]
308 /// The LLVM types of each argument.
309 pub args: Vec<ArgType>,
311 /// LLVM return type.
316 pub cconv: llvm::CallConv
320 pub fn new<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
321 sig: ty::FnSig<'tcx>,
322 extra_args: &[Ty<'tcx>]) -> FnType {
323 let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args);
324 fn_ty.adjust_for_abi(ccx, sig);
328 pub fn new_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
329 sig: ty::FnSig<'tcx>,
330 extra_args: &[Ty<'tcx>]) -> FnType {
331 let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args);
332 // Don't pass the vtable, it's not an argument of the virtual fn.
333 fn_ty.args[1].ignore();
334 fn_ty.adjust_for_abi(ccx, sig);
338 fn unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
339 sig: ty::FnSig<'tcx>,
340 extra_args: &[Ty<'tcx>]) -> FnType {
342 let cconv = match ccx.sess().target.target.adjust_abi(sig.abi) {
343 RustIntrinsic | PlatformIntrinsic |
344 Rust | RustCall => llvm::CCallConv,
346 // It's the ABI's job to select this, not us.
347 System => bug!("system abi should be selected elsewhere"),
349 Stdcall => llvm::X86StdcallCallConv,
350 Fastcall => llvm::X86FastcallCallConv,
351 Vectorcall => llvm::X86_VectorCall,
352 C => llvm::CCallConv,
353 Unadjusted => llvm::CCallConv,
354 Win64 => llvm::X86_64_Win64,
355 SysV64 => llvm::X86_64_SysV,
356 Aapcs => llvm::ArmAapcsCallConv,
357 PtxKernel => llvm::PtxKernel,
358 Msp430Interrupt => llvm::Msp430Intr,
359 X86Interrupt => llvm::X86_Intr,
361 // These API constants ought to be more specific...
362 Cdecl => llvm::CCallConv,
365 let mut inputs = sig.inputs();
366 let extra_args = if sig.abi == RustCall {
367 assert!(!sig.variadic && extra_args.is_empty());
369 match sig.inputs().last().unwrap().sty {
370 ty::TyTuple(ref tupled_arguments, _) => {
371 inputs = &sig.inputs()[0..sig.inputs().len() - 1];
375 bug!("argument to function with \"rust-call\" ABI \
380 assert!(sig.variadic || extra_args.is_empty());
384 let target = &ccx.sess().target.target;
385 let win_x64_gnu = target.target_os == "windows"
386 && target.arch == "x86_64"
387 && target.target_env == "gnu";
388 let linux_s390x = target.target_os == "linux"
389 && target.arch == "s390x"
390 && target.target_env == "gnu";
391 let rust_abi = match sig.abi {
392 RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
396 let arg_of = |ty: Ty<'tcx>, is_return: bool| {
398 let llty = Type::i1(ccx);
399 let mut arg = ArgType::new(llty, llty);
400 arg.attrs.set(ArgAttribute::ZExt);
403 let mut arg = ArgType::new(type_of::type_of(ccx, ty),
404 type_of::sizing_type_of(ccx, ty));
405 if ty.is_integral() {
406 arg.signedness = Some(ty.is_signed());
408 // Rust enum types that map onto C enums also need to follow
409 // the target ABI zero-/sign-extension rules.
410 if let Layout::CEnum { signed, .. } = *ccx.layout_of(ty) {
411 arg.signedness = Some(signed);
413 if llsize_of_alloc(ccx, arg.ty) == 0 {
414 // For some forsaken reason, x86_64-pc-windows-gnu
415 // doesn't ignore zero-sized struct arguments.
416 // The same is true for s390x-unknown-linux-gnu.
417 if is_return || rust_abi ||
418 (!win_x64_gnu && !linux_s390x) {
426 let ret_ty = sig.output();
427 let mut ret = arg_of(ret_ty, true);
429 if !type_is_fat_ptr(ccx, ret_ty) {
430 // The `noalias` attribute on the return value is useful to a
431 // function ptr caller.
433 // `Box` pointer return values never alias because ownership
435 ret.attrs.set(ArgAttribute::NoAlias);
438 // We can also mark the return value as `dereferenceable` in certain cases
440 // These are not really pointers but pairs, (pointer, len)
441 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => {
442 ret.attrs.set_dereferenceable(ccx.size_of(ty));
444 ty::TyAdt(def, _) if def.is_box() => {
445 ret.attrs.set_dereferenceable(ccx.size_of(ret_ty.boxed_ty()));
451 let mut args = Vec::with_capacity(inputs.len() + extra_args.len());
453 // Handle safe Rust thin and fat pointers.
454 let rust_ptr_attrs = |ty: Ty<'tcx>, arg: &mut ArgType| match ty.sty {
455 // `Box` pointer parameters never alias because ownership is transferred
456 ty::TyAdt(def, _) if def.is_box() => {
457 arg.attrs.set(ArgAttribute::NoAlias);
461 ty::TyRef(b, mt) => {
462 use rustc::ty::{BrAnon, ReLateBound};
464 // `&mut` pointer parameters never alias other parameters, or mutable global data
466 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
467 // both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
468 // on memory dependencies rather than pointer equality
469 let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
471 if mt.mutbl != hir::MutMutable && !interior_unsafe {
472 arg.attrs.set(ArgAttribute::NoAlias);
475 if mt.mutbl == hir::MutImmutable && !interior_unsafe {
476 arg.attrs.set(ArgAttribute::ReadOnly);
479 // When a reference in an argument has no named lifetime, it's
480 // impossible for that reference to escape this function
481 // (returned or stored beyond the call by a closure).
482 if let ReLateBound(_, BrAnon(_)) = *b {
483 arg.attrs.set(ArgAttribute::NoCapture);
491 for ty in inputs.iter().chain(extra_args.iter()) {
492 let mut arg = arg_of(ty, false);
494 if type_is_fat_ptr(ccx, ty) {
495 let original_tys = arg.original_ty.field_types();
496 let sizing_tys = arg.ty.field_types();
497 assert_eq!((original_tys.len(), sizing_tys.len()), (2, 2));
499 let mut data = ArgType::new(original_tys[0], sizing_tys[0]);
500 let mut info = ArgType::new(original_tys[1], sizing_tys[1]);
502 if let Some(inner) = rust_ptr_attrs(ty, &mut data) {
503 data.attrs.set(ArgAttribute::NonNull);
504 if ccx.tcx().struct_tail(inner).is_trait() {
505 // vtables can be safely marked non-null, readonly
507 info.attrs.set(ArgAttribute::NonNull);
508 info.attrs.set(ArgAttribute::ReadOnly);
509 info.attrs.set(ArgAttribute::NoAlias);
515 if let Some(inner) = rust_ptr_attrs(ty, &mut arg) {
516 arg.attrs.set_dereferenceable(ccx.size_of(inner));
525 variadic: sig.variadic,
530 fn adjust_for_abi<'a, 'tcx>(&mut self,
531 ccx: &CrateContext<'a, 'tcx>,
532 sig: ty::FnSig<'tcx>) {
534 if abi == Abi::Unadjusted { return }
536 if abi == Abi::Rust || abi == Abi::RustCall ||
537 abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
538 let fixup = |arg: &mut ArgType| {
539 let mut llty = arg.ty;
541 // Replace newtypes with their inner-most type.
542 while llty.kind() == llvm::TypeKind::Struct {
543 let inner = llty.field_types();
544 if inner.len() != 1 {
550 if !llty.is_aggregate() {
551 // Scalars and vectors, always immediate.
553 // Needs a cast as we've unpacked a newtype.
554 arg.cast = Some(llty);
559 let size = llsize_of_alloc(ccx, llty);
560 if size > llsize_of_alloc(ccx, ccx.int_type()) {
561 arg.make_indirect(ccx);
563 // We want to pass small aggregates as immediates, but using
564 // a LLVM aggregate type for this leads to bad optimizations,
565 // so we pick an appropriately sized integer type instead.
566 arg.cast = Some(Type::ix(ccx, size * 8));
569 // Fat pointers are returned by-value.
570 if !self.ret.is_ignore() {
571 if !type_is_fat_ptr(ccx, sig.output()) {
572 fixup(&mut self.ret);
575 for arg in &mut self.args {
576 if arg.is_ignore() { continue; }
579 if self.ret.is_indirect() {
580 self.ret.attrs.set(ArgAttribute::StructRet);
585 match &ccx.sess().target.target.arch[..] {
587 let flavor = if abi == Abi::Fastcall {
588 cabi_x86::Flavor::Fastcall
590 cabi_x86::Flavor::General
592 cabi_x86::compute_abi_info(ccx, self, flavor);
594 "x86_64" => if abi == Abi::SysV64 {
595 cabi_x86_64::compute_abi_info(ccx, self);
596 } else if abi == Abi::Win64 || ccx.sess().target.target.options.is_like_windows {
597 cabi_x86_win64::compute_abi_info(ccx, self);
599 cabi_x86_64::compute_abi_info(ccx, self);
601 "aarch64" => cabi_aarch64::compute_abi_info(ccx, self),
603 let flavor = if ccx.sess().target.target.target_os == "ios" {
604 cabi_arm::Flavor::Ios
606 cabi_arm::Flavor::General
608 cabi_arm::compute_abi_info(ccx, self, flavor);
610 "mips" => cabi_mips::compute_abi_info(ccx, self),
611 "mips64" => cabi_mips64::compute_abi_info(ccx, self),
612 "powerpc" => cabi_powerpc::compute_abi_info(ccx, self),
613 "powerpc64" => cabi_powerpc64::compute_abi_info(ccx, self),
614 "s390x" => cabi_s390x::compute_abi_info(ccx, self),
615 "asmjs" => cabi_asmjs::compute_abi_info(ccx, self),
616 "wasm32" => cabi_asmjs::compute_abi_info(ccx, self),
617 "msp430" => cabi_msp430::compute_abi_info(ccx, self),
618 "sparc" => cabi_sparc::compute_abi_info(ccx, self),
619 "sparc64" => cabi_sparc64::compute_abi_info(ccx, self),
620 "nvptx" => cabi_nvptx::compute_abi_info(ccx, self),
621 "nvptx64" => cabi_nvptx64::compute_abi_info(ccx, self),
622 a => ccx.sess().fatal(&format!("unrecognized arch \"{}\" in target specification", a))
625 if self.ret.is_indirect() {
626 self.ret.attrs.set(ArgAttribute::StructRet);
630 pub fn llvm_type(&self, ccx: &CrateContext) -> Type {
631 let mut llargument_tys = Vec::new();
633 let llreturn_ty = if self.ret.is_ignore() {
635 } else if self.ret.is_indirect() {
636 llargument_tys.push(self.ret.original_ty.ptr_to());
639 self.ret.cast.unwrap_or(self.ret.original_ty)
642 for arg in &self.args {
647 if let Some(ty) = arg.pad {
648 llargument_tys.push(ty);
651 let llarg_ty = if arg.is_indirect() {
652 arg.original_ty.ptr_to()
654 arg.cast.unwrap_or(arg.original_ty)
657 llargument_tys.push(llarg_ty);
661 Type::variadic_func(&llargument_tys, &llreturn_ty)
663 Type::func(&llargument_tys, &llreturn_ty)
667 pub fn apply_attrs_llfn(&self, llfn: ValueRef) {
668 let mut i = if self.ret.is_indirect() { 1 } else { 0 };
669 if !self.ret.is_ignore() {
670 self.ret.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
673 for arg in &self.args {
674 if !arg.is_ignore() {
675 if arg.pad.is_some() { i += 1; }
676 arg.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
682 pub fn apply_attrs_callsite(&self, callsite: ValueRef) {
683 let mut i = if self.ret.is_indirect() { 1 } else { 0 };
684 if !self.ret.is_ignore() {
685 self.ret.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
688 for arg in &self.args {
689 if !arg.is_ignore() {
690 if arg.pad.is_some() { i += 1; }
691 arg.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
696 if self.cconv != llvm::CCallConv {
697 llvm::SetInstructionCallConv(callsite, self.cconv);
702 pub fn align_up_to(off: usize, a: usize) -> usize {
703 return (off + a - 1) / a * a;
706 fn align(off: usize, ty: Type, pointer: usize) -> usize {
707 let a = ty_align(ty, pointer);
708 return align_up_to(off, a);
711 pub fn ty_align(ty: Type, pointer: usize) -> usize {
713 Integer => ((ty.int_width() as usize) + 7) / 8,
721 let str_tys = ty.field_types();
722 str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t, pointer)))
726 let elt = ty.element_type();
727 ty_align(elt, pointer)
730 let len = ty.vector_length();
731 let elt = ty.element_type();
732 ty_align(elt, pointer) * len
734 _ => bug!("ty_align: unhandled type")
738 pub fn ty_size(ty: Type, pointer: usize) -> usize {
740 Integer => ((ty.int_width() as usize) + 7) / 8,
746 let str_tys = ty.field_types();
747 str_tys.iter().fold(0, |s, t| s + ty_size(*t, pointer))
749 let str_tys = ty.field_types();
750 let size = str_tys.iter().fold(0, |s, t| {
751 align(s, *t, pointer) + ty_size(*t, pointer)
753 align(size, ty, pointer)
757 let len = ty.array_length();
758 let elt = ty.element_type();
759 let eltsz = ty_size(elt, pointer);
763 let len = ty.vector_length();
764 let elt = ty.element_type();
765 let eltsz = ty_size(elt, pointer);
768 _ => bug!("ty_size: unhandled type")