]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/abi.rs
Auto merge of #55451 - estebank:arg-doc, r=pnkfelix
[rust.git] / src / librustc_codegen_llvm / 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, AttributePlace};
12 use base;
13 use builder::{Builder, MemFlags};
14 use common::C_usize;
15 use context::CodegenCx;
16 use mir::place::PlaceRef;
17 use mir::operand::OperandValue;
18 use type_::Type;
19 use type_of::{LayoutLlvmExt, PointerKind};
20 use value::Value;
21
22 use rustc_target::abi::{LayoutOf, Size, TyLayout, Abi as LayoutAbi};
23 use rustc::ty::{self, Ty};
24 use rustc::ty::layout;
25
26 use libc::c_uint;
27
28 pub use rustc_target::spec::abi::Abi;
29 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
30 pub use rustc_target::abi::call::*;
31
32 macro_rules! for_each_kind {
33     ($flags: ident, $f: ident, $($kind: ident),+) => ({
34         $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
35     })
36 }
37
38 trait ArgAttributeExt {
39     fn for_each_kind<F>(&self, f: F) where F: FnMut(llvm::Attribute);
40 }
41
42 impl ArgAttributeExt for ArgAttribute {
43     fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
44         for_each_kind!(self, f,
45                        ByVal, NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
46     }
47 }
48
49 pub trait ArgAttributesExt {
50     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value);
51     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value);
52 }
53
54 impl ArgAttributesExt for ArgAttributes {
55     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value) {
56         let mut regular = self.regular;
57         unsafe {
58             let deref = self.pointee_size.bytes();
59             if deref != 0 {
60                 if regular.contains(ArgAttribute::NonNull) {
61                     llvm::LLVMRustAddDereferenceableAttr(llfn,
62                                                          idx.as_uint(),
63                                                          deref);
64                 } else {
65                     llvm::LLVMRustAddDereferenceableOrNullAttr(llfn,
66                                                                idx.as_uint(),
67                                                                deref);
68                 }
69                 regular -= ArgAttribute::NonNull;
70             }
71             if let Some(align) = self.pointee_align {
72                 llvm::LLVMRustAddAlignmentAttr(llfn,
73                                                idx.as_uint(),
74                                                align.abi() as u32);
75             }
76             regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
77         }
78     }
79
80     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value) {
81         let mut regular = self.regular;
82         unsafe {
83             let deref = self.pointee_size.bytes();
84             if deref != 0 {
85                 if regular.contains(ArgAttribute::NonNull) {
86                     llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
87                                                                  idx.as_uint(),
88                                                                  deref);
89                 } else {
90                     llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(callsite,
91                                                                        idx.as_uint(),
92                                                                        deref);
93                 }
94                 regular -= ArgAttribute::NonNull;
95             }
96             if let Some(align) = self.pointee_align {
97                 llvm::LLVMRustAddAlignmentCallSiteAttr(callsite,
98                                                        idx.as_uint(),
99                                                        align.abi() as u32);
100             }
101             regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
102         }
103     }
104 }
105
106 pub trait LlvmType {
107     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
108 }
109
110 impl LlvmType for Reg {
111     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
112         match self.kind {
113             RegKind::Integer => Type::ix(cx, self.size.bits()),
114             RegKind::Float => {
115                 match self.size.bits() {
116                     32 => Type::f32(cx),
117                     64 => Type::f64(cx),
118                     _ => bug!("unsupported float: {:?}", self)
119                 }
120             }
121             RegKind::Vector => {
122                 Type::vector(Type::i8(cx), self.size.bytes())
123             }
124         }
125     }
126 }
127
128 impl LlvmType for CastTarget {
129     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
130         let rest_ll_unit = self.rest.unit.llvm_type(cx);
131         let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
132             (0, 0)
133         } else {
134             (self.rest.total.bytes() / self.rest.unit.size.bytes(),
135             self.rest.total.bytes() % self.rest.unit.size.bytes())
136         };
137
138         if self.prefix.iter().all(|x| x.is_none()) {
139             // Simplify to a single unit when there is no prefix and size <= unit size
140             if self.rest.total <= self.rest.unit.size {
141                 return rest_ll_unit;
142             }
143
144             // Simplify to array when all chunks are the same size and type
145             if rem_bytes == 0 {
146                 return Type::array(rest_ll_unit, rest_count);
147             }
148         }
149
150         // Create list of fields in the main structure
151         let mut args: Vec<_> =
152             self.prefix.iter().flat_map(|option_kind| option_kind.map(
153                 |kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
154             .chain((0..rest_count).map(|_| rest_ll_unit))
155             .collect();
156
157         // Append final integer
158         if rem_bytes != 0 {
159             // Only integers can be really split further.
160             assert_eq!(self.rest.unit.kind, RegKind::Integer);
161             args.push(Type::ix(cx, rem_bytes * 8));
162         }
163
164         Type::struct_(cx, &args, false)
165     }
166 }
167
168 pub trait ArgTypeExt<'ll, 'tcx> {
169     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
170     fn store(&self, bx: &Builder<'_, 'll, 'tcx>, val: &'ll Value, dst: PlaceRef<'ll, 'tcx>);
171     fn store_fn_arg(&self, bx: &Builder<'_, 'll, 'tcx>, idx: &mut usize, dst: PlaceRef<'ll, 'tcx>);
172 }
173
174 impl ArgTypeExt<'ll, 'tcx> for ArgType<'tcx, Ty<'tcx>> {
175     /// Get the LLVM type for a place of the original Rust type of
176     /// this argument/return, i.e. the result of `type_of::type_of`.
177     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
178         self.layout.llvm_type(cx)
179     }
180
181     /// Store a direct/indirect value described by this ArgType into a
182     /// place for the original Rust type of this argument/return.
183     /// Can be used for both storing formal arguments into Rust variables
184     /// or results of call/invoke instructions into their destinations.
185     fn store(&self, bx: &Builder<'_, 'll, 'tcx>, val: &'ll Value, dst: PlaceRef<'ll, 'tcx>) {
186         if self.is_ignore() {
187             return;
188         }
189         let cx = bx.cx;
190         if self.is_sized_indirect() {
191             OperandValue::Ref(val, None, self.layout.align).store(bx, dst)
192         } else if self.is_unsized_indirect() {
193             bug!("unsized ArgType must be handled through store_fn_arg");
194         } else if let PassMode::Cast(cast) = self.mode {
195             // FIXME(eddyb): Figure out when the simpler Store is safe, clang
196             // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
197             let can_store_through_cast_ptr = false;
198             if can_store_through_cast_ptr {
199                 let cast_dst = bx.pointercast(dst.llval, cast.llvm_type(cx).ptr_to());
200                 bx.store(val, cast_dst, self.layout.align);
201             } else {
202                 // The actual return type is a struct, but the ABI
203                 // adaptation code has cast it into some scalar type.  The
204                 // code that follows is the only reliable way I have
205                 // found to do a transform like i64 -> {i32,i32}.
206                 // Basically we dump the data onto the stack then memcpy it.
207                 //
208                 // Other approaches I tried:
209                 // - Casting rust ret pointer to the foreign type and using Store
210                 //   is (a) unsafe if size of foreign type > size of rust type and
211                 //   (b) runs afoul of strict aliasing rules, yielding invalid
212                 //   assembly under -O (specifically, the store gets removed).
213                 // - Truncating foreign type to correct integral type and then
214                 //   bitcasting to the struct type yields invalid cast errors.
215
216                 // We instead thus allocate some scratch space...
217                 let scratch_size = cast.size(cx);
218                 let scratch_align = cast.align(cx);
219                 let llscratch = bx.alloca(cast.llvm_type(cx), "abi_cast", scratch_align);
220                 bx.lifetime_start(llscratch, scratch_size);
221
222                 // ...where we first store the value...
223                 bx.store(val, llscratch, scratch_align);
224
225                 // ...and then memcpy it to the intended destination.
226                 base::call_memcpy(bx,
227                                   bx.pointercast(dst.llval, Type::i8p(cx)),
228                                   bx.pointercast(llscratch, Type::i8p(cx)),
229                                   C_usize(cx, self.layout.size.bytes()),
230                                   self.layout.align.min(scratch_align),
231                                   MemFlags::empty());
232
233                 bx.lifetime_end(llscratch, scratch_size);
234             }
235         } else {
236             OperandValue::Immediate(val).store(bx, dst);
237         }
238     }
239
240     fn store_fn_arg(&self, bx: &Builder<'a, 'll, 'tcx>, idx: &mut usize, dst: PlaceRef<'ll, 'tcx>) {
241         let mut next = || {
242             let val = llvm::get_param(bx.llfn(), *idx as c_uint);
243             *idx += 1;
244             val
245         };
246         match self.mode {
247             PassMode::Ignore => {},
248             PassMode::Pair(..) => {
249                 OperandValue::Pair(next(), next()).store(bx, dst);
250             }
251             PassMode::Indirect(_, Some(_)) => {
252                 OperandValue::Ref(next(), Some(next()), self.layout.align).store(bx, dst);
253             }
254             PassMode::Direct(_) | PassMode::Indirect(_, None) | PassMode::Cast(_) => {
255                 self.store(bx, next(), dst);
256             }
257         }
258     }
259 }
260
261 pub trait FnTypeExt<'tcx> {
262     fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self;
263     fn new(cx: &CodegenCx<'ll, 'tcx>,
264            sig: ty::FnSig<'tcx>,
265            extra_args: &[Ty<'tcx>]) -> Self;
266     fn new_vtable(cx: &CodegenCx<'ll, 'tcx>,
267                   sig: ty::FnSig<'tcx>,
268                   extra_args: &[Ty<'tcx>]) -> Self;
269     fn new_internal(
270         cx: &CodegenCx<'ll, 'tcx>,
271         sig: ty::FnSig<'tcx>,
272         extra_args: &[Ty<'tcx>],
273         mk_arg_type: impl Fn(Ty<'tcx>, Option<usize>) -> ArgType<'tcx, Ty<'tcx>>,
274     ) -> Self;
275     fn adjust_for_abi(&mut self,
276                       cx: &CodegenCx<'ll, 'tcx>,
277                       abi: Abi);
278     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
279     fn llvm_cconv(&self) -> llvm::CallConv;
280     fn apply_attrs_llfn(&self, llfn: &'ll Value);
281     fn apply_attrs_callsite(&self, bx: &Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
282 }
283
284 impl<'tcx> FnTypeExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
285     fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self {
286         let sig = instance.fn_sig(cx.tcx);
287         let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
288         FnType::new(cx, sig, &[])
289     }
290
291     fn new(cx: &CodegenCx<'ll, 'tcx>,
292            sig: ty::FnSig<'tcx>,
293            extra_args: &[Ty<'tcx>]) -> Self {
294         FnType::new_internal(cx, sig, extra_args, |ty, _| {
295             ArgType::new(cx.layout_of(ty))
296         })
297     }
298
299     fn new_vtable(cx: &CodegenCx<'ll, 'tcx>,
300                   sig: ty::FnSig<'tcx>,
301                   extra_args: &[Ty<'tcx>]) -> Self {
302         FnType::new_internal(cx, sig, extra_args, |ty, arg_idx| {
303             let mut layout = cx.layout_of(ty);
304             // Don't pass the vtable, it's not an argument of the virtual fn.
305             // Instead, pass just the data pointer, but give it the type `*const/mut dyn Trait`
306             // or `&/&mut dyn Trait` because this is special-cased elsewhere in codegen
307             if arg_idx == Some(0) {
308                 let fat_pointer_ty = if layout.is_unsized() {
309                     // unsized `self` is passed as a pointer to `self`
310                     // FIXME (mikeyhew) change this to use &own if it is ever added to the language
311                     cx.tcx.mk_mut_ptr(layout.ty)
312                 } else {
313                     match layout.abi {
314                         LayoutAbi::ScalarPair(..) => (),
315                         _ => bug!("receiver type has unsupported layout: {:?}", layout)
316                     }
317
318                     // In the case of Rc<Self>, we need to explicitly pass a *mut RcBox<Self>
319                     // with a Scalar (not ScalarPair) ABI. This is a hack that is understood
320                     // elsewhere in the compiler as a method on a `dyn Trait`.
321                     // To get the type `*mut RcBox<Self>`, we just keep unwrapping newtypes until we
322                     // get a built-in pointer type
323                     let mut fat_pointer_layout = layout;
324                     'descend_newtypes: while !fat_pointer_layout.ty.is_unsafe_ptr()
325                         && !fat_pointer_layout.ty.is_region_ptr()
326                     {
327                         'iter_fields: for i in 0..fat_pointer_layout.fields.count() {
328                             let field_layout = fat_pointer_layout.field(cx, i);
329
330                             if !field_layout.is_zst() {
331                                 fat_pointer_layout = field_layout;
332                                 continue 'descend_newtypes
333                             }
334                         }
335
336                         bug!("receiver has no non-zero-sized fields {:?}", fat_pointer_layout);
337                     }
338
339                     fat_pointer_layout.ty
340                 };
341
342                 // we now have a type like `*mut RcBox<dyn Trait>`
343                 // change its layout to that of `*mut ()`, a thin pointer, but keep the same type
344                 // this is understood as a special case elsewhere in the compiler
345                 let unit_pointer_ty = cx.tcx.mk_mut_ptr(cx.tcx.mk_unit());
346                 layout = cx.layout_of(unit_pointer_ty);
347                 layout.ty = fat_pointer_ty;
348             }
349             ArgType::new(layout)
350         })
351     }
352
353     fn new_internal(
354         cx: &CodegenCx<'ll, 'tcx>,
355         sig: ty::FnSig<'tcx>,
356         extra_args: &[Ty<'tcx>],
357         mk_arg_type: impl Fn(Ty<'tcx>, Option<usize>) -> ArgType<'tcx, Ty<'tcx>>,
358     ) -> Self {
359         debug!("FnType::new_internal({:?}, {:?})", sig, extra_args);
360
361         use self::Abi::*;
362         let conv = match cx.sess().target.target.adjust_abi(sig.abi) {
363             RustIntrinsic | PlatformIntrinsic |
364             Rust | RustCall => Conv::C,
365
366             // It's the ABI's job to select this, not ours.
367             System => bug!("system abi should be selected elsewhere"),
368
369             Stdcall => Conv::X86Stdcall,
370             Fastcall => Conv::X86Fastcall,
371             Vectorcall => Conv::X86VectorCall,
372             Thiscall => Conv::X86ThisCall,
373             C => Conv::C,
374             Unadjusted => Conv::C,
375             Win64 => Conv::X86_64Win64,
376             SysV64 => Conv::X86_64SysV,
377             Aapcs => Conv::ArmAapcs,
378             PtxKernel => Conv::PtxKernel,
379             Msp430Interrupt => Conv::Msp430Intr,
380             X86Interrupt => Conv::X86Intr,
381             AmdGpuKernel => Conv::AmdGpuKernel,
382
383             // These API constants ought to be more specific...
384             Cdecl => Conv::C,
385         };
386
387         let mut inputs = sig.inputs();
388         let extra_args = if sig.abi == RustCall {
389             assert!(!sig.variadic && extra_args.is_empty());
390
391             match sig.inputs().last().unwrap().sty {
392                 ty::Tuple(ref tupled_arguments) => {
393                     inputs = &sig.inputs()[0..sig.inputs().len() - 1];
394                     tupled_arguments
395                 }
396                 _ => {
397                     bug!("argument to function with \"rust-call\" ABI \
398                           is not a tuple");
399                 }
400             }
401         } else {
402             assert!(sig.variadic || extra_args.is_empty());
403             extra_args
404         };
405
406         let target = &cx.sess().target.target;
407         let win_x64_gnu = target.target_os == "windows"
408                        && target.arch == "x86_64"
409                        && target.target_env == "gnu";
410         let linux_s390x = target.target_os == "linux"
411                        && target.arch == "s390x"
412                        && target.target_env == "gnu";
413         let rust_abi = match sig.abi {
414             RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
415             _ => false
416         };
417
418         // Handle safe Rust thin and fat pointers.
419         let adjust_for_rust_scalar = |attrs: &mut ArgAttributes,
420                                       scalar: &layout::Scalar,
421                                       layout: TyLayout<'tcx, Ty<'tcx>>,
422                                       offset: Size,
423                                       is_return: bool| {
424             // Booleans are always an i1 that needs to be zero-extended.
425             if scalar.is_bool() {
426                 attrs.set(ArgAttribute::ZExt);
427                 return;
428             }
429
430             // Only pointer types handled below.
431             if scalar.value != layout::Pointer {
432                 return;
433             }
434
435             if scalar.valid_range.start() < scalar.valid_range.end() {
436                 if *scalar.valid_range.start() > 0 {
437                     attrs.set(ArgAttribute::NonNull);
438                 }
439             }
440
441             if let Some(pointee) = layout.pointee_info_at(cx, offset) {
442                 if let Some(kind) = pointee.safe {
443                     attrs.pointee_size = pointee.size;
444                     attrs.pointee_align = Some(pointee.align);
445
446                     // HACK(eddyb) LLVM inserts `llvm.assume` calls when inlining functions
447                     // with align attributes, and those calls later block optimizations.
448                     if !is_return && !cx.tcx.sess.opts.debugging_opts.arg_align_attributes {
449                         attrs.pointee_align = None;
450                     }
451
452                     // `Box` pointer parameters never alias because ownership is transferred
453                     // `&mut` pointer parameters never alias other parameters,
454                     // or mutable global data
455                     //
456                     // `&T` where `T` contains no `UnsafeCell<U>` is immutable,
457                     // and can be marked as both `readonly` and `noalias`, as
458                     // LLVM's definition of `noalias` is based solely on memory
459                     // dependencies rather than pointer equality
460                     let no_alias = match kind {
461                         PointerKind::Shared => false,
462                         PointerKind::UniqueOwned => true,
463                         PointerKind::Frozen |
464                         PointerKind::UniqueBorrowed => !is_return
465                     };
466                     if no_alias {
467                         attrs.set(ArgAttribute::NoAlias);
468                     }
469
470                     if kind == PointerKind::Frozen && !is_return {
471                         attrs.set(ArgAttribute::ReadOnly);
472                     }
473                 }
474             }
475         };
476
477         let arg_of = |ty: Ty<'tcx>, arg_idx: Option<usize>| {
478             let is_return = arg_idx.is_none();
479             let mut arg = mk_arg_type(ty, arg_idx);
480             if arg.layout.is_zst() {
481                 // For some forsaken reason, x86_64-pc-windows-gnu
482                 // doesn't ignore zero-sized struct arguments.
483                 // The same is true for s390x-unknown-linux-gnu.
484                 if is_return || rust_abi || (!win_x64_gnu && !linux_s390x) {
485                     arg.mode = PassMode::Ignore;
486                 }
487             }
488
489             // FIXME(eddyb) other ABIs don't have logic for scalar pairs.
490             if !is_return && rust_abi {
491                 if let layout::Abi::ScalarPair(ref a, ref b) = arg.layout.abi {
492                     let mut a_attrs = ArgAttributes::new();
493                     let mut b_attrs = ArgAttributes::new();
494                     adjust_for_rust_scalar(&mut a_attrs,
495                                            a,
496                                            arg.layout,
497                                            Size::ZERO,
498                                            false);
499                     adjust_for_rust_scalar(&mut b_attrs,
500                                            b,
501                                            arg.layout,
502                                            a.value.size(cx).abi_align(b.value.align(cx)),
503                                            false);
504                     arg.mode = PassMode::Pair(a_attrs, b_attrs);
505                     return arg;
506                 }
507             }
508
509             if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
510                 if let PassMode::Direct(ref mut attrs) = arg.mode {
511                     adjust_for_rust_scalar(attrs,
512                                            scalar,
513                                            arg.layout,
514                                            Size::ZERO,
515                                            is_return);
516                 }
517             }
518
519             arg
520         };
521
522         let mut fn_ty = FnType {
523             ret: arg_of(sig.output(), None),
524             args: inputs.iter().chain(extra_args).enumerate().map(|(i, ty)| {
525                 arg_of(ty, Some(i))
526             }).collect(),
527             variadic: sig.variadic,
528             conv,
529         };
530         fn_ty.adjust_for_abi(cx, sig.abi);
531         fn_ty
532     }
533
534     fn adjust_for_abi(&mut self,
535                       cx: &CodegenCx<'ll, 'tcx>,
536                       abi: Abi) {
537         if abi == Abi::Unadjusted { return }
538
539         if abi == Abi::Rust || abi == Abi::RustCall ||
540            abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
541             let fixup = |arg: &mut ArgType<'tcx, Ty<'tcx>>| {
542                 if arg.is_ignore() { return; }
543
544                 match arg.layout.abi {
545                     layout::Abi::Aggregate { .. } => {}
546
547                     // This is a fun case! The gist of what this is doing is
548                     // that we want callers and callees to always agree on the
549                     // ABI of how they pass SIMD arguments. If we were to *not*
550                     // make these arguments indirect then they'd be immediates
551                     // in LLVM, which means that they'd used whatever the
552                     // appropriate ABI is for the callee and the caller. That
553                     // means, for example, if the caller doesn't have AVX
554                     // enabled but the callee does, then passing an AVX argument
555                     // across this boundary would cause corrupt data to show up.
556                     //
557                     // This problem is fixed by unconditionally passing SIMD
558                     // arguments through memory between callers and callees
559                     // which should get them all to agree on ABI regardless of
560                     // target feature sets. Some more information about this
561                     // issue can be found in #44367.
562                     //
563                     // Note that the platform intrinsic ABI is exempt here as
564                     // that's how we connect up to LLVM and it's unstable
565                     // anyway, we control all calls to it in libstd.
566                     layout::Abi::Vector { .. }
567                         if abi != Abi::PlatformIntrinsic &&
568                             cx.sess().target.target.options.simd_types_indirect =>
569                     {
570                         arg.make_indirect();
571                         return
572                     }
573
574                     _ => return
575                 }
576
577                 let size = arg.layout.size;
578                 if arg.layout.is_unsized() || size > layout::Pointer.size(cx) {
579                     arg.make_indirect();
580                 } else {
581                     // We want to pass small aggregates as immediates, but using
582                     // a LLVM aggregate type for this leads to bad optimizations,
583                     // so we pick an appropriately sized integer type instead.
584                     arg.cast_to(Reg {
585                         kind: RegKind::Integer,
586                         size
587                     });
588                 }
589             };
590             fixup(&mut self.ret);
591             for arg in &mut self.args {
592                 fixup(arg);
593             }
594             if let PassMode::Indirect(ref mut attrs, _) = self.ret.mode {
595                 attrs.set(ArgAttribute::StructRet);
596             }
597             return;
598         }
599
600         if let Err(msg) = self.adjust_for_cabi(cx, abi) {
601             cx.sess().fatal(&msg);
602         }
603     }
604
605     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
606         let args_capacity: usize = self.args.iter().map(|arg|
607             if arg.pad.is_some() { 1 } else { 0 } +
608             if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
609         ).sum();
610         let mut llargument_tys = Vec::with_capacity(
611             if let PassMode::Indirect(..) = self.ret.mode { 1 } else { 0 } + args_capacity
612         );
613
614         let llreturn_ty = match self.ret.mode {
615             PassMode::Ignore => Type::void(cx),
616             PassMode::Direct(_) | PassMode::Pair(..) => {
617                 self.ret.layout.immediate_llvm_type(cx)
618             }
619             PassMode::Cast(cast) => cast.llvm_type(cx),
620             PassMode::Indirect(..) => {
621                 llargument_tys.push(self.ret.memory_ty(cx).ptr_to());
622                 Type::void(cx)
623             }
624         };
625
626         for arg in &self.args {
627             // add padding
628             if let Some(ty) = arg.pad {
629                 llargument_tys.push(ty.llvm_type(cx));
630             }
631
632             let llarg_ty = match arg.mode {
633                 PassMode::Ignore => continue,
634                 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
635                 PassMode::Pair(..) => {
636                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
637                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
638                     continue;
639                 }
640                 PassMode::Indirect(_, Some(_)) => {
641                     let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
642                     let ptr_layout = cx.layout_of(ptr_ty);
643                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
644                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
645                     continue;
646                 }
647                 PassMode::Cast(cast) => cast.llvm_type(cx),
648                 PassMode::Indirect(_, None) => arg.memory_ty(cx).ptr_to(),
649             };
650             llargument_tys.push(llarg_ty);
651         }
652
653         if self.variadic {
654             Type::variadic_func(&llargument_tys, llreturn_ty)
655         } else {
656             Type::func(&llargument_tys, llreturn_ty)
657         }
658     }
659
660     fn llvm_cconv(&self) -> llvm::CallConv {
661         match self.conv {
662             Conv::C => llvm::CCallConv,
663             Conv::AmdGpuKernel => llvm::AmdGpuKernel,
664             Conv::ArmAapcs => llvm::ArmAapcsCallConv,
665             Conv::Msp430Intr => llvm::Msp430Intr,
666             Conv::PtxKernel => llvm::PtxKernel,
667             Conv::X86Fastcall => llvm::X86FastcallCallConv,
668             Conv::X86Intr => llvm::X86_Intr,
669             Conv::X86Stdcall => llvm::X86StdcallCallConv,
670             Conv::X86ThisCall => llvm::X86_ThisCall,
671             Conv::X86VectorCall => llvm::X86_VectorCall,
672             Conv::X86_64SysV => llvm::X86_64_SysV,
673             Conv::X86_64Win64 => llvm::X86_64_Win64,
674         }
675     }
676
677     fn apply_attrs_llfn(&self, llfn: &'ll Value) {
678         let mut i = 0;
679         let mut apply = |attrs: &ArgAttributes| {
680             attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
681             i += 1;
682         };
683         match self.ret.mode {
684             PassMode::Direct(ref attrs) => {
685                 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
686             }
687             PassMode::Indirect(ref attrs, _) => apply(attrs),
688             _ => {}
689         }
690         for arg in &self.args {
691             if arg.pad.is_some() {
692                 apply(&ArgAttributes::new());
693             }
694             match arg.mode {
695                 PassMode::Ignore => {}
696                 PassMode::Direct(ref attrs) |
697                 PassMode::Indirect(ref attrs, None) => apply(attrs),
698                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
699                     apply(attrs);
700                     apply(extra_attrs);
701                 }
702                 PassMode::Pair(ref a, ref b) => {
703                     apply(a);
704                     apply(b);
705                 }
706                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
707             }
708         }
709     }
710
711     fn apply_attrs_callsite(&self, bx: &Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
712         let mut i = 0;
713         let mut apply = |attrs: &ArgAttributes| {
714             attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
715             i += 1;
716         };
717         match self.ret.mode {
718             PassMode::Direct(ref attrs) => {
719                 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite);
720             }
721             PassMode::Indirect(ref attrs, _) => apply(attrs),
722             _ => {}
723         }
724         if let layout::Abi::Scalar(ref scalar) = self.ret.layout.abi {
725             // If the value is a boolean, the range is 0..2 and that ultimately
726             // become 0..0 when the type becomes i1, which would be rejected
727             // by the LLVM verifier.
728             if let layout::Int(..) = scalar.value {
729                 if !scalar.is_bool() {
730                     let range = scalar.valid_range_exclusive(bx.cx);
731                     if range.start != range.end {
732                         bx.range_metadata(callsite, range);
733                     }
734                 }
735             }
736         }
737         for arg in &self.args {
738             if arg.pad.is_some() {
739                 apply(&ArgAttributes::new());
740             }
741             match arg.mode {
742                 PassMode::Ignore => {}
743                 PassMode::Direct(ref attrs) |
744                 PassMode::Indirect(ref attrs, None) => apply(attrs),
745                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
746                     apply(attrs);
747                     apply(extra_attrs);
748                 }
749                 PassMode::Pair(ref a, ref b) => {
750                     apply(a);
751                     apply(b);
752                 }
753                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
754             }
755         }
756
757         let cconv = self.llvm_cconv();
758         if cconv != llvm::CCallConv {
759             llvm::SetInstructionCallConv(callsite, cconv);
760         }
761     }
762 }