]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/abi.rs
Auto merge of #61300 - indygreg:upgrade-cross-make, r=sanxiyn
[rust.git] / src / librustc_codegen_llvm / abi.rs
1 use crate::llvm::{self, AttributePlace};
2 use crate::builder::Builder;
3 use crate::context::CodegenCx;
4 use crate::type_::Type;
5 use crate::value::Value;
6 use crate::type_of::{LayoutLlvmExt};
7 use rustc_codegen_ssa::MemFlags;
8 use rustc_codegen_ssa::mir::place::PlaceRef;
9 use rustc_codegen_ssa::mir::operand::OperandValue;
10 use rustc_target::abi::call::ArgType;
11
12 use rustc_codegen_ssa::traits::*;
13
14 use rustc_target::abi::{HasDataLayout, LayoutOf};
15 use rustc::ty::{Ty};
16 use rustc::ty::layout::{self};
17
18 use libc::c_uint;
19
20 pub use rustc_target::spec::abi::Abi;
21 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
22 pub use rustc_target::abi::call::*;
23
24 macro_rules! for_each_kind {
25     ($flags: ident, $f: ident, $($kind: ident),+) => ({
26         $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
27     })
28 }
29
30 trait ArgAttributeExt {
31     fn for_each_kind<F>(&self, f: F) where F: FnMut(llvm::Attribute);
32 }
33
34 impl ArgAttributeExt for ArgAttribute {
35     fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
36         for_each_kind!(self, f,
37                        ByVal, NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
38     }
39 }
40
41 pub trait ArgAttributesExt {
42     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value);
43     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value);
44 }
45
46 impl ArgAttributesExt for ArgAttributes {
47     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value) {
48         let mut regular = self.regular;
49         unsafe {
50             let deref = self.pointee_size.bytes();
51             if deref != 0 {
52                 if regular.contains(ArgAttribute::NonNull) {
53                     llvm::LLVMRustAddDereferenceableAttr(llfn,
54                                                          idx.as_uint(),
55                                                          deref);
56                 } else {
57                     llvm::LLVMRustAddDereferenceableOrNullAttr(llfn,
58                                                                idx.as_uint(),
59                                                                deref);
60                 }
61                 regular -= ArgAttribute::NonNull;
62             }
63             if let Some(align) = self.pointee_align {
64                 llvm::LLVMRustAddAlignmentAttr(llfn,
65                                                idx.as_uint(),
66                                                align.bytes() as u32);
67             }
68             regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
69         }
70     }
71
72     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value) {
73         let mut regular = self.regular;
74         unsafe {
75             let deref = self.pointee_size.bytes();
76             if deref != 0 {
77                 if regular.contains(ArgAttribute::NonNull) {
78                     llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
79                                                                  idx.as_uint(),
80                                                                  deref);
81                 } else {
82                     llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(callsite,
83                                                                        idx.as_uint(),
84                                                                        deref);
85                 }
86                 regular -= ArgAttribute::NonNull;
87             }
88             if let Some(align) = self.pointee_align {
89                 llvm::LLVMRustAddAlignmentCallSiteAttr(callsite,
90                                                        idx.as_uint(),
91                                                        align.bytes() as u32);
92             }
93             regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
94         }
95     }
96 }
97
98 pub trait LlvmType {
99     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
100 }
101
102 impl LlvmType for Reg {
103     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
104         match self.kind {
105             RegKind::Integer => cx.type_ix(self.size.bits()),
106             RegKind::Float => {
107                 match self.size.bits() {
108                     32 => cx.type_f32(),
109                     64 => cx.type_f64(),
110                     _ => bug!("unsupported float: {:?}", self)
111                 }
112             }
113             RegKind::Vector => {
114                 cx.type_vector(cx.type_i8(), self.size.bytes())
115             }
116         }
117     }
118 }
119
120 impl LlvmType for CastTarget {
121     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
122         let rest_ll_unit = self.rest.unit.llvm_type(cx);
123         let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
124             (0, 0)
125         } else {
126             (self.rest.total.bytes() / self.rest.unit.size.bytes(),
127             self.rest.total.bytes() % self.rest.unit.size.bytes())
128         };
129
130         if self.prefix.iter().all(|x| x.is_none()) {
131             // Simplify to a single unit when there is no prefix and size <= unit size
132             if self.rest.total <= self.rest.unit.size {
133                 return rest_ll_unit;
134             }
135
136             // Simplify to array when all chunks are the same size and type
137             if rem_bytes == 0 {
138                 return cx.type_array(rest_ll_unit, rest_count);
139             }
140         }
141
142         // Create list of fields in the main structure
143         let mut args: Vec<_> =
144             self.prefix.iter().flat_map(|option_kind| option_kind.map(
145                 |kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
146             .chain((0..rest_count).map(|_| rest_ll_unit))
147             .collect();
148
149         // Append final integer
150         if rem_bytes != 0 {
151             // Only integers can be really split further.
152             assert_eq!(self.rest.unit.kind, RegKind::Integer);
153             args.push(cx.type_ix(rem_bytes * 8));
154         }
155
156         cx.type_struct(&args, false)
157     }
158 }
159
160 pub trait ArgTypeExt<'ll, 'tcx> {
161     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
162     fn store(
163         &self,
164         bx: &mut Builder<'_, 'll, 'tcx>,
165         val: &'ll Value,
166         dst: PlaceRef<'tcx, &'ll Value>,
167     );
168     fn store_fn_arg(
169         &self,
170         bx: &mut Builder<'_, 'll, 'tcx>,
171         idx: &mut usize,
172         dst: PlaceRef<'tcx, &'ll Value>,
173     );
174 }
175
176 impl ArgTypeExt<'ll, 'tcx> for ArgType<'tcx, Ty<'tcx>> {
177     /// Gets the LLVM type for a place of the original Rust type of
178     /// this argument/return, i.e., the result of `type_of::type_of`.
179     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
180         self.layout.llvm_type(cx)
181     }
182
183     /// Stores a direct/indirect value described by this ArgType into a
184     /// place for the original Rust type of this argument/return.
185     /// Can be used for both storing formal arguments into Rust variables
186     /// or results of call/invoke instructions into their destinations.
187     fn store(
188         &self,
189         bx: &mut Builder<'_, 'll, 'tcx>,
190         val: &'ll Value,
191         dst: PlaceRef<'tcx, &'ll Value>,
192     ) {
193         if self.is_ignore() {
194             return;
195         }
196         if self.is_sized_indirect() {
197             OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
198         } else if self.is_unsized_indirect() {
199             bug!("unsized ArgType must be handled through store_fn_arg");
200         } else if let PassMode::Cast(cast) = self.mode {
201             // FIXME(eddyb): Figure out when the simpler Store is safe, clang
202             // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
203             let can_store_through_cast_ptr = false;
204             if can_store_through_cast_ptr {
205                 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
206                 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
207                 bx.store(val, cast_dst, self.layout.align.abi);
208             } else {
209                 // The actual return type is a struct, but the ABI
210                 // adaptation code has cast it into some scalar type.  The
211                 // code that follows is the only reliable way I have
212                 // found to do a transform like i64 -> {i32,i32}.
213                 // Basically we dump the data onto the stack then memcpy it.
214                 //
215                 // Other approaches I tried:
216                 // - Casting rust ret pointer to the foreign type and using Store
217                 //   is (a) unsafe if size of foreign type > size of rust type and
218                 //   (b) runs afoul of strict aliasing rules, yielding invalid
219                 //   assembly under -O (specifically, the store gets removed).
220                 // - Truncating foreign type to correct integral type and then
221                 //   bitcasting to the struct type yields invalid cast errors.
222
223                 // We instead thus allocate some scratch space...
224                 let scratch_size = cast.size(bx);
225                 let scratch_align = cast.align(bx);
226                 let llscratch = bx.alloca(cast.llvm_type(bx), "abi_cast", scratch_align);
227                 bx.lifetime_start(llscratch, scratch_size);
228
229                 // ...where we first store the value...
230                 bx.store(val, llscratch, scratch_align);
231
232                 // ...and then memcpy it to the intended destination.
233                 bx.memcpy(
234                     dst.llval,
235                     self.layout.align.abi,
236                     llscratch,
237                     scratch_align,
238                     bx.const_usize(self.layout.size.bytes()),
239                     MemFlags::empty()
240                 );
241
242                 bx.lifetime_end(llscratch, scratch_size);
243             }
244         } else {
245             OperandValue::Immediate(val).store(bx, dst);
246         }
247     }
248
249     fn store_fn_arg(
250         &self,
251         bx: &mut Builder<'a, 'll, 'tcx>,
252         idx: &mut usize,
253         dst: PlaceRef<'tcx, &'ll Value>,
254     ) {
255         let mut next = || {
256             let val = llvm::get_param(bx.llfn(), *idx as c_uint);
257             *idx += 1;
258             val
259         };
260         match self.mode {
261             PassMode::Ignore(_) => {}
262             PassMode::Pair(..) => {
263                 OperandValue::Pair(next(), next()).store(bx, dst);
264             }
265             PassMode::Indirect(_, Some(_)) => {
266                 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
267             }
268             PassMode::Direct(_) | PassMode::Indirect(_, None) | PassMode::Cast(_) => {
269                 let next_arg = next();
270                 self.store(bx, next_arg, dst);
271             }
272         }
273     }
274 }
275
276 impl ArgTypeMethods<'tcx> for Builder<'a, 'll, 'tcx> {
277     fn store_fn_arg(
278         &mut self,
279         ty: &ArgType<'tcx, Ty<'tcx>>,
280         idx: &mut usize, dst: PlaceRef<'tcx, Self::Value>
281     ) {
282         ty.store_fn_arg(self, idx, dst)
283     }
284     fn store_arg_ty(
285         &mut self,
286         ty: &ArgType<'tcx, Ty<'tcx>>,
287         val: &'ll Value,
288         dst: PlaceRef<'tcx, &'ll Value>
289     ) {
290         ty.store(self, val, dst)
291     }
292     fn memory_ty(&self, ty: &ArgType<'tcx, Ty<'tcx>>) -> &'ll Type {
293         ty.memory_ty(self)
294     }
295 }
296
297 pub trait FnTypeLlvmExt<'tcx> {
298     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
299     fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
300     fn llvm_cconv(&self) -> llvm::CallConv;
301     fn apply_attrs_llfn(&self, llfn: &'ll Value);
302     fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
303 }
304
305 impl<'tcx> FnTypeLlvmExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
306     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
307         let args_capacity: usize = self.args.iter().map(|arg|
308             if arg.pad.is_some() { 1 } else { 0 } +
309             if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
310         ).sum();
311         let mut llargument_tys = Vec::with_capacity(
312             if let PassMode::Indirect(..) = self.ret.mode { 1 } else { 0 } + args_capacity
313         );
314
315         let llreturn_ty = match self.ret.mode {
316             PassMode::Ignore(IgnoreMode::Zst) => cx.type_void(),
317             PassMode::Ignore(IgnoreMode::CVarArgs) =>
318                 bug!("`va_list` should never be a return type"),
319             PassMode::Direct(_) | PassMode::Pair(..) => {
320                 self.ret.layout.immediate_llvm_type(cx)
321             }
322             PassMode::Cast(cast) => cast.llvm_type(cx),
323             PassMode::Indirect(..) => {
324                 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
325                 cx.type_void()
326             }
327         };
328
329         for arg in &self.args {
330             // add padding
331             if let Some(ty) = arg.pad {
332                 llargument_tys.push(ty.llvm_type(cx));
333             }
334
335             let llarg_ty = match arg.mode {
336                 PassMode::Ignore(_) => continue,
337                 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
338                 PassMode::Pair(..) => {
339                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
340                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
341                     continue;
342                 }
343                 PassMode::Indirect(_, Some(_)) => {
344                     let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
345                     let ptr_layout = cx.layout_of(ptr_ty);
346                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
347                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
348                     continue;
349                 }
350                 PassMode::Cast(cast) => cast.llvm_type(cx),
351                 PassMode::Indirect(_, None) => cx.type_ptr_to(arg.memory_ty(cx)),
352             };
353             llargument_tys.push(llarg_ty);
354         }
355
356         if self.c_variadic {
357             cx.type_variadic_func(&llargument_tys, llreturn_ty)
358         } else {
359             cx.type_func(&llargument_tys, llreturn_ty)
360         }
361     }
362
363     fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
364         unsafe {
365             llvm::LLVMPointerType(self.llvm_type(cx),
366                                   cx.data_layout().instruction_address_space as c_uint)
367         }
368     }
369
370     fn llvm_cconv(&self) -> llvm::CallConv {
371         match self.conv {
372             Conv::C => llvm::CCallConv,
373             Conv::AmdGpuKernel => llvm::AmdGpuKernel,
374             Conv::ArmAapcs => llvm::ArmAapcsCallConv,
375             Conv::Msp430Intr => llvm::Msp430Intr,
376             Conv::PtxKernel => llvm::PtxKernel,
377             Conv::X86Fastcall => llvm::X86FastcallCallConv,
378             Conv::X86Intr => llvm::X86_Intr,
379             Conv::X86Stdcall => llvm::X86StdcallCallConv,
380             Conv::X86ThisCall => llvm::X86_ThisCall,
381             Conv::X86VectorCall => llvm::X86_VectorCall,
382             Conv::X86_64SysV => llvm::X86_64_SysV,
383             Conv::X86_64Win64 => llvm::X86_64_Win64,
384         }
385     }
386
387     fn apply_attrs_llfn(&self, llfn: &'ll Value) {
388         let mut i = 0;
389         let mut apply = |attrs: &ArgAttributes| {
390             attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
391             i += 1;
392         };
393         match self.ret.mode {
394             PassMode::Direct(ref attrs) => {
395                 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
396             }
397             PassMode::Indirect(ref attrs, _) => apply(attrs),
398             _ => {}
399         }
400         for arg in &self.args {
401             if arg.pad.is_some() {
402                 apply(&ArgAttributes::new());
403             }
404             match arg.mode {
405                 PassMode::Ignore(_) => {}
406                 PassMode::Direct(ref attrs) |
407                 PassMode::Indirect(ref attrs, None) => apply(attrs),
408                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
409                     apply(attrs);
410                     apply(extra_attrs);
411                 }
412                 PassMode::Pair(ref a, ref b) => {
413                     apply(a);
414                     apply(b);
415                 }
416                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
417             }
418         }
419     }
420
421     fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
422         let mut i = 0;
423         let mut apply = |attrs: &ArgAttributes| {
424             attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
425             i += 1;
426         };
427         match self.ret.mode {
428             PassMode::Direct(ref attrs) => {
429                 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite);
430             }
431             PassMode::Indirect(ref attrs, _) => apply(attrs),
432             _ => {}
433         }
434         if let layout::Abi::Scalar(ref scalar) = self.ret.layout.abi {
435             // If the value is a boolean, the range is 0..2 and that ultimately
436             // become 0..0 when the type becomes i1, which would be rejected
437             // by the LLVM verifier.
438             if let layout::Int(..) = scalar.value {
439                 if !scalar.is_bool() {
440                     let range = scalar.valid_range_exclusive(bx);
441                     if range.start != range.end {
442                         bx.range_metadata(callsite, range);
443                     }
444                 }
445             }
446         }
447         for arg in &self.args {
448             if arg.pad.is_some() {
449                 apply(&ArgAttributes::new());
450             }
451             match arg.mode {
452                 PassMode::Ignore(_) => {}
453                 PassMode::Direct(ref attrs) |
454                 PassMode::Indirect(ref attrs, None) => apply(attrs),
455                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
456                     apply(attrs);
457                     apply(extra_attrs);
458                 }
459                 PassMode::Pair(ref a, ref b) => {
460                     apply(a);
461                     apply(b);
462                 }
463                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
464             }
465         }
466
467         let cconv = self.llvm_cconv();
468         if cconv != llvm::CCallConv {
469             llvm::SetInstructionCallConv(callsite, cconv);
470         }
471     }
472 }
473
474 impl AbiBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
475     fn apply_attrs_callsite(
476         &mut self,
477         ty: &FnType<'tcx, Ty<'tcx>>,
478         callsite: Self::Value
479     ) {
480         ty.apply_attrs_callsite(self, callsite)
481     }
482
483     fn get_param(&self, index: usize) -> Self::Value {
484         llvm::get_param(self.llfn(), index as c_uint)
485     }
486 }