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 use rustc::mir::interpret::{ConstValue, ErrorHandled};
14 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
24 use super::{FunctionCx, LocalRef};
25 use super::place::PlaceRef;
27 /// The representation of a Rust value. The enum variant is in fact
28 /// uniquely determined by the value's type, but is kept as a
30 #[derive(Copy, Clone, Debug)]
31 pub enum OperandValue<V> {
32 /// A reference to the actual operand. The data is guaranteed
33 /// to be valid for the operand's lifetime.
34 /// The second value, if any, is the extra data (vtable or length)
35 /// which indicates that it refers to an unsized rvalue.
36 Ref(V, Option<V>, Align),
37 /// A single LLVM value.
39 /// A pair of immediate LLVM values. Used by fat pointers too.
43 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
46 /// NOTE: unless you know a value's type exactly, you should not
47 /// generate LLVM opcodes acting on it and instead act via methods,
48 /// to avoid nasty edge cases. In particular, using `Builder::store`
49 /// directly is sure to cause problems -- use `OperandRef::store`
51 #[derive(Copy, Clone)]
52 pub struct OperandRef<'tcx, V> {
54 pub val: OperandValue<V>,
56 // The layout of value, based on its Rust type.
57 pub layout: TyLayout<'tcx>,
60 impl<V: CodegenObject> fmt::Debug for OperandRef<'tcx, V> {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
66 impl<'a, 'tcx: 'a, V: CodegenObject> OperandRef<'tcx, V> {
67 pub fn new_zst<Cx: CodegenMethods<'tcx, Value = V>>(
69 layout: TyLayout<'tcx>
70 ) -> OperandRef<'tcx, V> {
71 assert!(layout.is_zst());
73 val: OperandValue::Immediate(cx.const_undef(cx.immediate_backend_type(layout))),
78 pub fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
80 val: &'tcx ty::Const<'tcx>
81 ) -> Result<Self, ErrorHandled> {
82 let layout = bx.cx().layout_of(val.ty);
85 return Ok(OperandRef::new_zst(bx.cx(), layout));
88 let val = match val.val {
89 ConstValue::Unevaluated(..) => bug!(),
90 ConstValue::Scalar(x) => {
91 let scalar = match layout.abi {
92 layout::Abi::Scalar(ref x) => x,
93 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
95 let llval = bx.cx().scalar_to_backend(
98 bx.cx().immediate_backend_type(layout),
100 OperandValue::Immediate(llval)
102 ConstValue::ScalarPair(a, b) => {
103 let (a_scalar, b_scalar) = match layout.abi {
104 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
105 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
107 let a_llval = bx.cx().scalar_to_backend(
110 bx.cx().scalar_pair_element_backend_type(layout, 0, true),
112 let b_llval = bx.cx().scalar_to_backend(
115 bx.cx().scalar_pair_element_backend_type(layout, 1, true),
117 OperandValue::Pair(a_llval, b_llval)
119 ConstValue::ByRef(_, alloc, offset) => {
120 return Ok(bx.load_operand(bx.cx().from_const_alloc(layout, alloc, offset)));
130 /// Asserts that this operand refers to a scalar and returns
131 /// a reference to its value.
132 pub fn immediate(self) -> V {
134 OperandValue::Immediate(s) => s,
135 _ => bug!("not immediate: {:?}", self)
139 pub fn deref<Cx: CodegenMethods<'tcx, Value = V>>(
142 ) -> PlaceRef<'tcx, V> {
143 let projected_ty = self.layout.ty.builtin_deref(true)
144 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
145 let (llptr, llextra) = match self.val {
146 OperandValue::Immediate(llptr) => (llptr, None),
147 OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
148 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
150 let layout = cx.layout_of(projected_ty);
159 /// If this operand is a `Pair`, we return an aggregate with the two values.
160 /// For other cases, see `immediate`.
161 pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
165 if let OperandValue::Pair(a, b) = self.val {
166 let llty = bx.cx().backend_type(self.layout);
167 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
169 // Reconstruct the immediate aggregate.
170 let mut llpair = bx.cx().const_undef(llty);
171 let imm_a = base::from_immediate(bx, a);
172 let imm_b = base::from_immediate(bx, b);
173 llpair = bx.insert_value(llpair, imm_a, 0);
174 llpair = bx.insert_value(llpair, imm_b, 1);
181 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
182 pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
185 layout: TyLayout<'tcx>
187 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
188 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
191 // Deconstruct the immediate aggregate.
192 let a_llval = bx.extract_value(llval, 0);
193 let a_llval = base::to_immediate_scalar(bx, a_llval, a);
194 let b_llval = bx.extract_value(llval, 1);
195 let b_llval = base::to_immediate_scalar(bx, b_llval, b);
196 OperandValue::Pair(a_llval, b_llval)
198 OperandValue::Immediate(llval)
200 OperandRef { val, layout }
203 pub fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
208 let field = self.layout.field(bx.cx(), i);
209 let offset = self.layout.fields.offset(i);
211 let mut val = match (self.val, &self.layout.abi) {
212 // If the field is ZST, it has no data.
213 _ if field.is_zst() => {
214 return OperandRef::new_zst(bx.cx(), field);
217 // Newtype of a scalar, scalar pair or vector.
218 (OperandValue::Immediate(_), _) |
219 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
220 assert_eq!(offset.bytes(), 0);
224 // Extract a scalar component from a pair.
225 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
226 if offset.bytes() == 0 {
227 assert_eq!(field.size, a.value.size(bx.cx()));
228 OperandValue::Immediate(a_llval)
230 assert_eq!(offset, a.value.size(bx.cx())
231 .abi_align(b.value.align(bx.cx())));
232 assert_eq!(field.size, b.value.size(bx.cx()));
233 OperandValue::Immediate(b_llval)
237 // `#[repr(simd)]` types are also immediate.
238 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
239 OperandValue::Immediate(
240 bx.extract_element(llval, bx.cx().const_usize(i as u64)))
243 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
246 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
248 OperandValue::Immediate(ref mut llval) => {
249 *llval = bx.bitcast(*llval, bx.cx().immediate_backend_type(field));
251 OperandValue::Pair(ref mut a, ref mut b) => {
252 *a = bx.bitcast(*a, bx.cx().scalar_pair_element_backend_type(field, 0, true));
253 *b = bx.bitcast(*b, bx.cx().scalar_pair_element_backend_type(field, 1, true));
255 OperandValue::Ref(..) => bug!()
265 impl<'a, 'tcx: 'a, V: CodegenObject> OperandValue<V> {
266 pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
269 dest: PlaceRef<'tcx, V>
271 self.store_with_flags(bx, dest, MemFlags::empty());
274 pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
277 dest: PlaceRef<'tcx, V>
279 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
282 pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
285 dest: PlaceRef<'tcx, V>,
287 self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
290 pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
293 dest: PlaceRef<'tcx, V>
295 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
298 fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
301 dest: PlaceRef<'tcx, V>,
304 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
305 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
306 // value is through `undef`, and store itself is useless.
307 if dest.layout.is_zst() {
311 OperandValue::Ref(r, None, source_align) => {
312 base::memcpy_ty(bx, dest.llval, dest.align, r, source_align,
315 OperandValue::Ref(_, Some(_), _) => {
316 bug!("cannot directly store unsized values");
318 OperandValue::Immediate(s) => {
319 let val = base::from_immediate(bx, s);
320 bx.store_with_flags(val, dest.llval, dest.align, flags);
322 OperandValue::Pair(a, b) => {
323 for (i, &x) in [a, b].iter().enumerate() {
324 let llptr = bx.struct_gep(dest.llval, i as u64);
325 let val = base::from_immediate(bx, x);
326 bx.store_with_flags(val, llptr, dest.align, flags);
331 pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
334 indirect_dest: PlaceRef<'tcx, V>
336 debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
337 let flags = MemFlags::empty();
339 // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
340 let unsized_ty = indirect_dest.layout.ty.builtin_deref(true)
341 .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest)).ty;
343 let (llptr, llextra) =
344 if let OperandValue::Ref(llptr, Some(llextra), _) = self {
347 bug!("store_unsized called with a sized value")
350 // FIXME: choose an appropriate alignment, or use dynamic align somehow
351 let max_align = Align::from_bits(128, 128).unwrap();
352 let min_align = Align::from_bits(8, 8).unwrap();
354 // Allocate an appropriate region on the stack, and copy the value into it
355 let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
356 let lldst = bx.array_alloca(bx.cx().type_i8(), llsize, "unsized_tmp", max_align);
357 bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags);
359 // Store the allocated region and the extra to the indirect place.
360 let indirect_operand = OperandValue::Pair(lldst, llextra);
361 indirect_operand.store(bx, indirect_dest);
365 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
366 fn maybe_codegen_consume_direct(
369 place: &mir::Place<'tcx>
370 ) -> Option<OperandRef<'tcx, Bx::Value>> {
371 debug!("maybe_codegen_consume_direct(place={:?})", place);
373 // watch out for locals that do not have an
374 // alloca; they are handled somewhat differently
375 if let mir::Place::Local(index) = *place {
376 match self.locals[index] {
377 LocalRef::Operand(Some(o)) => {
380 LocalRef::Operand(None) => {
381 bug!("use of {:?} before def", place);
383 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
389 // Moves out of scalar and scalar pair fields are trivial.
390 if let &mir::Place::Projection(ref proj) = place {
391 if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
393 mir::ProjectionElem::Field(ref f, _) => {
394 return Some(o.extract_field(bx, f.index()));
396 mir::ProjectionElem::Index(_) |
397 mir::ProjectionElem::ConstantIndex { .. } => {
398 // ZSTs don't require any actual memory access.
399 // FIXME(eddyb) deduplicate this with the identical
400 // checks in `codegen_consume` and `extract_field`.
401 let elem = o.layout.field(bx.cx(), 0);
403 return Some(OperandRef::new_zst(bx.cx(), elem));
414 pub fn codegen_consume(
417 place: &mir::Place<'tcx>
418 ) -> OperandRef<'tcx, Bx::Value> {
419 debug!("codegen_consume(place={:?})", place);
421 let ty = self.monomorphized_place_ty(place);
422 let layout = bx.cx().layout_of(ty);
424 // ZSTs don't require any actual memory access.
426 return OperandRef::new_zst(bx.cx(), layout);
429 if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
433 // for most places, to consume them we just load them
434 // out from their home
435 let place = self.codegen_place(bx, place);
436 bx.load_operand(place)
439 pub fn codegen_operand(
442 operand: &mir::Operand<'tcx>
443 ) -> OperandRef<'tcx, Bx::Value> {
444 debug!("codegen_operand(operand={:?})", operand);
447 mir::Operand::Copy(ref place) |
448 mir::Operand::Move(ref place) => {
449 self.codegen_consume(bx, place)
452 mir::Operand::Constant(ref constant) => {
453 let ty = self.monomorphize(&constant.ty);
454 self.eval_mir_constant(bx, constant)
455 .and_then(|c| OperandRef::from_const(bx, c))
456 .unwrap_or_else(|err| {
458 // errored or at least linted
459 ErrorHandled::Reported => {},
460 ErrorHandled::TooGeneric => {
461 bug!("codgen encountered polymorphic constant")
464 // Allow RalfJ to sleep soundly knowing that even refactorings that remove
465 // the above error (or silence it under some conditions) will not cause UB
466 let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
467 bx.call(fnname, &[], None);
468 // We've errored, so we don't have to produce working code.
469 let layout = bx.cx().layout_of(ty);
470 bx.load_operand(PlaceRef::new_sized(
471 bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))),