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.
12 use rustc::mir::interpret::ConstEvalErr;
13 use rustc_mir::interpret::{read_target_uint, const_val_field};
14 use rustc::hir::def_id::DefId;
16 use rustc_data_structures::indexed_vec::Idx;
17 use rustc_data_structures::sync::Lrc;
18 use rustc::mir::interpret::{GlobalId, Pointer, Scalar, Allocation, ConstValue, AllocType};
19 use rustc::ty::{self, Ty};
20 use rustc::ty::layout::{self, HasDataLayout, LayoutOf, Size};
22 use common::{CodegenCx};
23 use common::{C_bytes, C_struct, C_uint_big, C_undef, C_usize};
25 use type_of::LayoutLlvmExt;
27 use syntax::ast::Mutability;
28 use syntax::codemap::Span;
31 use super::super::callee;
32 use super::FunctionCx;
34 pub fn scalar_to_llvm(
35 cx: &CodegenCx<'ll, '_>,
37 layout: &layout::Scalar,
40 let bitsize = if layout.is_bool() { 1 } else { layout.value.size(cx).bits() };
42 Scalar::Bits { defined, .. } if (defined as u64) < bitsize || defined == 0 => {
43 C_undef(Type::ix(cx, bitsize))
45 Scalar::Bits { bits, .. } => {
46 let llval = C_uint_big(Type::ix(cx, bitsize), bits);
47 if layout.value == layout::Pointer {
48 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
50 consts::bitcast(llval, llty)
54 let alloc_type = cx.tcx.alloc_map.lock().get(ptr.alloc_id);
55 let base_addr = match alloc_type {
56 Some(AllocType::Memory(alloc)) => {
57 let init = const_alloc_to_llvm(cx, alloc);
58 if alloc.runtime_mutability == Mutability::Mutable {
59 consts::addr_of_mut(cx, init, alloc.align, "byte_str")
61 consts::addr_of(cx, init, alloc.align, "byte_str")
64 Some(AllocType::Function(fn_instance)) => {
65 callee::get_fn(cx, fn_instance)
67 Some(AllocType::Static(def_id)) => {
68 assert!(cx.tcx.is_static(def_id).is_some());
69 consts::get_static(cx, def_id)
71 None => bug!("missing allocation {:?}", ptr.alloc_id),
73 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
74 consts::bitcast(base_addr, Type::i8p(cx)),
75 &C_usize(cx, ptr.offset.bytes()),
78 if layout.value != layout::Pointer {
79 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
81 consts::bitcast(llval, llty)
87 pub fn const_alloc_to_llvm(cx: &CodegenCx<'ll, '_>, alloc: &Allocation) -> &'ll Value {
88 let mut llvals = Vec::with_capacity(alloc.relocations.len() + 1);
89 let layout = cx.data_layout();
90 let pointer_size = layout.pointer_size.bytes() as usize;
92 let mut next_offset = 0;
93 for &(offset, alloc_id) in alloc.relocations.iter() {
94 let offset = offset.bytes();
95 assert_eq!(offset as usize as u64, offset);
96 let offset = offset as usize;
97 if offset > next_offset {
98 llvals.push(C_bytes(cx, &alloc.bytes[next_offset..offset]));
100 let ptr_offset = read_target_uint(
102 &alloc.bytes[offset..(offset + pointer_size)],
103 ).expect("const_alloc_to_llvm: could not read relocation pointer") as u64;
104 llvals.push(scalar_to_llvm(
106 Pointer { alloc_id, offset: Size::from_bytes(ptr_offset) }.into(),
108 value: layout::Primitive::Pointer,
113 next_offset = offset + pointer_size;
115 if alloc.bytes.len() >= next_offset {
116 llvals.push(C_bytes(cx, &alloc.bytes[next_offset ..]));
119 C_struct(cx, &llvals, true)
122 pub fn codegen_static_initializer(
123 cx: &CodegenCx<'ll, 'tcx>,
125 ) -> Result<(&'ll Value, &'tcx Allocation), Lrc<ConstEvalErr<'tcx>>> {
126 let instance = ty::Instance::mono(cx.tcx, def_id);
131 let param_env = ty::ParamEnv::reveal_all();
132 let static_ = cx.tcx.const_eval(param_env.and(cid))?;
134 let alloc = match static_.val {
135 ConstValue::ByRef(alloc, n) if n.bytes() == 0 => alloc,
136 _ => bug!("static const eval returned {:#?}", static_),
138 Ok((const_alloc_to_llvm(cx, alloc), alloc))
141 impl FunctionCx<'a, 'll, 'tcx> {
144 bx: &Builder<'a, 'll, 'tcx>,
145 constant: &'tcx ty::Const<'tcx>,
146 ) -> Result<&'tcx ty::Const<'tcx>, Lrc<ConstEvalErr<'tcx>>> {
148 ConstValue::Unevaluated(def_id, ref substs) => {
150 let param_env = ty::ParamEnv::reveal_all();
151 let instance = ty::Instance::resolve(tcx, param_env, def_id, substs).unwrap();
156 tcx.const_eval(param_env.and(cid))
162 pub fn eval_mir_constant(
164 bx: &Builder<'a, 'll, 'tcx>,
165 constant: &mir::Constant<'tcx>,
166 ) -> Result<&'tcx ty::Const<'tcx>, Lrc<ConstEvalErr<'tcx>>> {
167 let c = self.monomorphize(&constant.literal);
168 self.fully_evaluate(bx, c)
171 /// process constant containing SIMD shuffle indices
172 pub fn simd_shuffle_indices(
174 bx: &Builder<'a, 'll, 'tcx>,
177 constant: Result<&'tcx ty::Const<'tcx>, Lrc<ConstEvalErr<'tcx>>>,
178 ) -> (&'ll Value, Ty<'tcx>) {
181 let field_ty = c.ty.builtin_index().unwrap();
182 let fields = match c.ty.sty {
183 ty::TyArray(_, n) => n.unwrap_usize(bx.tcx()),
184 ref other => bug!("invalid simd shuffle type: {}", other),
186 let values: Result<Vec<_>, Lrc<_>> = (0..fields).map(|field| {
187 let field = const_val_field(
189 ty::ParamEnv::reveal_all(),
192 mir::Field::new(field as usize),
195 if let Some(prim) = field.to_scalar() {
196 let layout = bx.cx.layout_of(field_ty);
197 let scalar = match layout.abi {
198 layout::Abi::Scalar(ref x) => x,
199 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
203 layout.immediate_llvm_type(bx.cx),
206 bug!("simd shuffle field {:?}", field)
209 let llval = C_struct(bx.cx, &values?, false);
212 .unwrap_or_else(|e| {
215 "could not evaluate shuffle_indices at compile time",
217 // We've errored, so we don't have to produce working code.
218 let ty = self.monomorphize(&ty);
219 let llty = bx.cx.layout_of(ty).llvm_type(bx.cx);