]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/common.rs
Fixes doc important trait display on mobile
[rust.git] / src / librustc_trans / 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 trans modules.
14
15 use llvm;
16 use llvm::{ValueRef, ContextRef, TypeKind};
17 use llvm::{True, False, Bool, OperandBundleDef};
18 use rustc::hir::def_id::DefId;
19 use rustc::hir::map::DefPathData;
20 use rustc::middle::lang_items::LangItem;
21 use abi;
22 use base;
23 use builder::Builder;
24 use consts;
25 use declare;
26 use type_::Type;
27 use type_of::LayoutLlvmExt;
28 use value::Value;
29 use rustc::traits;
30 use rustc::ty::{self, Ty, TyCtxt};
31 use rustc::ty::layout::{HasDataLayout, LayoutOf};
32 use rustc::ty::subst::{Kind, Subst, Substs};
33 use rustc::hir;
34
35 use libc::{c_uint, c_char};
36 use std::iter;
37
38 use syntax::abi::Abi;
39 use syntax::symbol::InternedString;
40 use syntax_pos::{Span, DUMMY_SP};
41
42 pub use context::{CrateContext, SharedCrateContext};
43
44 pub fn type_needs_drop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
45     ty.needs_drop(tcx, ty::ParamEnv::empty(traits::Reveal::All))
46 }
47
48 pub fn type_is_sized<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
49     ty.is_sized(tcx, ty::ParamEnv::empty(traits::Reveal::All), DUMMY_SP)
50 }
51
52 pub fn type_is_freeze<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
53     ty.is_freeze(tcx, ty::ParamEnv::empty(traits::Reveal::All), DUMMY_SP)
54 }
55
56 /*
57 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
58 *
59 * An "extern" is an LLVM symbol we wind up emitting an undefined external
60 * reference to. This means "we don't have the thing in this compilation unit,
61 * please make sure you link it in at runtime". This could be a reference to
62 * C code found in a C library, or rust code found in a rust crate.
63 *
64 * Most "externs" are implicitly declared (automatically) as a result of a
65 * user declaring an extern _module_ dependency; this causes the rust driver
66 * to locate an extern crate, scan its compilation metadata, and emit extern
67 * declarations for any symbols used by the declaring crate.
68 *
69 * A "foreign" is an extern that references C (or other non-rust ABI) code.
70 * There is no metadata to scan for extern references so in these cases either
71 * a header-digester like bindgen, or manual function prototypes, have to
72 * serve as declarators. So these are usually given explicitly as prototype
73 * declarations, in rust code, with ABI attributes on them noting which ABI to
74 * link via.
75 *
76 * An "upcall" is a foreign call generated by the compiler (not corresponding
77 * to any user-written call in the code) into the runtime library, to perform
78 * some helper task such as bringing a task to life, allocating memory, etc.
79 *
80 */
81
82 /// A structure representing an active landing pad for the duration of a basic
83 /// block.
84 ///
85 /// Each `Block` may contain an instance of this, indicating whether the block
86 /// is part of a landing pad or not. This is used to make decision about whether
87 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
88 /// use `invoke`) and also about various function call metadata.
89 ///
90 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
91 /// just a bunch of `None` instances (not too interesting), but for MSVC
92 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
93 /// When inside of a landing pad, each function call in LLVM IR needs to be
94 /// annotated with which landing pad it's a part of. This is accomplished via
95 /// the `OperandBundleDef` value created for MSVC landing pads.
96 pub struct Funclet {
97     cleanuppad: ValueRef,
98     operand: OperandBundleDef,
99 }
100
101 impl Funclet {
102     pub fn new(cleanuppad: ValueRef) -> Funclet {
103         Funclet {
104             cleanuppad,
105             operand: OperandBundleDef::new("funclet", &[cleanuppad]),
106         }
107     }
108
109     pub fn cleanuppad(&self) -> ValueRef {
110         self.cleanuppad
111     }
112
113     pub fn bundle(&self) -> &OperandBundleDef {
114         &self.operand
115     }
116 }
117
118 pub fn val_ty(v: ValueRef) -> Type {
119     unsafe {
120         Type::from_ref(llvm::LLVMTypeOf(v))
121     }
122 }
123
124 // LLVM constant constructors.
125 pub fn C_null(t: Type) -> ValueRef {
126     unsafe {
127         llvm::LLVMConstNull(t.to_ref())
128     }
129 }
130
131 pub fn C_undef(t: Type) -> ValueRef {
132     unsafe {
133         llvm::LLVMGetUndef(t.to_ref())
134     }
135 }
136
137 pub fn C_int(t: Type, i: i64) -> ValueRef {
138     unsafe {
139         llvm::LLVMConstInt(t.to_ref(), i as u64, True)
140     }
141 }
142
143 pub fn C_uint(t: Type, i: u64) -> ValueRef {
144     unsafe {
145         llvm::LLVMConstInt(t.to_ref(), i, False)
146     }
147 }
148
149 pub fn C_uint_big(t: Type, u: u128) -> ValueRef {
150     unsafe {
151         let words = [u as u64, (u >> 64) as u64];
152         llvm::LLVMConstIntOfArbitraryPrecision(t.to_ref(), 2, words.as_ptr())
153     }
154 }
155
156 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
157     C_uint(Type::i1(ccx), val as u64)
158 }
159
160 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
161     C_int(Type::i32(ccx), i as i64)
162 }
163
164 pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef {
165     C_uint(Type::i32(ccx), i as u64)
166 }
167
168 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
169     C_uint(Type::i64(ccx), i)
170 }
171
172 pub fn C_usize(ccx: &CrateContext, i: u64) -> ValueRef {
173     let bit_size = ccx.data_layout().pointer_size.bits();
174     if bit_size < 64 {
175         // make sure it doesn't overflow
176         assert!(i < (1<<bit_size));
177     }
178
179     C_uint(ccx.isize_ty(), i)
180 }
181
182 pub fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef {
183     C_uint(Type::i8(ccx), i as u64)
184 }
185
186
187 // This is a 'c-like' raw string, which differs from
188 // our boxed-and-length-annotated strings.
189 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
190     unsafe {
191         if let Some(&llval) = cx.const_cstr_cache().borrow().get(&s) {
192             return llval;
193         }
194
195         let sc = llvm::LLVMConstStringInContext(cx.llcx(),
196                                                 s.as_ptr() as *const c_char,
197                                                 s.len() as c_uint,
198                                                 !null_terminated as Bool);
199         let sym = cx.generate_local_symbol_name("str");
200         let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
201             bug!("symbol `{}` is already defined", sym);
202         });
203         llvm::LLVMSetInitializer(g, sc);
204         llvm::LLVMSetGlobalConstant(g, True);
205         llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
206
207         cx.const_cstr_cache().borrow_mut().insert(s, g);
208         g
209     }
210 }
211
212 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
213 // you will be kicked off fast isel. See issue #4352 for an example of this.
214 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
215     let len = s.len();
216     let cs = consts::ptrcast(C_cstr(cx, s, false),
217         cx.layout_of(cx.tcx().mk_str()).llvm_type(cx).ptr_to());
218     C_fat_ptr(cx, cs, C_usize(cx, len as u64))
219 }
220
221 pub fn C_fat_ptr(cx: &CrateContext, ptr: ValueRef, meta: ValueRef) -> ValueRef {
222     assert_eq!(abi::FAT_PTR_ADDR, 0);
223     assert_eq!(abi::FAT_PTR_EXTRA, 1);
224     C_struct(cx, &[ptr, meta], false)
225 }
226
227 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
228     C_struct_in_context(cx.llcx(), elts, packed)
229 }
230
231 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
232     unsafe {
233         llvm::LLVMConstStructInContext(llcx,
234                                        elts.as_ptr(), elts.len() as c_uint,
235                                        packed as Bool)
236     }
237 }
238
239 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
240     unsafe {
241         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
242     }
243 }
244
245 pub fn C_vector(elts: &[ValueRef]) -> ValueRef {
246     unsafe {
247         return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
248     }
249 }
250
251 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
252     C_bytes_in_context(cx.llcx(), bytes)
253 }
254
255 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
256     unsafe {
257         let ptr = bytes.as_ptr() as *const c_char;
258         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
259     }
260 }
261
262 pub fn const_get_elt(v: ValueRef, idx: u64) -> ValueRef {
263     unsafe {
264         assert_eq!(idx as c_uint as u64, idx);
265         let us = &[idx as c_uint];
266         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
267
268         debug!("const_get_elt(v={:?}, idx={}, r={:?})",
269                Value(v), idx, Value(r));
270
271         r
272     }
273 }
274
275 pub fn const_to_uint(v: ValueRef) -> u64 {
276     unsafe {
277         llvm::LLVMConstIntGetZExtValue(v)
278     }
279 }
280
281 pub fn is_const_integral(v: ValueRef) -> bool {
282     unsafe {
283         !llvm::LLVMIsAConstantInt(v).is_null()
284     }
285 }
286
287 #[inline]
288 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
289     ((hi as u128) << 64) | (lo as u128)
290 }
291
292 pub fn const_to_opt_u128(v: ValueRef, sign_ext: bool) -> Option<u128> {
293     unsafe {
294         if is_const_integral(v) {
295             let (mut lo, mut hi) = (0u64, 0u64);
296             let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
297                                                        &mut hi as *mut u64, &mut lo as *mut u64);
298             if success {
299                 Some(hi_lo_to_u128(lo, hi))
300             } else {
301                 None
302             }
303         } else {
304             None
305         }
306     }
307 }
308
309 pub fn langcall(tcx: TyCtxt,
310                 span: Option<Span>,
311                 msg: &str,
312                 li: LangItem)
313                 -> DefId {
314     match tcx.lang_items().require(li) {
315         Ok(id) => id,
316         Err(s) => {
317             let msg = format!("{} {}", msg, s);
318             match span {
319                 Some(span) => tcx.sess.span_fatal(span, &msg[..]),
320                 None => tcx.sess.fatal(&msg[..]),
321             }
322         }
323     }
324 }
325
326 // To avoid UB from LLVM, these two functions mask RHS with an
327 // appropriate mask unconditionally (i.e. the fallback behavior for
328 // all shifts). For 32- and 64-bit types, this matches the semantics
329 // of Java. (See related discussion on #1877 and #10183.)
330
331 pub fn build_unchecked_lshift<'a, 'tcx>(
332     bcx: &Builder<'a, 'tcx>,
333     lhs: ValueRef,
334     rhs: ValueRef
335 ) -> ValueRef {
336     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
337     // #1877, #10183: Ensure that input is always valid
338     let rhs = shift_mask_rhs(bcx, rhs);
339     bcx.shl(lhs, rhs)
340 }
341
342 pub fn build_unchecked_rshift<'a, 'tcx>(
343     bcx: &Builder<'a, 'tcx>, lhs_t: Ty<'tcx>, lhs: ValueRef, rhs: ValueRef
344 ) -> ValueRef {
345     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
346     // #1877, #10183: Ensure that input is always valid
347     let rhs = shift_mask_rhs(bcx, rhs);
348     let is_signed = lhs_t.is_signed();
349     if is_signed {
350         bcx.ashr(lhs, rhs)
351     } else {
352         bcx.lshr(lhs, rhs)
353     }
354 }
355
356 fn shift_mask_rhs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, rhs: ValueRef) -> ValueRef {
357     let rhs_llty = val_ty(rhs);
358     bcx.and(rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false))
359 }
360
361 pub fn shift_mask_val<'a, 'tcx>(
362     bcx: &Builder<'a, 'tcx>,
363     llty: Type,
364     mask_llty: Type,
365     invert: bool
366 ) -> ValueRef {
367     let kind = llty.kind();
368     match kind {
369         TypeKind::Integer => {
370             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
371             let val = llty.int_width() - 1;
372             if invert {
373                 C_int(mask_llty, !val as i64)
374             } else {
375                 C_uint(mask_llty, val)
376             }
377         },
378         TypeKind::Vector => {
379             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
380             bcx.vector_splat(mask_llty.vector_length(), mask)
381         },
382         _ => bug!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
383     }
384 }
385
386 pub fn ty_fn_sig<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
387                            ty: Ty<'tcx>)
388                            -> ty::PolyFnSig<'tcx>
389 {
390     match ty.sty {
391         ty::TyFnDef(..) |
392         // Shims currently have type TyFnPtr. Not sure this should remain.
393         ty::TyFnPtr(_) => ty.fn_sig(ccx.tcx()),
394         ty::TyClosure(def_id, substs) => {
395             let tcx = ccx.tcx();
396             let sig = tcx.fn_sig(def_id).subst(tcx, substs.substs);
397
398             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
399             sig.map_bound(|sig| tcx.mk_fn_sig(
400                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
401                 sig.output(),
402                 sig.variadic,
403                 sig.unsafety,
404                 sig.abi
405             ))
406         }
407         ty::TyGenerator(def_id, substs, _) => {
408             let tcx = ccx.tcx();
409             let sig = substs.generator_poly_sig(def_id, ccx.tcx());
410
411             let env_region = ty::ReLateBound(ty::DebruijnIndex::new(1), ty::BrEnv);
412             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
413
414             sig.map_bound(|sig| {
415                 let state_did = tcx.lang_items().gen_state().unwrap();
416                 let state_adt_ref = tcx.adt_def(state_did);
417                 let state_substs = tcx.mk_substs([Kind::from(sig.yield_ty),
418                     Kind::from(sig.return_ty)].iter());
419                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
420
421                 tcx.mk_fn_sig(iter::once(env_ty),
422                     ret_ty,
423                     false,
424                     hir::Unsafety::Normal,
425                     Abi::Rust
426                 )
427             })
428         }
429         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
430     }
431 }
432
433 pub fn is_inline_instance<'a, 'tcx>(
434     tcx: TyCtxt<'a, 'tcx, 'tcx>,
435     instance: &ty::Instance<'tcx>
436 ) -> bool {
437     let def_id = match instance.def {
438         ty::InstanceDef::Item(def_id) => def_id,
439         ty::InstanceDef::DropGlue(_, Some(_)) => return false,
440         _ => return true
441     };
442     match tcx.def_key(def_id).disambiguated_data.data {
443         DefPathData::StructCtor |
444         DefPathData::EnumVariant(..) |
445         DefPathData::ClosureExpr => true,
446         _ => false
447     }
448 }
449
450 /// Given a DefId and some Substs, produces the monomorphic item type.
451 pub fn def_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
452                         def_id: DefId,
453                         substs: &'tcx Substs<'tcx>)
454                         -> Ty<'tcx>
455 {
456     let ty = tcx.type_of(def_id);
457     tcx.trans_apply_param_substs(substs, &ty)
458 }
459
460 /// Return the substituted type of an instance.
461 pub fn instance_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
462                              instance: &ty::Instance<'tcx>)
463                              -> Ty<'tcx>
464 {
465     let ty = instance.def.def_ty(tcx);
466     tcx.trans_apply_param_substs(instance.substs, &ty)
467 }