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 codegen modules.
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;
25 use type_of::LayoutLlvmExt;
28 use rustc::ty::{self, Ty, TyCtxt};
29 use rustc::ty::layout::{HasDataLayout, LayoutOf};
32 use libc::{c_uint, c_char};
35 use rustc_target::spec::abi::Abi;
36 use syntax::symbol::LocalInternedString;
37 use syntax_pos::{Span, DUMMY_SP};
39 pub use context::CodegenCx;
41 pub fn type_needs_drop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
42 ty.needs_drop(tcx, ty::ParamEnv::reveal_all())
45 pub fn type_is_sized<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
46 ty.is_sized(tcx.at(DUMMY_SP), ty::ParamEnv::reveal_all())
49 pub fn type_is_freeze<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
50 ty.is_freeze(tcx, ty::ParamEnv::reveal_all(), DUMMY_SP)
54 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
56 * An "extern" is an LLVM symbol we wind up emitting an undefined external
57 * reference to. This means "we don't have the thing in this compilation unit,
58 * please make sure you link it in at runtime". This could be a reference to
59 * C code found in a C library, or rust code found in a rust crate.
61 * Most "externs" are implicitly declared (automatically) as a result of a
62 * user declaring an extern _module_ dependency; this causes the rust driver
63 * to locate an extern crate, scan its compilation metadata, and emit extern
64 * declarations for any symbols used by the declaring crate.
66 * A "foreign" is an extern that references C (or other non-rust ABI) code.
67 * There is no metadata to scan for extern references so in these cases either
68 * a header-digester like bindgen, or manual function prototypes, have to
69 * serve as declarators. So these are usually given explicitly as prototype
70 * declarations, in rust code, with ABI attributes on them noting which ABI to
73 * An "upcall" is a foreign call generated by the compiler (not corresponding
74 * to any user-written call in the code) into the runtime library, to perform
75 * some helper task such as bringing a task to life, allocating memory, etc.
79 /// A structure representing an active landing pad for the duration of a basic
82 /// Each `Block` may contain an instance of this, indicating whether the block
83 /// is part of a landing pad or not. This is used to make decision about whether
84 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
85 /// use `invoke`) and also about various function call metadata.
87 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
88 /// just a bunch of `None` instances (not too interesting), but for MSVC
89 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
90 /// When inside of a landing pad, each function call in LLVM IR needs to be
91 /// annotated with which landing pad it's a part of. This is accomplished via
92 /// the `OperandBundleDef` value created for MSVC landing pads.
93 pub struct Funclet<'ll> {
94 cleanuppad: &'ll Value,
95 operand: OperandBundleDef<'ll>,
99 pub fn new(cleanuppad: &'ll Value) -> Self {
102 operand: OperandBundleDef::new("funclet", &[cleanuppad]),
106 pub fn cleanuppad(&self) -> &'ll Value {
110 pub fn bundle(&self) -> &OperandBundleDef<'ll> {
115 pub fn val_ty(v: &'ll Value) -> &'ll Type {
121 // LLVM constant constructors.
122 pub fn C_null(t: &'ll Type) -> &'ll Value {
124 llvm::LLVMConstNull(t)
128 pub fn C_undef(t: &'ll Type) -> &'ll Value {
130 llvm::LLVMGetUndef(t)
134 pub fn C_int(t: &'ll Type, i: i64) -> &'ll Value {
136 llvm::LLVMConstInt(t, i as u64, True)
140 pub fn C_uint(t: &'ll Type, i: u64) -> &'ll Value {
142 llvm::LLVMConstInt(t, i, False)
146 pub fn C_uint_big(t: &'ll Type, u: u128) -> &'ll Value {
148 let words = [u as u64, (u >> 64) as u64];
149 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
153 pub fn C_bool(cx: &CodegenCx<'ll, '_>, val: bool) -> &'ll Value {
154 C_uint(Type::i1(cx), val as u64)
157 pub fn C_i32(cx: &CodegenCx<'ll, '_>, i: i32) -> &'ll Value {
158 C_int(Type::i32(cx), i as i64)
161 pub fn C_u32(cx: &CodegenCx<'ll, '_>, i: u32) -> &'ll Value {
162 C_uint(Type::i32(cx), i as u64)
165 pub fn C_u64(cx: &CodegenCx<'ll, '_>, i: u64) -> &'ll Value {
166 C_uint(Type::i64(cx), i)
169 pub fn C_usize(cx: &CodegenCx<'ll, '_>, i: u64) -> &'ll Value {
170 let bit_size = cx.data_layout().pointer_size.bits();
172 // make sure it doesn't overflow
173 assert!(i < (1<<bit_size));
176 C_uint(cx.isize_ty, i)
179 pub fn C_u8(cx: &CodegenCx<'ll, '_>, i: u8) -> &'ll Value {
180 C_uint(Type::i8(cx), i as u64)
184 // This is a 'c-like' raw string, which differs from
185 // our boxed-and-length-annotated strings.
187 cx: &CodegenCx<'ll, '_>,
188 s: LocalInternedString,
189 null_terminated: bool,
192 if let Some(&llval) = cx.const_cstr_cache.borrow().get(&s) {
196 let sc = llvm::LLVMConstStringInContext(cx.llcx,
197 s.as_ptr() as *const c_char,
199 !null_terminated as Bool);
200 let sym = cx.generate_local_symbol_name("str");
201 let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
202 bug!("symbol `{}` is already defined", sym);
204 llvm::LLVMSetInitializer(g, sc);
205 llvm::LLVMSetGlobalConstant(g, True);
206 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
208 cx.const_cstr_cache.borrow_mut().insert(s, g);
213 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
214 // you will be kicked off fast isel. See issue #4352 for an example of this.
215 pub fn C_str_slice(cx: &CodegenCx<'ll, '_>, s: LocalInternedString) -> &'ll Value {
217 let cs = consts::ptrcast(C_cstr(cx, s, false),
218 cx.layout_of(cx.tcx.mk_str()).llvm_type(cx).ptr_to());
219 C_fat_ptr(cx, cs, C_usize(cx, len as u64))
222 pub fn C_fat_ptr(cx: &CodegenCx<'ll, '_>, ptr: &'ll Value, meta: &'ll Value) -> &'ll Value {
223 assert_eq!(abi::FAT_PTR_ADDR, 0);
224 assert_eq!(abi::FAT_PTR_EXTRA, 1);
225 C_struct(cx, &[ptr, meta], false)
228 pub fn C_struct(cx: &CodegenCx<'ll, '_>, elts: &[&'ll Value], packed: bool) -> &'ll Value {
229 C_struct_in_context(cx.llcx, elts, packed)
232 pub fn C_struct_in_context(
233 llcx: &'ll llvm::Context,
238 llvm::LLVMConstStructInContext(llcx,
239 elts.as_ptr(), elts.len() as c_uint,
244 pub fn C_array(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
246 return llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint);
250 pub fn C_vector(elts: &[&'ll Value]) -> &'ll Value {
252 return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
256 pub fn C_bytes(cx: &CodegenCx<'ll, '_>, bytes: &[u8]) -> &'ll Value {
257 C_bytes_in_context(cx.llcx, bytes)
260 pub fn C_bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
262 let ptr = bytes.as_ptr() as *const c_char;
263 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
267 pub fn const_get_elt(v: &'ll Value, idx: u64) -> &'ll Value {
269 assert_eq!(idx as c_uint as u64, idx);
270 let us = &[idx as c_uint];
271 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
273 debug!("const_get_elt(v={:?}, idx={}, r={:?})",
280 pub fn const_get_real(v: &'ll Value) -> Option<(f64, bool)> {
282 if is_const_real(v) {
283 let mut loses_info: llvm::Bool = ::std::mem::uninitialized();
284 let r = llvm::LLVMConstRealGetDouble(v, &mut loses_info);
285 let loses_info = if loses_info == 1 { true } else { false };
286 Some((r, loses_info))
293 pub fn const_to_uint(v: &'ll Value) -> u64 {
295 llvm::LLVMConstIntGetZExtValue(v)
299 pub fn is_const_integral(v: &'ll Value) -> bool {
301 llvm::LLVMIsAConstantInt(v).is_some()
305 pub fn is_const_real(v: &'ll Value) -> bool {
307 llvm::LLVMIsAConstantFP(v).is_some()
313 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
314 ((hi as u128) << 64) | (lo as u128)
317 pub fn const_to_opt_u128(v: &'ll Value, sign_ext: bool) -> Option<u128> {
319 if is_const_integral(v) {
320 let (mut lo, mut hi) = (0u64, 0u64);
321 let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
324 Some(hi_lo_to_u128(lo, hi))
334 pub fn langcall(tcx: TyCtxt,
339 tcx.lang_items().require(li).unwrap_or_else(|s| {
340 let msg = format!("{} {}", msg, s);
342 Some(span) => tcx.sess.span_fatal(span, &msg[..]),
343 None => tcx.sess.fatal(&msg[..]),
348 // To avoid UB from LLVM, these two functions mask RHS with an
349 // appropriate mask unconditionally (i.e. the fallback behavior for
350 // all shifts). For 32- and 64-bit types, this matches the semantics
351 // of Java. (See related discussion on #1877 and #10183.)
353 pub fn build_unchecked_lshift(
354 bx: &Builder<'a, 'll, 'tcx>,
358 let rhs = base::cast_shift_expr_rhs(bx, hir::BinOpKind::Shl, lhs, rhs);
359 // #1877, #10183: Ensure that input is always valid
360 let rhs = shift_mask_rhs(bx, rhs);
364 pub fn build_unchecked_rshift(
365 bx: &Builder<'a, 'll, 'tcx>, lhs_t: Ty<'tcx>, lhs: &'ll Value, rhs: &'ll Value
367 let rhs = base::cast_shift_expr_rhs(bx, hir::BinOpKind::Shr, lhs, rhs);
368 // #1877, #10183: Ensure that input is always valid
369 let rhs = shift_mask_rhs(bx, rhs);
370 let is_signed = lhs_t.is_signed();
378 fn shift_mask_rhs(bx: &Builder<'a, 'll, 'tcx>, rhs: &'ll Value) -> &'ll Value {
379 let rhs_llty = val_ty(rhs);
380 bx.and(rhs, shift_mask_val(bx, rhs_llty, rhs_llty, false))
383 pub fn shift_mask_val(
384 bx: &Builder<'a, 'll, 'tcx>,
386 mask_llty: &'ll Type,
389 let kind = llty.kind();
391 TypeKind::Integer => {
392 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
393 let val = llty.int_width() - 1;
395 C_int(mask_llty, !val as i64)
397 C_uint(mask_llty, val)
400 TypeKind::Vector => {
401 let mask = shift_mask_val(bx, llty.element_type(), mask_llty.element_type(), invert);
402 bx.vector_splat(mask_llty.vector_length(), mask)
404 _ => bug!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
408 pub fn ty_fn_sig<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
410 -> ty::PolyFnSig<'tcx>
414 // Shims currently have type FnPtr. Not sure this should remain.
415 ty::FnPtr(_) => ty.fn_sig(cx.tcx),
416 ty::Closure(def_id, substs) => {
418 let sig = substs.closure_sig(def_id, tcx);
420 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
421 sig.map_bound(|sig| tcx.mk_fn_sig(
422 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
429 ty::Generator(def_id, substs, _) => {
431 let sig = substs.poly_sig(def_id, cx.tcx);
433 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
434 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
436 sig.map_bound(|sig| {
437 let state_did = tcx.lang_items().gen_state().unwrap();
438 let state_adt_ref = tcx.adt_def(state_did);
439 let state_substs = tcx.intern_substs(&[
441 sig.return_ty.into(),
443 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
445 tcx.mk_fn_sig(iter::once(env_ty),
448 hir::Unsafety::Normal,
453 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)