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