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;
14 use rustc::mir::interpret::ConstValue;
16 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
17 use rustc_data_structures::indexed_vec::Idx;
18 use rustc_data_structures::sync::Lrc;
21 use common::{CodegenCx, C_undef, C_usize};
22 use builder::{Builder, MemFlags};
24 use type_of::LayoutLlvmExt;
28 use super::{FunctionCx, LocalRef};
29 use super::constant::scalar_to_llvm;
30 use super::place::PlaceRef;
32 /// The representation of a Rust value. The enum variant is in fact
33 /// uniquely determined by the value's type, but is kept as a
35 #[derive(Copy, Clone)]
36 pub enum OperandValue {
37 /// A reference to the actual operand. The data is guaranteed
38 /// to be valid for the operand's lifetime.
40 /// A single LLVM value.
42 /// A pair of immediate LLVM values. Used by fat pointers too.
43 Pair(ValueRef, ValueRef)
46 impl fmt::Debug for OperandValue {
47 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49 OperandValue::Ref(r, align) => {
50 write!(f, "Ref({:?}, {:?})", Value(r), align)
52 OperandValue::Immediate(i) => {
53 write!(f, "Immediate({:?})", Value(i))
55 OperandValue::Pair(a, b) => {
56 write!(f, "Pair({:?}, {:?})", Value(a), Value(b))
62 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
65 /// NOTE: unless you know a value's type exactly, you should not
66 /// generate LLVM opcodes acting on it and instead act via methods,
67 /// to avoid nasty edge cases. In particular, using `Builder::store`
68 /// directly is sure to cause problems -- use `OperandRef::store`
70 #[derive(Copy, Clone)]
71 pub struct OperandRef<'tcx> {
73 pub val: OperandValue,
75 // The layout of value, based on its Rust type.
76 pub layout: TyLayout<'tcx>,
79 impl<'tcx> fmt::Debug for OperandRef<'tcx> {
80 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
85 impl<'a, 'tcx> OperandRef<'tcx> {
86 pub fn new_zst(cx: &CodegenCx<'a, 'tcx>,
87 layout: TyLayout<'tcx>) -> OperandRef<'tcx> {
88 assert!(layout.is_zst());
90 val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
95 pub fn from_const(bx: &Builder<'a, 'tcx>,
96 val: &'tcx ty::Const<'tcx>)
97 -> Result<OperandRef<'tcx>, Lrc<ConstEvalErr<'tcx>>> {
98 let layout = bx.cx.layout_of(val.ty);
101 return Ok(OperandRef::new_zst(bx.cx, layout));
104 let val = match val.val {
105 ConstValue::Unevaluated(..) => bug!(),
106 ConstValue::Scalar(x) => {
107 let scalar = match layout.abi {
108 layout::Abi::Scalar(ref x) => x,
109 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
111 let llval = scalar_to_llvm(
115 layout.immediate_llvm_type(bx.cx),
117 OperandValue::Immediate(llval)
119 ConstValue::ScalarPair(a, b) => {
120 let (a_scalar, b_scalar) = match layout.abi {
121 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
122 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
124 let a_llval = scalar_to_llvm(
128 layout.scalar_pair_element_llvm_type(bx.cx, 0, true),
130 let b_llval = scalar_to_llvm(
134 layout.scalar_pair_element_llvm_type(bx.cx, 1, true),
136 OperandValue::Pair(a_llval, b_llval)
138 ConstValue::ByRef(alloc, offset) => {
139 return Ok(PlaceRef::from_const_alloc(bx, layout, alloc, offset).load(bx));
149 /// Asserts that this operand refers to a scalar and returns
150 /// a reference to its value.
151 pub fn immediate(self) -> ValueRef {
153 OperandValue::Immediate(s) => s,
154 _ => bug!("not immediate: {:?}", self)
158 pub fn deref(self, cx: &CodegenCx<'a, 'tcx>) -> PlaceRef<'tcx> {
159 let projected_ty = self.layout.ty.builtin_deref(true)
160 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
161 let (llptr, llextra) = match self.val {
162 OperandValue::Immediate(llptr) => (llptr, 0 as *mut _),
163 OperandValue::Pair(llptr, llextra) => (llptr, llextra),
164 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
166 let layout = cx.layout_of(projected_ty);
175 /// If this operand is a `Pair`, we return an aggregate with the two values.
176 /// For other cases, see `immediate`.
177 pub fn immediate_or_packed_pair(self, bx: &Builder<'a, 'tcx>) -> ValueRef {
178 if let OperandValue::Pair(a, b) = self.val {
179 let llty = self.layout.llvm_type(bx.cx);
180 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
182 // Reconstruct the immediate aggregate.
183 let mut llpair = C_undef(llty);
184 llpair = bx.insert_value(llpair, base::from_immediate(bx, a), 0);
185 llpair = bx.insert_value(llpair, base::from_immediate(bx, b), 1);
192 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
193 pub fn from_immediate_or_packed_pair(bx: &Builder<'a, 'tcx>,
195 layout: TyLayout<'tcx>)
196 -> OperandRef<'tcx> {
197 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
198 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
201 // Deconstruct the immediate aggregate.
202 let a_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 0), a);
203 let b_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 1), b);
204 OperandValue::Pair(a_llval, b_llval)
206 OperandValue::Immediate(llval)
208 OperandRef { val, layout }
211 pub fn extract_field(&self, bx: &Builder<'a, 'tcx>, i: usize) -> OperandRef<'tcx> {
212 let field = self.layout.field(bx.cx, i);
213 let offset = self.layout.fields.offset(i);
215 let mut val = match (self.val, &self.layout.abi) {
216 // If the field is ZST, it has no data.
217 _ if field.is_zst() => {
218 return OperandRef::new_zst(bx.cx, field);
221 // Newtype of a scalar, scalar pair or vector.
222 (OperandValue::Immediate(_), _) |
223 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
224 assert_eq!(offset.bytes(), 0);
228 // Extract a scalar component from a pair.
229 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
230 if offset.bytes() == 0 {
231 assert_eq!(field.size, a.value.size(bx.cx));
232 OperandValue::Immediate(a_llval)
234 assert_eq!(offset, a.value.size(bx.cx)
235 .abi_align(b.value.align(bx.cx)));
236 assert_eq!(field.size, b.value.size(bx.cx));
237 OperandValue::Immediate(b_llval)
241 // `#[repr(simd)]` types are also immediate.
242 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
243 OperandValue::Immediate(
244 bx.extract_element(llval, C_usize(bx.cx, i as u64)))
247 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
250 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
252 OperandValue::Immediate(ref mut llval) => {
253 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
255 OperandValue::Pair(ref mut a, ref mut b) => {
256 *a = bx.bitcast(*a, field.scalar_pair_element_llvm_type(bx.cx, 0, true));
257 *b = bx.bitcast(*b, field.scalar_pair_element_llvm_type(bx.cx, 1, true));
259 OperandValue::Ref(..) => bug!()
269 impl<'a, 'tcx> OperandValue {
270 pub fn store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
271 self.store_with_flags(bx, dest, MemFlags::empty());
274 pub fn volatile_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
275 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
278 pub fn unaligned_volatile_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
279 self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
282 pub fn nontemporal_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
283 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
286 fn store_with_flags(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>, flags: MemFlags) {
287 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
288 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
289 // value is through `undef`, and store itself is useless.
290 if dest.layout.is_zst() {
294 OperandValue::Ref(r, source_align) => {
295 base::memcpy_ty(bx, dest.llval, r, dest.layout,
296 source_align.min(dest.align), flags)
298 OperandValue::Immediate(s) => {
299 let val = base::from_immediate(bx, s);
300 bx.store_with_flags(val, dest.llval, dest.align, flags);
302 OperandValue::Pair(a, b) => {
303 for (i, &x) in [a, b].iter().enumerate() {
304 let llptr = bx.struct_gep(dest.llval, i as u64);
305 let val = base::from_immediate(bx, x);
306 bx.store_with_flags(val, llptr, dest.align, flags);
313 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
314 fn maybe_codegen_consume_direct(&mut self,
315 bx: &Builder<'a, 'tcx>,
316 place: &mir::Place<'tcx>)
317 -> Option<OperandRef<'tcx>>
319 debug!("maybe_codegen_consume_direct(place={:?})", place);
321 // watch out for locals that do not have an
322 // alloca; they are handled somewhat differently
323 if let mir::Place::Local(index) = *place {
324 match self.locals[index] {
325 LocalRef::Operand(Some(o)) => {
328 LocalRef::Operand(None) => {
329 bug!("use of {:?} before def", place);
331 LocalRef::Place(..) => {
337 // Moves out of scalar and scalar pair fields are trivial.
338 if let &mir::Place::Projection(ref proj) = place {
339 if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
341 mir::ProjectionElem::Field(ref f, _) => {
342 return Some(o.extract_field(bx, f.index()));
344 mir::ProjectionElem::Index(_) |
345 mir::ProjectionElem::ConstantIndex { .. } => {
346 // ZSTs don't require any actual memory access.
347 // FIXME(eddyb) deduplicate this with the identical
348 // checks in `codegen_consume` and `extract_field`.
349 let elem = o.layout.field(bx.cx, 0);
351 return Some(OperandRef::new_zst(bx.cx, elem));
362 pub fn codegen_consume(&mut self,
363 bx: &Builder<'a, 'tcx>,
364 place: &mir::Place<'tcx>)
367 debug!("codegen_consume(place={:?})", place);
369 let ty = self.monomorphized_place_ty(place);
370 let layout = bx.cx.layout_of(ty);
372 // ZSTs don't require any actual memory access.
374 return OperandRef::new_zst(bx.cx, layout);
377 if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
381 // for most places, to consume them we just load them
382 // out from their home
383 self.codegen_place(bx, place).load(bx)
386 pub fn codegen_operand(&mut self,
387 bx: &Builder<'a, 'tcx>,
388 operand: &mir::Operand<'tcx>)
391 debug!("codegen_operand(operand={:?})", operand);
394 mir::Operand::Copy(ref place) |
395 mir::Operand::Move(ref place) => {
396 self.codegen_consume(bx, place)
399 mir::Operand::Constant(ref constant) => {
400 let ty = self.monomorphize(&constant.ty);
401 self.eval_mir_constant(bx, constant)
402 .and_then(|c| OperandRef::from_const(bx, c))
403 .unwrap_or_else(|err| {
405 bx.tcx().at(constant.span),
406 "could not evaluate constant operand",
408 // Allow RalfJ to sleep soundly knowing that even refactorings that remove
409 // the above error (or silence it under some conditions) will not cause UB
410 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
411 bx.call(fnname, &[], None);
412 // We've errored, so we don't have to produce working code.
413 let layout = bx.cx.layout_of(ty);
415 C_undef(layout.llvm_type(bx.cx).ptr_to()),