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