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