]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/common.rs
Rollup merge of #66341 - crgl:vec-deque-extend, r=Amanieu
[rust.git] / src / librustc_codegen_llvm / common.rs
1 #![allow(non_camel_case_types, non_snake_case)]
2
3 //! Code that is useful in various codegen modules.
4
5 use crate::llvm::{self, True, False, Bool, BasicBlock, OperandBundleDef, ConstantInt};
6 use crate::consts;
7 use crate::type_::Type;
8 use crate::type_of::LayoutLlvmExt;
9 use crate::value::Value;
10 use rustc_codegen_ssa::traits::*;
11
12 use crate::consts::const_alloc_to_llvm;
13 use rustc::ty::layout::{HasDataLayout, LayoutOf, self, TyLayout, Size};
14 use rustc::mir::interpret::{Scalar, GlobalAlloc, Allocation};
15 use rustc_codegen_ssa::mir::place::PlaceRef;
16
17 use libc::{c_uint, c_char};
18
19 use syntax::symbol::Symbol;
20 use syntax::ast::Mutability;
21
22 pub use crate::context::CodegenCx;
23
24 /*
25 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
26 *
27 * An "extern" is an LLVM symbol we wind up emitting an undefined external
28 * reference to. This means "we don't have the thing in this compilation unit,
29 * please make sure you link it in at runtime". This could be a reference to
30 * C code found in a C library, or rust code found in a rust crate.
31 *
32 * Most "externs" are implicitly declared (automatically) as a result of a
33 * user declaring an extern _module_ dependency; this causes the rust driver
34 * to locate an extern crate, scan its compilation metadata, and emit extern
35 * declarations for any symbols used by the declaring crate.
36 *
37 * A "foreign" is an extern that references C (or other non-rust ABI) code.
38 * There is no metadata to scan for extern references so in these cases either
39 * a header-digester like bindgen, or manual function prototypes, have to
40 * serve as declarators. So these are usually given explicitly as prototype
41 * declarations, in rust code, with ABI attributes on them noting which ABI to
42 * link via.
43 *
44 * An "upcall" is a foreign call generated by the compiler (not corresponding
45 * to any user-written call in the code) into the runtime library, to perform
46 * some helper task such as bringing a task to life, allocating memory, etc.
47 *
48 */
49
50 /// A structure representing an active landing pad for the duration of a basic
51 /// block.
52 ///
53 /// Each `Block` may contain an instance of this, indicating whether the block
54 /// is part of a landing pad or not. This is used to make decision about whether
55 /// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
56 /// use `invoke`) and also about various function call metadata.
57 ///
58 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
59 /// just a bunch of `None` instances (not too interesting), but for MSVC
60 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
61 /// When inside of a landing pad, each function call in LLVM IR needs to be
62 /// annotated with which landing pad it's a part of. This is accomplished via
63 /// the `OperandBundleDef` value created for MSVC landing pads.
64 pub struct Funclet<'ll> {
65     cleanuppad: &'ll Value,
66     operand: OperandBundleDef<'ll>,
67 }
68
69 impl Funclet<'ll> {
70     pub fn new(cleanuppad: &'ll Value) -> Self {
71         Funclet {
72             cleanuppad,
73             operand: OperandBundleDef::new("funclet", &[cleanuppad]),
74         }
75     }
76
77     pub fn cleanuppad(&self) -> &'ll Value {
78         self.cleanuppad
79     }
80
81     pub fn bundle(&self) -> &OperandBundleDef<'ll> {
82         &self.operand
83     }
84 }
85
86 impl BackendTypes for CodegenCx<'ll, 'tcx> {
87     type Value = &'ll Value;
88     type Function = &'ll Value;
89
90     type BasicBlock = &'ll BasicBlock;
91     type Type = &'ll Type;
92     type Funclet = Funclet<'ll>;
93
94     type DIScope = &'ll llvm::debuginfo::DIScope;
95 }
96
97 impl CodegenCx<'ll, 'tcx> {
98     pub fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
99         unsafe {
100             return llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint);
101         }
102     }
103
104     pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
105         unsafe {
106             return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
107         }
108     }
109
110     pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
111         bytes_in_context(self.llcx, bytes)
112     }
113
114     fn const_cstr(
115         &self,
116         s: Symbol,
117         null_terminated: bool,
118     ) -> &'ll Value {
119         unsafe {
120             if let Some(&llval) = self.const_cstr_cache.borrow().get(&s) {
121                 return llval;
122             }
123
124             let s_str = s.as_str();
125             let sc = llvm::LLVMConstStringInContext(self.llcx,
126                                                     s_str.as_ptr() as *const c_char,
127                                                     s_str.len() as c_uint,
128                                                     !null_terminated as Bool);
129             let sym = self.generate_local_symbol_name("str");
130             let g = self.define_global(&sym[..], self.val_ty(sc)).unwrap_or_else(||{
131                 bug!("symbol `{}` is already defined", sym);
132             });
133             llvm::LLVMSetInitializer(g, sc);
134             llvm::LLVMSetGlobalConstant(g, True);
135             llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
136
137             self.const_cstr_cache.borrow_mut().insert(s, g);
138             g
139         }
140     }
141
142     pub fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
143         unsafe {
144             assert_eq!(idx as c_uint as u64, idx);
145             let us = &[idx as c_uint];
146             let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
147
148             debug!("const_get_elt(v={:?}, idx={}, r={:?})",
149                    v, idx, r);
150
151             r
152         }
153     }
154 }
155
156 impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
157     fn const_null(&self, t: &'ll Type) -> &'ll Value {
158         unsafe {
159             llvm::LLVMConstNull(t)
160         }
161     }
162
163     fn const_undef(&self, t: &'ll Type) -> &'ll Value {
164         unsafe {
165             llvm::LLVMGetUndef(t)
166         }
167     }
168
169     fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
170         unsafe {
171             llvm::LLVMConstInt(t, i as u64, True)
172         }
173     }
174
175     fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
176         unsafe {
177             llvm::LLVMConstInt(t, i, False)
178         }
179     }
180
181     fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
182         unsafe {
183             let words = [u as u64, (u >> 64) as u64];
184             llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
185         }
186     }
187
188     fn const_bool(&self, val: bool) -> &'ll Value {
189         self.const_uint(self.type_i1(), val as u64)
190     }
191
192     fn const_i32(&self, i: i32) -> &'ll Value {
193         self.const_int(self.type_i32(), i as i64)
194     }
195
196     fn const_u32(&self, i: u32) -> &'ll Value {
197         self.const_uint(self.type_i32(), i as u64)
198     }
199
200     fn const_u64(&self, i: u64) -> &'ll Value {
201         self.const_uint(self.type_i64(), i)
202     }
203
204     fn const_usize(&self, i: u64) -> &'ll Value {
205         let bit_size = self.data_layout().pointer_size.bits();
206         if bit_size < 64 {
207             // make sure it doesn't overflow
208             assert!(i < (1<<bit_size));
209         }
210
211         self.const_uint(self.isize_ty, i)
212     }
213
214     fn const_u8(&self, i: u8) -> &'ll Value {
215         self.const_uint(self.type_i8(), i as u64)
216     }
217
218     fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
219         unsafe { llvm::LLVMConstReal(t, val) }
220     }
221
222     fn const_str(&self, s: Symbol) -> (&'ll Value, &'ll Value) {
223         let len = s.as_str().len();
224         let cs = consts::ptrcast(self.const_cstr(s, false),
225             self.type_ptr_to(self.layout_of(self.tcx.mk_str()).llvm_type(self)));
226         (cs, self.const_usize(len as u64))
227     }
228
229     fn const_struct(
230         &self,
231         elts: &[&'ll Value],
232         packed: bool
233     ) -> &'ll Value {
234         struct_in_context(self.llcx, elts, packed)
235     }
236
237     fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
238         try_as_const_integral(v).map(|v| unsafe {
239             llvm::LLVMConstIntGetZExtValue(v)
240         })
241     }
242
243     fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
244         try_as_const_integral(v).and_then(|v| unsafe {
245             let (mut lo, mut hi) = (0u64, 0u64);
246             let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
247                                                         &mut hi, &mut lo);
248             success.then_some(hi_lo_to_u128(lo, hi))
249         })
250     }
251
252     fn scalar_to_backend(
253         &self,
254         cv: Scalar,
255         layout: &layout::Scalar,
256         llty: &'ll Type,
257     ) -> &'ll Value {
258         let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
259         match cv {
260             Scalar::Raw { size: 0, .. } => {
261                 assert_eq!(0, layout.value.size(self).bytes());
262                 self.const_undef(self.type_ix(0))
263             },
264             Scalar::Raw { data, size } => {
265                 assert_eq!(size as u64, layout.value.size(self).bytes());
266                 let llval = self.const_uint_big(self.type_ix(bitsize), data);
267                 if layout.value == layout::Pointer {
268                     unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
269                 } else {
270                     self.const_bitcast(llval, llty)
271                 }
272             },
273             Scalar::Ptr(ptr) => {
274                 let alloc_kind = self.tcx.alloc_map.lock().get(ptr.alloc_id);
275                 let base_addr = match alloc_kind {
276                     Some(GlobalAlloc::Memory(alloc)) => {
277                         let init = const_alloc_to_llvm(self, alloc);
278                         if alloc.mutability == Mutability::Mutable {
279                             self.static_addr_of_mut(init, alloc.align, None)
280                         } else {
281                             self.static_addr_of(init, alloc.align, None)
282                         }
283                     }
284                     Some(GlobalAlloc::Function(fn_instance)) => {
285                         self.get_fn_addr(fn_instance)
286                     }
287                     Some(GlobalAlloc::Static(def_id)) => {
288                         assert!(self.tcx.is_static(def_id));
289                         self.get_static(def_id)
290                     }
291                     None => bug!("missing allocation {:?}", ptr.alloc_id),
292                 };
293                 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
294                     self.const_bitcast(base_addr, self.type_i8p()),
295                     &self.const_usize(ptr.offset.bytes()),
296                     1,
297                 ) };
298                 if layout.value != layout::Pointer {
299                     unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
300                 } else {
301                     self.const_bitcast(llval, llty)
302                 }
303             }
304         }
305     }
306
307     fn from_const_alloc(
308         &self,
309         layout: TyLayout<'tcx>,
310         alloc: &Allocation,
311         offset: Size,
312     ) -> PlaceRef<'tcx, &'ll Value> {
313         assert_eq!(alloc.align, layout.align.abi);
314         let llty = self.type_ptr_to(layout.llvm_type(self));
315         let llval = if layout.size == Size::ZERO {
316             let llval = self.const_usize(alloc.align.bytes());
317             unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
318         } else {
319             let init = const_alloc_to_llvm(self, alloc);
320             let base_addr = self.static_addr_of(init, alloc.align, None);
321
322             let llval = unsafe { llvm::LLVMConstInBoundsGEP(
323                 self.const_bitcast(base_addr, self.type_i8p()),
324                 &self.const_usize(offset.bytes()),
325                 1,
326             )};
327             self.const_bitcast(llval, llty)
328         };
329         PlaceRef::new_sized(llval, layout)
330     }
331
332     fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
333         consts::ptrcast(val, ty)
334     }
335 }
336
337 pub fn val_ty(v: &'ll Value) -> &'ll Type {
338     unsafe {
339         llvm::LLVMTypeOf(v)
340     }
341 }
342
343 pub fn bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
344     unsafe {
345         let ptr = bytes.as_ptr() as *const c_char;
346         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
347     }
348 }
349
350 pub fn struct_in_context(
351     llcx: &'a llvm::Context,
352     elts: &[&'a Value],
353     packed: bool,
354 ) -> &'a Value {
355     unsafe {
356         llvm::LLVMConstStructInContext(llcx,
357                                        elts.as_ptr(), elts.len() as c_uint,
358                                        packed as Bool)
359     }
360 }
361
362 #[inline]
363 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
364     ((hi as u128) << 64) | (lo as u128)
365 }
366
367 fn try_as_const_integral(v: &'ll Value) -> Option<&'ll ConstantInt> {
368     unsafe {
369         llvm::LLVMIsAConstantInt(v)
370     }
371 }