]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/constant.rs
0d682d5d6f6a1478fc86286a5ab68379a95b7abd
[rust.git] / src / librustc_codegen_llvm / mir / constant.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 use llvm::{self, ValueRef};
12 use rustc::mir::interpret::ConstEvalErr;
13 use rustc_mir::interpret::{read_target_uint, const_val_field};
14 use rustc::hir::def_id::DefId;
15 use rustc::mir;
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};
21 use builder::Builder;
22 use common::{CodegenCx};
23 use common::{C_bytes, C_struct, C_uint_big, C_undef, C_usize};
24 use consts;
25 use type_of::LayoutLlvmExt;
26 use type_::Type;
27 use syntax::ast::Mutability;
28 use syntax::codemap::Span;
29
30 use super::super::callee;
31 use super::FunctionCx;
32
33 pub fn scalar_to_llvm(cx: &CodegenCx,
34                        cv: Scalar,
35                        layout: &layout::Scalar,
36                        llty: Type) -> ValueRef {
37     let bitsize = if layout.is_bool() { 1 } else { layout.value.size(cx).bits() };
38     match cv {
39         Scalar::Bits { defined, .. } if (defined as u64) < bitsize || defined == 0 => {
40             C_undef(Type::ix(cx, bitsize))
41         },
42         Scalar::Bits { bits, .. } => {
43             let llval = C_uint_big(Type::ix(cx, bitsize), bits);
44             if layout.value == layout::Pointer {
45                 unsafe { llvm::LLVMConstIntToPtr(llval, llty.to_ref()) }
46             } else {
47                 consts::bitcast(llval, llty)
48             }
49         },
50         Scalar::Ptr(ptr) => {
51             let alloc_type = cx.tcx.alloc_map.lock().get(ptr.alloc_id);
52             let base_addr = match alloc_type {
53                 Some(AllocType::Memory(alloc)) => {
54                     let init = const_alloc_to_llvm(cx, alloc);
55                     if alloc.runtime_mutability == Mutability::Mutable {
56                         consts::addr_of_mut(cx, init, alloc.align, "byte_str")
57                     } else {
58                         consts::addr_of(cx, init, alloc.align, "byte_str")
59                     }
60                 }
61                 Some(AllocType::Function(fn_instance)) => {
62                     callee::get_fn(cx, fn_instance)
63                 }
64                 Some(AllocType::Static(def_id)) => {
65                     assert!(cx.tcx.is_static(def_id).is_some());
66                     consts::get_static(cx, def_id)
67                 }
68                 None => bug!("missing allocation {:?}", ptr.alloc_id),
69             };
70             let llval = unsafe { llvm::LLVMConstInBoundsGEP(
71                 consts::bitcast(base_addr, Type::i8p(cx)),
72                 &C_usize(cx, ptr.offset.bytes()),
73                 1,
74             ) };
75             if layout.value != layout::Pointer {
76                 unsafe { llvm::LLVMConstPtrToInt(llval, llty.to_ref()) }
77             } else {
78                 consts::bitcast(llval, llty)
79             }
80         }
81     }
82 }
83
84 pub fn const_alloc_to_llvm(cx: &CodegenCx, alloc: &Allocation) -> ValueRef {
85     let mut llvals = Vec::with_capacity(alloc.relocations.len() + 1);
86     let layout = cx.data_layout();
87     let pointer_size = layout.pointer_size.bytes() as usize;
88
89     let mut next_offset = 0;
90     for &(offset, alloc_id) in alloc.relocations.iter() {
91         let offset = offset.bytes();
92         assert_eq!(offset as usize as u64, offset);
93         let offset = offset as usize;
94         if offset > next_offset {
95             llvals.push(C_bytes(cx, &alloc.bytes[next_offset..offset]));
96         }
97         let ptr_offset = read_target_uint(
98             layout.endian,
99             &alloc.bytes[offset..(offset + pointer_size)],
100         ).expect("const_alloc_to_llvm: could not read relocation pointer") as u64;
101         llvals.push(scalar_to_llvm(
102             cx,
103             Pointer { alloc_id, offset: Size::from_bytes(ptr_offset) }.into(),
104             &layout::Scalar {
105                 value: layout::Primitive::Pointer,
106                 valid_range: 0..=!0
107             },
108             Type::i8p(cx)
109         ));
110         next_offset = offset + pointer_size;
111     }
112     if alloc.bytes.len() >= next_offset {
113         llvals.push(C_bytes(cx, &alloc.bytes[next_offset ..]));
114     }
115
116     C_struct(cx, &llvals, true)
117 }
118
119 pub fn codegen_static_initializer<'a, 'tcx>(
120     cx: &CodegenCx<'a, 'tcx>,
121     def_id: DefId,
122 ) -> Result<(ValueRef, &'tcx Allocation), Lrc<ConstEvalErr<'tcx>>> {
123     let instance = ty::Instance::mono(cx.tcx, def_id);
124     let cid = GlobalId {
125         instance,
126         promoted: None,
127     };
128     let param_env = ty::ParamEnv::reveal_all();
129     let static_ = cx.tcx.const_eval(param_env.and(cid))?;
130
131     let alloc = match static_.val {
132         ConstValue::ByRef(alloc, n) if n.bytes() == 0 => alloc,
133         _ => bug!("static const eval returned {:#?}", static_),
134     };
135     Ok((const_alloc_to_llvm(cx, alloc), alloc))
136 }
137
138 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
139     fn fully_evaluate(
140         &mut self,
141         bx: &Builder<'a, 'tcx>,
142         constant: &'tcx ty::Const<'tcx>,
143     ) -> Result<&'tcx ty::Const<'tcx>, Lrc<ConstEvalErr<'tcx>>> {
144         match constant.val {
145             ConstValue::Unevaluated(def_id, ref substs) => {
146                 let tcx = bx.tcx();
147                 let param_env = ty::ParamEnv::reveal_all();
148                 let instance = ty::Instance::resolve(tcx, param_env, def_id, substs).unwrap();
149                 let cid = GlobalId {
150                     instance,
151                     promoted: None,
152                 };
153                 tcx.const_eval(param_env.and(cid))
154             },
155             _ => Ok(constant),
156         }
157     }
158
159     pub fn eval_mir_constant(
160         &mut self,
161         bx: &Builder<'a, 'tcx>,
162         constant: &mir::Constant<'tcx>,
163     ) -> Result<&'tcx ty::Const<'tcx>, Lrc<ConstEvalErr<'tcx>>> {
164         let c = self.monomorphize(&constant.literal);
165         self.fully_evaluate(bx, c)
166     }
167
168     /// process constant containing SIMD shuffle indices
169     pub fn simd_shuffle_indices(
170         &mut self,
171         bx: &Builder<'a, 'tcx>,
172         span: Span,
173         ty: Ty<'tcx>,
174         constant: Result<&'tcx ty::Const<'tcx>, Lrc<ConstEvalErr<'tcx>>>,
175     ) -> (ValueRef, Ty<'tcx>) {
176         constant
177             .and_then(|c| {
178                 let field_ty = c.ty.builtin_index().unwrap();
179                 let fields = match c.ty.sty {
180                     ty::TyArray(_, n) => n.unwrap_usize(bx.tcx()),
181                     ref other => bug!("invalid simd shuffle type: {}", other),
182                 };
183                 let values: Result<Vec<ValueRef>, Lrc<_>> = (0..fields).map(|field| {
184                     let field = const_val_field(
185                         bx.tcx(),
186                         ty::ParamEnv::reveal_all(),
187                         self.instance,
188                         None,
189                         mir::Field::new(field as usize),
190                         c,
191                     )?;
192                     if let Some(prim) = field.to_scalar() {
193                         let layout = bx.cx.layout_of(field_ty);
194                         let scalar = match layout.abi {
195                             layout::Abi::Scalar(ref x) => x,
196                             _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
197                         };
198                         Ok(scalar_to_llvm(
199                             bx.cx, prim, scalar,
200                             layout.immediate_llvm_type(bx.cx),
201                         ))
202                     } else {
203                         bug!("simd shuffle field {:?}", field)
204                     }
205                 }).collect();
206                 let llval = C_struct(bx.cx, &values?, false);
207                 Ok((llval, c.ty))
208             })
209             .unwrap_or_else(|e| {
210                 e.report_as_error(
211                     bx.tcx().at(span),
212                     "could not evaluate shuffle_indices at compile time",
213                 );
214                 // We've errored, so we don't have to produce working code.
215                 let ty = self.monomorphize(&ty);
216                 let llty = bx.cx.layout_of(ty).llvm_type(bx.cx);
217                 (C_undef(llty), ty)
218             })
219     }
220 }