]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/constant.rs
rustc_const_math: use apfloat::ieee::{Single,Double} in ConstFloat.
[rust.git] / src / librustc_trans / mir / constant.rs
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.
4 //
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.
10
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;
18 use rustc::mir;
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 {adt, base, machine};
26 use abi::{self, Abi};
27 use callee;
28 use builder::Builder;
29 use common::{self, CrateContext, const_get_elt, val_ty};
30 use common::{C_array, C_bool, C_bytes, C_floating_f64, C_integral, C_big_integral};
31 use common::{C_null, C_struct, C_str_slice, C_undef, C_uint, C_vector, is_undef};
32 use common::const_to_opt_u128;
33 use consts;
34 use monomorphize;
35 use type_of;
36 use type_::Type;
37 use value::Value;
38
39 use syntax_pos::Span;
40
41 use std::fmt;
42 use std::ptr;
43
44 use super::lvalue::Alignment;
45 use super::operand::{OperandRef, OperandValue};
46 use super::MirContext;
47
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> {
53     pub llval: ValueRef,
54     pub ty: Ty<'tcx>
55 }
56
57 impl<'tcx> Const<'tcx> {
58     pub fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> {
59         Const {
60             llval: llval,
61             ty: ty
62         }
63     }
64
65     pub fn from_constint<'a>(ccx: &CrateContext<'a, 'tcx>, ci: &ConstInt)
66     -> Const<'tcx> {
67         let tcx = ccx.tcx();
68         let (llval, ty) = match *ci {
69             I8(v) => (C_integral(Type::i8(ccx), v as u64, true), tcx.types.i8),
70             I16(v) => (C_integral(Type::i16(ccx), v as u64, true), tcx.types.i16),
71             I32(v) => (C_integral(Type::i32(ccx), v as u64, true), tcx.types.i32),
72             I64(v) => (C_integral(Type::i64(ccx), v as u64, true), tcx.types.i64),
73             I128(v) => (C_big_integral(Type::i128(ccx), v as u128), tcx.types.i128),
74             Isize(v) => {
75                 let i = v.as_i64(ccx.tcx().sess.target.int_type);
76                 (C_integral(Type::int(ccx), i as u64, true), tcx.types.isize)
77             },
78             U8(v) => (C_integral(Type::i8(ccx), v as u64, false), tcx.types.u8),
79             U16(v) => (C_integral(Type::i16(ccx), v as u64, false), tcx.types.u16),
80             U32(v) => (C_integral(Type::i32(ccx), v as u64, false), tcx.types.u32),
81             U64(v) => (C_integral(Type::i64(ccx), v, false), tcx.types.u64),
82             U128(v) => (C_big_integral(Type::i128(ccx), v), tcx.types.u128),
83             Usize(v) => {
84                 let u = v.as_u64(ccx.tcx().sess.target.uint_type);
85                 (C_integral(Type::int(ccx), u, false), tcx.types.usize)
86             },
87         };
88         Const { llval: llval, ty: ty }
89     }
90
91     /// Translate ConstVal into a LLVM constant value.
92     pub fn from_constval<'a>(ccx: &CrateContext<'a, 'tcx>,
93                              cv: ConstVal,
94                              ty: Ty<'tcx>)
95                              -> Const<'tcx> {
96         let llty = type_of::type_of(ccx, ty);
97         let val = match cv {
98             ConstVal::Float(v) => {
99                 let v_f64 = match v {
100                     ConstFloat::F32(v) => f32::from_bits(v) as f64,
101                     ConstFloat::F64(v) => f64::from_bits(v)
102                 };
103                 C_floating_f64(v_f64, llty)
104             }
105             ConstVal::Bool(v) => C_bool(ccx, v),
106             ConstVal::Integral(ref i) => return Const::from_constint(ccx, i),
107             ConstVal::Str(ref v) => C_str_slice(ccx, v.clone()),
108             ConstVal::ByteStr(ref v) => consts::addr_of(ccx, C_bytes(ccx, v), 1, "byte_str"),
109             ConstVal::Char(c) => C_integral(Type::char(ccx), c as u64, false),
110             ConstVal::Function(..) => C_null(type_of::type_of(ccx, ty)),
111             ConstVal::Variant(_) |
112             ConstVal::Struct(_) | ConstVal::Tuple(_) |
113             ConstVal::Array(..) | ConstVal::Repeat(..) => {
114                 bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv)
115             }
116         };
117
118         assert!(!ty.has_erasable_regions());
119
120         Const::new(val, ty)
121     }
122
123     fn get_pair(&self) -> (ValueRef, ValueRef) {
124         (const_get_elt(self.llval, &[0]),
125          const_get_elt(self.llval, &[1]))
126     }
127
128     fn get_fat_ptr(&self) -> (ValueRef, ValueRef) {
129         assert_eq!(abi::FAT_PTR_ADDR, 0);
130         assert_eq!(abi::FAT_PTR_EXTRA, 1);
131         self.get_pair()
132     }
133
134     fn as_lvalue(&self) -> ConstLvalue<'tcx> {
135         ConstLvalue {
136             base: Base::Value(self.llval),
137             llextra: ptr::null_mut(),
138             ty: self.ty
139         }
140     }
141
142     pub fn to_operand<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> OperandRef<'tcx> {
143         let llty = type_of::immediate_type_of(ccx, self.ty);
144         let llvalty = val_ty(self.llval);
145
146         let val = if llty == llvalty && common::type_is_imm_pair(ccx, self.ty) {
147             let (a, b) = self.get_pair();
148             OperandValue::Pair(a, b)
149         } else if llty == llvalty && common::type_is_immediate(ccx, self.ty) {
150             // If the types match, we can use the value directly.
151             OperandValue::Immediate(self.llval)
152         } else {
153             // Otherwise, or if the value is not immediate, we create
154             // a constant LLVM global and cast its address if necessary.
155             let align = ccx.align_of(self.ty);
156             let ptr = consts::addr_of(ccx, self.llval, align, "const");
157             OperandValue::Ref(consts::ptrcast(ptr, llty.ptr_to()), Alignment::AbiAligned)
158         };
159
160         OperandRef {
161             val: val,
162             ty: self.ty
163         }
164     }
165 }
166
167 impl<'tcx> fmt::Debug for Const<'tcx> {
168     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169         write!(f, "Const({:?}: {:?})", Value(self.llval), self.ty)
170     }
171 }
172
173 #[derive(Copy, Clone)]
174 enum Base {
175     /// A constant value without an unique address.
176     Value(ValueRef),
177
178     /// String literal base pointer (cast from array).
179     Str(ValueRef),
180
181     /// The address of a static.
182     Static(ValueRef)
183 }
184
185 /// An lvalue as seen from a constant.
186 #[derive(Copy, Clone)]
187 struct ConstLvalue<'tcx> {
188     base: Base,
189     llextra: ValueRef,
190     ty: Ty<'tcx>
191 }
192
193 impl<'tcx> ConstLvalue<'tcx> {
194     fn to_const(&self, span: Span) -> Const<'tcx> {
195         match self.base {
196             Base::Value(val) => Const::new(val, self.ty),
197             Base::Str(ptr) => {
198                 span_bug!(span, "loading from `str` ({:?}) in constant",
199                           Value(ptr))
200             }
201             Base::Static(val) => {
202                 span_bug!(span, "loading from `static` ({:?}) in constant",
203                           Value(val))
204             }
205         }
206     }
207
208     pub fn len<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef {
209         match self.ty.sty {
210             ty::TyArray(_, n) => C_uint(ccx, n),
211             ty::TySlice(_) | ty::TyStr => {
212                 assert!(self.llextra != ptr::null_mut());
213                 self.llextra
214             }
215             _ => bug!("unexpected type `{}` in ConstLvalue::len", self.ty)
216         }
217     }
218 }
219
220 /// Machinery for translating a constant's MIR to LLVM values.
221 /// FIXME(eddyb) use miri and lower its allocations to LLVM.
222 struct MirConstContext<'a, 'tcx: 'a> {
223     ccx: &'a CrateContext<'a, 'tcx>,
224     mir: &'a mir::Mir<'tcx>,
225
226     /// Type parameters for const fn and associated constants.
227     substs: &'tcx Substs<'tcx>,
228
229     /// Values of locals in a constant or const fn.
230     locals: IndexVec<mir::Local, Option<Result<Const<'tcx>, ConstEvalErr<'tcx>>>>
231 }
232
233 fn add_err<'tcx, U, V>(failure: &mut Result<U, ConstEvalErr<'tcx>>,
234                        value: &Result<V, ConstEvalErr<'tcx>>)
235 {
236     if let &Err(ref err) = value {
237         if failure.is_ok() {
238             *failure = Err(err.clone());
239         }
240     }
241 }
242
243 impl<'a, 'tcx> MirConstContext<'a, 'tcx> {
244     fn new(ccx: &'a CrateContext<'a, 'tcx>,
245            mir: &'a mir::Mir<'tcx>,
246            substs: &'tcx Substs<'tcx>,
247            args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
248            -> MirConstContext<'a, 'tcx> {
249         let mut context = MirConstContext {
250             ccx: ccx,
251             mir: mir,
252             substs: substs,
253             locals: (0..mir.local_decls.len()).map(|_| None).collect(),
254         };
255         for (i, arg) in args.into_iter().enumerate() {
256             // Locals after local 0 are the function arguments
257             let index = mir::Local::new(i + 1);
258             context.locals[index] = Some(arg);
259         }
260         context
261     }
262
263     fn trans_def(ccx: &'a CrateContext<'a, 'tcx>,
264                  def_id: DefId,
265                  substs: &'tcx Substs<'tcx>,
266                  args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
267                  -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
268         let instance = monomorphize::resolve(ccx.shared(), def_id, substs);
269         let mir = ccx.tcx().instance_mir(instance.def);
270         MirConstContext::new(ccx, &mir, instance.substs, args).trans()
271     }
272
273     fn monomorphize<T>(&self, value: &T) -> T
274         where T: TransNormalize<'tcx>
275     {
276         self.ccx.tcx().trans_apply_param_substs(self.substs, value)
277     }
278
279     fn trans(&mut self) -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
280         let tcx = self.ccx.tcx();
281         let mut bb = mir::START_BLOCK;
282
283         // Make sure to evaluate all statemenets to
284         // report as many errors as we possibly can.
285         let mut failure = Ok(());
286
287         loop {
288             let data = &self.mir[bb];
289             for statement in &data.statements {
290                 let span = statement.source_info.span;
291                 match statement.kind {
292                     mir::StatementKind::Assign(ref dest, ref rvalue) => {
293                         let ty = dest.ty(self.mir, tcx);
294                         let ty = self.monomorphize(&ty).to_ty(tcx);
295                         let value = self.const_rvalue(rvalue, ty, span);
296                         add_err(&mut failure, &value);
297                         self.store(dest, value, span);
298                     }
299                     mir::StatementKind::StorageLive(_) |
300                     mir::StatementKind::StorageDead(_) |
301                     mir::StatementKind::EndRegion(_) |
302                     mir::StatementKind::Nop => {}
303                     mir::StatementKind::InlineAsm { .. } |
304                     mir::StatementKind::SetDiscriminant{ .. } => {
305                         span_bug!(span, "{:?} should not appear in constants?", statement.kind);
306                     }
307                 }
308             }
309
310             let terminator = data.terminator();
311             let span = terminator.source_info.span;
312             bb = match terminator.kind {
313                 mir::TerminatorKind::Drop { target, .. } | // No dropping.
314                 mir::TerminatorKind::Goto { target } => target,
315                 mir::TerminatorKind::Return => {
316                     failure?;
317                     return self.locals[mir::RETURN_POINTER].clone().unwrap_or_else(|| {
318                         span_bug!(span, "no returned value in constant");
319                     });
320                 }
321
322                 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, .. } => {
323                     let cond = self.const_operand(cond, span)?;
324                     let cond_bool = common::const_to_uint(cond.llval) != 0;
325                     if cond_bool != expected {
326                         let err = match *msg {
327                             mir::AssertMessage::BoundsCheck { ref len, ref index } => {
328                                 let len = self.const_operand(len, span)?;
329                                 let index = self.const_operand(index, span)?;
330                                 ErrKind::IndexOutOfBounds {
331                                     len: common::const_to_uint(len.llval),
332                                     index: common::const_to_uint(index.llval)
333                                 }
334                             }
335                             mir::AssertMessage::Math(ref err) => {
336                                 ErrKind::Math(err.clone())
337                             }
338                         };
339
340                         let err = ConstEvalErr { span: span, kind: err };
341                         err.report(tcx, span, "expression");
342                         failure = Err(err);
343                     }
344                     target
345                 }
346
347                 mir::TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
348                     let fn_ty = func.ty(self.mir, tcx);
349                     let fn_ty = self.monomorphize(&fn_ty);
350                     let (def_id, substs) = match fn_ty.sty {
351                         ty::TyFnDef(def_id, substs) => (def_id, substs),
352                         _ => span_bug!(span, "calling {:?} (of type {}) in constant",
353                                        func, fn_ty)
354                     };
355
356                     let mut arg_vals = IndexVec::with_capacity(args.len());
357                     for arg in args {
358                         let arg_val = self.const_operand(arg, span);
359                         add_err(&mut failure, &arg_val);
360                         arg_vals.push(arg_val);
361                     }
362                     if let Some((ref dest, target)) = *destination {
363                         let result = if fn_ty.fn_sig(tcx).abi() == Abi::RustIntrinsic {
364                             match &tcx.item_name(def_id).as_str()[..] {
365                                 "size_of" => {
366                                     let llval = C_uint(self.ccx,
367                                         self.ccx.size_of(substs.type_at(0)));
368                                     Ok(Const::new(llval, tcx.types.usize))
369                                 }
370                                 "min_align_of" => {
371                                     let llval = C_uint(self.ccx,
372                                         self.ccx.align_of(substs.type_at(0)));
373                                     Ok(Const::new(llval, tcx.types.usize))
374                                 }
375                                 _ => span_bug!(span, "{:?} in constant", terminator.kind)
376                             }
377                         } else {
378                             MirConstContext::trans_def(self.ccx, def_id, substs, arg_vals)
379                         };
380                         add_err(&mut failure, &result);
381                         self.store(dest, result, span);
382                         target
383                     } else {
384                         span_bug!(span, "diverging {:?} in constant", terminator.kind);
385                     }
386                 }
387                 _ => span_bug!(span, "{:?} in constant", terminator.kind)
388             };
389         }
390     }
391
392     fn store(&mut self,
393              dest: &mir::Lvalue<'tcx>,
394              value: Result<Const<'tcx>, ConstEvalErr<'tcx>>,
395              span: Span) {
396         if let mir::Lvalue::Local(index) = *dest {
397             self.locals[index] = Some(value);
398         } else {
399             span_bug!(span, "assignment to {:?} in constant", dest);
400         }
401     }
402
403     fn const_lvalue(&self, lvalue: &mir::Lvalue<'tcx>, span: Span)
404                     -> Result<ConstLvalue<'tcx>, ConstEvalErr<'tcx>> {
405         let tcx = self.ccx.tcx();
406
407         if let mir::Lvalue::Local(index) = *lvalue {
408             return self.locals[index].clone().unwrap_or_else(|| {
409                 span_bug!(span, "{:?} not initialized", lvalue)
410             }).map(|v| v.as_lvalue());
411         }
412
413         let lvalue = match *lvalue {
414             mir::Lvalue::Local(_)  => bug!(), // handled above
415             mir::Lvalue::Static(box mir::Static { def_id, ty }) => {
416                 ConstLvalue {
417                     base: Base::Static(consts::get_static(self.ccx, def_id)),
418                     llextra: ptr::null_mut(),
419                     ty: self.monomorphize(&ty),
420                 }
421             }
422             mir::Lvalue::Projection(ref projection) => {
423                 let tr_base = self.const_lvalue(&projection.base, span)?;
424                 let projected_ty = LvalueTy::Ty { ty: tr_base.ty }
425                     .projection_ty(tcx, &projection.elem);
426                 let base = tr_base.to_const(span);
427                 let projected_ty = self.monomorphize(&projected_ty).to_ty(tcx);
428                 let is_sized = self.ccx.shared().type_is_sized(projected_ty);
429
430                 let (projected, llextra) = match projection.elem {
431                     mir::ProjectionElem::Deref => {
432                         let (base, extra) = if is_sized {
433                             (base.llval, ptr::null_mut())
434                         } else {
435                             base.get_fat_ptr()
436                         };
437                         if self.ccx.statics().borrow().contains_key(&base) {
438                             (Base::Static(base), extra)
439                         } else if let ty::TyStr = projected_ty.sty {
440                             (Base::Str(base), extra)
441                         } else {
442                             let v = base;
443                             let v = self.ccx.const_unsized().borrow().get(&v).map_or(v, |&v| v);
444                             let mut val = unsafe { llvm::LLVMGetInitializer(v) };
445                             if val.is_null() {
446                                 span_bug!(span, "dereference of non-constant pointer `{:?}`",
447                                           Value(base));
448                             }
449                             if projected_ty.is_bool() {
450                                 let i1_type = Type::i1(self.ccx);
451                                 if val_ty(val) != i1_type {
452                                     unsafe {
453                                         val = llvm::LLVMConstTrunc(val, i1_type.to_ref());
454                                     }
455                                 }
456                             }
457                             (Base::Value(val), extra)
458                         }
459                     }
460                     mir::ProjectionElem::Field(ref field, _) => {
461                         let llprojected = adt::const_get_field(self.ccx, tr_base.ty, base.llval,
462                                                                field.index());
463                         let llextra = if is_sized {
464                             ptr::null_mut()
465                         } else {
466                             tr_base.llextra
467                         };
468                         (Base::Value(llprojected), llextra)
469                     }
470                     mir::ProjectionElem::Index(ref index) => {
471                         let llindex = self.const_operand(index, span)?.llval;
472
473                         let iv = if let Some(iv) = common::const_to_opt_u128(llindex, false) {
474                             iv
475                         } else {
476                             span_bug!(span, "index is not an integer-constant expression")
477                         };
478
479                         // Produce an undef instead of a LLVM assertion on OOB.
480                         let len = common::const_to_uint(tr_base.len(self.ccx));
481                         let llelem = if iv < len as u128 {
482                             const_get_elt(base.llval, &[iv as u32])
483                         } else {
484                             C_undef(type_of::type_of(self.ccx, projected_ty))
485                         };
486
487                         (Base::Value(llelem), ptr::null_mut())
488                     }
489                     _ => span_bug!(span, "{:?} in constant", projection.elem)
490                 };
491                 ConstLvalue {
492                     base: projected,
493                     llextra: llextra,
494                     ty: projected_ty
495                 }
496             }
497         };
498         Ok(lvalue)
499     }
500
501     fn const_operand(&self, operand: &mir::Operand<'tcx>, span: Span)
502                      -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
503         debug!("const_operand({:?} @ {:?})", operand, span);
504         let result = match *operand {
505             mir::Operand::Consume(ref lvalue) => {
506                 Ok(self.const_lvalue(lvalue, span)?.to_const(span))
507             }
508
509             mir::Operand::Constant(ref constant) => {
510                 let ty = self.monomorphize(&constant.ty);
511                 match constant.literal.clone() {
512                     mir::Literal::Item { def_id, substs } => {
513                         let substs = self.monomorphize(&substs);
514                         MirConstContext::trans_def(self.ccx, def_id, substs, IndexVec::new())
515                     }
516                     mir::Literal::Promoted { index } => {
517                         let mir = &self.mir.promoted[index];
518                         MirConstContext::new(self.ccx, mir, self.substs, IndexVec::new()).trans()
519                     }
520                     mir::Literal::Value { value } => {
521                         Ok(Const::from_constval(self.ccx, value, ty))
522                     }
523                 }
524             }
525         };
526         debug!("const_operand({:?} @ {:?}) = {:?}", operand, span,
527                result.as_ref().ok());
528         result
529     }
530
531     fn const_array(&self, array_ty: Ty<'tcx>, fields: &[ValueRef])
532                    -> Const<'tcx>
533     {
534         let elem_ty = array_ty.builtin_index().unwrap_or_else(|| {
535             bug!("bad array type {:?}", array_ty)
536         });
537         let llunitty = type_of::type_of(self.ccx, elem_ty);
538         // If the array contains enums, an LLVM array won't work.
539         let val = if fields.iter().all(|&f| val_ty(f) == llunitty) {
540             C_array(llunitty, fields)
541         } else {
542             C_struct(self.ccx, fields, false)
543         };
544         Const::new(val, array_ty)
545     }
546
547     fn const_rvalue(&self, rvalue: &mir::Rvalue<'tcx>,
548                     dest_ty: Ty<'tcx>, span: Span)
549                     -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
550         let tcx = self.ccx.tcx();
551         debug!("const_rvalue({:?}: {:?} @ {:?})", rvalue, dest_ty, span);
552         let val = match *rvalue {
553             mir::Rvalue::Use(ref operand) => self.const_operand(operand, span)?,
554
555             mir::Rvalue::Repeat(ref elem, ref count) => {
556                 let elem = self.const_operand(elem, span)?;
557                 let size = count.as_u64(tcx.sess.target.uint_type);
558                 let fields = vec![elem.llval; size as usize];
559                 self.const_array(dest_ty, &fields)
560             }
561
562             mir::Rvalue::Aggregate(ref kind, ref operands) => {
563                 // Make sure to evaluate all operands to
564                 // report as many errors as we possibly can.
565                 let mut fields = Vec::with_capacity(operands.len());
566                 let mut failure = Ok(());
567                 for operand in operands {
568                     match self.const_operand(operand, span) {
569                         Ok(val) => fields.push(val.llval),
570                         Err(err) => if failure.is_ok() { failure = Err(err); }
571                     }
572                 }
573                 failure?;
574
575                 match **kind {
576                     mir::AggregateKind::Array(_) => {
577                         self.const_array(dest_ty, &fields)
578                     }
579                     mir::AggregateKind::Adt(..) |
580                     mir::AggregateKind::Closure(..) |
581                     mir::AggregateKind::Tuple => {
582                         Const::new(trans_const(self.ccx, dest_ty, kind, &fields), dest_ty)
583                     }
584                 }
585             }
586
587             mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
588                 let operand = self.const_operand(source, span)?;
589                 let cast_ty = self.monomorphize(&cast_ty);
590
591                 let val = match *kind {
592                     mir::CastKind::ReifyFnPointer => {
593                         match operand.ty.sty {
594                             ty::TyFnDef(def_id, substs) => {
595                                 callee::resolve_and_get_fn(self.ccx, def_id, substs)
596                             }
597                             _ => {
598                                 span_bug!(span, "{} cannot be reified to a fn ptr",
599                                           operand.ty)
600                             }
601                         }
602                     }
603                     mir::CastKind::ClosureFnPointer => {
604                         match operand.ty.sty {
605                             ty::TyClosure(def_id, substs) => {
606                                 // Get the def_id for FnOnce::call_once
607                                 let fn_once = tcx.lang_items.fn_once_trait().unwrap();
608                                 let call_once = tcx
609                                     .global_tcx().associated_items(fn_once)
610                                     .find(|it| it.kind == ty::AssociatedKind::Method)
611                                     .unwrap().def_id;
612                                 // Now create its substs [Closure, Tuple]
613                                 let input = tcx.fn_sig(def_id)
614                                     .subst(tcx, substs.substs).input(0);
615                                 let input = tcx.erase_late_bound_regions_and_normalize(&input);
616                                 let substs = tcx.mk_substs([operand.ty, input]
617                                     .iter().cloned().map(Kind::from));
618                                 callee::resolve_and_get_fn(self.ccx, call_once, substs)
619                             }
620                             _ => {
621                                 bug!("{} cannot be cast to a fn ptr", operand.ty)
622                             }
623                         }
624                     }
625                     mir::CastKind::UnsafeFnPointer => {
626                         // this is a no-op at the LLVM level
627                         operand.llval
628                     }
629                     mir::CastKind::Unsize => {
630                         // unsize targets other than to a fat pointer currently
631                         // can't be in constants.
632                         assert!(common::type_is_fat_ptr(self.ccx, cast_ty));
633
634                         let pointee_ty = operand.ty.builtin_deref(true, ty::NoPreference)
635                             .expect("consts: unsizing got non-pointer type").ty;
636                         let (base, old_info) = if !self.ccx.shared().type_is_sized(pointee_ty) {
637                             // Normally, the source is a thin pointer and we are
638                             // adding extra info to make a fat pointer. The exception
639                             // is when we are upcasting an existing object fat pointer
640                             // to use a different vtable. In that case, we want to
641                             // load out the original data pointer so we can repackage
642                             // it.
643                             let (base, extra) = operand.get_fat_ptr();
644                             (base, Some(extra))
645                         } else {
646                             (operand.llval, None)
647                         };
648
649                         let unsized_ty = cast_ty.builtin_deref(true, ty::NoPreference)
650                             .expect("consts: unsizing got non-pointer target type").ty;
651                         let ptr_ty = type_of::in_memory_type_of(self.ccx, unsized_ty).ptr_to();
652                         let base = consts::ptrcast(base, ptr_ty);
653                         let info = base::unsized_info(self.ccx, pointee_ty,
654                                                       unsized_ty, old_info);
655
656                         if old_info.is_none() {
657                             let prev_const = self.ccx.const_unsized().borrow_mut()
658                                                      .insert(base, operand.llval);
659                             assert!(prev_const.is_none() || prev_const == Some(operand.llval));
660                         }
661                         assert_eq!(abi::FAT_PTR_ADDR, 0);
662                         assert_eq!(abi::FAT_PTR_EXTRA, 1);
663                         C_struct(self.ccx, &[base, info], false)
664                     }
665                     mir::CastKind::Misc if common::type_is_immediate(self.ccx, operand.ty) => {
666                         debug_assert!(common::type_is_immediate(self.ccx, cast_ty));
667                         let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
668                         let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
669                         let ll_t_out = type_of::immediate_type_of(self.ccx, cast_ty);
670                         let llval = operand.llval;
671                         let signed = if let CastTy::Int(IntTy::CEnum) = r_t_in {
672                             let l = self.ccx.layout_of(operand.ty);
673                             adt::is_discr_signed(&l)
674                         } else {
675                             operand.ty.is_signed()
676                         };
677
678                         unsafe {
679                             match (r_t_in, r_t_out) {
680                                 (CastTy::Int(_), CastTy::Int(_)) => {
681                                     let s = signed as llvm::Bool;
682                                     llvm::LLVMConstIntCast(llval, ll_t_out.to_ref(), s)
683                                 }
684                                 (CastTy::Int(_), CastTy::Float) => {
685                                     if signed {
686                                         llvm::LLVMConstSIToFP(llval, ll_t_out.to_ref())
687                                     } else {
688                                         llvm::LLVMConstUIToFP(llval, ll_t_out.to_ref())
689                                     }
690                                 }
691                                 (CastTy::Float, CastTy::Float) => {
692                                     llvm::LLVMConstFPCast(llval, ll_t_out.to_ref())
693                                 }
694                                 (CastTy::Float, CastTy::Int(IntTy::I)) => {
695                                     llvm::LLVMConstFPToSI(llval, ll_t_out.to_ref())
696                                 }
697                                 (CastTy::Float, CastTy::Int(_)) => {
698                                     llvm::LLVMConstFPToUI(llval, ll_t_out.to_ref())
699                                 }
700                                 (CastTy::Ptr(_), CastTy::Ptr(_)) |
701                                 (CastTy::FnPtr, CastTy::Ptr(_)) |
702                                 (CastTy::RPtr(_), CastTy::Ptr(_)) => {
703                                     consts::ptrcast(llval, ll_t_out)
704                                 }
705                                 (CastTy::Int(_), CastTy::Ptr(_)) => {
706                                     llvm::LLVMConstIntToPtr(llval, ll_t_out.to_ref())
707                                 }
708                                 (CastTy::Ptr(_), CastTy::Int(_)) |
709                                 (CastTy::FnPtr, CastTy::Int(_)) => {
710                                     llvm::LLVMConstPtrToInt(llval, ll_t_out.to_ref())
711                                 }
712                                 _ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
713                             }
714                         }
715                     }
716                     mir::CastKind::Misc => { // Casts from a fat-ptr.
717                         let ll_cast_ty = type_of::immediate_type_of(self.ccx, cast_ty);
718                         let ll_from_ty = type_of::immediate_type_of(self.ccx, operand.ty);
719                         if common::type_is_fat_ptr(self.ccx, operand.ty) {
720                             let (data_ptr, meta_ptr) = operand.get_fat_ptr();
721                             if common::type_is_fat_ptr(self.ccx, cast_ty) {
722                                 let ll_cft = ll_cast_ty.field_types();
723                                 let ll_fft = ll_from_ty.field_types();
724                                 let data_cast = consts::ptrcast(data_ptr, ll_cft[0]);
725                                 assert_eq!(ll_cft[1].kind(), ll_fft[1].kind());
726                                 C_struct(self.ccx, &[data_cast, meta_ptr], false)
727                             } else { // cast to thin-ptr
728                                 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
729                                 // pointer-cast of that pointer to desired pointer type.
730                                 consts::ptrcast(data_ptr, ll_cast_ty)
731                             }
732                         } else {
733                             bug!("Unexpected non-fat-pointer operand")
734                         }
735                     }
736                 };
737                 Const::new(val, cast_ty)
738             }
739
740             mir::Rvalue::Ref(_, bk, ref lvalue) => {
741                 let tr_lvalue = self.const_lvalue(lvalue, span)?;
742
743                 let ty = tr_lvalue.ty;
744                 let ref_ty = tcx.mk_ref(tcx.types.re_erased,
745                     ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() });
746
747                 let base = match tr_lvalue.base {
748                     Base::Value(llval) => {
749                         // FIXME: may be wrong for &*(&simd_vec as &fmt::Debug)
750                         let align = if self.ccx.shared().type_is_sized(ty) {
751                             self.ccx.align_of(ty)
752                         } else {
753                             self.ccx.tcx().data_layout.pointer_align.abi() as machine::llalign
754                         };
755                         if bk == mir::BorrowKind::Mut {
756                             consts::addr_of_mut(self.ccx, llval, align, "ref_mut")
757                         } else {
758                             consts::addr_of(self.ccx, llval, align, "ref")
759                         }
760                     }
761                     Base::Str(llval) |
762                     Base::Static(llval) => llval
763                 };
764
765                 let ptr = if self.ccx.shared().type_is_sized(ty) {
766                     base
767                 } else {
768                     C_struct(self.ccx, &[base, tr_lvalue.llextra], false)
769                 };
770                 Const::new(ptr, ref_ty)
771             }
772
773             mir::Rvalue::Len(ref lvalue) => {
774                 let tr_lvalue = self.const_lvalue(lvalue, span)?;
775                 Const::new(tr_lvalue.len(self.ccx), tcx.types.usize)
776             }
777
778             mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
779                 let lhs = self.const_operand(lhs, span)?;
780                 let rhs = self.const_operand(rhs, span)?;
781                 let ty = lhs.ty;
782                 let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
783                 let (lhs, rhs) = (lhs.llval, rhs.llval);
784                 Const::new(const_scalar_binop(op, lhs, rhs, ty), binop_ty)
785             }
786
787             mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
788                 let lhs = self.const_operand(lhs, span)?;
789                 let rhs = self.const_operand(rhs, span)?;
790                 let ty = lhs.ty;
791                 let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
792                 let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
793                 let (lhs, rhs) = (lhs.llval, rhs.llval);
794                 assert!(!ty.is_fp());
795
796                 match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
797                     Some((llval, of)) => {
798                         let llof = C_bool(self.ccx, of);
799                         Const::new(C_struct(self.ccx, &[llval, llof], false), binop_ty)
800                     }
801                     None => {
802                         span_bug!(span, "{:?} got non-integer operands: {:?} and {:?}",
803                                   rvalue, Value(lhs), Value(rhs));
804                     }
805                 }
806             }
807
808             mir::Rvalue::UnaryOp(op, ref operand) => {
809                 let operand = self.const_operand(operand, span)?;
810                 let lloperand = operand.llval;
811                 let llval = match op {
812                     mir::UnOp::Not => {
813                         unsafe {
814                             llvm::LLVMConstNot(lloperand)
815                         }
816                     }
817                     mir::UnOp::Neg => {
818                         let is_float = operand.ty.is_fp();
819                         unsafe {
820                             if is_float {
821                                 llvm::LLVMConstFNeg(lloperand)
822                             } else {
823                                 llvm::LLVMConstNeg(lloperand)
824                             }
825                         }
826                     }
827                 };
828                 Const::new(llval, operand.ty)
829             }
830
831             mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
832                 assert!(self.ccx.shared().type_is_sized(ty));
833                 let llval = C_uint(self.ccx, self.ccx.size_of(ty));
834                 Const::new(llval, tcx.types.usize)
835             }
836
837             _ => span_bug!(span, "{:?} in constant", rvalue)
838         };
839
840         debug!("const_rvalue({:?}: {:?} @ {:?}) = {:?}", rvalue, dest_ty, span, val);
841
842         Ok(val)
843     }
844
845 }
846
847 fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
848     match t.sty {
849         ty::TyInt(int_type) => const_to_opt_u128(value, true)
850             .and_then(|input| ConstInt::new_signed(input as i128, int_type,
851                                                    tcx.sess.target.int_type)),
852         ty::TyUint(uint_type) => const_to_opt_u128(value, false)
853             .and_then(|input| ConstInt::new_unsigned(input, uint_type,
854                                                      tcx.sess.target.uint_type)),
855         _ => None
856
857     }
858 }
859
860 pub fn const_scalar_binop(op: mir::BinOp,
861                           lhs: ValueRef,
862                           rhs: ValueRef,
863                           input_ty: Ty) -> ValueRef {
864     assert!(!input_ty.is_simd());
865     let is_float = input_ty.is_fp();
866     let signed = input_ty.is_signed();
867
868     unsafe {
869         match op {
870             mir::BinOp::Add if is_float => llvm::LLVMConstFAdd(lhs, rhs),
871             mir::BinOp::Add             => llvm::LLVMConstAdd(lhs, rhs),
872
873             mir::BinOp::Sub if is_float => llvm::LLVMConstFSub(lhs, rhs),
874             mir::BinOp::Sub             => llvm::LLVMConstSub(lhs, rhs),
875
876             mir::BinOp::Mul if is_float => llvm::LLVMConstFMul(lhs, rhs),
877             mir::BinOp::Mul             => llvm::LLVMConstMul(lhs, rhs),
878
879             mir::BinOp::Div if is_float => llvm::LLVMConstFDiv(lhs, rhs),
880             mir::BinOp::Div if signed   => llvm::LLVMConstSDiv(lhs, rhs),
881             mir::BinOp::Div             => llvm::LLVMConstUDiv(lhs, rhs),
882
883             mir::BinOp::Rem if is_float => llvm::LLVMConstFRem(lhs, rhs),
884             mir::BinOp::Rem if signed   => llvm::LLVMConstSRem(lhs, rhs),
885             mir::BinOp::Rem             => llvm::LLVMConstURem(lhs, rhs),
886
887             mir::BinOp::BitXor => llvm::LLVMConstXor(lhs, rhs),
888             mir::BinOp::BitAnd => llvm::LLVMConstAnd(lhs, rhs),
889             mir::BinOp::BitOr  => llvm::LLVMConstOr(lhs, rhs),
890             mir::BinOp::Shl    => {
891                 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
892                 llvm::LLVMConstShl(lhs, rhs)
893             }
894             mir::BinOp::Shr    => {
895                 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
896                 if signed { llvm::LLVMConstAShr(lhs, rhs) }
897                 else      { llvm::LLVMConstLShr(lhs, rhs) }
898             }
899             mir::BinOp::Eq | mir::BinOp::Ne |
900             mir::BinOp::Lt | mir::BinOp::Le |
901             mir::BinOp::Gt | mir::BinOp::Ge => {
902                 if is_float {
903                     let cmp = base::bin_op_to_fcmp_predicate(op.to_hir_binop());
904                     llvm::LLVMConstFCmp(cmp, lhs, rhs)
905                 } else {
906                     let cmp = base::bin_op_to_icmp_predicate(op.to_hir_binop(),
907                                                                 signed);
908                     llvm::LLVMConstICmp(cmp, lhs, rhs)
909                 }
910             }
911             mir::BinOp::Offset => unreachable!("BinOp::Offset in const-eval!")
912         }
913     }
914 }
915
916 pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
917                                             op: mir::BinOp,
918                                             lllhs: ValueRef,
919                                             llrhs: ValueRef,
920                                             input_ty: Ty<'tcx>)
921                                             -> Option<(ValueRef, bool)> {
922     if let (Some(lhs), Some(rhs)) = (to_const_int(lllhs, input_ty, tcx),
923                                      to_const_int(llrhs, input_ty, tcx)) {
924         let result = match op {
925             mir::BinOp::Add => lhs + rhs,
926             mir::BinOp::Sub => lhs - rhs,
927             mir::BinOp::Mul => lhs * rhs,
928             mir::BinOp::Shl => lhs << rhs,
929             mir::BinOp::Shr => lhs >> rhs,
930             _ => {
931                 bug!("Operator `{:?}` is not a checkable operator", op)
932             }
933         };
934
935         let of = match result {
936             Ok(_) => false,
937             Err(ConstMathErr::Overflow(_)) |
938             Err(ConstMathErr::ShiftNegative) => true,
939             Err(err) => {
940                 bug!("Operator `{:?}` on `{:?}` and `{:?}` errored: {}",
941                      op, lhs, rhs, err.description());
942             }
943         };
944
945         Some((const_scalar_binop(op, lllhs, llrhs, input_ty), of))
946     } else {
947         None
948     }
949 }
950
951 impl<'a, 'tcx> MirContext<'a, 'tcx> {
952     pub fn trans_constant(&mut self,
953                           bcx: &Builder<'a, 'tcx>,
954                           constant: &mir::Constant<'tcx>)
955                           -> Const<'tcx>
956     {
957         debug!("trans_constant({:?})", constant);
958         let ty = self.monomorphize(&constant.ty);
959         let result = match constant.literal.clone() {
960             mir::Literal::Item { def_id, substs } => {
961                 let substs = self.monomorphize(&substs);
962                 MirConstContext::trans_def(bcx.ccx, def_id, substs, IndexVec::new())
963             }
964             mir::Literal::Promoted { index } => {
965                 let mir = &self.mir.promoted[index];
966                 MirConstContext::new(bcx.ccx, mir, self.param_substs, IndexVec::new()).trans()
967             }
968             mir::Literal::Value { value } => {
969                 Ok(Const::from_constval(bcx.ccx, value, ty))
970             }
971         };
972
973         let result = result.unwrap_or_else(|_| {
974             // We've errored, so we don't have to produce working code.
975             let llty = type_of::type_of(bcx.ccx, ty);
976             Const::new(C_undef(llty), ty)
977         });
978
979         debug!("trans_constant({:?}) = {:?}", constant, result);
980         result
981     }
982 }
983
984
985 pub fn trans_static_initializer<'a, 'tcx>(
986     ccx: &CrateContext<'a, 'tcx>,
987     def_id: DefId)
988     -> Result<ValueRef, ConstEvalErr<'tcx>>
989 {
990     MirConstContext::trans_def(ccx, def_id, Substs::empty(), IndexVec::new())
991         .map(|c| c.llval)
992 }
993
994 /// Construct a constant value, suitable for initializing a
995 /// GlobalVariable, given a case and constant values for its fields.
996 /// Note that this may have a different LLVM type (and different
997 /// alignment!) from the representation's `type_of`, so it needs a
998 /// pointer cast before use.
999 ///
1000 /// The LLVM type system does not directly support unions, and only
1001 /// pointers can be bitcast, so a constant (and, by extension, the
1002 /// GlobalVariable initialized by it) will have a type that can vary
1003 /// depending on which case of an enum it is.
1004 ///
1005 /// To understand the alignment situation, consider `enum E { V64(u64),
1006 /// V32(u32, u32) }` on Windows.  The type has 8-byte alignment to
1007 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1008 /// i32, i32}`, which is 4-byte aligned.
1009 ///
1010 /// Currently the returned value has the same size as the type, but
1011 /// this could be changed in the future to avoid allocating unnecessary
1012 /// space after values of shorter-than-maximum cases.
1013 fn trans_const<'a, 'tcx>(
1014     ccx: &CrateContext<'a, 'tcx>,
1015     t: Ty<'tcx>,
1016     kind: &mir::AggregateKind,
1017     vals: &[ValueRef]
1018 ) -> ValueRef {
1019     let l = ccx.layout_of(t);
1020     let variant_index = match *kind {
1021         mir::AggregateKind::Adt(_, index, _, _) => index,
1022         _ => 0,
1023     };
1024     match *l {
1025         layout::CEnum { discr: d, min, max, .. } => {
1026             let discr = match *kind {
1027                 mir::AggregateKind::Adt(adt_def, _, _, _) => {
1028                     adt_def.discriminant_for_variant(ccx.tcx(), variant_index)
1029                            .to_u128_unchecked() as u64
1030                 },
1031                 _ => 0,
1032             };
1033             assert_eq!(vals.len(), 0);
1034             adt::assert_discr_in_range(min, max, discr);
1035             C_integral(Type::from_integer(ccx, d), discr, true)
1036         }
1037         layout::General { discr: d, ref variants, .. } => {
1038             let variant = &variants[variant_index];
1039             let lldiscr = C_integral(Type::from_integer(ccx, d), variant_index as u64, true);
1040             let mut vals_with_discr = vec![lldiscr];
1041             vals_with_discr.extend_from_slice(vals);
1042             let mut contents = build_const_struct(ccx, &variant, &vals_with_discr[..]);
1043             let needed_padding = l.size(ccx).bytes() - variant.stride().bytes();
1044             if needed_padding > 0 {
1045                 contents.push(padding(ccx, needed_padding));
1046             }
1047             C_struct(ccx, &contents[..], false)
1048         }
1049         layout::UntaggedUnion { ref variants, .. }=> {
1050             assert_eq!(variant_index, 0);
1051             let contents = build_const_union(ccx, variants, vals[0]);
1052             C_struct(ccx, &contents, variants.packed)
1053         }
1054         layout::Univariant { ref variant, .. } => {
1055             assert_eq!(variant_index, 0);
1056             let contents = build_const_struct(ccx, &variant, vals);
1057             C_struct(ccx, &contents[..], variant.packed)
1058         }
1059         layout::Vector { .. } => {
1060             C_vector(vals)
1061         }
1062         layout::RawNullablePointer { nndiscr, .. } => {
1063             if variant_index as u64 == nndiscr {
1064                 assert_eq!(vals.len(), 1);
1065                 vals[0]
1066             } else {
1067                 C_null(type_of::type_of(ccx, t))
1068             }
1069         }
1070         layout::StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1071             if variant_index as u64 == nndiscr {
1072                 C_struct(ccx, &build_const_struct(ccx, &nonnull, vals), false)
1073             } else {
1074                 // Always use null even if it's not the `discrfield`th
1075                 // field; see #8506.
1076                 C_null(type_of::type_of(ccx, t))
1077             }
1078         }
1079         _ => bug!("trans_const: cannot handle type {} repreented as {:#?}", t, l)
1080     }
1081 }
1082
1083 /// Building structs is a little complicated, because we might need to
1084 /// insert padding if a field's value is less aligned than its type.
1085 ///
1086 /// Continuing the example from `trans_const`, a value of type `(u32,
1087 /// E)` should have the `E` at offset 8, but if that field's
1088 /// initializer is 4-byte aligned then simply translating the tuple as
1089 /// a two-element struct will locate it at offset 4, and accesses to it
1090 /// will read the wrong memory.
1091 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1092                                 st: &layout::Struct,
1093                                 vals: &[ValueRef])
1094                                 -> Vec<ValueRef> {
1095     assert_eq!(vals.len(), st.offsets.len());
1096
1097     if vals.len() == 0 {
1098         return Vec::new();
1099     }
1100
1101     // offset of current value
1102     let mut offset = 0;
1103     let mut cfields = Vec::new();
1104     cfields.reserve(st.offsets.len()*2);
1105
1106     let parts = st.field_index_by_increasing_offset().map(|i| {
1107         (&vals[i], st.offsets[i].bytes())
1108     });
1109     for (&val, target_offset) in parts {
1110         if offset < target_offset {
1111             cfields.push(padding(ccx, target_offset - offset));
1112             offset = target_offset;
1113         }
1114         assert!(!is_undef(val));
1115         cfields.push(val);
1116         offset += machine::llsize_of_alloc(ccx, val_ty(val));
1117     }
1118
1119     if offset < st.stride().bytes() {
1120         cfields.push(padding(ccx, st.stride().bytes() - offset));
1121     }
1122
1123     cfields
1124 }
1125
1126 fn build_const_union<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1127                                un: &layout::Union,
1128                                field_val: ValueRef)
1129                                -> Vec<ValueRef> {
1130     let mut cfields = vec![field_val];
1131
1132     let offset = machine::llsize_of_alloc(ccx, val_ty(field_val));
1133     let size = un.stride().bytes();
1134     if offset != size {
1135         cfields.push(padding(ccx, size - offset));
1136     }
1137
1138     cfields
1139 }
1140
1141 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1142     C_undef(Type::array(&Type::i8(ccx), size))
1143 }