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