1 use rustc::mir::interpret::{ConstValue, ErrorHandled};
4 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
14 use super::{FunctionCx, LocalRef};
15 use super::place::PlaceRef;
17 /// The representation of a Rust value. The enum variant is in fact
18 /// uniquely determined by the value's type, but is kept as a
20 #[derive(Copy, Clone, Debug)]
21 pub enum OperandValue<V> {
22 /// A reference to the actual operand. The data is guaranteed
23 /// to be valid for the operand's lifetime.
24 /// The second value, if any, is the extra data (vtable or length)
25 /// which indicates that it refers to an unsized rvalue.
26 Ref(V, Option<V>, Align),
27 /// A single LLVM value.
29 /// A pair of immediate LLVM values. Used by fat pointers too.
33 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
36 /// NOTE: unless you know a value's type exactly, you should not
37 /// generate LLVM opcodes acting on it and instead act via methods,
38 /// to avoid nasty edge cases. In particular, using `Builder::store`
39 /// directly is sure to cause problems -- use `OperandRef::store`
41 #[derive(Copy, Clone)]
42 pub struct OperandRef<'tcx, V> {
44 pub val: OperandValue<V>,
46 // The layout of value, based on its Rust type.
47 pub layout: TyLayout<'tcx>,
50 impl<V: CodegenObject> fmt::Debug for OperandRef<'tcx, V> {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
56 impl<'a, 'tcx: 'a, V: CodegenObject> OperandRef<'tcx, V> {
57 pub fn new_zst<Cx: CodegenMethods<'tcx, Value = V>>(
59 layout: TyLayout<'tcx>
60 ) -> OperandRef<'tcx, V> {
61 assert!(layout.is_zst());
63 val: OperandValue::Immediate(cx.const_undef(cx.immediate_backend_type(layout))),
68 pub fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
71 ) -> Result<Self, ErrorHandled> {
72 let layout = bx.cx().layout_of(val.ty);
75 return Ok(OperandRef::new_zst(bx.cx(), layout));
78 let val = match val.val {
79 ConstValue::Scalar(x) => {
80 let scalar = match layout.abi {
81 layout::Abi::Scalar(ref x) => x,
82 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
84 let llval = bx.cx().scalar_to_backend(
87 bx.cx().immediate_backend_type(layout),
89 OperandValue::Immediate(llval)
91 ConstValue::ScalarPair(a, b) => {
92 let (a_scalar, b_scalar) = match layout.abi {
93 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
94 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
96 let a_llval = bx.cx().scalar_to_backend(
99 bx.cx().scalar_pair_element_backend_type(layout, 0, true),
101 let b_llval = bx.cx().scalar_to_backend(
104 bx.cx().scalar_pair_element_backend_type(layout, 1, true),
106 OperandValue::Pair(a_llval, b_llval)
108 ConstValue::ByRef(_, alloc, offset) => {
109 return Ok(bx.load_operand(bx.cx().from_const_alloc(layout, alloc, offset)));
119 /// Asserts that this operand refers to a scalar and returns
120 /// a reference to its value.
121 pub fn immediate(self) -> V {
123 OperandValue::Immediate(s) => s,
124 _ => bug!("not immediate: {:?}", self)
128 pub fn deref<Cx: CodegenMethods<'tcx, Value = V>>(
131 ) -> PlaceRef<'tcx, V> {
132 let projected_ty = self.layout.ty.builtin_deref(true)
133 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
134 let (llptr, llextra) = match self.val {
135 OperandValue::Immediate(llptr) => (llptr, None),
136 OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
137 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
139 let layout = cx.layout_of(projected_ty);
144 align: layout.align.abi,
148 /// If this operand is a `Pair`, we return an aggregate with the two values.
149 /// For other cases, see `immediate`.
150 pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
154 if let OperandValue::Pair(a, b) = self.val {
155 let llty = bx.cx().backend_type(self.layout);
156 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
158 // Reconstruct the immediate aggregate.
159 let mut llpair = bx.cx().const_undef(llty);
160 let imm_a = base::from_immediate(bx, a);
161 let imm_b = base::from_immediate(bx, b);
162 llpair = bx.insert_value(llpair, imm_a, 0);
163 llpair = bx.insert_value(llpair, imm_b, 1);
170 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
171 pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
174 layout: TyLayout<'tcx>
176 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
177 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
180 // Deconstruct the immediate aggregate.
181 let a_llval = bx.extract_value(llval, 0);
182 let a_llval = base::to_immediate_scalar(bx, a_llval, a);
183 let b_llval = bx.extract_value(llval, 1);
184 let b_llval = base::to_immediate_scalar(bx, b_llval, b);
185 OperandValue::Pair(a_llval, b_llval)
187 OperandValue::Immediate(llval)
189 OperandRef { val, layout }
192 pub fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
197 let field = self.layout.field(bx.cx(), i);
198 let offset = self.layout.fields.offset(i);
200 let mut val = match (self.val, &self.layout.abi) {
201 // If the field is ZST, it has no data.
202 _ if field.is_zst() => {
203 return OperandRef::new_zst(bx.cx(), field);
206 // Newtype of a scalar, scalar pair or vector.
207 (OperandValue::Immediate(_), _) |
208 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
209 assert_eq!(offset.bytes(), 0);
213 // Extract a scalar component from a pair.
214 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
215 if offset.bytes() == 0 {
216 assert_eq!(field.size, a.value.size(bx.cx()));
217 OperandValue::Immediate(a_llval)
219 assert_eq!(offset, a.value.size(bx.cx())
220 .align_to(b.value.align(bx.cx()).abi));
221 assert_eq!(field.size, b.value.size(bx.cx()));
222 OperandValue::Immediate(b_llval)
226 // `#[repr(simd)]` types are also immediate.
227 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
228 OperandValue::Immediate(
229 bx.extract_element(llval, bx.cx().const_usize(i as u64)))
232 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
235 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
236 // Bools in union fields needs to be truncated.
237 let to_immediate_or_cast = |bx: &mut Bx, val, ty| {
238 if ty == bx.cx().type_i1() {
246 OperandValue::Immediate(ref mut llval) => {
247 *llval = to_immediate_or_cast(bx, *llval, bx.cx().immediate_backend_type(field));
249 OperandValue::Pair(ref mut a, ref mut b) => {
250 *a = to_immediate_or_cast(bx, *a, bx.cx()
251 .scalar_pair_element_backend_type(field, 0, true));
252 *b = to_immediate_or_cast(bx, *b, bx.cx()
253 .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 let (a_scalar, b_scalar) = match dest.layout.abi {
324 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
325 _ => bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout)
327 let b_offset = a_scalar.value.size(bx).align_to(b_scalar.value.align(bx).abi);
329 let llptr = bx.struct_gep(dest.llval, 0);
330 let val = base::from_immediate(bx, a);
331 let align = dest.align;
332 bx.store_with_flags(val, llptr, align, flags);
334 let llptr = bx.struct_gep(dest.llval, 1);
335 let val = base::from_immediate(bx, b);
336 let align = dest.align.restrict_for_offset(b_offset);
337 bx.store_with_flags(val, llptr, align, flags);
341 pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
344 indirect_dest: PlaceRef<'tcx, V>
346 debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
347 let flags = MemFlags::empty();
349 // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
350 let unsized_ty = indirect_dest.layout.ty.builtin_deref(true)
351 .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest)).ty;
353 let (llptr, llextra) =
354 if let OperandValue::Ref(llptr, Some(llextra), _) = self {
357 bug!("store_unsized called with a sized value")
360 // FIXME: choose an appropriate alignment, or use dynamic align somehow
361 let max_align = Align::from_bits(128).unwrap();
362 let min_align = Align::from_bits(8).unwrap();
364 // Allocate an appropriate region on the stack, and copy the value into it
365 let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
366 let lldst = bx.array_alloca(bx.cx().type_i8(), llsize, "unsized_tmp", max_align);
367 bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags);
369 // Store the allocated region and the extra to the indirect place.
370 let indirect_operand = OperandValue::Pair(lldst, llextra);
371 indirect_operand.store(bx, indirect_dest);
375 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
376 fn maybe_codegen_consume_direct(
379 place: &mir::Place<'tcx>
380 ) -> Option<OperandRef<'tcx, Bx::Value>> {
381 debug!("maybe_codegen_consume_direct(place={:?})", place);
383 // watch out for locals that do not have an
384 // alloca; they are handled somewhat differently
385 if let mir::Place::Local(index) = *place {
386 match self.locals[index] {
387 LocalRef::Operand(Some(o)) => {
390 LocalRef::Operand(None) => {
391 bug!("use of {:?} before def", place);
393 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
399 // Moves out of scalar and scalar pair fields are trivial.
400 if let &mir::Place::Projection(ref proj) = place {
401 if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
403 mir::ProjectionElem::Field(ref f, _) => {
404 return Some(o.extract_field(bx, f.index()));
406 mir::ProjectionElem::Index(_) |
407 mir::ProjectionElem::ConstantIndex { .. } => {
408 // ZSTs don't require any actual memory access.
409 // FIXME(eddyb) deduplicate this with the identical
410 // checks in `codegen_consume` and `extract_field`.
411 let elem = o.layout.field(bx.cx(), 0);
413 return Some(OperandRef::new_zst(bx.cx(), elem));
424 pub fn codegen_consume(
427 place: &mir::Place<'tcx>
428 ) -> OperandRef<'tcx, Bx::Value> {
429 debug!("codegen_consume(place={:?})", place);
431 let ty = self.monomorphized_place_ty(place);
432 let layout = bx.cx().layout_of(ty);
434 // ZSTs don't require any actual memory access.
436 return OperandRef::new_zst(bx.cx(), layout);
439 if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
443 // for most places, to consume them we just load them
444 // out from their home
445 let place = self.codegen_place(bx, place);
446 bx.load_operand(place)
449 pub fn codegen_operand(
452 operand: &mir::Operand<'tcx>
453 ) -> OperandRef<'tcx, Bx::Value> {
454 debug!("codegen_operand(operand={:?})", operand);
457 mir::Operand::Copy(ref place) |
458 mir::Operand::Move(ref place) => {
459 self.codegen_consume(bx, place)
462 mir::Operand::Constant(ref constant) => {
463 let ty = self.monomorphize(&constant.ty);
464 self.eval_mir_constant(bx, constant)
465 .and_then(|c| OperandRef::from_const(bx, c))
466 .unwrap_or_else(|err| {
468 // errored or at least linted
469 ErrorHandled::Reported => {},
470 ErrorHandled::TooGeneric => {
471 bug!("codgen encountered polymorphic constant")
474 // Allow RalfJ to sleep soundly knowing that even refactorings that remove
475 // the above error (or silence it under some conditions) will not cause UB
477 // We've errored, so we don't have to produce working code.
478 let layout = bx.cx().layout_of(ty);
479 bx.load_operand(PlaceRef::new_sized(
480 bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))),