]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/abi.rs
Auto merge of #35856 - phimuemue:master, r=brson
[rust.git] / src / librustc_trans / abi.rs
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.
4 //
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.
10
11 use llvm::{self, ValueRef};
12 use base;
13 use build::AllocaFcx;
14 use common::{type_is_fat_ptr, BlockAndBuilder, C_uint};
15 use context::CrateContext;
16 use cabi_x86;
17 use cabi_x86_64;
18 use cabi_x86_win64;
19 use cabi_arm;
20 use cabi_aarch64;
21 use cabi_powerpc;
22 use cabi_powerpc64;
23 use cabi_mips;
24 use cabi_mips64;
25 use cabi_asmjs;
26 use machine::{llalign_of_min, llsize_of, llsize_of_real, llsize_of_store};
27 use type_::Type;
28 use type_of;
29
30 use rustc::hir;
31 use rustc::ty::{self, Ty};
32
33 use libc::c_uint;
34 use std::cmp;
35
36 pub use syntax::abi::Abi;
37 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
38
39 #[derive(Clone, Copy, PartialEq, Debug)]
40 enum ArgKind {
41     /// Pass the argument directly using the normal converted
42     /// LLVM type or by coercing to another specified type
43     Direct,
44     /// Pass the argument indirectly via a hidden pointer
45     Indirect,
46     /// Ignore the argument (useful for empty struct)
47     Ignore,
48 }
49
50 /// Information about how a specific C type
51 /// should be passed to or returned from a function
52 ///
53 /// This is borrowed from clang's ABIInfo.h
54 #[derive(Clone, Copy, Debug)]
55 pub struct ArgType {
56     kind: ArgKind,
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.
61     ///
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.
73     pub ty: Type,
74     /// Signedness for integer types, None for other types
75     pub signedness: Option<bool>,
76     /// Coerced LLVM Type
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
82 }
83
84 impl ArgType {
85     fn new(original_ty: Type, ty: Type) -> ArgType {
86         ArgType {
87             kind: ArgKind::Direct,
88             original_ty: original_ty,
89             ty: ty,
90             signedness: None,
91             cast: None,
92             pad: None,
93             attrs: llvm::Attributes::default()
94         }
95     }
96
97     pub fn make_indirect(&mut self, ccx: &CrateContext) {
98         assert_eq!(self.kind, ArgKind::Direct);
99
100         // Wipe old attributes, likely not valid through indirection.
101         self.attrs = llvm::Attributes::default();
102
103         let llarg_sz = llsize_of_real(ccx, self.ty);
104
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);
111
112         self.kind = ArgKind::Indirect;
113     }
114
115     pub fn ignore(&mut self) {
116         assert_eq!(self.kind, ArgKind::Direct);
117         self.kind = ArgKind::Ignore;
118     }
119
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
126                 } else {
127                     llvm::Attribute::ZExt
128                 });
129             }
130         }
131     }
132
133     pub fn is_indirect(&self) -> bool {
134         self.kind == ArgKind::Indirect
135     }
136
137     pub fn is_ignore(&self) -> bool {
138         self.kind == ArgKind::Ignore
139     }
140
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) {
145             Type::i8(ccx)
146         } else {
147             self.original_ty
148         }
149     }
150
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() {
157             return;
158         }
159         let ccx = bcx.ccx();
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);
172                 unsafe {
173                     llvm::LLVMSetAlignment(store, llalign);
174                 }
175             } else {
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.
181                 //
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.
189
190                 // We instead thus allocate some scratch space...
191                 let llscratch = AllocaFcx(bcx.fcx(), ty, "abi_cast");
192                 base::Lifetime::Start.call(bcx, llscratch);
193
194                 // ...where we first store the value...
195                 bcx.store(val, llscratch);
196
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);
204
205                 base::Lifetime::End.call(bcx, llscratch);
206             }
207         } else {
208             if self.original_ty == Type::i1(ccx) {
209                 val = bcx.zext(val, Type::i8(ccx));
210             }
211             bcx.store(val, dst);
212         }
213     }
214
215     pub fn store_fn_arg(&self, bcx: &BlockAndBuilder, idx: &mut usize, dst: ValueRef) {
216         if self.pad.is_some() {
217             *idx += 1;
218         }
219         if self.is_ignore() {
220             return;
221         }
222         let val = llvm::get_param(bcx.fcx().llfn, *idx as c_uint);
223         *idx += 1;
224         self.store(bcx, val, dst);
225     }
226 }
227
228 /// Metadata describing how the arguments to a native function
229 /// should be passed in order to respect the native ABI.
230 ///
231 /// I will do my best to describe this structure, but these
232 /// comments are reverse-engineered and may be inaccurate. -NDM
233 #[derive(Clone)]
234 pub struct FnType {
235     /// The LLVM types of each argument.
236     pub args: Vec<ArgType>,
237
238     /// LLVM return type.
239     pub ret: ArgType,
240
241     pub variadic: bool,
242
243     pub cconv: llvm::CallConv
244 }
245
246 impl FnType {
247     pub fn new<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
248                          abi: Abi,
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);
253         fn_ty
254     }
255
256     pub fn unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
257                                 abi: Abi,
258                                 sig: &ty::FnSig<'tcx>,
259                                 extra_args: &[Ty<'tcx>]) -> FnType {
260         use self::Abi::*;
261         let cconv = match ccx.sess().target.target.adjust_abi(abi) {
262             RustIntrinsic | PlatformIntrinsic |
263             Rust | RustCall => llvm::CCallConv,
264
265             // It's the ABI's job to select this, not us.
266             System => bug!("system abi should be selected elsewhere"),
267
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,
274
275             // These API constants ought to be more specific...
276             Cdecl => llvm::CCallConv,
277             Aapcs => llvm::CCallConv,
278         };
279
280         let mut inputs = &sig.inputs[..];
281         let extra_args = if abi == RustCall {
282             assert!(!sig.variadic && extra_args.is_empty());
283
284             match inputs[inputs.len() - 1].sty {
285                 ty::TyTuple(ref tupled_arguments) => {
286                     inputs = &inputs[..inputs.len() - 1];
287                     &tupled_arguments[..]
288                 }
289                 _ => {
290                     bug!("argument to function with \"rust-call\" ABI \
291                           is not a tuple");
292                 }
293             }
294         } else {
295             assert!(sig.variadic || extra_args.is_empty());
296             extra_args
297         };
298
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,
305             _ => false
306         };
307
308         let arg_of = |ty: Ty<'tcx>, is_return: bool| {
309             if ty.is_bool() {
310                 let llty = Type::i1(ccx);
311                 let mut arg = ArgType::new(llty, llty);
312                 arg.attrs.set(llvm::Attribute::ZExt);
313                 arg
314             } else {
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());
319                 }
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 {
324                         arg.ignore();
325                     }
326                 }
327                 arg
328             }
329         };
330
331         let ret_ty = sig.output;
332         let mut ret = arg_of(ret_ty, true);
333
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
339                 // is transferred
340                 ret.attrs.set(llvm::Attribute::NoAlias);
341             }
342
343             // We can also mark the return value as `dereferenceable` in certain cases
344             match ret_ty.sty {
345                 // These are not really pointers but pairs, (pointer, len)
346                 ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
347                 ty::TyBox(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);
351                 }
352                 _ => {}
353             }
354         }
355
356         let mut args = Vec::with_capacity(inputs.len() + extra_args.len());
357
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);
363                 Some(inner)
364             }
365
366             ty::TyRef(b, mt) => {
367                 use rustc::ty::{BrAnon, ReLateBound};
368
369                 // `&mut` pointer parameters never alias other parameters, or mutable global data
370                 //
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();
375
376                 if mt.mutbl != hir::MutMutable && !interior_unsafe {
377                     arg.attrs.set(llvm::Attribute::NoAlias);
378                 }
379
380                 if mt.mutbl == hir::MutImmutable && !interior_unsafe {
381                     arg.attrs.set(llvm::Attribute::ReadOnly);
382                 }
383
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);
389                 }
390
391                 Some(mt.ty)
392             }
393             _ => None
394         };
395
396         for ty in inputs.iter().chain(extra_args.iter()) {
397             let mut arg = arg_of(ty, false);
398
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));
403
404                 let mut data = ArgType::new(original_tys[0], sizing_tys[0]);
405                 let mut info = ArgType::new(original_tys[1], sizing_tys[1]);
406
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);
411                     }
412                 }
413                 args.push(data);
414                 args.push(info);
415             } else {
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);
420                 }
421                 args.push(arg);
422             }
423         }
424
425         FnType {
426             args: args,
427             ret: ret,
428             variadic: sig.variadic,
429             cconv: cconv
430         }
431     }
432
433     pub fn adjust_for_abi<'a, 'tcx>(&mut self,
434                                     ccx: &CrateContext<'a, 'tcx>,
435                                     abi: Abi,
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;
441
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 {
446                         break;
447                     }
448                     llty = inner[0];
449                 }
450
451                 if !llty.is_aggregate() {
452                     // Scalars and vectors, always immediate.
453                     if llty != arg.ty {
454                         // Needs a cast as we've unpacked a newtype.
455                         arg.cast = Some(llty);
456                     }
457                     return;
458                 }
459
460                 let size = llsize_of_real(ccx, llty);
461                 if size > llsize_of_real(ccx, ccx.int_type()) {
462                     arg.make_indirect(ccx);
463                 } else if size > 0 {
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));
468                 }
469             };
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);
474                 }
475             }
476             for arg in &mut self.args {
477                 if arg.is_ignore() { continue; }
478                 fixup(arg);
479             }
480             if self.ret.is_indirect() {
481                 self.ret.attrs.set(llvm::Attribute::StructRet);
482             }
483             return;
484         }
485
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);
492             } else {
493                 cabi_x86_64::compute_abi_info(ccx, self);
494             },
495             "aarch64" => cabi_aarch64::compute_abi_info(ccx, self),
496             "arm" => {
497                 let flavor = if ccx.sess().target.target.target_os == "ios" {
498                     cabi_arm::Flavor::Ios
499                 } else {
500                     cabi_arm::Flavor::General
501                 };
502                 cabi_arm::compute_abi_info(ccx, self, flavor);
503             },
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))
510         }
511
512         if self.ret.is_indirect() {
513             self.ret.attrs.set(llvm::Attribute::StructRet);
514         }
515     }
516
517     pub fn llvm_type(&self, ccx: &CrateContext) -> Type {
518         let mut llargument_tys = Vec::new();
519
520         let llreturn_ty = if self.ret.is_ignore() {
521             Type::void(ccx)
522         } else if self.ret.is_indirect() {
523             llargument_tys.push(self.ret.original_ty.ptr_to());
524             Type::void(ccx)
525         } else {
526             self.ret.cast.unwrap_or(self.ret.original_ty)
527         };
528
529         for arg in &self.args {
530             if arg.is_ignore() {
531                 continue;
532             }
533             // add padding
534             if let Some(ty) = arg.pad {
535                 llargument_tys.push(ty);
536             }
537
538             let llarg_ty = if arg.is_indirect() {
539                 arg.original_ty.ptr_to()
540             } else {
541                 arg.cast.unwrap_or(arg.original_ty)
542             };
543
544             llargument_tys.push(llarg_ty);
545         }
546
547         if self.variadic {
548             Type::variadic_func(&llargument_tys, &llreturn_ty)
549         } else {
550             Type::func(&llargument_tys, &llreturn_ty)
551         }
552     }
553
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);
558         }
559         i += 1;
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);
564                 i += 1;
565             }
566         }
567     }
568
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);
573         }
574         i += 1;
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);
579                 i += 1;
580             }
581         }
582
583         if self.cconv != llvm::CCallConv {
584             llvm::SetInstructionCallConv(callsite, self.cconv);
585         }
586     }
587 }