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::ty::layout::{self, Align, LayoutOf, TyLayout};
14 use rustc_data_structures::indexed_vec::Idx;
17 use common::{self, CodegenCx, C_undef, C_usize};
20 use type_of::LayoutLlvmExt;
26 use super::{FunctionCx, LocalRef};
27 use super::place::PlaceRef;
29 /// The representation of a Rust value. The enum variant is in fact
30 /// uniquely determined by the value's type, but is kept as a
32 #[derive(Copy, Clone)]
33 pub enum OperandValue {
34 /// A reference to the actual operand. The data is guaranteed
35 /// to be valid for the operand's lifetime.
37 /// A single LLVM value.
39 /// A pair of immediate LLVM values. Used by fat pointers too.
40 Pair(ValueRef, ValueRef)
43 impl fmt::Debug for OperandValue {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46 OperandValue::Ref(r, align) => {
47 write!(f, "Ref({:?}, {:?})", Value(r), align)
49 OperandValue::Immediate(i) => {
50 write!(f, "Immediate({:?})", Value(i))
52 OperandValue::Pair(a, b) => {
53 write!(f, "Pair({:?}, {:?})", Value(a), Value(b))
59 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
62 /// NOTE: unless you know a value's type exactly, you should not
63 /// generate LLVM opcodes acting on it and instead act via methods,
64 /// to avoid nasty edge cases. In particular, using `Builder::store`
65 /// directly is sure to cause problems -- use `OperandRef::store`
67 #[derive(Copy, Clone)]
68 pub struct OperandRef<'tcx> {
70 pub val: OperandValue,
72 // The layout of value, based on its Rust type.
73 pub layout: TyLayout<'tcx>,
76 impl<'tcx> fmt::Debug for OperandRef<'tcx> {
77 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
82 impl<'a, 'tcx> OperandRef<'tcx> {
83 pub fn new_zst(cx: &CodegenCx<'a, 'tcx>,
84 layout: TyLayout<'tcx>) -> OperandRef<'tcx> {
85 assert!(layout.is_zst());
87 val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
92 /// Asserts that this operand refers to a scalar and returns
93 /// a reference to its value.
94 pub fn immediate(self) -> ValueRef {
96 OperandValue::Immediate(s) => s,
97 _ => bug!("not immediate: {:?}", self)
101 pub fn deref(self, cx: &CodegenCx<'a, 'tcx>) -> PlaceRef<'tcx> {
102 let projected_ty = self.layout.ty.builtin_deref(true)
103 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
104 let (llptr, llextra) = match self.val {
105 OperandValue::Immediate(llptr) => (llptr, ptr::null_mut()),
106 OperandValue::Pair(llptr, llextra) => (llptr, llextra),
107 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
109 let layout = cx.layout_of(projected_ty);
118 /// If this operand is a `Pair`, we return an aggregate with the two values.
119 /// For other cases, see `immediate`.
120 pub fn immediate_or_packed_pair(self, bx: &Builder<'a, 'tcx>) -> ValueRef {
121 if let OperandValue::Pair(a, b) = self.val {
122 let llty = self.layout.llvm_type(bx.cx);
123 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
125 // Reconstruct the immediate aggregate.
126 let mut llpair = C_undef(llty);
127 llpair = bx.insert_value(llpair, a, 0);
128 llpair = bx.insert_value(llpair, b, 1);
135 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
136 pub fn from_immediate_or_packed_pair(bx: &Builder<'a, 'tcx>,
138 layout: TyLayout<'tcx>)
139 -> OperandRef<'tcx> {
140 let val = if layout.is_llvm_scalar_pair() {
141 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
144 // Deconstruct the immediate aggregate.
145 OperandValue::Pair(bx.extract_value(llval, 0),
146 bx.extract_value(llval, 1))
148 OperandValue::Immediate(llval)
150 OperandRef { val, layout }
153 pub fn extract_field(&self, bx: &Builder<'a, 'tcx>, i: usize) -> OperandRef<'tcx> {
154 let field = self.layout.field(bx.cx, i);
155 let offset = self.layout.fields.offset(i);
157 let mut val = match (self.val, &self.layout.abi) {
158 // If we're uninhabited, or the field is ZST, it has no data.
159 _ if self.layout.abi == layout::Abi::Uninhabited || field.is_zst() => {
161 val: OperandValue::Immediate(C_undef(field.immediate_llvm_type(bx.cx))),
166 // Newtype of a scalar, scalar pair or vector.
167 (OperandValue::Immediate(_), _) |
168 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
169 assert_eq!(offset.bytes(), 0);
173 // Extract a scalar component from a pair.
174 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
175 if offset.bytes() == 0 {
176 assert_eq!(field.size, a.value.size(bx.cx));
177 OperandValue::Immediate(a_llval)
179 assert_eq!(offset, a.value.size(bx.cx)
180 .abi_align(b.value.align(bx.cx)));
181 assert_eq!(field.size, b.value.size(bx.cx));
182 OperandValue::Immediate(b_llval)
186 // `#[repr(simd)]` types are also immediate.
187 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
188 OperandValue::Immediate(
189 bx.extract_element(llval, C_usize(bx.cx, i as u64)))
192 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
195 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
197 OperandValue::Immediate(ref mut llval) => {
198 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
200 OperandValue::Pair(ref mut a, ref mut b) => {
201 *a = bx.bitcast(*a, field.scalar_pair_element_llvm_type(bx.cx, 0));
202 *b = bx.bitcast(*b, field.scalar_pair_element_llvm_type(bx.cx, 1));
204 OperandValue::Ref(..) => bug!()
214 impl<'a, 'tcx> OperandValue {
215 pub fn store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
216 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
217 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
218 // value is through `undef`, and store itself is useless.
219 if dest.layout.is_zst() {
223 OperandValue::Ref(r, source_align) =>
224 base::memcpy_ty(bx, dest.llval, r, dest.layout,
225 source_align.min(dest.align)),
226 OperandValue::Immediate(s) => {
227 bx.store(base::from_immediate(bx, s), dest.llval, dest.align);
229 OperandValue::Pair(a, b) => {
230 for (i, &x) in [a, b].iter().enumerate() {
231 let mut llptr = bx.struct_gep(dest.llval, i as u64);
232 // Make sure to always store i1 as i8.
233 if common::val_ty(x) == Type::i1(bx.cx) {
234 llptr = bx.pointercast(llptr, Type::i8p(bx.cx));
236 bx.store(base::from_immediate(bx, x), llptr, dest.align);
243 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
244 fn maybe_trans_consume_direct(&mut self,
245 bx: &Builder<'a, 'tcx>,
246 place: &mir::Place<'tcx>)
247 -> Option<OperandRef<'tcx>>
249 debug!("maybe_trans_consume_direct(place={:?})", place);
251 // watch out for locals that do not have an
252 // alloca; they are handled somewhat differently
253 if let mir::Place::Local(index) = *place {
254 match self.locals[index] {
255 LocalRef::Operand(Some(o)) => {
258 LocalRef::Operand(None) => {
259 bug!("use of {:?} before def", place);
261 LocalRef::Place(..) => {
267 // Moves out of scalar and scalar pair fields are trivial.
268 if let &mir::Place::Projection(ref proj) = place {
269 if let Some(o) = self.maybe_trans_consume_direct(bx, &proj.base) {
271 mir::ProjectionElem::Field(ref f, _) => {
272 return Some(o.extract_field(bx, f.index()));
274 mir::ProjectionElem::Index(_) |
275 mir::ProjectionElem::ConstantIndex { .. } => {
276 // ZSTs don't require any actual memory access.
277 // FIXME(eddyb) deduplicate this with the identical
278 // checks in `trans_consume` and `extract_field`.
279 let elem = o.layout.field(bx.cx, 0);
281 return Some(OperandRef::new_zst(bx.cx, elem));
292 pub fn trans_consume(&mut self,
293 bx: &Builder<'a, 'tcx>,
294 place: &mir::Place<'tcx>)
297 debug!("trans_consume(place={:?})", place);
299 let ty = self.monomorphized_place_ty(place);
300 let layout = bx.cx.layout_of(ty);
302 // ZSTs don't require any actual memory access.
304 return OperandRef::new_zst(bx.cx, layout);
307 if let Some(o) = self.maybe_trans_consume_direct(bx, place) {
311 // for most places, to consume them we just load them
312 // out from their home
313 self.trans_place(bx, place).load(bx)
316 pub fn trans_operand(&mut self,
317 bx: &Builder<'a, 'tcx>,
318 operand: &mir::Operand<'tcx>)
321 debug!("trans_operand(operand={:?})", operand);
324 mir::Operand::Copy(ref place) |
325 mir::Operand::Move(ref place) => {
326 self.trans_consume(bx, place)
329 mir::Operand::Constant(ref constant) => {
330 let val = self.trans_constant(&bx, constant);
331 let operand = val.to_operand(bx.cx);
332 if let OperandValue::Ref(ptr, align) = operand.val {
333 // If this is a OperandValue::Ref to an immediate constant, load it.
334 PlaceRef::new_sized(ptr, operand.layout, align).load(bx)