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, True, False, Bool, BasicBlock, OperandBundleDef};
16 use rustc::hir::def_id::DefId;
17 use rustc::middle::lang_items::LangItem;
22 use type_of::LayoutLlvmExt;
26 use rustc::ty::{Ty, TyCtxt};
27 use rustc::ty::layout::{HasDataLayout, LayoutOf, self, TyLayout, Size};
28 use rustc::mir::interpret::{Scalar, AllocType, Allocation};
30 use mir::constant::const_alloc_to_llvm;
31 use mir::place::PlaceRef;
32 use rustc_codegen_ssa::common::TypeKind;
34 use libc::{c_uint, c_char};
36 use syntax::symbol::LocalInternedString;
37 use syntax::ast::Mutability;
40 pub use context::CodegenCx;
43 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
45 * An "extern" is an LLVM symbol we wind up emitting an undefined external
46 * reference to. This means "we don't have the thing in this compilation unit,
47 * please make sure you link it in at runtime". This could be a reference to
48 * C code found in a C library, or rust code found in a rust crate.
50 * Most "externs" are implicitly declared (automatically) as a result of a
51 * user declaring an extern _module_ dependency; this causes the rust driver
52 * to locate an extern crate, scan its compilation metadata, and emit extern
53 * declarations for any symbols used by the declaring crate.
55 * A "foreign" is an extern that references C (or other non-rust ABI) code.
56 * There is no metadata to scan for extern references so in these cases either
57 * a header-digester like bindgen, or manual function prototypes, have to
58 * serve as declarators. So these are usually given explicitly as prototype
59 * declarations, in rust code, with ABI attributes on them noting which ABI to
62 * An "upcall" is a foreign call generated by the compiler (not corresponding
63 * to any user-written call in the code) into the runtime library, to perform
64 * some helper task such as bringing a task to life, allocating memory, etc.
68 /// A structure representing an active landing pad for the duration of a basic
71 /// Each `Block` may contain an instance of this, indicating whether the block
72 /// is part of a landing pad or not. This is used to make decision about whether
73 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
74 /// use `invoke`) and also about various function call metadata.
76 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
77 /// just a bunch of `None` instances (not too interesting), but for MSVC
78 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
79 /// When inside of a landing pad, each function call in LLVM IR needs to be
80 /// annotated with which landing pad it's a part of. This is accomplished via
81 /// the `OperandBundleDef` value created for MSVC landing pads.
82 pub struct Funclet<'ll> {
83 cleanuppad: &'ll Value,
84 operand: OperandBundleDef<'ll>,
88 pub fn new(cleanuppad: &'ll Value) -> Self {
91 operand: OperandBundleDef::new("funclet", &[cleanuppad]),
95 pub fn cleanuppad(&self) -> &'ll Value {
99 pub fn bundle(&self) -> &OperandBundleDef<'ll> {
104 impl BackendTypes for CodegenCx<'ll, 'tcx> {
105 type Value = &'ll Value;
106 type BasicBlock = &'ll BasicBlock;
107 type Type = &'ll Type;
108 type Context = &'ll llvm::Context;
109 type Funclet = Funclet<'ll>;
111 type DIScope = &'ll llvm::debuginfo::DIScope;
114 impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
115 fn const_null(&self, t: &'ll Type) -> &'ll Value {
117 llvm::LLVMConstNull(t)
121 fn const_undef(&self, t: &'ll Type) -> &'ll Value {
123 llvm::LLVMGetUndef(t)
127 fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
129 llvm::LLVMConstInt(t, i as u64, True)
133 fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
135 llvm::LLVMConstInt(t, i, False)
139 fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
141 let words = [u as u64, (u >> 64) as u64];
142 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
146 fn const_bool(&self, val: bool) -> &'ll Value {
147 self.const_uint(self.type_i1(), val as u64)
150 fn const_i32(&self, i: i32) -> &'ll Value {
151 self.const_int(self.type_i32(), i as i64)
154 fn const_u32(&self, i: u32) -> &'ll Value {
155 self.const_uint(self.type_i32(), i as u64)
158 fn const_u64(&self, i: u64) -> &'ll Value {
159 self.const_uint(self.type_i64(), i)
162 fn const_usize(&self, i: u64) -> &'ll Value {
163 let bit_size = self.data_layout().pointer_size.bits();
165 // make sure it doesn't overflow
166 assert!(i < (1<<bit_size));
169 self.const_uint(self.isize_ty, i)
172 fn const_u8(&self, i: u8) -> &'ll Value {
173 self.const_uint(self.type_i8(), i as u64)
178 s: LocalInternedString,
179 null_terminated: bool,
182 if let Some(&llval) = self.const_cstr_cache.borrow().get(&s) {
186 let sc = llvm::LLVMConstStringInContext(self.llcx,
187 s.as_ptr() as *const c_char,
189 !null_terminated as Bool);
190 let sym = self.generate_local_symbol_name("str");
191 let g = self.define_global(&sym[..], self.val_ty(sc)).unwrap_or_else(||{
192 bug!("symbol `{}` is already defined", sym);
194 llvm::LLVMSetInitializer(g, sc);
195 llvm::LLVMSetGlobalConstant(g, True);
196 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
198 self.const_cstr_cache.borrow_mut().insert(s, g);
203 fn const_str_slice(&self, s: LocalInternedString) -> &'ll Value {
205 let cs = consts::ptrcast(self.const_cstr(s, false),
206 self.type_ptr_to(self.layout_of(self.tcx.mk_str()).llvm_type(self)));
207 self.const_fat_ptr(cs, self.const_usize(len as u64))
215 assert_eq!(abi::FAT_PTR_ADDR, 0);
216 assert_eq!(abi::FAT_PTR_EXTRA, 1);
217 self.const_struct(&[ptr, meta], false)
225 struct_in_context(self.llcx, elts, packed)
228 fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
230 return llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint);
234 fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
236 return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
240 fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
241 bytes_in_context(self.llcx, bytes)
244 fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
246 assert_eq!(idx as c_uint as u64, idx);
247 let us = &[idx as c_uint];
248 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
250 debug!("const_get_elt(v={:?}, idx={}, r={:?})",
257 fn const_get_real(&self, v: &'ll Value) -> Option<(f64, bool)> {
259 if self.is_const_real(v) {
260 let mut loses_info: llvm::Bool = ::std::mem::uninitialized();
261 let r = llvm::LLVMConstRealGetDouble(v, &mut loses_info);
262 let loses_info = if loses_info == 1 { true } else { false };
263 Some((r, loses_info))
270 fn const_to_uint(&self, v: &'ll Value) -> u64 {
272 llvm::LLVMConstIntGetZExtValue(v)
276 fn is_const_integral(&self, v: &'ll Value) -> bool {
278 llvm::LLVMIsAConstantInt(v).is_some()
282 fn is_const_real(&self, v: &'ll Value) -> bool {
284 llvm::LLVMIsAConstantFP(v).is_some()
288 fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
290 if self.is_const_integral(v) {
291 let (mut lo, mut hi) = (0u64, 0u64);
292 let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
295 Some(hi_lo_to_u128(lo, hi))
305 fn scalar_to_backend(
308 layout: &layout::Scalar,
311 let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
313 Scalar::Bits { size: 0, .. } => {
314 assert_eq!(0, layout.value.size(self).bytes());
315 self.const_undef(self.type_ix(0))
317 Scalar::Bits { bits, size } => {
318 assert_eq!(size as u64, layout.value.size(self).bytes());
319 let llval = self.const_uint_big(self.type_ix(bitsize), bits);
320 if layout.value == layout::Pointer {
321 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
323 self.static_bitcast(llval, llty)
326 Scalar::Ptr(ptr) => {
327 let alloc_type = self.tcx.alloc_map.lock().get(ptr.alloc_id);
328 let base_addr = match alloc_type {
329 Some(AllocType::Memory(alloc)) => {
330 let init = const_alloc_to_llvm(self, alloc);
331 if alloc.mutability == Mutability::Mutable {
332 self.static_addr_of_mut(init, alloc.align, None)
334 self.static_addr_of(init, alloc.align, None)
337 Some(AllocType::Function(fn_instance)) => {
338 self.get_fn(fn_instance)
340 Some(AllocType::Static(def_id)) => {
341 assert!(self.tcx.is_static(def_id).is_some());
342 self.get_static(def_id)
344 None => bug!("missing allocation {:?}", ptr.alloc_id),
346 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
347 self.static_bitcast(base_addr, self.type_i8p()),
348 &self.const_usize(ptr.offset.bytes()),
351 if layout.value != layout::Pointer {
352 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
354 self.static_bitcast(llval, llty)
362 layout: TyLayout<'tcx>,
365 ) -> PlaceRef<'tcx, &'ll Value> {
366 let init = const_alloc_to_llvm(self, alloc);
367 let base_addr = self.static_addr_of(init, layout.align, None);
369 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
370 self.static_bitcast(base_addr, self.type_i8p()),
371 &self.const_usize(offset.bytes()),
374 let llval = self.static_bitcast(llval, self.type_ptr_to(layout.llvm_type(self)));
375 PlaceRef::new_sized(llval, layout, alloc.align)
379 pub fn val_ty(v: &'ll Value) -> &'ll Type {
385 pub fn bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
387 let ptr = bytes.as_ptr() as *const c_char;
388 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
392 pub fn struct_in_context(
393 llcx: &'a llvm::Context,
398 llvm::LLVMConstStructInContext(llcx,
399 elts.as_ptr(), elts.len() as c_uint,
405 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
406 ((hi as u128) << 64) | (lo as u128)
409 pub fn langcall(tcx: TyCtxt,
414 tcx.lang_items().require(li).unwrap_or_else(|s| {
415 let msg = format!("{} {}", msg, s);
417 Some(span) => tcx.sess.span_fatal(span, &msg[..]),
418 None => tcx.sess.fatal(&msg[..]),
423 // To avoid UB from LLVM, these two functions mask RHS with an
424 // appropriate mask unconditionally (i.e. the fallback behavior for
425 // all shifts). For 32- and 64-bit types, this matches the semantics
426 // of Java. (See related discussion on #1877 and #10183.)
428 pub fn build_unchecked_lshift<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
433 let rhs = base::cast_shift_expr_rhs(bx, hir::BinOpKind::Shl, lhs, rhs);
434 // #1877, #10183: Ensure that input is always valid
435 let rhs = shift_mask_rhs(bx, rhs);
439 pub fn build_unchecked_rshift<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
445 let rhs = base::cast_shift_expr_rhs(bx, hir::BinOpKind::Shr, lhs, rhs);
446 // #1877, #10183: Ensure that input is always valid
447 let rhs = shift_mask_rhs(bx, rhs);
448 let is_signed = lhs_t.is_signed();
456 fn shift_mask_rhs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
460 let rhs_llty = bx.cx().val_ty(rhs);
461 bx.and(rhs, shift_mask_val(bx, rhs_llty, rhs_llty, false))
464 pub fn shift_mask_val<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
470 let kind = bx.cx().type_kind(llty);
472 TypeKind::Integer => {
473 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
474 let val = bx.cx().int_width(llty) - 1;
476 bx.cx().const_int(mask_llty, !val as i64)
478 bx.cx().const_uint(mask_llty, val)
481 TypeKind::Vector => {
482 let mask = shift_mask_val(
484 bx.cx().element_type(llty),
485 bx.cx().element_type(mask_llty),
488 bx.vector_splat(bx.cx().vector_length(mask_llty), mask)
490 _ => bug!("shift_mask_val: expected Integer or Vector, found {:?}", kind),