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};
14 use common::{type_is_fat_ptr, BlockAndBuilder, C_uint};
15 use context::CrateContext;
26 use machine::{llalign_of_min, llsize_of, llsize_of_real, llsize_of_store};
31 use rustc::ty::{self, Ty};
36 pub use syntax::abi::Abi;
37 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
39 #[derive(Clone, Copy, PartialEq, Debug)]
41 /// Pass the argument directly using the normal converted
42 /// LLVM type or by coercing to another specified type
44 /// Pass the argument indirectly via a hidden pointer
46 /// Ignore the argument (useful for empty struct)
50 /// Information about how a specific C type
51 /// should be passed to or returned from a function
53 /// This is borrowed from clang's ABIInfo.h
54 #[derive(Clone, Copy, Debug)]
57 /// Original LLVM type
58 pub original_ty: Type,
59 /// Sizing LLVM type (pointers are opaque).
60 /// Unlike original_ty, this is guaranteed to be complete.
62 /// For example, while we're computing the function pointer type in
63 /// `struct Foo(fn(Foo));`, `original_ty` is still LLVM's `%Foo = {}`.
64 /// The field type will likely end up being `void(%Foo)*`, but we cannot
65 /// use `%Foo` to compute properties (e.g. size and alignment) of `Foo`,
66 /// until `%Foo` is completed by having all of its field types inserted,
67 /// so `ty` holds the "sizing type" of `Foo`, which replaces all pointers
68 /// with opaque ones, resulting in `{i8*}` for `Foo`.
69 /// ABI-specific logic can then look at the size, alignment and fields of
70 /// `{i8*}` in order to determine how the argument will be passed.
71 /// Only later will `original_ty` aka `%Foo` be used in the LLVM function
72 /// pointer type, without ever having introspected it.
74 /// Signedness for integer types, None for other types
75 pub signedness: Option<bool>,
77 pub cast: Option<Type>,
78 /// Dummy argument, which is emitted before the real argument
79 pub pad: Option<Type>,
80 /// LLVM attributes of argument
81 pub attrs: llvm::Attributes
85 fn new(original_ty: Type, ty: Type) -> ArgType {
87 kind: ArgKind::Direct,
88 original_ty: original_ty,
93 attrs: llvm::Attributes::default()
97 pub fn make_indirect(&mut self, ccx: &CrateContext) {
98 assert_eq!(self.kind, ArgKind::Direct);
100 // Wipe old attributes, likely not valid through indirection.
101 self.attrs = llvm::Attributes::default();
103 let llarg_sz = llsize_of_real(ccx, self.ty);
105 // For non-immediate arguments the callee gets its own copy of
106 // the value on the stack, so there are no aliases. It's also
107 // program-invisible so can't possibly capture
108 self.attrs.set(llvm::Attribute::NoAlias)
109 .set(llvm::Attribute::NoCapture)
110 .set_dereferenceable(llarg_sz);
112 self.kind = ArgKind::Indirect;
115 pub fn ignore(&mut self) {
116 assert_eq!(self.kind, ArgKind::Direct);
117 self.kind = ArgKind::Ignore;
120 pub fn extend_integer_width_to(&mut self, bits: u64) {
121 // Only integers have signedness
122 if let Some(signed) = self.signedness {
123 if self.ty.int_width() < bits {
124 self.attrs.set(if signed {
125 llvm::Attribute::SExt
127 llvm::Attribute::ZExt
133 pub fn is_indirect(&self) -> bool {
134 self.kind == ArgKind::Indirect
137 pub fn is_ignore(&self) -> bool {
138 self.kind == ArgKind::Ignore
141 /// Get the LLVM type for an lvalue of the original Rust type of
142 /// this argument/return, i.e. the result of `type_of::type_of`.
143 pub fn memory_ty(&self, ccx: &CrateContext) -> Type {
144 if self.original_ty == Type::i1(ccx) {
151 /// Store a direct/indirect value described by this ArgType into a
152 /// lvalue for the original Rust type of this argument/return.
153 /// Can be used for both storing formal arguments into Rust variables
154 /// or results of call/invoke instructions into their destinations.
155 pub fn store(&self, bcx: &BlockAndBuilder, mut val: ValueRef, dst: ValueRef) {
156 if self.is_ignore() {
160 if self.is_indirect() {
161 let llsz = llsize_of(ccx, self.ty);
162 let llalign = llalign_of_min(ccx, self.ty);
163 base::call_memcpy(bcx, dst, val, llsz, llalign as u32);
164 } else if let Some(ty) = self.cast {
165 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
166 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
167 let can_store_through_cast_ptr = false;
168 if can_store_through_cast_ptr {
169 let cast_dst = bcx.pointercast(dst, ty.ptr_to());
170 let store = bcx.store(val, cast_dst);
171 let llalign = llalign_of_min(ccx, self.ty);
173 llvm::LLVMSetAlignment(store, llalign);
176 // The actual return type is a struct, but the ABI
177 // adaptation code has cast it into some scalar type. The
178 // code that follows is the only reliable way I have
179 // found to do a transform like i64 -> {i32,i32}.
180 // Basically we dump the data onto the stack then memcpy it.
182 // Other approaches I tried:
183 // - Casting rust ret pointer to the foreign type and using Store
184 // is (a) unsafe if size of foreign type > size of rust type and
185 // (b) runs afoul of strict aliasing rules, yielding invalid
186 // assembly under -O (specifically, the store gets removed).
187 // - Truncating foreign type to correct integral type and then
188 // bitcasting to the struct type yields invalid cast errors.
190 // We instead thus allocate some scratch space...
191 let llscratch = AllocaFcx(bcx.fcx(), ty, "abi_cast");
192 base::Lifetime::Start.call(bcx, llscratch);
194 // ...where we first store the value...
195 bcx.store(val, llscratch);
197 // ...and then memcpy it to the intended destination.
198 base::call_memcpy(bcx,
199 bcx.pointercast(dst, Type::i8p(ccx)),
200 bcx.pointercast(llscratch, Type::i8p(ccx)),
201 C_uint(ccx, llsize_of_store(ccx, self.ty)),
202 cmp::min(llalign_of_min(ccx, self.ty),
203 llalign_of_min(ccx, ty)) as u32);
205 base::Lifetime::End.call(bcx, llscratch);
208 if self.original_ty == Type::i1(ccx) {
209 val = bcx.zext(val, Type::i8(ccx));
215 pub fn store_fn_arg(&self, bcx: &BlockAndBuilder, idx: &mut usize, dst: ValueRef) {
216 if self.pad.is_some() {
219 if self.is_ignore() {
222 let val = llvm::get_param(bcx.fcx().llfn, *idx as c_uint);
224 self.store(bcx, val, dst);
228 /// Metadata describing how the arguments to a native function
229 /// should be passed in order to respect the native ABI.
231 /// I will do my best to describe this structure, but these
232 /// comments are reverse-engineered and may be inaccurate. -NDM
235 /// The LLVM types of each argument.
236 pub args: Vec<ArgType>,
238 /// LLVM return type.
243 pub cconv: llvm::CallConv
247 pub fn new<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
249 sig: &ty::FnSig<'tcx>,
250 extra_args: &[Ty<'tcx>]) -> FnType {
251 let mut fn_ty = FnType::unadjusted(ccx, abi, sig, extra_args);
252 fn_ty.adjust_for_abi(ccx, abi, sig);
256 pub fn unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
258 sig: &ty::FnSig<'tcx>,
259 extra_args: &[Ty<'tcx>]) -> FnType {
261 let cconv = match ccx.sess().target.target.adjust_abi(abi) {
262 RustIntrinsic | PlatformIntrinsic |
263 Rust | RustCall => llvm::CCallConv,
265 // It's the ABI's job to select this, not us.
266 System => bug!("system abi should be selected elsewhere"),
268 Stdcall => llvm::X86StdcallCallConv,
269 Fastcall => llvm::X86FastcallCallConv,
270 Vectorcall => llvm::X86_VectorCall,
271 C => llvm::CCallConv,
272 Win64 => llvm::X86_64_Win64,
273 SysV64 => llvm::X86_64_SysV,
275 // These API constants ought to be more specific...
276 Cdecl => llvm::CCallConv,
277 Aapcs => llvm::CCallConv,
280 let mut inputs = &sig.inputs[..];
281 let extra_args = if abi == RustCall {
282 assert!(!sig.variadic && extra_args.is_empty());
284 match inputs[inputs.len() - 1].sty {
285 ty::TyTuple(ref tupled_arguments) => {
286 inputs = &inputs[..inputs.len() - 1];
287 &tupled_arguments[..]
290 bug!("argument to function with \"rust-call\" ABI \
295 assert!(sig.variadic || extra_args.is_empty());
299 let target = &ccx.sess().target.target;
300 let win_x64_gnu = target.target_os == "windows"
301 && target.arch == "x86_64"
302 && target.target_env == "gnu";
303 let rust_abi = match abi {
304 RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
308 let arg_of = |ty: Ty<'tcx>, is_return: bool| {
310 let llty = Type::i1(ccx);
311 let mut arg = ArgType::new(llty, llty);
312 arg.attrs.set(llvm::Attribute::ZExt);
315 let mut arg = ArgType::new(type_of::type_of(ccx, ty),
316 type_of::sizing_type_of(ccx, ty));
317 if ty.is_integral() {
318 arg.signedness = Some(ty.is_signed());
320 if llsize_of_real(ccx, arg.ty) == 0 {
321 // For some forsaken reason, x86_64-pc-windows-gnu
322 // doesn't ignore zero-sized struct arguments.
323 if is_return || rust_abi || !win_x64_gnu {
331 let ret_ty = sig.output;
332 let mut ret = arg_of(ret_ty, true);
334 if !type_is_fat_ptr(ccx.tcx(), ret_ty) {
335 // The `noalias` attribute on the return value is useful to a
336 // function ptr caller.
337 if let ty::TyBox(_) = ret_ty.sty {
338 // `Box` pointer return values never alias because ownership
340 ret.attrs.set(llvm::Attribute::NoAlias);
343 // We can also mark the return value as `dereferenceable` in certain cases
345 // These are not really pointers but pairs, (pointer, len)
346 ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
348 let llty = type_of::sizing_type_of(ccx, ty);
349 let llsz = llsize_of_real(ccx, llty);
350 ret.attrs.set_dereferenceable(llsz);
356 let mut args = Vec::with_capacity(inputs.len() + extra_args.len());
358 // Handle safe Rust thin and fat pointers.
359 let rust_ptr_attrs = |ty: Ty<'tcx>, arg: &mut ArgType| match ty.sty {
360 // `Box` pointer parameters never alias because ownership is transferred
361 ty::TyBox(inner) => {
362 arg.attrs.set(llvm::Attribute::NoAlias);
366 ty::TyRef(b, mt) => {
367 use rustc::ty::{BrAnon, ReLateBound};
369 // `&mut` pointer parameters never alias other parameters, or mutable global data
371 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
372 // both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
373 // on memory dependencies rather than pointer equality
374 let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
376 if mt.mutbl != hir::MutMutable && !interior_unsafe {
377 arg.attrs.set(llvm::Attribute::NoAlias);
380 if mt.mutbl == hir::MutImmutable && !interior_unsafe {
381 arg.attrs.set(llvm::Attribute::ReadOnly);
384 // When a reference in an argument has no named lifetime, it's
385 // impossible for that reference to escape this function
386 // (returned or stored beyond the call by a closure).
387 if let ReLateBound(_, BrAnon(_)) = *b {
388 arg.attrs.set(llvm::Attribute::NoCapture);
396 for ty in inputs.iter().chain(extra_args.iter()) {
397 let mut arg = arg_of(ty, false);
399 if type_is_fat_ptr(ccx.tcx(), ty) {
400 let original_tys = arg.original_ty.field_types();
401 let sizing_tys = arg.ty.field_types();
402 assert_eq!((original_tys.len(), sizing_tys.len()), (2, 2));
404 let mut data = ArgType::new(original_tys[0], sizing_tys[0]);
405 let mut info = ArgType::new(original_tys[1], sizing_tys[1]);
407 if let Some(inner) = rust_ptr_attrs(ty, &mut data) {
408 data.attrs.set(llvm::Attribute::NonNull);
409 if ccx.tcx().struct_tail(inner).is_trait() {
410 info.attrs.set(llvm::Attribute::NonNull);
416 if let Some(inner) = rust_ptr_attrs(ty, &mut arg) {
417 let llty = type_of::sizing_type_of(ccx, inner);
418 let llsz = llsize_of_real(ccx, llty);
419 arg.attrs.set_dereferenceable(llsz);
428 variadic: sig.variadic,
433 pub fn adjust_for_abi<'a, 'tcx>(&mut self,
434 ccx: &CrateContext<'a, 'tcx>,
436 sig: &ty::FnSig<'tcx>) {
437 if abi == Abi::Rust || abi == Abi::RustCall ||
438 abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
439 let fixup = |arg: &mut ArgType| {
440 let mut llty = arg.ty;
442 // Replace newtypes with their inner-most type.
443 while llty.kind() == llvm::TypeKind::Struct {
444 let inner = llty.field_types();
445 if inner.len() != 1 {
451 if !llty.is_aggregate() {
452 // Scalars and vectors, always immediate.
454 // Needs a cast as we've unpacked a newtype.
455 arg.cast = Some(llty);
460 let size = llsize_of_real(ccx, llty);
461 if size > llsize_of_real(ccx, ccx.int_type()) {
462 arg.make_indirect(ccx);
464 // We want to pass small aggregates as immediates, but using
465 // a LLVM aggregate type for this leads to bad optimizations,
466 // so we pick an appropriately sized integer type instead.
467 arg.cast = Some(Type::ix(ccx, size * 8));
470 // Fat pointers are returned by-value.
471 if !self.ret.is_ignore() {
472 if !type_is_fat_ptr(ccx.tcx(), sig.output) {
473 fixup(&mut self.ret);
476 for arg in &mut self.args {
477 if arg.is_ignore() { continue; }
480 if self.ret.is_indirect() {
481 self.ret.attrs.set(llvm::Attribute::StructRet);
486 match &ccx.sess().target.target.arch[..] {
487 "x86" => cabi_x86::compute_abi_info(ccx, self),
488 "x86_64" => if abi == Abi::SysV64 {
489 cabi_x86_64::compute_abi_info(ccx, self);
490 } else if abi == Abi::Win64 || ccx.sess().target.target.options.is_like_windows {
491 cabi_x86_win64::compute_abi_info(ccx, self);
493 cabi_x86_64::compute_abi_info(ccx, self);
495 "aarch64" => cabi_aarch64::compute_abi_info(ccx, self),
497 let flavor = if ccx.sess().target.target.target_os == "ios" {
498 cabi_arm::Flavor::Ios
500 cabi_arm::Flavor::General
502 cabi_arm::compute_abi_info(ccx, self, flavor);
504 "mips" => cabi_mips::compute_abi_info(ccx, self),
505 "mips64" => cabi_mips64::compute_abi_info(ccx, self),
506 "powerpc" => cabi_powerpc::compute_abi_info(ccx, self),
507 "powerpc64" => cabi_powerpc64::compute_abi_info(ccx, self),
508 "asmjs" => cabi_asmjs::compute_abi_info(ccx, self),
509 a => ccx.sess().fatal(&format!("unrecognized arch \"{}\" in target specification", a))
512 if self.ret.is_indirect() {
513 self.ret.attrs.set(llvm::Attribute::StructRet);
517 pub fn llvm_type(&self, ccx: &CrateContext) -> Type {
518 let mut llargument_tys = Vec::new();
520 let llreturn_ty = if self.ret.is_ignore() {
522 } else if self.ret.is_indirect() {
523 llargument_tys.push(self.ret.original_ty.ptr_to());
526 self.ret.cast.unwrap_or(self.ret.original_ty)
529 for arg in &self.args {
534 if let Some(ty) = arg.pad {
535 llargument_tys.push(ty);
538 let llarg_ty = if arg.is_indirect() {
539 arg.original_ty.ptr_to()
541 arg.cast.unwrap_or(arg.original_ty)
544 llargument_tys.push(llarg_ty);
548 Type::variadic_func(&llargument_tys, &llreturn_ty)
550 Type::func(&llargument_tys, &llreturn_ty)
554 pub fn apply_attrs_llfn(&self, llfn: ValueRef) {
555 let mut i = if self.ret.is_indirect() { 1 } else { 0 };
556 if !self.ret.is_ignore() {
557 self.ret.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
560 for arg in &self.args {
561 if !arg.is_ignore() {
562 if arg.pad.is_some() { i += 1; }
563 arg.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
569 pub fn apply_attrs_callsite(&self, callsite: ValueRef) {
570 let mut i = if self.ret.is_indirect() { 1 } else { 0 };
571 if !self.ret.is_ignore() {
572 self.ret.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
575 for arg in &self.args {
576 if !arg.is_ignore() {
577 if arg.pad.is_some() { i += 1; }
578 arg.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
583 if self.cconv != llvm::CCallConv {
584 llvm::SetInstructionCallConv(callsite, self.cconv);