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::ConstFloat::*;
15 use rustc_const_math::{ConstInt, ConstMathErr};
16 use rustc::hir::def_id::DefId;
17 use rustc::infer::TransNormalize;
19 use rustc::mir::tcx::LvalueTy;
20 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
21 use rustc::ty::layout::{self, LayoutTyper};
22 use rustc::ty::cast::{CastTy, IntTy};
23 use rustc::ty::subst::{Kind, Substs, Subst};
24 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
25 use {abi, adt, base, machine};
28 use common::{self, CrateContext, const_get_elt, val_ty};
29 use common::{C_array, C_bool, C_bytes, C_floating_f64, C_integral, C_big_integral};
30 use common::{C_null, C_struct, C_str_slice, C_undef, C_uint, C_vector, is_undef};
31 use common::const_to_opt_u128;
43 use super::lvalue::Alignment;
44 use super::operand::{OperandRef, OperandValue};
45 use super::MirContext;
47 /// A sized constant rvalue.
48 /// The LLVM type might not be the same for a single Rust type,
49 /// e.g. each enum variant would have its own LLVM struct type.
50 #[derive(Copy, Clone)]
51 pub struct Const<'tcx> {
56 impl<'tcx> Const<'tcx> {
57 pub fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> {
64 pub fn from_constint<'a>(ccx: &CrateContext<'a, 'tcx>, ci: &ConstInt)
67 let (llval, ty) = match *ci {
68 I8(v) => (C_integral(Type::i8(ccx), v as u64, true), tcx.types.i8),
69 I16(v) => (C_integral(Type::i16(ccx), v as u64, true), tcx.types.i16),
70 I32(v) => (C_integral(Type::i32(ccx), v as u64, true), tcx.types.i32),
71 I64(v) => (C_integral(Type::i64(ccx), v as u64, true), tcx.types.i64),
72 I128(v) => (C_big_integral(Type::i128(ccx), v as u128), tcx.types.i128),
74 let i = v.as_i64(ccx.tcx().sess.target.int_type);
75 (C_integral(Type::int(ccx), i as u64, true), tcx.types.isize)
77 U8(v) => (C_integral(Type::i8(ccx), v as u64, false), tcx.types.u8),
78 U16(v) => (C_integral(Type::i16(ccx), v as u64, false), tcx.types.u16),
79 U32(v) => (C_integral(Type::i32(ccx), v as u64, false), tcx.types.u32),
80 U64(v) => (C_integral(Type::i64(ccx), v, false), tcx.types.u64),
81 U128(v) => (C_big_integral(Type::i128(ccx), v), tcx.types.u128),
83 let u = v.as_u64(ccx.tcx().sess.target.uint_type);
84 (C_integral(Type::int(ccx), u, false), tcx.types.usize)
87 Const { llval: llval, ty: ty }
90 /// Translate ConstVal into a LLVM constant value.
91 pub fn from_constval<'a>(ccx: &CrateContext<'a, 'tcx>,
95 let llty = type_of::type_of(ccx, ty);
97 ConstVal::Float(F32(v)) => C_floating_f64(v as f64, llty),
98 ConstVal::Float(F64(v)) => C_floating_f64(v, llty),
99 ConstVal::Bool(v) => C_bool(ccx, v),
100 ConstVal::Integral(ref i) => return Const::from_constint(ccx, i),
101 ConstVal::Str(ref v) => C_str_slice(ccx, v.clone()),
102 ConstVal::ByteStr(ref v) => consts::addr_of(ccx, C_bytes(ccx, v), 1, "byte_str"),
103 ConstVal::Char(c) => C_integral(Type::char(ccx), c as u64, false),
104 ConstVal::Function(..) => C_null(type_of::type_of(ccx, ty)),
105 ConstVal::Variant(_) |
106 ConstVal::Struct(_) | ConstVal::Tuple(_) |
107 ConstVal::Array(..) | ConstVal::Repeat(..) => {
108 bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv)
112 assert!(!ty.has_erasable_regions());
117 fn get_pair(&self) -> (ValueRef, ValueRef) {
118 (const_get_elt(self.llval, &[0]),
119 const_get_elt(self.llval, &[1]))
122 fn get_fat_ptr(&self) -> (ValueRef, ValueRef) {
123 assert_eq!(abi::FAT_PTR_ADDR, 0);
124 assert_eq!(abi::FAT_PTR_EXTRA, 1);
128 fn as_lvalue(&self) -> ConstLvalue<'tcx> {
130 base: Base::Value(self.llval),
131 llextra: ptr::null_mut(),
136 pub fn to_operand<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> OperandRef<'tcx> {
137 let llty = type_of::immediate_type_of(ccx, self.ty);
138 let llvalty = val_ty(self.llval);
140 let val = if llty == llvalty && common::type_is_imm_pair(ccx, self.ty) {
141 let (a, b) = self.get_pair();
142 OperandValue::Pair(a, b)
143 } else if llty == llvalty && common::type_is_immediate(ccx, self.ty) {
144 // If the types match, we can use the value directly.
145 OperandValue::Immediate(self.llval)
147 // Otherwise, or if the value is not immediate, we create
148 // a constant LLVM global and cast its address if necessary.
149 let align = ccx.align_of(self.ty);
150 let ptr = consts::addr_of(ccx, self.llval, align, "const");
151 OperandValue::Ref(consts::ptrcast(ptr, llty.ptr_to()), Alignment::AbiAligned)
161 impl<'tcx> fmt::Debug for Const<'tcx> {
162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163 write!(f, "Const({:?}: {:?})", Value(self.llval), self.ty)
167 #[derive(Copy, Clone)]
169 /// A constant value without an unique address.
172 /// String literal base pointer (cast from array).
175 /// The address of a static.
179 /// An lvalue as seen from a constant.
180 #[derive(Copy, Clone)]
181 struct ConstLvalue<'tcx> {
187 impl<'tcx> ConstLvalue<'tcx> {
188 fn to_const(&self, span: Span) -> Const<'tcx> {
190 Base::Value(val) => Const::new(val, self.ty),
192 span_bug!(span, "loading from `str` ({:?}) in constant",
195 Base::Static(val) => {
196 span_bug!(span, "loading from `static` ({:?}) in constant",
202 pub fn len<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef {
204 ty::TyArray(_, n) => C_uint(ccx, n),
205 ty::TySlice(_) | ty::TyStr => {
206 assert!(self.llextra != ptr::null_mut());
209 _ => bug!("unexpected type `{}` in ConstLvalue::len", self.ty)
214 /// Machinery for translating a constant's MIR to LLVM values.
215 /// FIXME(eddyb) use miri and lower its allocations to LLVM.
216 struct MirConstContext<'a, 'tcx: 'a> {
217 ccx: &'a CrateContext<'a, 'tcx>,
218 mir: &'a mir::Mir<'tcx>,
220 /// Type parameters for const fn and associated constants.
221 substs: &'tcx Substs<'tcx>,
223 /// Values of locals in a constant or const fn.
224 locals: IndexVec<mir::Local, Option<Const<'tcx>>>
228 impl<'a, 'tcx> MirConstContext<'a, 'tcx> {
229 fn new(ccx: &'a CrateContext<'a, 'tcx>,
230 mir: &'a mir::Mir<'tcx>,
231 substs: &'tcx Substs<'tcx>,
232 args: IndexVec<mir::Local, Const<'tcx>>)
233 -> MirConstContext<'a, 'tcx> {
234 let mut context = MirConstContext {
238 locals: (0..mir.local_decls.len()).map(|_| None).collect(),
240 for (i, arg) in args.into_iter().enumerate() {
241 // Locals after local 0 are the function arguments
242 let index = mir::Local::new(i + 1);
243 context.locals[index] = Some(arg);
248 fn trans_def(ccx: &'a CrateContext<'a, 'tcx>,
250 substs: &'tcx Substs<'tcx>,
251 args: IndexVec<mir::Local, Const<'tcx>>)
252 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
253 let instance = monomorphize::resolve(ccx.shared(), def_id, substs);
254 let mir = ccx.tcx().instance_mir(instance.def);
255 MirConstContext::new(ccx, &mir, instance.substs, args).trans()
258 fn monomorphize<T>(&self, value: &T) -> T
259 where T: TransNormalize<'tcx>
261 self.ccx.tcx().trans_apply_param_substs(self.substs, value)
264 fn trans(&mut self) -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
265 let tcx = self.ccx.tcx();
266 let mut bb = mir::START_BLOCK;
268 // Make sure to evaluate all statemenets to
269 // report as many errors as we possibly can.
270 let mut failure = Ok(());
273 let data = &self.mir[bb];
274 for statement in &data.statements {
275 let span = statement.source_info.span;
276 match statement.kind {
277 mir::StatementKind::Assign(ref dest, ref rvalue) => {
278 let ty = dest.ty(self.mir, tcx);
279 let ty = self.monomorphize(&ty).to_ty(tcx);
280 match self.const_rvalue(rvalue, ty, span) {
281 Ok(value) => self.store(dest, value, span),
282 Err(err) => if failure.is_ok() { failure = Err(err); }
285 mir::StatementKind::StorageLive(_) |
286 mir::StatementKind::StorageDead(_) |
287 mir::StatementKind::Nop => {}
288 mir::StatementKind::InlineAsm { .. } |
289 mir::StatementKind::SetDiscriminant{ .. } => {
290 span_bug!(span, "{:?} should not appear in constants?", statement.kind);
295 let terminator = data.terminator();
296 let span = terminator.source_info.span;
297 bb = match terminator.kind {
298 mir::TerminatorKind::Drop { target, .. } | // No dropping.
299 mir::TerminatorKind::Goto { target } => target,
300 mir::TerminatorKind::Return => {
302 return Ok(self.locals[mir::RETURN_POINTER].unwrap_or_else(|| {
303 span_bug!(span, "no returned value in constant");
307 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, .. } => {
308 let cond = self.const_operand(cond, span)?;
309 let cond_bool = common::const_to_uint(cond.llval) != 0;
310 if cond_bool != expected {
311 let err = match *msg {
312 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
313 let len = self.const_operand(len, span)?;
314 let index = self.const_operand(index, span)?;
315 ErrKind::IndexOutOfBounds {
316 len: common::const_to_uint(len.llval),
317 index: common::const_to_uint(index.llval)
320 mir::AssertMessage::Math(ref err) => {
321 ErrKind::Math(err.clone())
325 let err = ConstEvalErr { span: span, kind: err };
326 err.report(tcx, span, "expression");
332 mir::TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
333 let fn_ty = func.ty(self.mir, tcx);
334 let fn_ty = self.monomorphize(&fn_ty);
335 let (def_id, substs) = match fn_ty.sty {
336 ty::TyFnDef(def_id, substs, _) => (def_id, substs),
337 _ => span_bug!(span, "calling {:?} (of type {}) in constant",
341 let mut const_args = IndexVec::with_capacity(args.len());
343 match self.const_operand(arg, span) {
344 Ok(arg) => { const_args.push(arg); },
345 Err(err) => if failure.is_ok() { failure = Err(err); }
348 if let Some((ref dest, target)) = *destination {
349 match MirConstContext::trans_def(self.ccx, def_id, substs, const_args) {
350 Ok(value) => self.store(dest, value, span),
351 Err(err) => if failure.is_ok() { failure = Err(err); }
355 span_bug!(span, "diverging {:?} in constant", terminator.kind);
358 _ => span_bug!(span, "{:?} in constant", terminator.kind)
363 fn store(&mut self, dest: &mir::Lvalue<'tcx>, value: Const<'tcx>, span: Span) {
364 if let mir::Lvalue::Local(index) = *dest {
365 self.locals[index] = Some(value);
367 span_bug!(span, "assignment to {:?} in constant", dest);
371 fn const_lvalue(&self, lvalue: &mir::Lvalue<'tcx>, span: Span)
372 -> Result<ConstLvalue<'tcx>, ConstEvalErr<'tcx>> {
373 let tcx = self.ccx.tcx();
375 if let mir::Lvalue::Local(index) = *lvalue {
376 return Ok(self.locals[index].unwrap_or_else(|| {
377 span_bug!(span, "{:?} not initialized", lvalue)
381 let lvalue = match *lvalue {
382 mir::Lvalue::Local(_) => bug!(), // handled above
383 mir::Lvalue::Static(box mir::Static { def_id, ty }) => {
385 base: Base::Static(consts::get_static(self.ccx, def_id)),
386 llextra: ptr::null_mut(),
387 ty: self.monomorphize(&ty),
390 mir::Lvalue::Projection(ref projection) => {
391 let tr_base = self.const_lvalue(&projection.base, span)?;
392 let projected_ty = LvalueTy::Ty { ty: tr_base.ty }
393 .projection_ty(tcx, &projection.elem);
394 let base = tr_base.to_const(span);
395 let projected_ty = self.monomorphize(&projected_ty).to_ty(tcx);
396 let is_sized = self.ccx.shared().type_is_sized(projected_ty);
398 let (projected, llextra) = match projection.elem {
399 mir::ProjectionElem::Deref => {
400 let (base, extra) = if is_sized {
401 (base.llval, ptr::null_mut())
405 if self.ccx.statics().borrow().contains_key(&base) {
406 (Base::Static(base), extra)
407 } else if let ty::TyStr = projected_ty.sty {
408 (Base::Str(base), extra)
411 let v = self.ccx.const_unsized().borrow().get(&v).map_or(v, |&v| v);
412 let mut val = unsafe { llvm::LLVMGetInitializer(v) };
414 span_bug!(span, "dereference of non-constant pointer `{:?}`",
417 if projected_ty.is_bool() {
419 val = llvm::LLVMConstTrunc(val, Type::i1(self.ccx).to_ref());
422 (Base::Value(val), extra)
425 mir::ProjectionElem::Field(ref field, _) => {
426 let llprojected = adt::const_get_field(self.ccx, tr_base.ty, base.llval,
428 let llextra = if is_sized {
433 (Base::Value(llprojected), llextra)
435 mir::ProjectionElem::Index(ref index) => {
436 let llindex = self.const_operand(index, span)?.llval;
438 let iv = if let Some(iv) = common::const_to_opt_u128(llindex, false) {
441 span_bug!(span, "index is not an integer-constant expression")
444 // Produce an undef instead of a LLVM assertion on OOB.
445 let len = common::const_to_uint(tr_base.len(self.ccx));
446 let llelem = if iv < len as u128 {
447 const_get_elt(base.llval, &[iv as u32])
449 C_undef(type_of::type_of(self.ccx, projected_ty))
452 (Base::Value(llelem), ptr::null_mut())
454 _ => span_bug!(span, "{:?} in constant", projection.elem)
466 fn const_operand(&self, operand: &mir::Operand<'tcx>, span: Span)
467 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
468 debug!("const_operand({:?} @ {:?})", operand, span);
469 let result = match *operand {
470 mir::Operand::Consume(ref lvalue) => {
471 Ok(self.const_lvalue(lvalue, span)?.to_const(span))
474 mir::Operand::Constant(ref constant) => {
475 let ty = self.monomorphize(&constant.ty);
476 match constant.literal.clone() {
477 mir::Literal::Item { def_id, substs } => {
478 let substs = self.monomorphize(&substs);
479 MirConstContext::trans_def(self.ccx, def_id, substs, IndexVec::new())
481 mir::Literal::Promoted { index } => {
482 let mir = &self.mir.promoted[index];
483 MirConstContext::new(self.ccx, mir, self.substs, IndexVec::new()).trans()
485 mir::Literal::Value { value } => {
486 Ok(Const::from_constval(self.ccx, value, ty))
491 debug!("const_operand({:?} @ {:?}) = {:?}", operand, span,
492 result.as_ref().ok());
496 fn const_array(&self, array_ty: Ty<'tcx>, fields: &[ValueRef])
499 let elem_ty = array_ty.builtin_index().unwrap_or_else(|| {
500 bug!("bad array type {:?}", array_ty)
502 let llunitty = type_of::type_of(self.ccx, elem_ty);
503 // If the array contains enums, an LLVM array won't work.
504 let val = if fields.iter().all(|&f| val_ty(f) == llunitty) {
505 C_array(llunitty, fields)
507 C_struct(self.ccx, fields, false)
509 Const::new(val, array_ty)
512 fn const_rvalue(&self, rvalue: &mir::Rvalue<'tcx>,
513 dest_ty: Ty<'tcx>, span: Span)
514 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
515 let tcx = self.ccx.tcx();
516 debug!("const_rvalue({:?}: {:?} @ {:?})", rvalue, dest_ty, span);
517 let val = match *rvalue {
518 mir::Rvalue::Use(ref operand) => self.const_operand(operand, span)?,
520 mir::Rvalue::Repeat(ref elem, ref count) => {
521 let elem = self.const_operand(elem, span)?;
522 let size = count.as_u64(tcx.sess.target.uint_type);
523 let fields = vec![elem.llval; size as usize];
524 self.const_array(dest_ty, &fields)
527 mir::Rvalue::Aggregate(ref kind, ref operands) => {
528 // Make sure to evaluate all operands to
529 // report as many errors as we possibly can.
530 let mut fields = Vec::with_capacity(operands.len());
531 let mut failure = Ok(());
532 for operand in operands {
533 match self.const_operand(operand, span) {
534 Ok(val) => fields.push(val.llval),
535 Err(err) => if failure.is_ok() { failure = Err(err); }
541 mir::AggregateKind::Array(_) => {
542 self.const_array(dest_ty, &fields)
544 mir::AggregateKind::Adt(..) |
545 mir::AggregateKind::Closure(..) |
546 mir::AggregateKind::Tuple => {
547 Const::new(trans_const(self.ccx, dest_ty, kind, &fields), dest_ty)
552 mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
553 let operand = self.const_operand(source, span)?;
554 let cast_ty = self.monomorphize(&cast_ty);
556 let val = match *kind {
557 mir::CastKind::ReifyFnPointer => {
558 match operand.ty.sty {
559 ty::TyFnDef(def_id, substs, _) => {
560 callee::resolve_and_get_fn(self.ccx, def_id, substs)
563 span_bug!(span, "{} cannot be reified to a fn ptr",
568 mir::CastKind::ClosureFnPointer => {
569 match operand.ty.sty {
570 ty::TyClosure(def_id, substs) => {
571 // Get the def_id for FnOnce::call_once
572 let fn_once = tcx.lang_items.fn_once_trait().unwrap();
574 .global_tcx().associated_items(fn_once)
575 .find(|it| it.kind == ty::AssociatedKind::Method)
577 // Now create its substs [Closure, Tuple]
578 let input = tcx.closure_type(def_id)
579 .subst(tcx, substs.substs).input(0);
580 let input = tcx.erase_late_bound_regions_and_normalize(&input);
581 let substs = tcx.mk_substs([operand.ty, input]
582 .iter().cloned().map(Kind::from));
583 callee::resolve_and_get_fn(self.ccx, call_once, substs)
586 bug!("{} cannot be cast to a fn ptr", operand.ty)
590 mir::CastKind::UnsafeFnPointer => {
591 // this is a no-op at the LLVM level
594 mir::CastKind::Unsize => {
595 // unsize targets other than to a fat pointer currently
596 // can't be in constants.
597 assert!(common::type_is_fat_ptr(self.ccx, cast_ty));
599 let pointee_ty = operand.ty.builtin_deref(true, ty::NoPreference)
600 .expect("consts: unsizing got non-pointer type").ty;
601 let (base, old_info) = if !self.ccx.shared().type_is_sized(pointee_ty) {
602 // Normally, the source is a thin pointer and we are
603 // adding extra info to make a fat pointer. The exception
604 // is when we are upcasting an existing object fat pointer
605 // to use a different vtable. In that case, we want to
606 // load out the original data pointer so we can repackage
608 let (base, extra) = operand.get_fat_ptr();
611 (operand.llval, None)
614 let unsized_ty = cast_ty.builtin_deref(true, ty::NoPreference)
615 .expect("consts: unsizing got non-pointer target type").ty;
616 let ptr_ty = type_of::in_memory_type_of(self.ccx, unsized_ty).ptr_to();
617 let base = consts::ptrcast(base, ptr_ty);
618 let info = base::unsized_info(self.ccx, pointee_ty,
619 unsized_ty, old_info);
621 if old_info.is_none() {
622 let prev_const = self.ccx.const_unsized().borrow_mut()
623 .insert(base, operand.llval);
624 assert!(prev_const.is_none() || prev_const == Some(operand.llval));
626 assert_eq!(abi::FAT_PTR_ADDR, 0);
627 assert_eq!(abi::FAT_PTR_EXTRA, 1);
628 C_struct(self.ccx, &[base, info], false)
630 mir::CastKind::Misc if common::type_is_immediate(self.ccx, operand.ty) => {
631 debug_assert!(common::type_is_immediate(self.ccx, cast_ty));
632 let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
633 let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
634 let ll_t_out = type_of::immediate_type_of(self.ccx, cast_ty);
635 let llval = operand.llval;
636 let signed = if let CastTy::Int(IntTy::CEnum) = r_t_in {
637 let l = self.ccx.layout_of(operand.ty);
638 adt::is_discr_signed(&l)
640 operand.ty.is_signed()
644 match (r_t_in, r_t_out) {
645 (CastTy::Int(_), CastTy::Int(_)) => {
646 let s = signed as llvm::Bool;
647 llvm::LLVMConstIntCast(llval, ll_t_out.to_ref(), s)
649 (CastTy::Int(_), CastTy::Float) => {
651 llvm::LLVMConstSIToFP(llval, ll_t_out.to_ref())
653 llvm::LLVMConstUIToFP(llval, ll_t_out.to_ref())
656 (CastTy::Float, CastTy::Float) => {
657 llvm::LLVMConstFPCast(llval, ll_t_out.to_ref())
659 (CastTy::Float, CastTy::Int(IntTy::I)) => {
660 llvm::LLVMConstFPToSI(llval, ll_t_out.to_ref())
662 (CastTy::Float, CastTy::Int(_)) => {
663 llvm::LLVMConstFPToUI(llval, ll_t_out.to_ref())
665 (CastTy::Ptr(_), CastTy::Ptr(_)) |
666 (CastTy::FnPtr, CastTy::Ptr(_)) |
667 (CastTy::RPtr(_), CastTy::Ptr(_)) => {
668 consts::ptrcast(llval, ll_t_out)
670 (CastTy::Int(_), CastTy::Ptr(_)) => {
671 llvm::LLVMConstIntToPtr(llval, ll_t_out.to_ref())
673 (CastTy::Ptr(_), CastTy::Int(_)) |
674 (CastTy::FnPtr, CastTy::Int(_)) => {
675 llvm::LLVMConstPtrToInt(llval, ll_t_out.to_ref())
677 _ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
681 mir::CastKind::Misc => { // Casts from a fat-ptr.
682 let ll_cast_ty = type_of::immediate_type_of(self.ccx, cast_ty);
683 let ll_from_ty = type_of::immediate_type_of(self.ccx, operand.ty);
684 if common::type_is_fat_ptr(self.ccx, operand.ty) {
685 let (data_ptr, meta_ptr) = operand.get_fat_ptr();
686 if common::type_is_fat_ptr(self.ccx, cast_ty) {
687 let ll_cft = ll_cast_ty.field_types();
688 let ll_fft = ll_from_ty.field_types();
689 let data_cast = consts::ptrcast(data_ptr, ll_cft[0]);
690 assert_eq!(ll_cft[1].kind(), ll_fft[1].kind());
691 C_struct(self.ccx, &[data_cast, meta_ptr], false)
692 } else { // cast to thin-ptr
693 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
694 // pointer-cast of that pointer to desired pointer type.
695 consts::ptrcast(data_ptr, ll_cast_ty)
698 bug!("Unexpected non-fat-pointer operand")
702 Const::new(val, cast_ty)
705 mir::Rvalue::Ref(_, bk, ref lvalue) => {
706 let tr_lvalue = self.const_lvalue(lvalue, span)?;
708 let ty = tr_lvalue.ty;
709 let ref_ty = tcx.mk_ref(tcx.types.re_erased,
710 ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() });
712 let base = match tr_lvalue.base {
713 Base::Value(llval) => {
714 // FIXME: may be wrong for &*(&simd_vec as &fmt::Debug)
715 let align = if self.ccx.shared().type_is_sized(ty) {
716 self.ccx.align_of(ty)
718 self.ccx.tcx().data_layout.pointer_align.abi() as machine::llalign
720 if bk == mir::BorrowKind::Mut {
721 consts::addr_of_mut(self.ccx, llval, align, "ref_mut")
723 consts::addr_of(self.ccx, llval, align, "ref")
727 Base::Static(llval) => llval
730 let ptr = if self.ccx.shared().type_is_sized(ty) {
733 C_struct(self.ccx, &[base, tr_lvalue.llextra], false)
735 Const::new(ptr, ref_ty)
738 mir::Rvalue::Len(ref lvalue) => {
739 let tr_lvalue = self.const_lvalue(lvalue, span)?;
740 Const::new(tr_lvalue.len(self.ccx), tcx.types.usize)
743 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
744 let lhs = self.const_operand(lhs, span)?;
745 let rhs = self.const_operand(rhs, span)?;
747 let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
748 let (lhs, rhs) = (lhs.llval, rhs.llval);
749 Const::new(const_scalar_binop(op, lhs, rhs, ty), binop_ty)
752 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
753 let lhs = self.const_operand(lhs, span)?;
754 let rhs = self.const_operand(rhs, span)?;
756 let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
757 let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
758 let (lhs, rhs) = (lhs.llval, rhs.llval);
759 assert!(!ty.is_fp());
761 match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
762 Some((llval, of)) => {
763 let llof = C_bool(self.ccx, of);
764 Const::new(C_struct(self.ccx, &[llval, llof], false), binop_ty)
767 span_bug!(span, "{:?} got non-integer operands: {:?} and {:?}",
768 rvalue, Value(lhs), Value(rhs));
773 mir::Rvalue::UnaryOp(op, ref operand) => {
774 let operand = self.const_operand(operand, span)?;
775 let lloperand = operand.llval;
776 let llval = match op {
779 llvm::LLVMConstNot(lloperand)
783 let is_float = operand.ty.is_fp();
786 llvm::LLVMConstFNeg(lloperand)
788 llvm::LLVMConstNeg(lloperand)
793 Const::new(llval, operand.ty)
796 _ => span_bug!(span, "{:?} in constant", rvalue)
799 debug!("const_rvalue({:?}: {:?} @ {:?}) = {:?}", rvalue, dest_ty, span, val);
806 fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
808 ty::TyInt(int_type) => const_to_opt_u128(value, true)
809 .and_then(|input| ConstInt::new_signed(input as i128, int_type,
810 tcx.sess.target.int_type)),
811 ty::TyUint(uint_type) => const_to_opt_u128(value, false)
812 .and_then(|input| ConstInt::new_unsigned(input, uint_type,
813 tcx.sess.target.uint_type)),
819 pub fn const_scalar_binop(op: mir::BinOp,
822 input_ty: Ty) -> ValueRef {
823 assert!(!input_ty.is_simd());
824 let is_float = input_ty.is_fp();
825 let signed = input_ty.is_signed();
829 mir::BinOp::Add if is_float => llvm::LLVMConstFAdd(lhs, rhs),
830 mir::BinOp::Add => llvm::LLVMConstAdd(lhs, rhs),
832 mir::BinOp::Sub if is_float => llvm::LLVMConstFSub(lhs, rhs),
833 mir::BinOp::Sub => llvm::LLVMConstSub(lhs, rhs),
835 mir::BinOp::Mul if is_float => llvm::LLVMConstFMul(lhs, rhs),
836 mir::BinOp::Mul => llvm::LLVMConstMul(lhs, rhs),
838 mir::BinOp::Div if is_float => llvm::LLVMConstFDiv(lhs, rhs),
839 mir::BinOp::Div if signed => llvm::LLVMConstSDiv(lhs, rhs),
840 mir::BinOp::Div => llvm::LLVMConstUDiv(lhs, rhs),
842 mir::BinOp::Rem if is_float => llvm::LLVMConstFRem(lhs, rhs),
843 mir::BinOp::Rem if signed => llvm::LLVMConstSRem(lhs, rhs),
844 mir::BinOp::Rem => llvm::LLVMConstURem(lhs, rhs),
846 mir::BinOp::BitXor => llvm::LLVMConstXor(lhs, rhs),
847 mir::BinOp::BitAnd => llvm::LLVMConstAnd(lhs, rhs),
848 mir::BinOp::BitOr => llvm::LLVMConstOr(lhs, rhs),
850 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
851 llvm::LLVMConstShl(lhs, rhs)
854 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
855 if signed { llvm::LLVMConstAShr(lhs, rhs) }
856 else { llvm::LLVMConstLShr(lhs, rhs) }
858 mir::BinOp::Eq | mir::BinOp::Ne |
859 mir::BinOp::Lt | mir::BinOp::Le |
860 mir::BinOp::Gt | mir::BinOp::Ge => {
862 let cmp = base::bin_op_to_fcmp_predicate(op.to_hir_binop());
863 llvm::LLVMConstFCmp(cmp, lhs, rhs)
865 let cmp = base::bin_op_to_icmp_predicate(op.to_hir_binop(),
867 llvm::LLVMConstICmp(cmp, lhs, rhs)
874 pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
879 -> Option<(ValueRef, bool)> {
880 if let (Some(lhs), Some(rhs)) = (to_const_int(lllhs, input_ty, tcx),
881 to_const_int(llrhs, input_ty, tcx)) {
882 let result = match op {
883 mir::BinOp::Add => lhs + rhs,
884 mir::BinOp::Sub => lhs - rhs,
885 mir::BinOp::Mul => lhs * rhs,
886 mir::BinOp::Shl => lhs << rhs,
887 mir::BinOp::Shr => lhs >> rhs,
889 bug!("Operator `{:?}` is not a checkable operator", op)
893 let of = match result {
895 Err(ConstMathErr::Overflow(_)) |
896 Err(ConstMathErr::ShiftNegative) => true,
898 bug!("Operator `{:?}` on `{:?}` and `{:?}` errored: {}",
899 op, lhs, rhs, err.description());
903 Some((const_scalar_binop(op, lllhs, llrhs, input_ty), of))
909 impl<'a, 'tcx> MirContext<'a, 'tcx> {
910 pub fn trans_constant(&mut self,
911 bcx: &Builder<'a, 'tcx>,
912 constant: &mir::Constant<'tcx>)
915 debug!("trans_constant({:?})", constant);
916 let ty = self.monomorphize(&constant.ty);
917 let result = match constant.literal.clone() {
918 mir::Literal::Item { def_id, substs } => {
919 let substs = self.monomorphize(&substs);
920 MirConstContext::trans_def(bcx.ccx, def_id, substs, IndexVec::new())
922 mir::Literal::Promoted { index } => {
923 let mir = &self.mir.promoted[index];
924 MirConstContext::new(bcx.ccx, mir, self.param_substs, IndexVec::new()).trans()
926 mir::Literal::Value { value } => {
927 Ok(Const::from_constval(bcx.ccx, value, ty))
931 let result = result.unwrap_or_else(|_| {
932 // We've errored, so we don't have to produce working code.
933 let llty = type_of::type_of(bcx.ccx, ty);
934 Const::new(C_undef(llty), ty)
937 debug!("trans_constant({:?}) = {:?}", constant, result);
943 pub fn trans_static_initializer<'a, 'tcx>(
944 ccx: &CrateContext<'a, 'tcx>,
946 -> Result<ValueRef, ConstEvalErr<'tcx>>
948 MirConstContext::trans_def(ccx, def_id, Substs::empty(), IndexVec::new())
952 /// Construct a constant value, suitable for initializing a
953 /// GlobalVariable, given a case and constant values for its fields.
954 /// Note that this may have a different LLVM type (and different
955 /// alignment!) from the representation's `type_of`, so it needs a
956 /// pointer cast before use.
958 /// The LLVM type system does not directly support unions, and only
959 /// pointers can be bitcast, so a constant (and, by extension, the
960 /// GlobalVariable initialized by it) will have a type that can vary
961 /// depending on which case of an enum it is.
963 /// To understand the alignment situation, consider `enum E { V64(u64),
964 /// V32(u32, u32) }` on Windows. The type has 8-byte alignment to
965 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
966 /// i32, i32}`, which is 4-byte aligned.
968 /// Currently the returned value has the same size as the type, but
969 /// this could be changed in the future to avoid allocating unnecessary
970 /// space after values of shorter-than-maximum cases.
971 fn trans_const<'a, 'tcx>(
972 ccx: &CrateContext<'a, 'tcx>,
974 kind: &mir::AggregateKind,
977 let l = ccx.layout_of(t);
978 let variant_index = match *kind {
979 mir::AggregateKind::Adt(_, index, _, _) => index,
983 layout::CEnum { discr: d, min, max, .. } => {
984 let discr = match *kind {
985 mir::AggregateKind::Adt(adt_def, _, _, _) => {
986 adt_def.discriminant_for_variant(ccx.tcx(), variant_index)
987 .to_u128_unchecked() as u64
991 assert_eq!(vals.len(), 0);
992 adt::assert_discr_in_range(min, max, discr);
993 C_integral(Type::from_integer(ccx, d), discr, true)
995 layout::General { discr: d, ref variants, .. } => {
996 let variant = &variants[variant_index];
997 let lldiscr = C_integral(Type::from_integer(ccx, d), variant_index as u64, true);
998 let mut vals_with_discr = vec![lldiscr];
999 vals_with_discr.extend_from_slice(vals);
1000 let mut contents = build_const_struct(ccx, &variant, &vals_with_discr[..]);
1001 let needed_padding = l.size(ccx).bytes() - variant.stride().bytes();
1002 if needed_padding > 0 {
1003 contents.push(padding(ccx, needed_padding));
1005 C_struct(ccx, &contents[..], false)
1007 layout::UntaggedUnion { ref variants, .. }=> {
1008 assert_eq!(variant_index, 0);
1009 let contents = build_const_union(ccx, variants, vals[0]);
1010 C_struct(ccx, &contents, variants.packed)
1012 layout::Univariant { ref variant, .. } => {
1013 assert_eq!(variant_index, 0);
1014 let contents = build_const_struct(ccx, &variant, vals);
1015 C_struct(ccx, &contents[..], variant.packed)
1017 layout::Vector { .. } => {
1020 layout::RawNullablePointer { nndiscr, .. } => {
1021 if variant_index as u64 == nndiscr {
1022 assert_eq!(vals.len(), 1);
1025 C_null(type_of::type_of(ccx, t))
1028 layout::StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1029 if variant_index as u64 == nndiscr {
1030 C_struct(ccx, &build_const_struct(ccx, &nonnull, vals), false)
1032 // Always use null even if it's not the `discrfield`th
1033 // field; see #8506.
1034 C_null(type_of::type_of(ccx, t))
1037 _ => bug!("trans_const: cannot handle type {} repreented as {:#?}", t, l)
1041 /// Building structs is a little complicated, because we might need to
1042 /// insert padding if a field's value is less aligned than its type.
1044 /// Continuing the example from `trans_const`, a value of type `(u32,
1045 /// E)` should have the `E` at offset 8, but if that field's
1046 /// initializer is 4-byte aligned then simply translating the tuple as
1047 /// a two-element struct will locate it at offset 4, and accesses to it
1048 /// will read the wrong memory.
1049 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1050 st: &layout::Struct,
1053 assert_eq!(vals.len(), st.offsets.len());
1055 if vals.len() == 0 {
1059 // offset of current value
1061 let mut cfields = Vec::new();
1062 cfields.reserve(st.offsets.len()*2);
1064 let parts = st.field_index_by_increasing_offset().map(|i| {
1065 (&vals[i], st.offsets[i].bytes())
1067 for (&val, target_offset) in parts {
1068 if offset < target_offset {
1069 cfields.push(padding(ccx, target_offset - offset));
1070 offset = target_offset;
1072 assert!(!is_undef(val));
1074 offset += machine::llsize_of_alloc(ccx, val_ty(val));
1077 if offset < st.stride().bytes() {
1078 cfields.push(padding(ccx, st.stride().bytes() - offset));
1084 fn build_const_union<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1086 field_val: ValueRef)
1088 let mut cfields = vec![field_val];
1090 let offset = machine::llsize_of_alloc(ccx, val_ty(field_val));
1091 let size = un.stride().bytes();
1093 cfields.push(padding(ccx, size - offset));
1099 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1100 C_undef(Type::array(&Type::i8(ccx), size))