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::Unevaluated(..) => bug!("unevaluated constant in `OperandRef::from_const`"),
80 ConstValue::Param(_) => bug!("encountered a ConstValue::Param in codegen"),
81 ConstValue::Infer(_) => bug!("encountered a ConstValue::Infer in codegen"),
82 ConstValue::Scalar(x) => {
83 let scalar = match layout.abi {
84 layout::Abi::Scalar(ref x) => x,
85 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
87 let llval = bx.cx().scalar_to_backend(
90 bx.cx().immediate_backend_type(layout),
92 OperandValue::Immediate(llval)
94 ConstValue::Slice(a, b) => {
95 let a_scalar = match layout.abi {
96 layout::Abi::ScalarPair(ref a, _) => a,
97 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
99 let a_llval = bx.cx().scalar_to_backend(
102 bx.cx().scalar_pair_element_backend_type(layout, 0, true),
104 let b_llval = bx.cx().const_usize(b);
105 OperandValue::Pair(a_llval, b_llval)
107 ConstValue::ByRef(ptr, alloc) => {
108 return Ok(bx.load_operand(bx.cx().from_const_alloc(layout, alloc, ptr.offset)));
118 /// Asserts that this operand refers to a scalar and returns
119 /// a reference to its value.
120 pub fn immediate(self) -> V {
122 OperandValue::Immediate(s) => s,
123 _ => bug!("not immediate: {:?}", self)
127 pub fn deref<Cx: CodegenMethods<'tcx, Value = V>>(
130 ) -> PlaceRef<'tcx, V> {
131 let projected_ty = self.layout.ty.builtin_deref(true)
132 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
133 let (llptr, llextra) = match self.val {
134 OperandValue::Immediate(llptr) => (llptr, None),
135 OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
136 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
138 let layout = cx.layout_of(projected_ty);
143 align: layout.align.abi,
147 /// If this operand is a `Pair`, we return an aggregate with the two values.
148 /// For other cases, see `immediate`.
149 pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
153 if let OperandValue::Pair(a, b) = self.val {
154 let llty = bx.cx().backend_type(self.layout);
155 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
157 // Reconstruct the immediate aggregate.
158 let mut llpair = bx.cx().const_undef(llty);
159 let imm_a = base::from_immediate(bx, a);
160 let imm_b = base::from_immediate(bx, b);
161 llpair = bx.insert_value(llpair, imm_a, 0);
162 llpair = bx.insert_value(llpair, imm_b, 1);
169 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
170 pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
173 layout: TyLayout<'tcx>
175 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
176 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
179 // Deconstruct the immediate aggregate.
180 let a_llval = bx.extract_value(llval, 0);
181 let a_llval = base::to_immediate_scalar(bx, a_llval, a);
182 let b_llval = bx.extract_value(llval, 1);
183 let b_llval = base::to_immediate_scalar(bx, b_llval, b);
184 OperandValue::Pair(a_llval, b_llval)
186 OperandValue::Immediate(llval)
188 OperandRef { val, layout }
191 pub fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
196 let field = self.layout.field(bx.cx(), i);
197 let offset = self.layout.fields.offset(i);
199 let mut val = match (self.val, &self.layout.abi) {
200 // If the field is ZST, it has no data.
201 _ if field.is_zst() => {
202 return OperandRef::new_zst(bx.cx(), field);
205 // Newtype of a scalar, scalar pair or vector.
206 (OperandValue::Immediate(_), _) |
207 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
208 assert_eq!(offset.bytes(), 0);
212 // Extract a scalar component from a pair.
213 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
214 if offset.bytes() == 0 {
215 assert_eq!(field.size, a.value.size(bx.cx()));
216 OperandValue::Immediate(a_llval)
218 assert_eq!(offset, a.value.size(bx.cx())
219 .align_to(b.value.align(bx.cx()).abi));
220 assert_eq!(field.size, b.value.size(bx.cx()));
221 OperandValue::Immediate(b_llval)
225 // `#[repr(simd)]` types are also immediate.
226 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
227 OperandValue::Immediate(
228 bx.extract_element(llval, bx.cx().const_usize(i as u64)))
231 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
234 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
235 // Bools in union fields needs to be truncated.
236 let to_immediate_or_cast = |bx: &mut Bx, val, ty| {
237 if ty == bx.cx().type_i1() {
245 OperandValue::Immediate(ref mut llval) => {
246 *llval = to_immediate_or_cast(bx, *llval, bx.cx().immediate_backend_type(field));
248 OperandValue::Pair(ref mut a, ref mut b) => {
249 *a = to_immediate_or_cast(bx, *a, bx.cx()
250 .scalar_pair_element_backend_type(field, 0, true));
251 *b = to_immediate_or_cast(bx, *b, bx.cx()
252 .scalar_pair_element_backend_type(field, 1, true));
254 OperandValue::Ref(..) => bug!()
264 impl<'a, 'tcx: 'a, V: CodegenObject> OperandValue<V> {
265 pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
268 dest: PlaceRef<'tcx, V>
270 self.store_with_flags(bx, dest, MemFlags::empty());
273 pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
276 dest: PlaceRef<'tcx, V>
278 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
281 pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
284 dest: PlaceRef<'tcx, V>,
286 self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
289 pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
292 dest: PlaceRef<'tcx, V>
294 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
297 fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
300 dest: PlaceRef<'tcx, V>,
303 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
304 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
305 // value is through `undef`, and store itself is useless.
306 if dest.layout.is_zst() {
310 OperandValue::Ref(r, None, source_align) => {
311 base::memcpy_ty(bx, dest.llval, dest.align, r, source_align,
314 OperandValue::Ref(_, Some(_), _) => {
315 bug!("cannot directly store unsized values");
317 OperandValue::Immediate(s) => {
318 let val = base::from_immediate(bx, s);
319 bx.store_with_flags(val, dest.llval, dest.align, flags);
321 OperandValue::Pair(a, b) => {
322 let (a_scalar, b_scalar) = match dest.layout.abi {
323 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
324 _ => bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout)
326 let b_offset = a_scalar.value.size(bx).align_to(b_scalar.value.align(bx).abi);
328 let llptr = bx.struct_gep(dest.llval, 0);
329 let val = base::from_immediate(bx, a);
330 let align = dest.align;
331 bx.store_with_flags(val, llptr, align, flags);
333 let llptr = bx.struct_gep(dest.llval, 1);
334 let val = base::from_immediate(bx, b);
335 let align = dest.align.restrict_for_offset(b_offset);
336 bx.store_with_flags(val, llptr, align, flags);
340 pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
343 indirect_dest: PlaceRef<'tcx, V>
345 debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
346 let flags = MemFlags::empty();
348 // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
349 let unsized_ty = indirect_dest.layout.ty.builtin_deref(true)
350 .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest)).ty;
352 let (llptr, llextra) =
353 if let OperandValue::Ref(llptr, Some(llextra), _) = self {
356 bug!("store_unsized called with a sized value")
359 // FIXME: choose an appropriate alignment, or use dynamic align somehow
360 let max_align = Align::from_bits(128).unwrap();
361 let min_align = Align::from_bits(8).unwrap();
363 // Allocate an appropriate region on the stack, and copy the value into it
364 let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
365 let lldst = bx.array_alloca(bx.cx().type_i8(), llsize, "unsized_tmp", max_align);
366 bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags);
368 // Store the allocated region and the extra to the indirect place.
369 let indirect_operand = OperandValue::Pair(lldst, llextra);
370 indirect_operand.store(bx, indirect_dest);
374 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
375 fn maybe_codegen_consume_direct(
378 place: &mir::Place<'tcx>
379 ) -> Option<OperandRef<'tcx, Bx::Value>> {
380 debug!("maybe_codegen_consume_direct(place={:?})", place);
382 // watch out for locals that do not have an
383 // alloca; they are handled somewhat differently
384 if let mir::Place::Base(mir::PlaceBase::Local(index)) = *place {
385 match self.locals[index] {
386 LocalRef::Operand(Some(o)) => {
389 LocalRef::Operand(None) => {
390 bug!("use of {:?} before def", place);
392 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
398 // Moves out of scalar and scalar pair fields are trivial.
399 if let &mir::Place::Projection(ref proj) = place {
400 if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
402 mir::ProjectionElem::Field(ref f, _) => {
403 return Some(o.extract_field(bx, f.index()));
405 mir::ProjectionElem::Index(_) |
406 mir::ProjectionElem::ConstantIndex { .. } => {
407 // ZSTs don't require any actual memory access.
408 // FIXME(eddyb) deduplicate this with the identical
409 // checks in `codegen_consume` and `extract_field`.
410 let elem = o.layout.field(bx.cx(), 0);
412 return Some(OperandRef::new_zst(bx.cx(), elem));
423 pub fn codegen_consume(
426 place: &mir::Place<'tcx>
427 ) -> OperandRef<'tcx, Bx::Value> {
428 debug!("codegen_consume(place={:?})", place);
430 let ty = self.monomorphized_place_ty(place);
431 let layout = bx.cx().layout_of(ty);
433 // ZSTs don't require any actual memory access.
435 return OperandRef::new_zst(bx.cx(), layout);
438 if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
442 // for most places, to consume them we just load them
443 // out from their home
444 let place = self.codegen_place(bx, place);
445 bx.load_operand(place)
448 pub fn codegen_operand(
451 operand: &mir::Operand<'tcx>
452 ) -> OperandRef<'tcx, Bx::Value> {
453 debug!("codegen_operand(operand={:?})", operand);
456 mir::Operand::Copy(ref place) |
457 mir::Operand::Move(ref place) => {
458 self.codegen_consume(bx, place)
461 mir::Operand::Constant(ref constant) => {
462 let ty = self.monomorphize(&constant.ty);
463 self.eval_mir_constant(bx, constant)
464 .and_then(|c| OperandRef::from_const(bx, c))
465 .unwrap_or_else(|err| {
467 // errored or at least linted
468 ErrorHandled::Reported => {},
469 ErrorHandled::TooGeneric => {
470 bug!("codgen encountered polymorphic constant")
473 // Allow RalfJ to sleep soundly knowing that even refactorings that remove
474 // the above error (or silence it under some conditions) will not cause UB
476 // We've errored, so we don't have to produce working code.
477 let layout = bx.cx().layout_of(ty);
478 bx.load_operand(PlaceRef::new_sized(
479 bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))),