]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/common.rs
Rollup merge of #55252 - SimonSapin:maybeuninit-new, r=bluss
[rust.git] / src / librustc_codegen_llvm / common.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(non_camel_case_types, non_snake_case)]
12
13 //! Code that is useful in various codegen modules.
14
15 use llvm::{self, TypeKind};
16 use llvm::{True, False, Bool, OperandBundleDef};
17 use rustc::hir::def_id::DefId;
18 use rustc::middle::lang_items::LangItem;
19 use abi;
20 use base;
21 use builder::Builder;
22 use consts;
23 use declare;
24 use type_::Type;
25 use type_of::LayoutLlvmExt;
26 use value::Value;
27
28 use rustc::ty::{self, Ty, TyCtxt};
29 use rustc::ty::layout::{HasDataLayout, LayoutOf};
30 use rustc::hir;
31
32 use libc::{c_uint, c_char};
33
34 use syntax::symbol::LocalInternedString;
35 use syntax_pos::{Span, DUMMY_SP};
36
37 pub use context::CodegenCx;
38
39 pub fn type_needs_drop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
40     ty.needs_drop(tcx, ty::ParamEnv::reveal_all())
41 }
42
43 pub fn type_is_sized<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
44     ty.is_sized(tcx.at(DUMMY_SP), ty::ParamEnv::reveal_all())
45 }
46
47 pub fn type_is_freeze<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
48     ty.is_freeze(tcx, ty::ParamEnv::reveal_all(), DUMMY_SP)
49 }
50
51 /*
52 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
53 *
54 * An "extern" is an LLVM symbol we wind up emitting an undefined external
55 * reference to. This means "we don't have the thing in this compilation unit,
56 * please make sure you link it in at runtime". This could be a reference to
57 * C code found in a C library, or rust code found in a rust crate.
58 *
59 * Most "externs" are implicitly declared (automatically) as a result of a
60 * user declaring an extern _module_ dependency; this causes the rust driver
61 * to locate an extern crate, scan its compilation metadata, and emit extern
62 * declarations for any symbols used by the declaring crate.
63 *
64 * A "foreign" is an extern that references C (or other non-rust ABI) code.
65 * There is no metadata to scan for extern references so in these cases either
66 * a header-digester like bindgen, or manual function prototypes, have to
67 * serve as declarators. So these are usually given explicitly as prototype
68 * declarations, in rust code, with ABI attributes on them noting which ABI to
69 * link via.
70 *
71 * An "upcall" is a foreign call generated by the compiler (not corresponding
72 * to any user-written call in the code) into the runtime library, to perform
73 * some helper task such as bringing a task to life, allocating memory, etc.
74 *
75 */
76
77 /// A structure representing an active landing pad for the duration of a basic
78 /// block.
79 ///
80 /// Each `Block` may contain an instance of this, indicating whether the block
81 /// is part of a landing pad or not. This is used to make decision about whether
82 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
83 /// use `invoke`) and also about various function call metadata.
84 ///
85 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
86 /// just a bunch of `None` instances (not too interesting), but for MSVC
87 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
88 /// When inside of a landing pad, each function call in LLVM IR needs to be
89 /// annotated with which landing pad it's a part of. This is accomplished via
90 /// the `OperandBundleDef` value created for MSVC landing pads.
91 pub struct Funclet<'ll> {
92     cleanuppad: &'ll Value,
93     operand: OperandBundleDef<'ll>,
94 }
95
96 impl Funclet<'ll> {
97     pub fn new(cleanuppad: &'ll Value) -> Self {
98         Funclet {
99             cleanuppad,
100             operand: OperandBundleDef::new("funclet", &[cleanuppad]),
101         }
102     }
103
104     pub fn cleanuppad(&self) -> &'ll Value {
105         self.cleanuppad
106     }
107
108     pub fn bundle(&self) -> &OperandBundleDef<'ll> {
109         &self.operand
110     }
111 }
112
113 pub fn val_ty(v: &'ll Value) -> &'ll Type {
114     unsafe {
115         llvm::LLVMTypeOf(v)
116     }
117 }
118
119 // LLVM constant constructors.
120 pub fn C_null(t: &'ll Type) -> &'ll Value {
121     unsafe {
122         llvm::LLVMConstNull(t)
123     }
124 }
125
126 pub fn C_undef(t: &'ll Type) -> &'ll Value {
127     unsafe {
128         llvm::LLVMGetUndef(t)
129     }
130 }
131
132 pub fn C_int(t: &'ll Type, i: i64) -> &'ll Value {
133     unsafe {
134         llvm::LLVMConstInt(t, i as u64, True)
135     }
136 }
137
138 pub fn C_uint(t: &'ll Type, i: u64) -> &'ll Value {
139     unsafe {
140         llvm::LLVMConstInt(t, i, False)
141     }
142 }
143
144 pub fn C_uint_big(t: &'ll Type, u: u128) -> &'ll Value {
145     unsafe {
146         let words = [u as u64, (u >> 64) as u64];
147         llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
148     }
149 }
150
151 pub fn C_bool(cx: &CodegenCx<'ll, '_>, val: bool) -> &'ll Value {
152     C_uint(Type::i1(cx), val as u64)
153 }
154
155 pub fn C_i32(cx: &CodegenCx<'ll, '_>, i: i32) -> &'ll Value {
156     C_int(Type::i32(cx), i as i64)
157 }
158
159 pub fn C_u32(cx: &CodegenCx<'ll, '_>, i: u32) -> &'ll Value {
160     C_uint(Type::i32(cx), i as u64)
161 }
162
163 pub fn C_u64(cx: &CodegenCx<'ll, '_>, i: u64) -> &'ll Value {
164     C_uint(Type::i64(cx), i)
165 }
166
167 pub fn C_usize(cx: &CodegenCx<'ll, '_>, i: u64) -> &'ll Value {
168     let bit_size = cx.data_layout().pointer_size.bits();
169     if bit_size < 64 {
170         // make sure it doesn't overflow
171         assert!(i < (1<<bit_size));
172     }
173
174     C_uint(cx.isize_ty, i)
175 }
176
177 pub fn C_u8(cx: &CodegenCx<'ll, '_>, i: u8) -> &'ll Value {
178     C_uint(Type::i8(cx), i as u64)
179 }
180
181
182 // This is a 'c-like' raw string, which differs from
183 // our boxed-and-length-annotated strings.
184 pub fn C_cstr(
185     cx: &CodegenCx<'ll, '_>,
186     s: LocalInternedString,
187     null_terminated: bool,
188 ) -> &'ll Value {
189     unsafe {
190         if let Some(&llval) = cx.const_cstr_cache.borrow().get(&s) {
191             return llval;
192         }
193
194         let sc = llvm::LLVMConstStringInContext(cx.llcx,
195                                                 s.as_ptr() as *const c_char,
196                                                 s.len() as c_uint,
197                                                 !null_terminated as Bool);
198         let sym = cx.generate_local_symbol_name("str");
199         let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
200             bug!("symbol `{}` is already defined", sym);
201         });
202         llvm::LLVMSetInitializer(g, sc);
203         llvm::LLVMSetGlobalConstant(g, True);
204         llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
205
206         cx.const_cstr_cache.borrow_mut().insert(s, g);
207         g
208     }
209 }
210
211 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
212 // you will be kicked off fast isel. See issue #4352 for an example of this.
213 pub fn C_str_slice(cx: &CodegenCx<'ll, '_>, s: LocalInternedString) -> &'ll Value {
214     let len = s.len();
215     let cs = consts::ptrcast(C_cstr(cx, s, false),
216         cx.layout_of(cx.tcx.mk_str()).llvm_type(cx).ptr_to());
217     C_fat_ptr(cx, cs, C_usize(cx, len as u64))
218 }
219
220 pub fn C_fat_ptr(cx: &CodegenCx<'ll, '_>, ptr: &'ll Value, meta: &'ll Value) -> &'ll Value {
221     assert_eq!(abi::FAT_PTR_ADDR, 0);
222     assert_eq!(abi::FAT_PTR_EXTRA, 1);
223     C_struct(cx, &[ptr, meta], false)
224 }
225
226 pub fn C_struct(cx: &CodegenCx<'ll, '_>, elts: &[&'ll Value], packed: bool) -> &'ll Value {
227     C_struct_in_context(cx.llcx, elts, packed)
228 }
229
230 pub fn C_struct_in_context(
231     llcx: &'ll llvm::Context,
232     elts: &[&'ll Value],
233     packed: bool,
234 ) -> &'ll Value {
235     unsafe {
236         llvm::LLVMConstStructInContext(llcx,
237                                        elts.as_ptr(), elts.len() as c_uint,
238                                        packed as Bool)
239     }
240 }
241
242 pub fn C_array(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
243     unsafe {
244         return llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint);
245     }
246 }
247
248 pub fn C_vector(elts: &[&'ll Value]) -> &'ll Value {
249     unsafe {
250         return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
251     }
252 }
253
254 pub fn C_bytes(cx: &CodegenCx<'ll, '_>, bytes: &[u8]) -> &'ll Value {
255     C_bytes_in_context(cx.llcx, bytes)
256 }
257
258 pub fn C_bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
259     unsafe {
260         let ptr = bytes.as_ptr() as *const c_char;
261         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
262     }
263 }
264
265 pub fn const_get_elt(v: &'ll Value, idx: u64) -> &'ll Value {
266     unsafe {
267         assert_eq!(idx as c_uint as u64, idx);
268         let us = &[idx as c_uint];
269         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
270
271         debug!("const_get_elt(v={:?}, idx={}, r={:?})",
272                v, idx, r);
273
274         r
275     }
276 }
277
278 pub fn const_get_real(v: &'ll Value) -> Option<(f64, bool)> {
279     unsafe {
280         if is_const_real(v) {
281             let mut loses_info: llvm::Bool = ::std::mem::uninitialized();
282             let r = llvm::LLVMConstRealGetDouble(v, &mut loses_info);
283             let loses_info = if loses_info == 1 { true } else { false };
284             Some((r, loses_info))
285         } else {
286             None
287         }
288     }
289 }
290
291 pub fn const_to_uint(v: &'ll Value) -> u64 {
292     unsafe {
293         llvm::LLVMConstIntGetZExtValue(v)
294     }
295 }
296
297 pub fn is_const_integral(v: &'ll Value) -> bool {
298     unsafe {
299         llvm::LLVMIsAConstantInt(v).is_some()
300     }
301 }
302
303 pub fn is_const_real(v: &'ll Value) -> bool {
304     unsafe {
305         llvm::LLVMIsAConstantFP(v).is_some()
306     }
307 }
308
309
310 #[inline]
311 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
312     ((hi as u128) << 64) | (lo as u128)
313 }
314
315 pub fn const_to_opt_u128(v: &'ll Value, sign_ext: bool) -> Option<u128> {
316     unsafe {
317         if is_const_integral(v) {
318             let (mut lo, mut hi) = (0u64, 0u64);
319             let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
320                                                        &mut hi, &mut lo);
321             if success {
322                 Some(hi_lo_to_u128(lo, hi))
323             } else {
324                 None
325             }
326         } else {
327             None
328         }
329     }
330 }
331
332 pub fn langcall(tcx: TyCtxt,
333                 span: Option<Span>,
334                 msg: &str,
335                 li: LangItem)
336                 -> DefId {
337     tcx.lang_items().require(li).unwrap_or_else(|s| {
338         let msg = format!("{} {}", msg, s);
339         match span {
340             Some(span) => tcx.sess.span_fatal(span, &msg[..]),
341             None => tcx.sess.fatal(&msg[..]),
342         }
343     })
344 }
345
346 // To avoid UB from LLVM, these two functions mask RHS with an
347 // appropriate mask unconditionally (i.e. the fallback behavior for
348 // all shifts). For 32- and 64-bit types, this matches the semantics
349 // of Java. (See related discussion on #1877 and #10183.)
350
351 pub fn build_unchecked_lshift(
352     bx: &Builder<'a, 'll, 'tcx>,
353     lhs: &'ll Value,
354     rhs: &'ll Value
355 ) -> &'ll Value {
356     let rhs = base::cast_shift_expr_rhs(bx, hir::BinOpKind::Shl, lhs, rhs);
357     // #1877, #10183: Ensure that input is always valid
358     let rhs = shift_mask_rhs(bx, rhs);
359     bx.shl(lhs, rhs)
360 }
361
362 pub fn build_unchecked_rshift(
363     bx: &Builder<'a, 'll, 'tcx>, lhs_t: Ty<'tcx>, lhs: &'ll Value, rhs: &'ll Value
364 ) -> &'ll Value {
365     let rhs = base::cast_shift_expr_rhs(bx, hir::BinOpKind::Shr, lhs, rhs);
366     // #1877, #10183: Ensure that input is always valid
367     let rhs = shift_mask_rhs(bx, rhs);
368     let is_signed = lhs_t.is_signed();
369     if is_signed {
370         bx.ashr(lhs, rhs)
371     } else {
372         bx.lshr(lhs, rhs)
373     }
374 }
375
376 fn shift_mask_rhs(bx: &Builder<'a, 'll, 'tcx>, rhs: &'ll Value) -> &'ll Value {
377     let rhs_llty = val_ty(rhs);
378     bx.and(rhs, shift_mask_val(bx, rhs_llty, rhs_llty, false))
379 }
380
381 pub fn shift_mask_val(
382     bx: &Builder<'a, 'll, 'tcx>,
383     llty: &'ll Type,
384     mask_llty: &'ll Type,
385     invert: bool
386 ) -> &'ll Value {
387     let kind = llty.kind();
388     match kind {
389         TypeKind::Integer => {
390             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
391             let val = llty.int_width() - 1;
392             if invert {
393                 C_int(mask_llty, !val as i64)
394             } else {
395                 C_uint(mask_llty, val)
396             }
397         },
398         TypeKind::Vector => {
399             let mask = shift_mask_val(bx, llty.element_type(), mask_llty.element_type(), invert);
400             bx.vector_splat(mask_llty.vector_length(), mask)
401         },
402         _ => bug!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
403     }
404 }