]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_gcc/src/common.rs
Merge commit '0c89065b934397b62838fe3e4ef6f6352fc52daf' into libgccjit-codegen
[rust.git] / compiler / rustc_codegen_gcc / src / common.rs
1 use std::convert::TryFrom;
2 use std::convert::TryInto;
3
4 use gccjit::{Block, CType, RValue, Type, ToRValue};
5 use rustc_codegen_ssa::mir::place::PlaceRef;
6 use rustc_codegen_ssa::traits::{
7     BaseTypeMethods,
8     ConstMethods,
9     DerivedTypeMethods,
10     MiscMethods,
11     StaticMethods,
12 };
13 use rustc_middle::bug;
14 use rustc_middle::mir::Mutability;
15 use rustc_middle::ty::{layout::TyAndLayout, ScalarInt};
16 use rustc_mir::interpret::{Allocation, GlobalAlloc, Scalar};
17 use rustc_span::Symbol;
18 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Pointer, Size};
19
20 use crate::consts::const_alloc_to_gcc;
21 use crate::context::CodegenCx;
22 use crate::type_of::LayoutGccExt;
23
24 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
25     pub fn const_bytes(&self, bytes: &[u8]) -> RValue<'gcc> {
26         bytes_in_context(self, bytes)
27     }
28
29     fn const_cstr(&self, symbol: Symbol, _null_terminated: bool) -> RValue<'gcc> {
30         // TODO: handle null_terminated.
31         if let Some(&value) = self.const_cstr_cache.borrow().get(&symbol) {
32             return value.to_rvalue();
33         }
34
35         let global = self.global_string(&*symbol.as_str());
36
37         self.const_cstr_cache.borrow_mut().insert(symbol, global.dereference(None));
38         global
39     }
40
41     fn global_string(&self, string: &str) -> RValue<'gcc> {
42         // TODO: handle non-null-terminated strings.
43         let string = self.context.new_string_literal(&*string);
44         let sym = self.generate_local_symbol_name("str");
45         // NOTE: TLS is always off for a string litteral.
46         // NOTE: string litterals do not have a link section.
47         let global = self.define_global(&sym, self.val_ty(string), false, None)
48             .unwrap_or_else(|| bug!("symbol `{}` is already defined", sym));
49         self.global_init_block.add_assignment(None, global.dereference(None), string);
50         global.to_rvalue()
51         //llvm::LLVMRustSetLinkage(global, llvm::Linkage::InternalLinkage);
52     }
53
54     pub fn inttoptr(&self, block: Block<'gcc>, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
55         let func = block.get_function();
56         let local = func.new_local(None, value.get_type(), "intLocal");
57         block.add_assignment(None, local, value);
58         let value_address = local.get_address(None);
59
60         let ptr = self.context.new_cast(None, value_address, dest_ty.make_pointer());
61         ptr.dereference(None).to_rvalue()
62     }
63
64     pub fn ptrtoint(&self, block: Block<'gcc>, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
65         // TODO: when libgccjit allow casting from pointer to int, remove this.
66         let func = block.get_function();
67         let local = func.new_local(None, value.get_type(), "ptrLocal");
68         block.add_assignment(None, local, value);
69         let ptr_address = local.get_address(None);
70
71         let ptr = self.context.new_cast(None, ptr_address, dest_ty.make_pointer());
72         ptr.dereference(None).to_rvalue()
73     }
74
75     /*pub fn const_vector(&self, elements: &[RValue<'gcc>]) -> RValue<'gcc> {
76         self.context.new_rvalue_from_vector(None, elements[0].get_type(), elements)
77     }*/
78 }
79
80 pub fn bytes_in_context<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, bytes: &[u8]) -> RValue<'gcc> {
81     let context = &cx.context;
82     let typ = context.new_array_type(None, context.new_type::<u8>(), bytes.len() as i32);
83     let global = cx.declare_unnamed_global(typ);
84     global.global_set_initializer(bytes);
85     global.to_rvalue()
86 }
87
88 pub fn type_is_pointer<'gcc>(typ: Type<'gcc>) -> bool {
89     typ.get_pointee().is_some()
90 }
91
92 impl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
93     fn const_null(&self, typ: Type<'gcc>) -> RValue<'gcc> {
94         if type_is_pointer(typ) {
95             self.context.new_null(typ)
96         }
97         else {
98             self.const_int(typ, 0)
99         }
100     }
101
102     fn const_undef(&self, typ: Type<'gcc>) -> RValue<'gcc> {
103         let local = self.current_func.borrow().expect("func")
104             .new_local(None, typ, "undefined");
105         if typ.is_struct().is_some() {
106             // NOTE: hack to workaround a limitation of the rustc API: see comment on
107             // CodegenCx.structs_as_pointer
108             let pointer = local.get_address(None);
109             self.structs_as_pointer.borrow_mut().insert(pointer);
110             pointer
111         }
112         else {
113             local.to_rvalue()
114         }
115     }
116
117     fn const_int(&self, typ: Type<'gcc>, int: i64) -> RValue<'gcc> {
118         self.context.new_rvalue_from_long(typ, i64::try_from(int).expect("i64::try_from"))
119     }
120
121     fn const_uint(&self, typ: Type<'gcc>, int: u64) -> RValue<'gcc> {
122         self.context.new_rvalue_from_long(typ, u64::try_from(int).expect("u64::try_from") as i64)
123     }
124
125     fn const_uint_big(&self, typ: Type<'gcc>, num: u128) -> RValue<'gcc> {
126         let num64: Result<i64, _> = num.try_into();
127         if let Ok(num) = num64 {
128             // FIXME: workaround for a bug where libgccjit is expecting a constant.
129             // The operations >> 64 and | low are making the normal case a non-constant.
130             return self.context.new_rvalue_from_long(typ, num as i64);
131         }
132
133         if num >> 64 != 0 {
134             // FIXME: use a new function new_rvalue_from_unsigned_long()?
135             let low = self.context.new_rvalue_from_long(self.u64_type, num as u64 as i64);
136             let high = self.context.new_rvalue_from_long(typ, (num >> 64) as u64 as i64);
137
138             let sixty_four = self.context.new_rvalue_from_long(typ, 64);
139             (high << sixty_four) | self.context.new_cast(None, low, typ)
140         }
141         else if typ.is_i128(self) {
142             let num = self.context.new_rvalue_from_long(self.u64_type, num as u64 as i64);
143             self.context.new_cast(None, num, typ)
144         }
145         else {
146             self.context.new_rvalue_from_long(typ, num as u64 as i64)
147         }
148     }
149
150     fn const_bool(&self, val: bool) -> RValue<'gcc> {
151         self.const_uint(self.type_i1(), val as u64)
152     }
153
154     fn const_i32(&self, i: i32) -> RValue<'gcc> {
155         self.const_int(self.type_i32(), i as i64)
156     }
157
158     fn const_u32(&self, i: u32) -> RValue<'gcc> {
159         self.const_uint(self.type_u32(), i as u64)
160     }
161
162     fn const_u64(&self, i: u64) -> RValue<'gcc> {
163         self.const_uint(self.type_u64(), i)
164     }
165
166     fn const_usize(&self, i: u64) -> RValue<'gcc> {
167         let bit_size = self.data_layout().pointer_size.bits();
168         if bit_size < 64 {
169             // make sure it doesn't overflow
170             assert!(i < (1 << bit_size));
171         }
172
173         self.const_uint(self.usize_type, i)
174     }
175
176     fn const_u8(&self, _i: u8) -> RValue<'gcc> {
177         unimplemented!();
178         //self.const_uint(self.type_i8(), i as u64)
179     }
180
181     fn const_real(&self, _t: Type<'gcc>, _val: f64) -> RValue<'gcc> {
182         unimplemented!();
183         //unsafe { llvm::LLVMConstReal(t, val) }
184     }
185
186     fn const_str(&self, s: Symbol) -> (RValue<'gcc>, RValue<'gcc>) {
187         let len = s.as_str().len();
188         let cs = self.const_ptrcast(self.const_cstr(s, false),
189             self.type_ptr_to(self.layout_of(self.tcx.types.str_).gcc_type(self, true)),
190         );
191         (cs, self.const_usize(len as u64))
192     }
193
194     fn const_struct(&self, values: &[RValue<'gcc>], packed: bool) -> RValue<'gcc> {
195         let fields: Vec<_> = values.iter()
196             .map(|value| value.get_type())
197             .collect();
198         // TODO: cache the type? It's anonymous, so probably not.
199         let name = fields.iter().map(|typ| format!("{:?}", typ)).collect::<Vec<_>>().join("_");
200         let typ = self.type_struct(&fields, packed);
201         let structure = self.global_init_func.new_local(None, typ, &name);
202         let struct_type = typ.is_struct().expect("struct type");
203         for (index, value) in values.iter().enumerate() {
204             let field = struct_type.get_field(index as i32);
205             let field_lvalue = structure.access_field(None, field);
206             self.global_init_block.add_assignment(None, field_lvalue, *value);
207         }
208         self.lvalue_to_rvalue(structure)
209     }
210
211     fn const_to_opt_uint(&self, _v: RValue<'gcc>) -> Option<u64> {
212         // TODO
213         None
214         //try_as_const_integral(v).map(|v| unsafe { llvm::LLVMConstIntGetZExtValue(v) })
215     }
216
217     fn const_to_opt_u128(&self, _v: RValue<'gcc>, _sign_ext: bool) -> Option<u128> {
218         // TODO
219         None
220         /*try_as_const_integral(v).and_then(|v| unsafe {
221             let (mut lo, mut hi) = (0u64, 0u64);
222             let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
223             success.then_some(hi_lo_to_u128(lo, hi))
224         })*/
225     }
226
227     fn scalar_to_backend(&self, cv: Scalar, layout: &abi::Scalar, ty: Type<'gcc>) -> RValue<'gcc> {
228         let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
229         match cv {
230             Scalar::Int(ScalarInt::ZST) => {
231                 assert_eq!(0, layout.value.size(self).bytes());
232                 self.const_undef(self.type_ix(0))
233             }
234             Scalar::Int(int) => {
235                 let data = int.assert_bits(layout.value.size(self));
236
237                 // FIXME: there's some issues with using the u128 code that follows, so hard-code
238                 // the paths for floating-point values.
239                 if ty == self.float_type {
240                     return self.context.new_rvalue_from_double(ty, f32::from_bits(data as u32) as f64);
241                 }
242                 else if ty == self.double_type {
243                     return self.context.new_rvalue_from_double(ty, f64::from_bits(data as u64));
244                 }
245
246                 let value = self.const_uint_big(self.type_ix(bitsize), data);
247                 if layout.value == Pointer {
248                     self.inttoptr(self.current_block.borrow().expect("block"), value, ty)
249                 } else {
250                     self.const_bitcast(value, ty)
251                 }
252             }
253             Scalar::Ptr(ptr, _size) => {
254                 let (alloc_id, offset) = ptr.into_parts();
255                 let base_addr =
256                     match self.tcx.global_alloc(alloc_id) {
257                         GlobalAlloc::Memory(alloc) => {
258                             let init = const_alloc_to_gcc(self, alloc);
259                             let value =
260                                 match alloc.mutability {
261                                     Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
262                                     _ => self.static_addr_of(init, alloc.align, None),
263                                 };
264                             if !self.sess().fewer_names() {
265                                 // TODO
266                                 //llvm::set_value_name(value, format!("{:?}", ptr.alloc_id).as_bytes());
267                             }
268                             value
269                         },
270                         GlobalAlloc::Function(fn_instance) => {
271                             self.get_fn_addr(fn_instance)
272                         },
273                         GlobalAlloc::Static(def_id) => {
274                             assert!(self.tcx.is_static(def_id));
275                             self.get_static(def_id)
276                         },
277                     };
278                 let ptr_type = base_addr.get_type();
279                 let base_addr = self.const_bitcast(base_addr, self.usize_type);
280                 let offset = self.context.new_rvalue_from_long(self.usize_type, offset.bytes() as i64);
281                 let ptr = self.const_bitcast(base_addr + offset, ptr_type);
282                 let value = ptr.dereference(None);
283                 if layout.value != Pointer {
284                     self.const_bitcast(value.to_rvalue(), ty)
285                 }
286                 else {
287                     self.const_bitcast(value.get_address(None), ty)
288                 }
289             }
290         }
291     }
292
293     fn const_data_from_alloc(&self, alloc: &Allocation) -> Self::Value {
294         const_alloc_to_gcc(self, alloc)
295     }
296
297     fn from_const_alloc(&self, layout: TyAndLayout<'tcx>, alloc: &Allocation, offset: Size) -> PlaceRef<'tcx, RValue<'gcc>> {
298         assert_eq!(alloc.align, layout.align.abi);
299         let ty = self.type_ptr_to(layout.gcc_type(self, true));
300         let value =
301             if layout.size == Size::ZERO {
302                 let value = self.const_usize(alloc.align.bytes());
303                 self.context.new_cast(None, value, ty)
304             }
305             else {
306                 let init = const_alloc_to_gcc(self, alloc);
307                 let base_addr = self.static_addr_of(init, alloc.align, None);
308
309                 let array = self.const_bitcast(base_addr, self.type_i8p());
310                 let value = self.context.new_array_access(None, array, self.const_usize(offset.bytes())).get_address(None);
311                 self.const_bitcast(value, ty)
312             };
313         PlaceRef::new_sized(value, layout)
314     }
315
316     fn const_ptrcast(&self, val: RValue<'gcc>, ty: Type<'gcc>) -> RValue<'gcc> {
317         self.context.new_cast(None, val, ty)
318     }
319 }
320
321 pub trait SignType<'gcc, 'tcx> {
322     fn is_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
323     fn is_unsigned(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
324     fn to_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc>;
325 }
326
327 impl<'gcc, 'tcx> SignType<'gcc, 'tcx> for Type<'gcc> {
328     fn is_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
329         self.is_i8(cx) || self.is_i16(cx) || self.is_i32(cx) || self.is_i64(cx) || self.is_i128(cx)
330     }
331
332     fn is_unsigned(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
333         self.is_u8(cx) || self.is_u16(cx) || self.is_u32(cx) || self.is_u64(cx) || self.is_u128(cx)
334     }
335
336     fn to_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc> {
337         if self.is_u8(cx) {
338             cx.i8_type
339         }
340         else if self.is_u16(cx) {
341             cx.i16_type
342         }
343         else if self.is_u32(cx) {
344             cx.i32_type
345         }
346         else if self.is_u64(cx) {
347             cx.i64_type
348         }
349         else if self.is_u128(cx) {
350             cx.i128_type
351         }
352         else {
353             self.clone()
354         }
355     }
356 }
357
358 pub trait TypeReflection<'gcc, 'tcx>  {
359     fn is_uchar(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
360     fn is_ushort(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
361     fn is_uint(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
362     fn is_ulong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
363     fn is_ulonglong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
364
365     fn is_i8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
366     fn is_u8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
367     fn is_i16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
368     fn is_u16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
369     fn is_i32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
370     fn is_u32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
371     fn is_i64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
372     fn is_u64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
373     fn is_i128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
374     fn is_u128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
375
376     fn is_f32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
377     fn is_f64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
378 }
379
380 impl<'gcc, 'tcx> TypeReflection<'gcc, 'tcx> for Type<'gcc> {
381     fn is_uchar(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
382         self.unqualified() == cx.u8_type
383     }
384
385     fn is_ushort(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
386         self.unqualified() == cx.u16_type
387     }
388
389     fn is_uint(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
390         self.unqualified() == cx.uint_type
391     }
392
393     fn is_ulong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
394         self.unqualified() == cx.ulong_type
395     }
396
397     fn is_ulonglong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
398         self.unqualified() == cx.ulonglong_type
399     }
400
401     fn is_i8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
402         self.unqualified() == cx.i8_type
403     }
404
405     fn is_u8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
406         self.unqualified() == cx.u8_type
407     }
408
409     fn is_i16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
410         self.unqualified() == cx.i16_type
411     }
412
413     fn is_u16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
414         self.unqualified() == cx.u16_type
415     }
416
417     fn is_i32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
418         self.unqualified() == cx.i32_type
419     }
420
421     fn is_u32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
422         self.unqualified() == cx.u32_type
423     }
424
425     fn is_i64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
426         self.unqualified() == cx.i64_type
427     }
428
429     fn is_u64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
430         self.unqualified() == cx.u64_type
431     }
432
433     fn is_i128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
434         self.unqualified() == cx.context.new_c_type(CType::Int128t)
435     }
436
437     fn is_u128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
438         self.unqualified() == cx.context.new_c_type(CType::UInt128t)
439     }
440
441     fn is_f32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
442         self.unqualified() == cx.context.new_type::<f32>()
443     }
444
445     fn is_f64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
446         self.unqualified() == cx.context.new_type::<f64>()
447     }
448 }