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.
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.
11 #![allow(non_camel_case_types, non_snake_case)]
13 //! Code that is useful in various trans modules.
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;
27 use type_of::LayoutLlvmExt;
30 use rustc::ty::{self, Ty, TyCtxt};
31 use rustc::ty::layout::{HasDataLayout, LayoutOf};
32 use rustc::ty::subst::{Kind, Subst, Substs};
35 use libc::{c_uint, c_char};
39 use syntax::symbol::InternedString;
40 use syntax_pos::{Span, DUMMY_SP};
42 pub use context::{CrateContext, SharedCrateContext};
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))
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)
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)
57 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
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.
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.
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
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.
82 /// A structure representing an active landing pad for the duration of a basic
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.
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.
98 operand: OperandBundleDef,
102 pub fn new(cleanuppad: ValueRef) -> Funclet {
105 operand: OperandBundleDef::new("funclet", &[cleanuppad]),
109 pub fn cleanuppad(&self) -> ValueRef {
113 pub fn bundle(&self) -> &OperandBundleDef {
118 pub fn val_ty(v: ValueRef) -> Type {
120 Type::from_ref(llvm::LLVMTypeOf(v))
124 // LLVM constant constructors.
125 pub fn C_null(t: Type) -> ValueRef {
127 llvm::LLVMConstNull(t.to_ref())
131 pub fn C_undef(t: Type) -> ValueRef {
133 llvm::LLVMGetUndef(t.to_ref())
137 pub fn C_int(t: Type, i: i64) -> ValueRef {
139 llvm::LLVMConstInt(t.to_ref(), i as u64, True)
143 pub fn C_uint(t: Type, i: u64) -> ValueRef {
145 llvm::LLVMConstInt(t.to_ref(), i, False)
149 pub fn C_uint_big(t: Type, u: u128) -> ValueRef {
151 let words = [u as u64, (u >> 64) as u64];
152 llvm::LLVMConstIntOfArbitraryPrecision(t.to_ref(), 2, words.as_ptr())
156 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
157 C_uint(Type::i1(ccx), val as u64)
160 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
161 C_int(Type::i32(ccx), i as i64)
164 pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef {
165 C_uint(Type::i32(ccx), i as u64)
168 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
169 C_uint(Type::i64(ccx), i)
172 pub fn C_usize(ccx: &CrateContext, i: u64) -> ValueRef {
173 let bit_size = ccx.data_layout().pointer_size.bits();
175 // make sure it doesn't overflow
176 assert!(i < (1<<bit_size));
179 C_uint(ccx.isize_ty(), i)
182 pub fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef {
183 C_uint(Type::i8(ccx), i as u64)
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 {
191 if let Some(&llval) = cx.const_cstr_cache().borrow().get(&s) {
195 let sc = llvm::LLVMConstStringInContext(cx.llcx(),
196 s.as_ptr() as *const c_char,
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);
203 llvm::LLVMSetInitializer(g, sc);
204 llvm::LLVMSetGlobalConstant(g, True);
205 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
207 cx.const_cstr_cache().borrow_mut().insert(s, g);
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 {
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))
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)
227 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
228 C_struct_in_context(cx.llcx(), elts, packed)
231 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
233 llvm::LLVMConstStructInContext(llcx,
234 elts.as_ptr(), elts.len() as c_uint,
239 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
241 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
245 pub fn C_vector(elts: &[ValueRef]) -> ValueRef {
247 return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
251 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
252 C_bytes_in_context(cx.llcx(), bytes)
255 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
257 let ptr = bytes.as_ptr() as *const c_char;
258 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
262 pub fn const_get_elt(v: ValueRef, idx: u64) -> ValueRef {
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);
268 debug!("const_get_elt(v={:?}, idx={}, r={:?})",
269 Value(v), idx, Value(r));
275 pub fn const_to_uint(v: ValueRef) -> u64 {
277 llvm::LLVMConstIntGetZExtValue(v)
281 pub fn is_const_integral(v: ValueRef) -> bool {
283 !llvm::LLVMIsAConstantInt(v).is_null()
288 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
289 ((hi as u128) << 64) | (lo as u128)
292 pub fn const_to_opt_u128(v: ValueRef, sign_ext: bool) -> Option<u128> {
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);
299 Some(hi_lo_to_u128(lo, hi))
309 pub fn langcall(tcx: TyCtxt,
314 match tcx.lang_items().require(li) {
317 let msg = format!("{} {}", msg, s);
319 Some(span) => tcx.sess.span_fatal(span, &msg[..]),
320 None => tcx.sess.fatal(&msg[..]),
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.)
331 pub fn build_unchecked_lshift<'a, 'tcx>(
332 bcx: &Builder<'a, 'tcx>,
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);
342 pub fn build_unchecked_rshift<'a, 'tcx>(
343 bcx: &Builder<'a, 'tcx>, lhs_t: Ty<'tcx>, lhs: ValueRef, rhs: 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();
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))
361 pub fn shift_mask_val<'a, 'tcx>(
362 bcx: &Builder<'a, 'tcx>,
367 let kind = llty.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;
373 C_int(mask_llty, !val as i64)
375 C_uint(mask_llty, val)
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)
382 _ => bug!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
386 pub fn ty_fn_sig<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
388 -> ty::PolyFnSig<'tcx>
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) => {
396 let sig = tcx.fn_sig(def_id).subst(tcx, substs.substs);
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()),
407 ty::TyGenerator(def_id, substs, _) => {
409 let sig = substs.generator_poly_sig(def_id, ccx.tcx());
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);
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);
421 tcx.mk_fn_sig(iter::once(env_ty),
424 hir::Unsafety::Normal,
429 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
433 pub fn is_inline_instance<'a, 'tcx>(
434 tcx: TyCtxt<'a, 'tcx, 'tcx>,
435 instance: &ty::Instance<'tcx>
437 let def_id = match instance.def {
438 ty::InstanceDef::Item(def_id) => def_id,
439 ty::InstanceDef::DropGlue(_, Some(_)) => return false,
442 match tcx.def_key(def_id).disambiguated_data.data {
443 DefPathData::StructCtor |
444 DefPathData::EnumVariant(..) |
445 DefPathData::ClosureExpr => true,
450 /// Given a DefId and some Substs, produces the monomorphic item type.
451 pub fn def_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
453 substs: &'tcx Substs<'tcx>)
456 let ty = tcx.type_of(def_id);
457 tcx.trans_apply_param_substs(substs, &ty)
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>)
465 let ty = instance.def.def_ty(tcx);
466 tcx.trans_apply_param_substs(instance.substs, &ty)