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 llvm::{self, ValueRef};
12 use rustc::middle::const_val::{ConstEvalErr, ConstVal, ErrKind};
13 use rustc_const_math::ConstInt::*;
14 use rustc_const_math::{ConstInt, ConstMathErr, MAX_F32_PLUS_HALF_ULP};
15 use rustc::hir::def_id::DefId;
16 use rustc::infer::TransNormalize;
19 use rustc::mir::tcx::PlaceTy;
20 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
21 use rustc::ty::layout::{self, LayoutOf, Size};
22 use rustc::ty::cast::{CastTy, IntTy};
23 use rustc::ty::subst::{Kind, Substs};
24 use rustc_apfloat::{ieee, Float, Status};
25 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
30 use common::{self, CodegenCx, const_get_elt, val_ty};
31 use common::{C_array, C_bool, C_bytes, C_int, C_uint, C_uint_big, C_u32, C_u64};
32 use common::{C_null, C_struct, C_str_slice, C_undef, C_usize, C_vector, C_fat_ptr};
33 use common::const_to_opt_u128;
35 use type_of::LayoutLlvmExt;
45 use super::operand::{OperandRef, OperandValue};
46 use super::FunctionCx;
48 /// A sized constant rvalue.
49 /// The LLVM type might not be the same for a single Rust type,
50 /// e.g. each enum variant would have its own LLVM struct type.
51 #[derive(Copy, Clone)]
52 pub struct Const<'tcx> {
57 impl<'a, 'tcx> Const<'tcx> {
58 pub fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> {
65 pub fn from_constint(cx: &CodegenCx<'a, 'tcx>, ci: &ConstInt) -> Const<'tcx> {
67 let (llval, ty) = match *ci {
68 I8(v) => (C_int(Type::i8(cx), v as i64), tcx.types.i8),
69 I16(v) => (C_int(Type::i16(cx), v as i64), tcx.types.i16),
70 I32(v) => (C_int(Type::i32(cx), v as i64), tcx.types.i32),
71 I64(v) => (C_int(Type::i64(cx), v as i64), tcx.types.i64),
72 I128(v) => (C_uint_big(Type::i128(cx), v as u128), tcx.types.i128),
73 Isize(v) => (C_int(Type::isize(cx), v.as_i64()), tcx.types.isize),
74 U8(v) => (C_uint(Type::i8(cx), v as u64), tcx.types.u8),
75 U16(v) => (C_uint(Type::i16(cx), v as u64), tcx.types.u16),
76 U32(v) => (C_uint(Type::i32(cx), v as u64), tcx.types.u32),
77 U64(v) => (C_uint(Type::i64(cx), v), tcx.types.u64),
78 U128(v) => (C_uint_big(Type::i128(cx), v), tcx.types.u128),
79 Usize(v) => (C_uint(Type::isize(cx), v.as_u64()), tcx.types.usize),
81 Const { llval: llval, ty: ty }
84 /// Translate ConstVal into a LLVM constant value.
85 pub fn from_constval(cx: &CodegenCx<'a, 'tcx>,
89 let llty = cx.layout_of(ty).llvm_type(cx);
91 ConstVal::Float(v) => {
92 let bits = match v.ty {
93 ast::FloatTy::F32 => C_u32(cx, v.bits as u32),
94 ast::FloatTy::F64 => C_u64(cx, v.bits as u64)
96 consts::bitcast(bits, llty)
98 ConstVal::Bool(v) => C_bool(cx, v),
99 ConstVal::Integral(ref i) => return Const::from_constint(cx, i),
100 ConstVal::Str(ref v) => C_str_slice(cx, v.clone()),
101 ConstVal::ByteStr(v) => {
102 consts::addr_of(cx, C_bytes(cx, v.data), cx.align_of(ty), "byte_str")
104 ConstVal::Char(c) => C_uint(Type::char(cx), c as u64),
105 ConstVal::Function(..) => C_undef(llty),
106 ConstVal::Variant(_) |
107 ConstVal::Aggregate(..) |
108 ConstVal::Unevaluated(..) => {
109 bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv)
113 assert!(!ty.has_erasable_regions());
118 fn get_field(&self, cx: &CodegenCx<'a, 'tcx>, i: usize) -> ValueRef {
119 let layout = cx.layout_of(self.ty);
120 let field = layout.field(cx, i);
122 return C_undef(field.immediate_llvm_type(cx));
124 let offset = layout.fields.offset(i);
126 layout::Abi::Scalar(_) |
127 layout::Abi::ScalarPair(..) |
128 layout::Abi::Vector { .. }
129 if offset.bytes() == 0 && field.size == layout.size => self.llval,
131 layout::Abi::ScalarPair(ref a, ref b) => {
132 if offset.bytes() == 0 {
133 assert_eq!(field.size, a.value.size(cx));
134 const_get_elt(self.llval, 0)
136 assert_eq!(offset, a.value.size(cx)
137 .abi_align(b.value.align(cx)));
138 assert_eq!(field.size, b.value.size(cx));
139 const_get_elt(self.llval, 1)
143 match layout.fields {
144 layout::FieldPlacement::Union(_) => self.llval,
145 _ => const_get_elt(self.llval, layout.llvm_field_index(i)),
151 fn get_pair(&self, cx: &CodegenCx<'a, 'tcx>) -> (ValueRef, ValueRef) {
152 (self.get_field(cx, 0), self.get_field(cx, 1))
155 fn get_fat_ptr(&self, cx: &CodegenCx<'a, 'tcx>) -> (ValueRef, ValueRef) {
156 assert_eq!(abi::FAT_PTR_ADDR, 0);
157 assert_eq!(abi::FAT_PTR_EXTRA, 1);
161 fn as_place(&self) -> ConstPlace<'tcx> {
163 base: Base::Value(self.llval),
164 llextra: ptr::null_mut(),
169 pub fn to_operand(&self, cx: &CodegenCx<'a, 'tcx>) -> OperandRef<'tcx> {
170 let layout = cx.layout_of(self.ty);
171 let llty = layout.immediate_llvm_type(cx);
172 let llvalty = val_ty(self.llval);
174 let val = if llty == llvalty && layout.is_llvm_scalar_pair() {
176 const_get_elt(self.llval, 0),
177 const_get_elt(self.llval, 1))
178 } else if llty == llvalty && layout.is_llvm_immediate() {
179 // If the types match, we can use the value directly.
180 OperandValue::Immediate(self.llval)
182 // Otherwise, or if the value is not immediate, we create
183 // a constant LLVM global and cast its address if necessary.
184 let align = cx.align_of(self.ty);
185 let ptr = consts::addr_of(cx, self.llval, align, "const");
186 OperandValue::Ref(consts::ptrcast(ptr, layout.llvm_type(cx).ptr_to()),
197 impl<'tcx> fmt::Debug for Const<'tcx> {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 write!(f, "Const({:?}: {:?})", Value(self.llval), self.ty)
203 #[derive(Copy, Clone)]
205 /// A constant value without an unique address.
208 /// String literal base pointer (cast from array).
211 /// The address of a static.
215 /// An place as seen from a constant.
216 #[derive(Copy, Clone)]
217 struct ConstPlace<'tcx> {
223 impl<'tcx> ConstPlace<'tcx> {
224 fn to_const(&self, span: Span) -> Const<'tcx> {
226 Base::Value(val) => Const::new(val, self.ty),
228 span_bug!(span, "loading from `str` ({:?}) in constant",
231 Base::Static(val) => {
232 span_bug!(span, "loading from `static` ({:?}) in constant",
238 pub fn len<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> ValueRef {
240 ty::TyArray(_, n) => {
241 C_usize(cx, n.val.to_const_int().unwrap().to_u64().unwrap())
243 ty::TySlice(_) | ty::TyStr => {
244 assert!(self.llextra != ptr::null_mut());
247 _ => bug!("unexpected type `{}` in ConstPlace::len", self.ty)
252 /// Machinery for translating a constant's MIR to LLVM values.
253 /// FIXME(eddyb) use miri and lower its allocations to LLVM.
254 struct MirConstContext<'a, 'tcx: 'a> {
255 cx: &'a CodegenCx<'a, 'tcx>,
256 mir: &'a mir::Mir<'tcx>,
258 /// Type parameters for const fn and associated constants.
259 substs: &'tcx Substs<'tcx>,
261 /// Values of locals in a constant or const fn.
262 locals: IndexVec<mir::Local, Option<Result<Const<'tcx>, ConstEvalErr<'tcx>>>>
265 fn add_err<'tcx, U, V>(failure: &mut Result<U, ConstEvalErr<'tcx>>,
266 value: &Result<V, ConstEvalErr<'tcx>>)
268 if let &Err(ref err) = value {
270 *failure = Err(err.clone());
275 impl<'a, 'tcx> MirConstContext<'a, 'tcx> {
276 fn new(cx: &'a CodegenCx<'a, 'tcx>,
277 mir: &'a mir::Mir<'tcx>,
278 substs: &'tcx Substs<'tcx>,
279 args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
280 -> MirConstContext<'a, 'tcx> {
281 let mut context = MirConstContext {
285 locals: (0..mir.local_decls.len()).map(|_| None).collect(),
287 for (i, arg) in args.into_iter().enumerate() {
288 // Locals after local 0 are the function arguments
289 let index = mir::Local::new(i + 1);
290 context.locals[index] = Some(arg);
295 fn trans_def(cx: &'a CodegenCx<'a, 'tcx>,
297 substs: &'tcx Substs<'tcx>,
298 args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
299 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
300 let instance = ty::Instance::resolve(cx.tcx,
301 ty::ParamEnv::empty(traits::Reveal::All),
304 let mir = cx.tcx.instance_mir(instance.def);
305 MirConstContext::new(cx, &mir, instance.substs, args).trans()
308 fn monomorphize<T>(&self, value: &T) -> T
309 where T: TransNormalize<'tcx>
311 self.cx.tcx.trans_apply_param_substs(self.substs, value)
314 fn trans(&mut self) -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
315 let tcx = self.cx.tcx;
316 let mut bb = mir::START_BLOCK;
318 // Make sure to evaluate all statemenets to
319 // report as many errors as we possibly can.
320 let mut failure = Ok(());
323 let data = &self.mir[bb];
324 for statement in &data.statements {
325 let span = statement.source_info.span;
326 match statement.kind {
327 mir::StatementKind::Assign(ref dest, ref rvalue) => {
328 let ty = dest.ty(self.mir, tcx);
329 let ty = self.monomorphize(&ty).to_ty(tcx);
330 let value = self.const_rvalue(rvalue, ty, span);
331 add_err(&mut failure, &value);
332 self.store(dest, value, span);
334 mir::StatementKind::StorageLive(_) |
335 mir::StatementKind::StorageDead(_) |
336 mir::StatementKind::Validate(..) |
337 mir::StatementKind::EndRegion(_) |
338 mir::StatementKind::Nop => {}
339 mir::StatementKind::InlineAsm { .. } |
340 mir::StatementKind::SetDiscriminant{ .. } => {
341 span_bug!(span, "{:?} should not appear in constants?", statement.kind);
346 let terminator = data.terminator();
347 let span = terminator.source_info.span;
348 bb = match terminator.kind {
349 mir::TerminatorKind::Drop { target, .. } | // No dropping.
350 mir::TerminatorKind::Goto { target } => target,
351 mir::TerminatorKind::Return => {
353 return self.locals[mir::RETURN_PLACE].clone().unwrap_or_else(|| {
354 span_bug!(span, "no returned value in constant");
358 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, .. } => {
359 let cond = self.const_operand(cond, span)?;
360 let cond_bool = common::const_to_uint(cond.llval) != 0;
361 if cond_bool != expected {
362 let err = match *msg {
363 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
364 let len = self.const_operand(len, span)?;
365 let index = self.const_operand(index, span)?;
366 ErrKind::IndexOutOfBounds {
367 len: common::const_to_uint(len.llval),
368 index: common::const_to_uint(index.llval)
371 mir::AssertMessage::Math(ref err) => {
372 ErrKind::Math(err.clone())
374 mir::AssertMessage::GeneratorResumedAfterReturn |
375 mir::AssertMessage::GeneratorResumedAfterPanic =>
376 span_bug!(span, "{:?} should not appear in constants?", msg),
379 let err = ConstEvalErr { span: span, kind: err };
380 err.report(tcx, span, "expression");
386 mir::TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
387 let fn_ty = func.ty(self.mir, tcx);
388 let fn_ty = self.monomorphize(&fn_ty);
389 let (def_id, substs) = match fn_ty.sty {
390 ty::TyFnDef(def_id, substs) => (def_id, substs),
391 _ => span_bug!(span, "calling {:?} (of type {}) in constant",
395 let mut arg_vals = IndexVec::with_capacity(args.len());
397 let arg_val = self.const_operand(arg, span);
398 add_err(&mut failure, &arg_val);
399 arg_vals.push(arg_val);
401 if let Some((ref dest, target)) = *destination {
402 let result = if fn_ty.fn_sig(tcx).abi() == Abi::RustIntrinsic {
403 match &tcx.item_name(def_id)[..] {
405 let llval = C_usize(self.cx,
406 self.cx.size_of(substs.type_at(0)).bytes());
407 Ok(Const::new(llval, tcx.types.usize))
410 let llval = C_usize(self.cx,
411 self.cx.align_of(substs.type_at(0)).abi());
412 Ok(Const::new(llval, tcx.types.usize))
414 _ => span_bug!(span, "{:?} in constant", terminator.kind)
416 } else if let Some((op, is_checked)) = self.is_binop_lang_item(def_id) {
418 assert_eq!(arg_vals.len(), 2);
419 let rhs = arg_vals.pop().unwrap()?;
420 let lhs = arg_vals.pop().unwrap()?;
422 let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
423 let (lhs, rhs) = (lhs.llval, rhs.llval);
424 Ok(Const::new(const_scalar_binop(op, lhs, rhs, binop_ty),
428 let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
429 let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
430 let (lhs, rhs) = (lhs.llval, rhs.llval);
431 assert!(!ty.is_fp());
433 match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
434 Some((llval, of)) => {
438 &mir::AggregateKind::Tuple,
440 Const::new(llval, val_ty),
441 Const::new(C_bool(self.cx, of), tcx.types.bool)
446 "{:?} got non-integer operands: {:?} and {:?}",
447 op, Value(lhs), Value(rhs));
453 MirConstContext::trans_def(self.cx, def_id, substs, arg_vals)
455 add_err(&mut failure, &result);
456 self.store(dest, result, span);
459 span_bug!(span, "diverging {:?} in constant", terminator.kind);
462 _ => span_bug!(span, "{:?} in constant", terminator.kind)
467 fn is_binop_lang_item(&mut self, def_id: DefId) -> Option<(mir::BinOp, bool)> {
468 let tcx = self.cx.tcx;
469 let items = tcx.lang_items();
470 let def_id = Some(def_id);
471 if items.i128_add_fn() == def_id { Some((mir::BinOp::Add, false)) }
472 else if items.u128_add_fn() == def_id { Some((mir::BinOp::Add, false)) }
473 else if items.i128_sub_fn() == def_id { Some((mir::BinOp::Sub, false)) }
474 else if items.u128_sub_fn() == def_id { Some((mir::BinOp::Sub, false)) }
475 else if items.i128_mul_fn() == def_id { Some((mir::BinOp::Mul, false)) }
476 else if items.u128_mul_fn() == def_id { Some((mir::BinOp::Mul, false)) }
477 else if items.i128_div_fn() == def_id { Some((mir::BinOp::Div, false)) }
478 else if items.u128_div_fn() == def_id { Some((mir::BinOp::Div, false)) }
479 else if items.i128_rem_fn() == def_id { Some((mir::BinOp::Rem, false)) }
480 else if items.u128_rem_fn() == def_id { Some((mir::BinOp::Rem, false)) }
481 else if items.i128_shl_fn() == def_id { Some((mir::BinOp::Shl, false)) }
482 else if items.u128_shl_fn() == def_id { Some((mir::BinOp::Shl, false)) }
483 else if items.i128_shr_fn() == def_id { Some((mir::BinOp::Shr, false)) }
484 else if items.u128_shr_fn() == def_id { Some((mir::BinOp::Shr, false)) }
485 else if items.i128_addo_fn() == def_id { Some((mir::BinOp::Add, true)) }
486 else if items.u128_addo_fn() == def_id { Some((mir::BinOp::Add, true)) }
487 else if items.i128_subo_fn() == def_id { Some((mir::BinOp::Sub, true)) }
488 else if items.u128_subo_fn() == def_id { Some((mir::BinOp::Sub, true)) }
489 else if items.i128_mulo_fn() == def_id { Some((mir::BinOp::Mul, true)) }
490 else if items.u128_mulo_fn() == def_id { Some((mir::BinOp::Mul, true)) }
491 else if items.i128_shlo_fn() == def_id { Some((mir::BinOp::Shl, true)) }
492 else if items.u128_shlo_fn() == def_id { Some((mir::BinOp::Shl, true)) }
493 else if items.i128_shro_fn() == def_id { Some((mir::BinOp::Shr, true)) }
494 else if items.u128_shro_fn() == def_id { Some((mir::BinOp::Shr, true)) }
499 dest: &mir::Place<'tcx>,
500 value: Result<Const<'tcx>, ConstEvalErr<'tcx>>,
502 if let mir::Place::Local(index) = *dest {
503 self.locals[index] = Some(value);
505 span_bug!(span, "assignment to {:?} in constant", dest);
509 fn const_place(&self, place: &mir::Place<'tcx>, span: Span)
510 -> Result<ConstPlace<'tcx>, ConstEvalErr<'tcx>> {
511 let tcx = self.cx.tcx;
513 if let mir::Place::Local(index) = *place {
514 return self.locals[index].clone().unwrap_or_else(|| {
515 span_bug!(span, "{:?} not initialized", place)
516 }).map(|v| v.as_place());
519 let place = match *place {
520 mir::Place::Local(_) => bug!(), // handled above
521 mir::Place::Static(box mir::Static { def_id, ty }) => {
523 base: Base::Static(consts::get_static(self.cx, def_id)),
524 llextra: ptr::null_mut(),
525 ty: self.monomorphize(&ty),
528 mir::Place::Projection(ref projection) => {
529 let tr_base = self.const_place(&projection.base, span)?;
530 let projected_ty = PlaceTy::Ty { ty: tr_base.ty }
531 .projection_ty(tcx, &projection.elem);
532 let base = tr_base.to_const(span);
533 let projected_ty = self.monomorphize(&projected_ty).to_ty(tcx);
534 let has_metadata = self.cx.type_has_metadata(projected_ty);
536 let (projected, llextra) = match projection.elem {
537 mir::ProjectionElem::Deref => {
538 let (base, extra) = if !has_metadata {
539 (base.llval, ptr::null_mut())
541 base.get_fat_ptr(self.cx)
543 if self.cx.statics.borrow().contains_key(&base) {
544 (Base::Static(base), extra)
545 } else if let ty::TyStr = projected_ty.sty {
546 (Base::Str(base), extra)
549 let v = self.cx.const_unsized.borrow().get(&v).map_or(v, |&v| v);
550 let mut val = unsafe { llvm::LLVMGetInitializer(v) };
552 span_bug!(span, "dereference of non-constant pointer `{:?}`",
555 let layout = self.cx.layout_of(projected_ty);
556 if let layout::Abi::Scalar(ref scalar) = layout.abi {
557 let i1_type = Type::i1(self.cx);
558 if scalar.is_bool() && val_ty(val) != i1_type {
560 val = llvm::LLVMConstTrunc(val, i1_type.to_ref());
564 (Base::Value(val), extra)
567 mir::ProjectionElem::Field(ref field, _) => {
568 let llprojected = base.get_field(self.cx, field.index());
569 let llextra = if !has_metadata {
574 (Base::Value(llprojected), llextra)
576 mir::ProjectionElem::Index(index) => {
577 let index = &mir::Operand::Copy(mir::Place::Local(index));
578 let llindex = self.const_operand(index, span)?.llval;
580 let iv = if let Some(iv) = common::const_to_opt_u128(llindex, false) {
583 span_bug!(span, "index is not an integer-constant expression")
586 // Produce an undef instead of a LLVM assertion on OOB.
587 let len = common::const_to_uint(tr_base.len(self.cx));
588 let llelem = if iv < len as u128 {
589 const_get_elt(base.llval, iv as u64)
591 C_undef(self.cx.layout_of(projected_ty).llvm_type(self.cx))
594 (Base::Value(llelem), ptr::null_mut())
596 _ => span_bug!(span, "{:?} in constant", projection.elem)
608 fn const_operand(&self, operand: &mir::Operand<'tcx>, span: Span)
609 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
610 debug!("const_operand({:?} @ {:?})", operand, span);
611 let result = match *operand {
612 mir::Operand::Copy(ref place) |
613 mir::Operand::Move(ref place) => {
614 Ok(self.const_place(place, span)?.to_const(span))
617 mir::Operand::Constant(ref constant) => {
618 let ty = self.monomorphize(&constant.ty);
619 match constant.literal.clone() {
620 mir::Literal::Promoted { index } => {
621 let mir = &self.mir.promoted[index];
622 MirConstContext::new(self.cx, mir, self.substs, IndexVec::new()).trans()
624 mir::Literal::Value { value } => {
625 if let ConstVal::Unevaluated(def_id, substs) = value.val {
626 let substs = self.monomorphize(&substs);
627 MirConstContext::trans_def(self.cx, def_id, substs, IndexVec::new())
629 Ok(Const::from_constval(self.cx, &value.val, ty))
635 debug!("const_operand({:?} @ {:?}) = {:?}", operand, span,
636 result.as_ref().ok());
640 fn const_array(&self, array_ty: Ty<'tcx>, fields: &[ValueRef])
643 let elem_ty = array_ty.builtin_index().unwrap_or_else(|| {
644 bug!("bad array type {:?}", array_ty)
646 let llunitty = self.cx.layout_of(elem_ty).llvm_type(self.cx);
647 // If the array contains enums, an LLVM array won't work.
648 let val = if fields.iter().all(|&f| val_ty(f) == llunitty) {
649 C_array(llunitty, fields)
651 C_struct(self.cx, fields, false)
653 Const::new(val, array_ty)
656 fn const_rvalue(&self, rvalue: &mir::Rvalue<'tcx>,
657 dest_ty: Ty<'tcx>, span: Span)
658 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
659 let tcx = self.cx.tcx;
660 debug!("const_rvalue({:?}: {:?} @ {:?})", rvalue, dest_ty, span);
661 let val = match *rvalue {
662 mir::Rvalue::Use(ref operand) => self.const_operand(operand, span)?,
664 mir::Rvalue::Repeat(ref elem, count) => {
665 let elem = self.const_operand(elem, span)?;
666 let size = count.as_u64();
667 assert_eq!(size as usize as u64, size);
668 let fields = vec![elem.llval; size as usize];
669 self.const_array(dest_ty, &fields)
672 mir::Rvalue::Aggregate(box mir::AggregateKind::Array(_), ref operands) => {
673 // Make sure to evaluate all operands to
674 // report as many errors as we possibly can.
675 let mut fields = Vec::with_capacity(operands.len());
676 let mut failure = Ok(());
677 for operand in operands {
678 match self.const_operand(operand, span) {
679 Ok(val) => fields.push(val.llval),
680 Err(err) => if failure.is_ok() { failure = Err(err); }
685 self.const_array(dest_ty, &fields)
688 mir::Rvalue::Aggregate(ref kind, ref operands) => {
689 // Make sure to evaluate all operands to
690 // report as many errors as we possibly can.
691 let mut fields = Vec::with_capacity(operands.len());
692 let mut failure = Ok(());
693 for operand in operands {
694 match self.const_operand(operand, span) {
695 Ok(val) => fields.push(val),
696 Err(err) => if failure.is_ok() { failure = Err(err); }
701 trans_const_adt(self.cx, dest_ty, kind, &fields)
704 mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
705 let operand = self.const_operand(source, span)?;
706 let cast_ty = self.monomorphize(&cast_ty);
708 let val = match *kind {
709 mir::CastKind::ReifyFnPointer => {
710 match operand.ty.sty {
711 ty::TyFnDef(def_id, substs) => {
712 callee::resolve_and_get_fn(self.cx, def_id, substs)
715 span_bug!(span, "{} cannot be reified to a fn ptr",
720 mir::CastKind::ClosureFnPointer => {
721 match operand.ty.sty {
722 ty::TyClosure(def_id, substs) => {
723 // Get the def_id for FnOnce::call_once
724 let fn_once = tcx.lang_items().fn_once_trait().unwrap();
726 .global_tcx().associated_items(fn_once)
727 .find(|it| it.kind == ty::AssociatedKind::Method)
729 // Now create its substs [Closure, Tuple]
730 let input = substs.closure_sig(def_id, tcx).input(0);
731 let input = tcx.erase_late_bound_regions_and_normalize(&input);
732 let substs = tcx.mk_substs([operand.ty, input]
733 .iter().cloned().map(Kind::from));
734 callee::resolve_and_get_fn(self.cx, call_once, substs)
737 bug!("{} cannot be cast to a fn ptr", operand.ty)
741 mir::CastKind::UnsafeFnPointer => {
742 // this is a no-op at the LLVM level
745 mir::CastKind::Unsize => {
746 let pointee_ty = operand.ty.builtin_deref(true, ty::NoPreference)
747 .expect("consts: unsizing got non-pointer type").ty;
748 let (base, old_info) = if !self.cx.type_is_sized(pointee_ty) {
749 // Normally, the source is a thin pointer and we are
750 // adding extra info to make a fat pointer. The exception
751 // is when we are upcasting an existing object fat pointer
752 // to use a different vtable. In that case, we want to
753 // load out the original data pointer so we can repackage
755 let (base, extra) = operand.get_fat_ptr(self.cx);
758 (operand.llval, None)
761 let unsized_ty = cast_ty.builtin_deref(true, ty::NoPreference)
762 .expect("consts: unsizing got non-pointer target type").ty;
763 let ptr_ty = self.cx.layout_of(unsized_ty).llvm_type(self.cx).ptr_to();
764 let base = consts::ptrcast(base, ptr_ty);
765 let info = base::unsized_info(self.cx, pointee_ty,
766 unsized_ty, old_info);
768 if old_info.is_none() {
769 let prev_const = self.cx.const_unsized.borrow_mut()
770 .insert(base, operand.llval);
771 assert!(prev_const.is_none() || prev_const == Some(operand.llval));
773 C_fat_ptr(self.cx, base, info)
775 mir::CastKind::Misc if self.cx.layout_of(operand.ty).is_llvm_immediate() => {
776 let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
777 let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
778 let cast_layout = self.cx.layout_of(cast_ty);
779 assert!(cast_layout.is_llvm_immediate());
780 let ll_t_out = cast_layout.immediate_llvm_type(self.cx);
781 let llval = operand.llval;
783 let mut signed = false;
784 let l = self.cx.layout_of(operand.ty);
785 if let layout::Abi::Scalar(ref scalar) = l.abi {
786 if let layout::Int(_, true) = scalar.value {
792 match (r_t_in, r_t_out) {
793 (CastTy::Int(_), CastTy::Int(_)) => {
794 let s = signed as llvm::Bool;
795 llvm::LLVMConstIntCast(llval, ll_t_out.to_ref(), s)
797 (CastTy::Int(_), CastTy::Float) => {
798 cast_const_int_to_float(self.cx, llval, signed, ll_t_out)
800 (CastTy::Float, CastTy::Float) => {
801 llvm::LLVMConstFPCast(llval, ll_t_out.to_ref())
803 (CastTy::Float, CastTy::Int(IntTy::I)) => {
804 cast_const_float_to_int(self.cx, &operand,
805 true, ll_t_out, span)
807 (CastTy::Float, CastTy::Int(_)) => {
808 cast_const_float_to_int(self.cx, &operand,
809 false, ll_t_out, span)
811 (CastTy::Ptr(_), CastTy::Ptr(_)) |
812 (CastTy::FnPtr, CastTy::Ptr(_)) |
813 (CastTy::RPtr(_), CastTy::Ptr(_)) => {
814 consts::ptrcast(llval, ll_t_out)
816 (CastTy::Int(_), CastTy::Ptr(_)) => {
817 let s = signed as llvm::Bool;
818 let usize_llval = llvm::LLVMConstIntCast(llval,
819 self.cx.isize_ty.to_ref(), s);
820 llvm::LLVMConstIntToPtr(usize_llval, ll_t_out.to_ref())
822 (CastTy::Ptr(_), CastTy::Int(_)) |
823 (CastTy::FnPtr, CastTy::Int(_)) => {
824 llvm::LLVMConstPtrToInt(llval, ll_t_out.to_ref())
826 _ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
830 mir::CastKind::Misc => { // Casts from a fat-ptr.
831 let l = self.cx.layout_of(operand.ty);
832 let cast = self.cx.layout_of(cast_ty);
833 if l.is_llvm_scalar_pair() {
834 let (data_ptr, meta) = operand.get_fat_ptr(self.cx);
835 if cast.is_llvm_scalar_pair() {
836 let data_cast = consts::ptrcast(data_ptr,
837 cast.scalar_pair_element_llvm_type(self.cx, 0));
838 C_fat_ptr(self.cx, data_cast, meta)
839 } else { // cast to thin-ptr
840 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
841 // pointer-cast of that pointer to desired pointer type.
842 let llcast_ty = cast.immediate_llvm_type(self.cx);
843 consts::ptrcast(data_ptr, llcast_ty)
846 bug!("Unexpected non-fat-pointer operand")
850 Const::new(val, cast_ty)
853 mir::Rvalue::Ref(_, bk, ref place) => {
854 let tr_place = self.const_place(place, span)?;
856 let ty = tr_place.ty;
857 let ref_ty = tcx.mk_ref(tcx.types.re_erased,
858 ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() });
860 let base = match tr_place.base {
861 Base::Value(llval) => {
862 // FIXME: may be wrong for &*(&simd_vec as &fmt::Debug)
863 let align = if self.cx.type_is_sized(ty) {
866 self.cx.tcx.data_layout.pointer_align
868 if bk == mir::BorrowKind::Mut {
869 consts::addr_of_mut(self.cx, llval, align, "ref_mut")
871 consts::addr_of(self.cx, llval, align, "ref")
875 Base::Static(llval) => llval
878 let ptr = if self.cx.type_is_sized(ty) {
881 C_fat_ptr(self.cx, base, tr_place.llextra)
883 Const::new(ptr, ref_ty)
886 mir::Rvalue::Len(ref place) => {
887 let tr_place = self.const_place(place, span)?;
888 Const::new(tr_place.len(self.cx), tcx.types.usize)
891 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
892 let lhs = self.const_operand(lhs, span)?;
893 let rhs = self.const_operand(rhs, span)?;
895 let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
896 let (lhs, rhs) = (lhs.llval, rhs.llval);
897 Const::new(const_scalar_binop(op, lhs, rhs, ty), binop_ty)
900 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
901 let lhs = self.const_operand(lhs, span)?;
902 let rhs = self.const_operand(rhs, span)?;
904 let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
905 let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
906 let (lhs, rhs) = (lhs.llval, rhs.llval);
907 assert!(!ty.is_fp());
909 match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
910 Some((llval, of)) => {
911 trans_const_adt(self.cx, binop_ty, &mir::AggregateKind::Tuple, &[
912 Const::new(llval, val_ty),
913 Const::new(C_bool(self.cx, of), tcx.types.bool)
917 span_bug!(span, "{:?} got non-integer operands: {:?} and {:?}",
918 rvalue, Value(lhs), Value(rhs));
923 mir::Rvalue::UnaryOp(op, ref operand) => {
924 let operand = self.const_operand(operand, span)?;
925 let lloperand = operand.llval;
926 let llval = match op {
929 llvm::LLVMConstNot(lloperand)
933 let is_float = operand.ty.is_fp();
936 llvm::LLVMConstFNeg(lloperand)
938 llvm::LLVMConstNeg(lloperand)
943 Const::new(llval, operand.ty)
946 mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
947 assert!(self.cx.type_is_sized(ty));
948 let llval = C_usize(self.cx, self.cx.size_of(ty).bytes());
949 Const::new(llval, tcx.types.usize)
952 _ => span_bug!(span, "{:?} in constant", rvalue)
955 debug!("const_rvalue({:?}: {:?} @ {:?}) = {:?}", rvalue, dest_ty, span, val);
962 fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
964 ty::TyInt(int_type) => const_to_opt_u128(value, true)
965 .and_then(|input| ConstInt::new_signed(input as i128, int_type,
966 tcx.sess.target.isize_ty)),
967 ty::TyUint(uint_type) => const_to_opt_u128(value, false)
968 .and_then(|input| ConstInt::new_unsigned(input, uint_type,
969 tcx.sess.target.usize_ty)),
975 pub fn const_scalar_binop(op: mir::BinOp,
978 input_ty: Ty) -> ValueRef {
979 assert!(!input_ty.is_simd());
980 let is_float = input_ty.is_fp();
981 let signed = input_ty.is_signed();
985 mir::BinOp::Add if is_float => llvm::LLVMConstFAdd(lhs, rhs),
986 mir::BinOp::Add => llvm::LLVMConstAdd(lhs, rhs),
988 mir::BinOp::Sub if is_float => llvm::LLVMConstFSub(lhs, rhs),
989 mir::BinOp::Sub => llvm::LLVMConstSub(lhs, rhs),
991 mir::BinOp::Mul if is_float => llvm::LLVMConstFMul(lhs, rhs),
992 mir::BinOp::Mul => llvm::LLVMConstMul(lhs, rhs),
994 mir::BinOp::Div if is_float => llvm::LLVMConstFDiv(lhs, rhs),
995 mir::BinOp::Div if signed => llvm::LLVMConstSDiv(lhs, rhs),
996 mir::BinOp::Div => llvm::LLVMConstUDiv(lhs, rhs),
998 mir::BinOp::Rem if is_float => llvm::LLVMConstFRem(lhs, rhs),
999 mir::BinOp::Rem if signed => llvm::LLVMConstSRem(lhs, rhs),
1000 mir::BinOp::Rem => llvm::LLVMConstURem(lhs, rhs),
1002 mir::BinOp::BitXor => llvm::LLVMConstXor(lhs, rhs),
1003 mir::BinOp::BitAnd => llvm::LLVMConstAnd(lhs, rhs),
1004 mir::BinOp::BitOr => llvm::LLVMConstOr(lhs, rhs),
1005 mir::BinOp::Shl => {
1006 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
1007 llvm::LLVMConstShl(lhs, rhs)
1009 mir::BinOp::Shr => {
1010 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
1011 if signed { llvm::LLVMConstAShr(lhs, rhs) }
1012 else { llvm::LLVMConstLShr(lhs, rhs) }
1014 mir::BinOp::Eq | mir::BinOp::Ne |
1015 mir::BinOp::Lt | mir::BinOp::Le |
1016 mir::BinOp::Gt | mir::BinOp::Ge => {
1018 let cmp = base::bin_op_to_fcmp_predicate(op.to_hir_binop());
1019 llvm::LLVMConstFCmp(cmp, lhs, rhs)
1021 let cmp = base::bin_op_to_icmp_predicate(op.to_hir_binop(),
1023 llvm::LLVMConstICmp(cmp, lhs, rhs)
1026 mir::BinOp::Offset => unreachable!("BinOp::Offset in const-eval!")
1031 pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1036 -> Option<(ValueRef, bool)> {
1037 if let (Some(lhs), Some(rhs)) = (to_const_int(lllhs, input_ty, tcx),
1038 to_const_int(llrhs, input_ty, tcx)) {
1039 let result = match op {
1040 mir::BinOp::Add => lhs + rhs,
1041 mir::BinOp::Sub => lhs - rhs,
1042 mir::BinOp::Mul => lhs * rhs,
1043 mir::BinOp::Shl => lhs << rhs,
1044 mir::BinOp::Shr => lhs >> rhs,
1046 bug!("Operator `{:?}` is not a checkable operator", op)
1050 let of = match result {
1052 Err(ConstMathErr::Overflow(_)) |
1053 Err(ConstMathErr::ShiftNegative) => true,
1055 bug!("Operator `{:?}` on `{:?}` and `{:?}` errored: {}",
1056 op, lhs, rhs, err.description());
1060 Some((const_scalar_binop(op, lllhs, llrhs, input_ty), of))
1066 unsafe fn cast_const_float_to_int(cx: &CodegenCx,
1070 span: Span) -> ValueRef {
1071 let llval = operand.llval;
1072 let float_bits = match operand.ty.sty {
1073 ty::TyFloat(fty) => fty.bit_width(),
1074 _ => bug!("cast_const_float_to_int: operand not a float"),
1076 // Note: this breaks if llval is a complex constant expression rather than a simple constant.
1077 // One way that might happen would be if addresses could be turned into integers in constant
1078 // expressions, but that doesn't appear to be possible?
1079 // In any case, an ICE is better than producing undef.
1080 let llval_bits = consts::bitcast(llval, Type::ix(cx, float_bits as u64));
1081 let bits = const_to_opt_u128(llval_bits, false).unwrap_or_else(|| {
1082 panic!("could not get bits of constant float {:?}",
1085 let int_width = int_ty.int_width() as usize;
1086 // Try to convert, but report an error for overflow and NaN. This matches HIR const eval.
1087 let cast_result = match float_bits {
1088 32 if signed => ieee::Single::from_bits(bits).to_i128(int_width).map(|v| v as u128),
1089 64 if signed => ieee::Double::from_bits(bits).to_i128(int_width).map(|v| v as u128),
1090 32 => ieee::Single::from_bits(bits).to_u128(int_width),
1091 64 => ieee::Double::from_bits(bits).to_u128(int_width),
1092 n => bug!("unsupported float width {}", n),
1094 if cast_result.status.contains(Status::INVALID_OP) {
1095 let err = ConstEvalErr { span: span, kind: ErrKind::CannotCast };
1096 err.report(cx.tcx, span, "expression");
1098 C_uint_big(int_ty, cast_result.value)
1101 unsafe fn cast_const_int_to_float(cx: &CodegenCx,
1104 float_ty: Type) -> ValueRef {
1105 // Note: this breaks if llval is a complex constant expression rather than a simple constant.
1106 // One way that might happen would be if addresses could be turned into integers in constant
1107 // expressions, but that doesn't appear to be possible?
1108 // In any case, an ICE is better than producing undef.
1109 let value = const_to_opt_u128(llval, signed).unwrap_or_else(|| {
1110 panic!("could not get z128 value of constant integer {:?}",
1114 llvm::LLVMConstSIToFP(llval, float_ty.to_ref())
1115 } else if float_ty.float_width() == 32 && value >= MAX_F32_PLUS_HALF_ULP {
1116 // We're casting to f32 and the value is > f32::MAX + 0.5 ULP -> round up to infinity.
1117 let infinity_bits = C_u32(cx, ieee::Single::INFINITY.to_bits() as u32);
1118 consts::bitcast(infinity_bits, float_ty)
1120 llvm::LLVMConstUIToFP(llval, float_ty.to_ref())
1124 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
1125 pub fn trans_constant(&mut self,
1126 bx: &Builder<'a, 'tcx>,
1127 constant: &mir::Constant<'tcx>)
1130 debug!("trans_constant({:?})", constant);
1131 let ty = self.monomorphize(&constant.ty);
1132 let result = match constant.literal.clone() {
1133 mir::Literal::Promoted { index } => {
1134 let mir = &self.mir.promoted[index];
1135 MirConstContext::new(bx.cx, mir, self.param_substs, IndexVec::new()).trans()
1137 mir::Literal::Value { value } => {
1138 if let ConstVal::Unevaluated(def_id, substs) = value.val {
1139 let substs = self.monomorphize(&substs);
1140 MirConstContext::trans_def(bx.cx, def_id, substs, IndexVec::new())
1142 Ok(Const::from_constval(bx.cx, &value.val, ty))
1147 let result = result.unwrap_or_else(|_| {
1148 // We've errored, so we don't have to produce working code.
1149 let llty = bx.cx.layout_of(ty).llvm_type(bx.cx);
1150 Const::new(C_undef(llty), ty)
1153 debug!("trans_constant({:?}) = {:?}", constant, result);
1159 pub fn trans_static_initializer<'a, 'tcx>(
1160 cx: &CodegenCx<'a, 'tcx>,
1162 -> Result<ValueRef, ConstEvalErr<'tcx>>
1164 MirConstContext::trans_def(cx, def_id, Substs::empty(), IndexVec::new())
1168 /// Construct a constant value, suitable for initializing a
1169 /// GlobalVariable, given a case and constant values for its fields.
1170 /// Note that this may have a different LLVM type (and different
1171 /// alignment!) from the representation's `type_of`, so it needs a
1172 /// pointer cast before use.
1174 /// The LLVM type system does not directly support unions, and only
1175 /// pointers can be bitcast, so a constant (and, by extension, the
1176 /// GlobalVariable initialized by it) will have a type that can vary
1177 /// depending on which case of an enum it is.
1179 /// To understand the alignment situation, consider `enum E { V64(u64),
1180 /// V32(u32, u32) }` on Windows. The type has 8-byte alignment to
1181 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1182 /// i32, i32}`, which is 4-byte aligned.
1184 /// Currently the returned value has the same size as the type, but
1185 /// this could be changed in the future to avoid allocating unnecessary
1186 /// space after values of shorter-than-maximum cases.
1187 fn trans_const_adt<'a, 'tcx>(
1188 cx: &CodegenCx<'a, 'tcx>,
1190 kind: &mir::AggregateKind,
1191 vals: &[Const<'tcx>]
1193 let l = cx.layout_of(t);
1194 let variant_index = match *kind {
1195 mir::AggregateKind::Adt(_, index, _, _) => index,
1199 if let layout::Abi::Uninhabited = l.abi {
1200 return Const::new(C_undef(l.llvm_type(cx)), t);
1204 layout::Variants::Single { index } => {
1205 assert_eq!(variant_index, index);
1206 if let layout::FieldPlacement::Union(_) = l.fields {
1207 assert_eq!(variant_index, 0);
1208 assert_eq!(vals.len(), 1);
1209 let (field_size, field_align) = cx.size_and_align_of(vals[0].ty);
1212 padding(cx, l.size - field_size)
1215 let packed = l.align.abi() < field_align.abi();
1216 Const::new(C_struct(cx, &contents, packed), t)
1218 if let layout::Abi::Vector { .. } = l.abi {
1219 if let layout::FieldPlacement::Array { .. } = l.fields {
1220 return Const::new(C_vector(&vals.iter().map(|x| x.llval)
1221 .collect::<Vec<_>>()), t);
1224 build_const_struct(cx, l, vals, None)
1227 layout::Variants::Tagged { .. } => {
1228 let discr = match *kind {
1229 mir::AggregateKind::Adt(adt_def, _, _, _) => {
1230 adt_def.discriminant_for_variant(cx.tcx, variant_index)
1231 .to_u128_unchecked() as u64
1235 let discr_field = l.field(cx, 0);
1236 let discr = C_int(discr_field.llvm_type(cx), discr as i64);
1237 if let layout::Abi::Scalar(_) = l.abi {
1238 Const::new(discr, t)
1240 let discr = Const::new(discr, discr_field.ty);
1241 build_const_struct(cx, l.for_variant(cx, variant_index), vals, Some(discr))
1244 layout::Variants::NicheFilling {
1250 if variant_index == dataful_variant {
1251 build_const_struct(cx, l.for_variant(cx, dataful_variant), vals, None)
1253 let niche = l.field(cx, 0);
1254 let niche_llty = niche.llvm_type(cx);
1255 let niche_value = ((variant_index - niche_variants.start) as u128)
1256 .wrapping_add(niche_start);
1257 // FIXME(eddyb) Check the actual primitive type here.
1258 let niche_llval = if niche_value == 0 {
1259 // HACK(eddyb) Using `C_null` as it works on all types.
1262 C_uint_big(niche_llty, niche_value)
1264 build_const_struct(cx, l, &[Const::new(niche_llval, niche.ty)], None)
1270 /// Building structs is a little complicated, because we might need to
1271 /// insert padding if a field's value is less aligned than its type.
1273 /// Continuing the example from `trans_const_adt`, a value of type `(u32,
1274 /// E)` should have the `E` at offset 8, but if that field's
1275 /// initializer is 4-byte aligned then simply translating the tuple as
1276 /// a two-element struct will locate it at offset 4, and accesses to it
1277 /// will read the wrong memory.
1278 fn build_const_struct<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1279 layout: layout::TyLayout<'tcx>,
1280 vals: &[Const<'tcx>],
1281 discr: Option<Const<'tcx>>)
1283 assert_eq!(vals.len(), layout.fields.count());
1286 layout::Abi::Scalar(_) |
1287 layout::Abi::ScalarPair(..) |
1288 layout::Abi::Vector { .. } if discr.is_none() => {
1289 let mut non_zst_fields = vals.iter().enumerate().map(|(i, f)| {
1290 (f, layout.fields.offset(i))
1291 }).filter(|&(f, _)| !cx.layout_of(f.ty).is_zst());
1292 match (non_zst_fields.next(), non_zst_fields.next()) {
1293 (Some((x, offset)), None) if offset.bytes() == 0 => {
1294 return Const::new(x.llval, layout.ty);
1296 (Some((a, a_offset)), Some((b, _))) if a_offset.bytes() == 0 => {
1297 return Const::new(C_struct(cx, &[a.llval, b.llval], false), layout.ty);
1299 (Some((a, _)), Some((b, b_offset))) if b_offset.bytes() == 0 => {
1300 return Const::new(C_struct(cx, &[b.llval, a.llval], false), layout.ty);
1308 // offset of current value
1309 let mut packed = false;
1310 let mut offset = Size::from_bytes(0);
1311 let mut cfields = Vec::new();
1312 cfields.reserve(discr.is_some() as usize + 1 + layout.fields.count() * 2);
1314 if let Some(discr) = discr {
1315 let (field_size, field_align) = cx.size_and_align_of(discr.ty);
1316 packed |= layout.align.abi() < field_align.abi();
1317 cfields.push(discr.llval);
1318 offset = field_size;
1321 let parts = layout.fields.index_by_increasing_offset().map(|i| {
1322 (vals[i], layout.fields.offset(i))
1324 for (val, target_offset) in parts {
1325 let (field_size, field_align) = cx.size_and_align_of(val.ty);
1326 packed |= layout.align.abi() < field_align.abi();
1327 cfields.push(padding(cx, target_offset - offset));
1328 cfields.push(val.llval);
1329 offset = target_offset + field_size;
1332 // Pad to the size of the whole type, not e.g. the variant.
1333 cfields.push(padding(cx, cx.size_of(layout.ty) - offset));
1335 Const::new(C_struct(cx, &cfields, packed), layout.ty)
1338 fn padding(cx: &CodegenCx, size: Size) -> ValueRef {
1339 C_undef(Type::array(&Type::i8(cx), size.bytes()))