]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/consts.rs
Merge VariantData and VariantData_
[rust.git] / src / librustc_trans / trans / consts.rs
1 // Copyright 2012 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
12 use back::abi;
13 use llvm;
14 use llvm::{ConstFCmp, ConstICmp, SetLinkage, SetUnnamedAddr};
15 use llvm::{InternalLinkage, ValueRef, Bool, True};
16 use metadata::cstore::LOCAL_CRATE;
17 use middle::{check_const, def};
18 use middle::const_eval::{self, ConstVal};
19 use middle::const_eval::{const_int_checked_neg, const_uint_checked_neg};
20 use middle::const_eval::{const_int_checked_add, const_uint_checked_add};
21 use middle::const_eval::{const_int_checked_sub, const_uint_checked_sub};
22 use middle::const_eval::{const_int_checked_mul, const_uint_checked_mul};
23 use middle::const_eval::{const_int_checked_div, const_uint_checked_div};
24 use middle::const_eval::{const_int_checked_rem, const_uint_checked_rem};
25 use middle::const_eval::{const_int_checked_shl, const_uint_checked_shl};
26 use middle::const_eval::{const_int_checked_shr, const_uint_checked_shr};
27 use middle::const_eval::EvalHint::ExprTypeChecked;
28 use middle::const_eval::eval_const_expr_partial;
29 use middle::def_id::DefId;
30 use trans::{adt, closure, debuginfo, expr, inline, machine};
31 use trans::base::{self, push_ctxt};
32 use trans::common::*;
33 use trans::declare;
34 use trans::monomorphize;
35 use trans::type_::Type;
36 use trans::type_of;
37 use middle::subst::Substs;
38 use middle::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
39 use middle::ty::adjustment::AdjustUnsafeFnPointer;
40 use middle::ty::{self, Ty};
41 use middle::ty::cast::{CastTy,IntTy};
42 use util::nodemap::NodeMap;
43
44 use rustc_front::hir;
45
46 use std::ffi::{CStr, CString};
47 use libc::c_uint;
48 use syntax::ast;
49 use syntax::attr;
50 use syntax::parse::token;
51 use syntax::ptr::P;
52
53 pub type FnArgMap<'a> = Option<&'a NodeMap<ValueRef>>;
54
55 pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &ast::Lit)
56     -> ValueRef {
57     let _icx = push_ctxt("trans_lit");
58     debug!("const_lit: {:?}", lit);
59     match lit.node {
60         ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
61         ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
62         ast::LitInt(i, ast::SignedIntLit(t, _)) => {
63             C_integral(Type::int_from_ty(cx, t), i, true)
64         }
65         ast::LitInt(u, ast::UnsignedIntLit(t)) => {
66             C_integral(Type::uint_from_ty(cx, t), u, false)
67         }
68         ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
69             let lit_int_ty = cx.tcx().node_id_to_type(e.id);
70             match lit_int_ty.sty {
71                 ty::TyInt(t) => {
72                     C_integral(Type::int_from_ty(cx, t), i as u64, true)
73                 }
74                 ty::TyUint(t) => {
75                     C_integral(Type::uint_from_ty(cx, t), i as u64, false)
76                 }
77                 _ => cx.sess().span_bug(lit.span,
78                         &format!("integer literal has type {:?} (expected int \
79                                  or usize)",
80                                 lit_int_ty))
81             }
82         }
83         ast::LitFloat(ref fs, t) => {
84             C_floating(&fs, Type::float_from_ty(cx, t))
85         }
86         ast::LitFloatUnsuffixed(ref fs) => {
87             let lit_float_ty = cx.tcx().node_id_to_type(e.id);
88             match lit_float_ty.sty {
89                 ty::TyFloat(t) => {
90                     C_floating(&fs, Type::float_from_ty(cx, t))
91                 }
92                 _ => {
93                     cx.sess().span_bug(lit.span,
94                         "floating point literal doesn't have the right type");
95                 }
96             }
97         }
98         ast::LitBool(b) => C_bool(cx, b),
99         ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
100         ast::LitByteStr(ref data) => {
101             addr_of(cx, C_bytes(cx, &data[..]), 1, "byte_str")
102         }
103     }
104 }
105
106 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
107     unsafe {
108         llvm::LLVMConstPointerCast(val, ty.to_ref())
109     }
110 }
111
112 fn addr_of_mut(ccx: &CrateContext,
113                cv: ValueRef,
114                align: machine::llalign,
115                kind: &str)
116                -> ValueRef {
117     unsafe {
118         // FIXME: this totally needs a better name generation scheme, perhaps a simple global
119         // counter? Also most other uses of gensym in trans.
120         let gsym = token::gensym("_");
121         let name = format!("{}{}", kind, gsym.0);
122         let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
123             ccx.sess().bug(&format!("symbol `{}` is already defined", name));
124         });
125         llvm::LLVMSetInitializer(gv, cv);
126         llvm::LLVMSetAlignment(gv, align);
127         SetLinkage(gv, InternalLinkage);
128         SetUnnamedAddr(gv, true);
129         gv
130     }
131 }
132
133 pub fn addr_of(ccx: &CrateContext,
134                cv: ValueRef,
135                align: machine::llalign,
136                kind: &str)
137                -> ValueRef {
138     match ccx.const_globals().borrow().get(&cv) {
139         Some(&gv) => {
140             unsafe {
141                 // Upgrade the alignment in cases where the same constant is used with different
142                 // alignment requirements
143                 if align > llvm::LLVMGetAlignment(gv) {
144                     llvm::LLVMSetAlignment(gv, align);
145                 }
146             }
147             return gv;
148         }
149         None => {}
150     }
151     let gv = addr_of_mut(ccx, cv, align, kind);
152     unsafe {
153         llvm::LLVMSetGlobalConstant(gv, True);
154     }
155     ccx.const_globals().borrow_mut().insert(cv, gv);
156     gv
157 }
158
159 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
160     let v = match cx.const_unsized().borrow().get(&v) {
161         Some(&v) => v,
162         None => v
163     };
164     unsafe {
165         llvm::LLVMGetInitializer(v)
166     }
167 }
168
169 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
170                          v: ValueRef,
171                          ty: Ty<'tcx>)
172                          -> (ValueRef, Ty<'tcx>) {
173     match ty.builtin_deref(true, ty::NoPreference) {
174         Some(mt) => {
175             if type_is_sized(cx.tcx(), mt.ty) {
176                 (const_deref_ptr(cx, v), mt.ty)
177             } else {
178                 // Derefing a fat pointer does not change the representation,
179                 // just the type to the unsized contents.
180                 (v, mt.ty)
181             }
182         }
183         None => {
184             cx.sess().bug(&format!("unexpected dereferenceable type {:?}",
185                                    ty))
186         }
187     }
188 }
189
190 fn const_fn_call<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
191                            node: ExprOrMethodCall,
192                            def_id: DefId,
193                            arg_vals: &[ValueRef],
194                            param_substs: &'tcx Substs<'tcx>) -> ValueRef {
195     let fn_like = const_eval::lookup_const_fn_by_id(ccx.tcx(), def_id);
196     let fn_like = fn_like.expect("lookup_const_fn_by_id failed in const_fn_call");
197
198     let args = &fn_like.decl().inputs;
199     assert_eq!(args.len(), arg_vals.len());
200
201     let arg_ids = args.iter().map(|arg| arg.pat.id);
202     let fn_args = arg_ids.zip(arg_vals.iter().cloned()).collect();
203
204     let substs = ccx.tcx().mk_substs(node_id_substs(ccx, node, param_substs));
205     match fn_like.body().expr {
206         Some(ref expr) => {
207             const_expr(ccx, &**expr, substs, Some(&fn_args)).0
208         }
209         None => C_nil(ccx)
210     }
211 }
212
213 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
214                                 def_id: DefId,
215                                 ref_expr: &hir::Expr)
216                                 -> &'tcx hir::Expr {
217     let def_id = inline::maybe_instantiate_inline(ccx, def_id);
218
219     if def_id.krate != LOCAL_CRATE {
220         ccx.sess().span_bug(ref_expr.span,
221                             "cross crate constant could not be inlined");
222     }
223
224     match const_eval::lookup_const_by_id(ccx.tcx(), def_id, Some(ref_expr.id)) {
225         Some(ref expr) => expr,
226         None => {
227             ccx.sess().span_bug(ref_expr.span, "constant item not found")
228         }
229     }
230 }
231
232 fn get_const_val(ccx: &CrateContext,
233                  def_id: DefId,
234                  ref_expr: &hir::Expr) -> ValueRef {
235     let expr = get_const_expr(ccx, def_id, ref_expr);
236     let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
237     get_const_expr_as_global(ccx, expr, check_const::ConstQualif::empty(), empty_substs)
238 }
239
240 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
241                                           expr: &hir::Expr,
242                                           qualif: check_const::ConstQualif,
243                                           param_substs: &'tcx Substs<'tcx>)
244                                           -> ValueRef {
245     debug!("get_const_expr_as_global: {:?}", expr.id);
246     // Special-case constants to cache a common global for all uses.
247     match expr.node {
248         hir::ExprPath(..) => {
249             let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
250             match def {
251                 def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
252                     if !ccx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
253                         debug!("get_const_expr_as_global ({:?}): found const {:?}",
254                                expr.id, def_id);
255                         return get_const_val(ccx, def_id, expr);
256                     }
257                 }
258                 _ => {}
259             }
260         }
261         _ => {}
262     }
263
264     let key = (expr.id, param_substs);
265     match ccx.const_values().borrow().get(&key) {
266         Some(&val) => return val,
267         None => {}
268     }
269     let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
270                                               &ccx.tcx().expr_ty(expr));
271     let val = if qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS) {
272         // Avoid autorefs as they would create global instead of stack
273         // references, even when only the latter are correct.
274         const_expr_unadjusted(ccx, expr, ty, param_substs, None)
275     } else {
276         const_expr(ccx, expr, param_substs, None).0
277     };
278
279     // boolean SSA values are i1, but they have to be stored in i8 slots,
280     // otherwise some LLVM optimization passes don't work as expected
281     let val = unsafe {
282         if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
283             llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
284         } else {
285             val
286         }
287     };
288
289     let lvalue = addr_of(ccx, val, type_of::align_of(ccx, ty), "const");
290     ccx.const_values().borrow_mut().insert(key, lvalue);
291     lvalue
292 }
293
294 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
295                             e: &hir::Expr,
296                             param_substs: &'tcx Substs<'tcx>,
297                             fn_args: FnArgMap)
298                             -> (ValueRef, Ty<'tcx>) {
299     let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
300                                                &cx.tcx().expr_ty(e));
301     let llconst = const_expr_unadjusted(cx, e, ety, param_substs, fn_args);
302     let mut llconst = llconst;
303     let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
304                                                             &cx.tcx().expr_ty_adjusted(e));
305     let opt_adj = cx.tcx().tables.borrow().adjustments.get(&e.id).cloned();
306     match opt_adj {
307         Some(AdjustReifyFnPointer) => {
308             // FIXME(#19925) once fn item types are
309             // zero-sized, we'll need to do something here
310         }
311         Some(AdjustUnsafeFnPointer) => {
312             // purely a type-level thing
313         }
314         Some(AdjustDerefRef(adj)) => {
315             let mut ty = ety;
316             // Save the last autoderef in case we can avoid it.
317             if adj.autoderefs > 0 {
318                 for _ in 0..adj.autoderefs-1 {
319                     let (dv, dt) = const_deref(cx, llconst, ty);
320                     llconst = dv;
321                     ty = dt;
322                 }
323             }
324
325             if adj.autoref.is_some() {
326                 if adj.autoderefs == 0 {
327                     // Don't copy data to do a deref+ref
328                     // (i.e., skip the last auto-deref).
329                     llconst = addr_of(cx, llconst, type_of::align_of(cx, ty), "autoref");
330                     ty = cx.tcx().mk_imm_ref(cx.tcx().mk_region(ty::ReStatic), ty);
331                 }
332             } else {
333                 let (dv, dt) = const_deref(cx, llconst, ty);
334                 llconst = dv;
335
336                 // If we derefed a fat pointer then we will have an
337                 // open type here. So we need to update the type with
338                 // the one returned from const_deref.
339                 ety_adjusted = dt;
340             }
341
342             if let Some(target) = adj.unsize {
343                 let target = monomorphize::apply_param_substs(cx.tcx(),
344                                                               param_substs,
345                                                               &target);
346
347                 let pointee_ty = ty.builtin_deref(true, ty::NoPreference)
348                     .expect("consts: unsizing got non-pointer type").ty;
349                 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
350                     // Normally, the source is a thin pointer and we are
351                     // adding extra info to make a fat pointer. The exception
352                     // is when we are upcasting an existing object fat pointer
353                     // to use a different vtable. In that case, we want to
354                     // load out the original data pointer so we can repackage
355                     // it.
356                     (const_get_elt(cx, llconst, &[abi::FAT_PTR_ADDR as u32]),
357                      Some(const_get_elt(cx, llconst, &[abi::FAT_PTR_EXTRA as u32])))
358                 } else {
359                     (llconst, None)
360                 };
361
362                 let unsized_ty = target.builtin_deref(true, ty::NoPreference)
363                     .expect("consts: unsizing got non-pointer target type").ty;
364                 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
365                 let base = ptrcast(base, ptr_ty);
366                 let info = expr::unsized_info(cx, pointee_ty, unsized_ty,
367                                               old_info, param_substs);
368
369                 if old_info.is_none() {
370                     let prev_const = cx.const_unsized().borrow_mut()
371                                        .insert(base, llconst);
372                     assert!(prev_const.is_none() || prev_const == Some(llconst));
373                 }
374                 assert_eq!(abi::FAT_PTR_ADDR, 0);
375                 assert_eq!(abi::FAT_PTR_EXTRA, 1);
376                 llconst = C_struct(cx, &[base, info], false);
377             }
378         }
379         None => {}
380     };
381
382     let llty = type_of::sizing_type_of(cx, ety_adjusted);
383     let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
384     let tsize = machine::llsize_of_alloc(cx, llty);
385     if csize != tsize {
386         cx.sess().abort_if_errors();
387         unsafe {
388             // FIXME these values could use some context
389             llvm::LLVMDumpValue(llconst);
390             llvm::LLVMDumpValue(C_undef(llty));
391         }
392         cx.sess().bug(&format!("const {:?} of type {:?} has size {} instead of {}",
393                          e, ety_adjusted,
394                          csize, tsize));
395     }
396     (llconst, ety_adjusted)
397 }
398
399 fn check_unary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
400                              te: ValueRef) {
401     // The only kind of unary expression that we check for validity
402     // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
403     if let hir::ExprUnary(hir::UnNeg, ref inner_e) = e.node {
404
405         // An unfortunate special case: we parse e.g. -128 as a
406         // negation of the literal 128, which means if we're expecting
407         // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
408         // 128 will have already overflowed to -128, and so then the
409         // constant evaluator thinks we're trying to negate -128.
410         //
411         // Catch this up front by looking for ExprLit directly,
412         // and just accepting it.
413         if let hir::ExprLit(_) = inner_e.node { return; }
414
415         let result = match t.sty {
416             ty::TyInt(int_type) => {
417                 let input = match const_to_opt_int(te) {
418                     Some(v) => v,
419                     None => return,
420                 };
421                 const_int_checked_neg(
422                     input, e, Some(const_eval::IntTy::from(cx.tcx(), int_type)))
423             }
424             ty::TyUint(uint_type) => {
425                 let input = match const_to_opt_uint(te) {
426                     Some(v) => v,
427                     None => return,
428                 };
429                 const_uint_checked_neg(
430                     input, e, Some(const_eval::UintTy::from(cx.tcx(), uint_type)))
431             }
432             _ => return,
433         };
434
435         // We do not actually care about a successful result.
436         if let Err(err) = result {
437             cx.tcx().sess.span_err(e.span, &err.description());
438         }
439     }
440 }
441
442 fn check_binary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
443                               te1: ValueRef, te2: ValueRef) {
444     let b = if let hir::ExprBinary(b, _, _) = e.node { b } else { return };
445
446     let result = match t.sty {
447         ty::TyInt(int_type) => {
448             let (lhs, rhs) = match (const_to_opt_int(te1),
449                                     const_to_opt_int(te2)) {
450                 (Some(v1), Some(v2)) => (v1, v2),
451                 _ => return,
452             };
453
454             let opt_ety = Some(const_eval::IntTy::from(cx.tcx(), int_type));
455             match b.node {
456                 hir::BiAdd => const_int_checked_add(lhs, rhs, e, opt_ety),
457                 hir::BiSub => const_int_checked_sub(lhs, rhs, e, opt_ety),
458                 hir::BiMul => const_int_checked_mul(lhs, rhs, e, opt_ety),
459                 hir::BiDiv => const_int_checked_div(lhs, rhs, e, opt_ety),
460                 hir::BiRem => const_int_checked_rem(lhs, rhs, e, opt_ety),
461                 hir::BiShl => const_int_checked_shl(lhs, rhs, e, opt_ety),
462                 hir::BiShr => const_int_checked_shr(lhs, rhs, e, opt_ety),
463                 _ => return,
464             }
465         }
466         ty::TyUint(uint_type) => {
467             let (lhs, rhs) = match (const_to_opt_uint(te1),
468                                     const_to_opt_uint(te2)) {
469                 (Some(v1), Some(v2)) => (v1, v2),
470                 _ => return,
471             };
472
473             let opt_ety = Some(const_eval::UintTy::from(cx.tcx(), uint_type));
474             match b.node {
475                 hir::BiAdd => const_uint_checked_add(lhs, rhs, e, opt_ety),
476                 hir::BiSub => const_uint_checked_sub(lhs, rhs, e, opt_ety),
477                 hir::BiMul => const_uint_checked_mul(lhs, rhs, e, opt_ety),
478                 hir::BiDiv => const_uint_checked_div(lhs, rhs, e, opt_ety),
479                 hir::BiRem => const_uint_checked_rem(lhs, rhs, e, opt_ety),
480                 hir::BiShl => const_uint_checked_shl(lhs, rhs, e, opt_ety),
481                 hir::BiShr => const_uint_checked_shr(lhs, rhs, e, opt_ety),
482                 _ => return,
483             }
484         }
485         _ => return,
486     };
487     // We do not actually care about a successful result.
488     if let Err(err) = result {
489         cx.tcx().sess.span_err(e.span, &err.description());
490     }
491 }
492
493 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
494                                    e: &hir::Expr,
495                                    ety: Ty<'tcx>,
496                                    param_substs: &'tcx Substs<'tcx>,
497                                    fn_args: FnArgMap)
498                                    -> ValueRef
499 {
500     debug!("const_expr_unadjusted(e={:?}, ety={:?}, param_substs={:?})",
501            e,
502            ety,
503            param_substs);
504
505     let map_list = |exprs: &[P<hir::Expr>]| -> Vec<ValueRef> {
506         exprs.iter()
507              .map(|e| const_expr(cx, &**e, param_substs, fn_args).0)
508              .collect()
509     };
510     let _icx = push_ctxt("const_expr");
511     match e.node {
512         hir::ExprLit(ref lit) => {
513             const_lit(cx, e, &**lit)
514         },
515         hir::ExprBinary(b, ref e1, ref e2) => {
516             /* Neither type is bottom, and we expect them to be unified
517              * already, so the following is safe. */
518             let (te1, ty) = const_expr(cx, &**e1, param_substs, fn_args);
519             debug!("const_expr_unadjusted: te1={}, ty={:?}",
520                    cx.tn().val_to_string(te1),
521                    ty);
522             assert!(!ty.is_simd());
523             let is_float = ty.is_fp();
524             let signed = ty.is_signed();
525
526             let (te2, _) = const_expr(cx, &**e2, param_substs, fn_args);
527
528             check_binary_expr_validity(cx, e, ty, te1, te2);
529
530             unsafe { match b.node {
531                 hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
532                 hir::BiAdd             => llvm::LLVMConstAdd(te1, te2),
533
534                 hir::BiSub if is_float => llvm::LLVMConstFSub(te1, te2),
535                 hir::BiSub             => llvm::LLVMConstSub(te1, te2),
536
537                 hir::BiMul if is_float => llvm::LLVMConstFMul(te1, te2),
538                 hir::BiMul             => llvm::LLVMConstMul(te1, te2),
539
540                 hir::BiDiv if is_float => llvm::LLVMConstFDiv(te1, te2),
541                 hir::BiDiv if signed   => llvm::LLVMConstSDiv(te1, te2),
542                 hir::BiDiv             => llvm::LLVMConstUDiv(te1, te2),
543
544                 hir::BiRem if is_float => llvm::LLVMConstFRem(te1, te2),
545                 hir::BiRem if signed   => llvm::LLVMConstSRem(te1, te2),
546                 hir::BiRem             => llvm::LLVMConstURem(te1, te2),
547
548                 hir::BiAnd    => llvm::LLVMConstAnd(te1, te2),
549                 hir::BiOr     => llvm::LLVMConstOr(te1, te2),
550                 hir::BiBitXor => llvm::LLVMConstXor(te1, te2),
551                 hir::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
552                 hir::BiBitOr  => llvm::LLVMConstOr(te1, te2),
553                 hir::BiShl    => {
554                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
555                     llvm::LLVMConstShl(te1, te2)
556                 },
557                 hir::BiShr    => {
558                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
559                     if signed { llvm::LLVMConstAShr(te1, te2) }
560                     else      { llvm::LLVMConstLShr(te1, te2) }
561                 },
562                 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe => {
563                     if is_float {
564                         let cmp = base::bin_op_to_fcmp_predicate(cx, b.node);
565                         ConstFCmp(cmp, te1, te2)
566                     } else {
567                         let cmp = base::bin_op_to_icmp_predicate(cx, b.node, signed);
568                         ConstICmp(cmp, te1, te2)
569                     }
570                 },
571             } } // unsafe { match b.node {
572         },
573         hir::ExprUnary(u, ref inner_e) => {
574             let (te, ty) = const_expr(cx, &**inner_e, param_substs, fn_args);
575
576             check_unary_expr_validity(cx, e, ty, te);
577
578             let is_float = ty.is_fp();
579             unsafe { match u {
580                 hir::UnDeref           => const_deref(cx, te, ty).0,
581                 hir::UnNot             => llvm::LLVMConstNot(te),
582                 hir::UnNeg if is_float => llvm::LLVMConstFNeg(te),
583                 hir::UnNeg             => llvm::LLVMConstNeg(te),
584             } }
585         },
586         hir::ExprField(ref base, field) => {
587             let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
588             let brepr = adt::represent_type(cx, bt);
589             let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
590             let ix = vinfo.field_index(field.node);
591             adt::const_get_field(cx, &*brepr, bv, vinfo.discr, ix)
592         },
593         hir::ExprTupField(ref base, idx) => {
594             let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
595             let brepr = adt::represent_type(cx, bt);
596             let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
597             adt::const_get_field(cx, &*brepr, bv, vinfo.discr, idx.node)
598         },
599
600         hir::ExprIndex(ref base, ref index) => {
601             let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
602             let iv = match eval_const_expr_partial(cx.tcx(), &index, ExprTypeChecked) {
603                 Ok(ConstVal::Int(i)) => i as u64,
604                 Ok(ConstVal::Uint(u)) => u,
605                 _ => cx.sess().span_bug(index.span,
606                                         "index is not an integer-constant expression")
607             };
608             let (arr, len) = match bt.sty {
609                 ty::TyArray(_, u) => (bv, C_uint(cx, u)),
610                 ty::TySlice(_) | ty::TyStr => {
611                     let e1 = const_get_elt(cx, bv, &[0]);
612                     (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
613                 },
614                 ty::TyRef(_, mt) => match mt.ty.sty {
615                     ty::TyArray(_, u) => {
616                         (const_deref_ptr(cx, bv), C_uint(cx, u))
617                     },
618                     _ => cx.sess().span_bug(base.span,
619                                             &format!("index-expr base must be a vector \
620                                                       or string type, found {:?}",
621                                                      bt)),
622                 },
623                 _ => cx.sess().span_bug(base.span,
624                                         &format!("index-expr base must be a vector \
625                                                   or string type, found {:?}",
626                                                  bt)),
627             };
628
629             let len = unsafe { llvm::LLVMConstIntGetZExtValue(len) as u64 };
630             let len = match bt.sty {
631                 ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => match ty.sty {
632                     ty::TyStr => {
633                         assert!(len > 0);
634                         len - 1
635                     },
636                     _ => len,
637                 },
638                 _ => len,
639             };
640             if iv >= len {
641                 // FIXME #3170: report this earlier on in the const-eval
642                 // pass. Reporting here is a bit late.
643                 span_err!(cx.sess(), e.span, E0515,
644                           "const index-expr is out of bounds");
645                 C_undef(val_ty(arr).element_type())
646             } else {
647                 const_get_elt(cx, arr, &[iv as c_uint])
648             }
649         },
650         hir::ExprCast(ref base, _) => {
651             let t_cast = ety;
652             let llty = type_of::type_of(cx, t_cast);
653             let (v, t_expr) = const_expr(cx, &**base, param_substs, fn_args);
654             debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
655             if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
656                 return v;
657             }
658             if type_is_fat_ptr(cx.tcx(), t_expr) {
659                 // Fat pointer casts.
660                 let t_cast_inner =
661                     t_cast.builtin_deref(true, ty::NoPreference).expect("cast to non-pointer").ty;
662                 let ptr_ty = type_of::in_memory_type_of(cx, t_cast_inner).ptr_to();
663                 let addr = ptrcast(const_get_elt(cx, v, &[abi::FAT_PTR_ADDR as u32]),
664                                    ptr_ty);
665                 if type_is_fat_ptr(cx.tcx(), t_cast) {
666                     let info = const_get_elt(cx, v, &[abi::FAT_PTR_EXTRA as u32]);
667                     return C_struct(cx, &[addr, info], false)
668                 } else {
669                     return addr;
670                 }
671             }
672             unsafe { match (
673                 CastTy::from_ty(t_expr).expect("bad input type for cast"),
674                 CastTy::from_ty(t_cast).expect("bad output type for cast"),
675             ) {
676                 (CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
677                     let repr = adt::represent_type(cx, t_expr);
678                     let discr = adt::const_get_discrim(cx, &*repr, v);
679                     let iv = C_integral(cx.int_type(), discr, false);
680                     let s = adt::is_discr_signed(&*repr) as Bool;
681                     llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
682                 },
683                 (CastTy::Int(_), CastTy::Int(_)) => {
684                     let s = t_expr.is_signed() as Bool;
685                     llvm::LLVMConstIntCast(v, llty.to_ref(), s)
686                 },
687                 (CastTy::Int(_), CastTy::Float) => {
688                     if t_expr.is_signed() {
689                         llvm::LLVMConstSIToFP(v, llty.to_ref())
690                     } else {
691                         llvm::LLVMConstUIToFP(v, llty.to_ref())
692                     }
693                 },
694                 (CastTy::Float, CastTy::Float) => llvm::LLVMConstFPCast(v, llty.to_ref()),
695                 (CastTy::Float, CastTy::Int(IntTy::I)) => llvm::LLVMConstFPToSI(v, llty.to_ref()),
696                 (CastTy::Float, CastTy::Int(_)) => llvm::LLVMConstFPToUI(v, llty.to_ref()),
697                 (CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FnPtr, CastTy::Ptr(_))
698                 | (CastTy::RPtr(_), CastTy::Ptr(_)) => {
699                     ptrcast(v, llty)
700                 },
701                 (CastTy::FnPtr, CastTy::FnPtr) => ptrcast(v, llty), // isn't this a coercion?
702                 (CastTy::Int(_), CastTy::Ptr(_)) => llvm::LLVMConstIntToPtr(v, llty.to_ref()),
703                 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
704                   llvm::LLVMConstPtrToInt(v, llty.to_ref())
705                 },
706                 _ => {
707                   cx.sess().impossible_case(e.span,
708                                             "bad combination of types for cast")
709                 },
710             } } // unsafe { match ( ... ) {
711         },
712         hir::ExprAddrOf(hir::MutImmutable, ref sub) => {
713             // If this is the address of some static, then we need to return
714             // the actual address of the static itself (short circuit the rest
715             // of const eval).
716             let mut cur = sub;
717             loop {
718                 match cur.node {
719                     hir::ExprBlock(ref blk) => {
720                         if let Some(ref sub) = blk.expr {
721                             cur = sub;
722                         } else {
723                             break;
724                         }
725                     },
726                     _ => break,
727                 }
728             }
729             let opt_def = cx.tcx().def_map.borrow().get(&cur.id).map(|d| d.full_def());
730             if let Some(def::DefStatic(def_id, _)) = opt_def {
731                 get_static_val(cx, def_id, ety)
732             } else {
733                 // If this isn't the address of a static, then keep going through
734                 // normal constant evaluation.
735                 let (v, ty) = const_expr(cx, &**sub, param_substs, fn_args);
736                 addr_of(cx, v, type_of::align_of(cx, ty), "ref")
737             }
738         },
739         hir::ExprAddrOf(hir::MutMutable, ref sub) => {
740             let (v, ty) = const_expr(cx, &**sub, param_substs, fn_args);
741             addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
742         },
743         hir::ExprTup(ref es) => {
744             let repr = adt::represent_type(cx, ety);
745             let vals = map_list(&es[..]);
746             adt::trans_const(cx, &*repr, 0, &vals[..])
747         },
748         hir::ExprStruct(_, ref fs, ref base_opt) => {
749             let repr = adt::represent_type(cx, ety);
750
751             let base_val = match *base_opt {
752                 Some(ref base) => Some(const_expr(cx, &**base, param_substs, fn_args)),
753                 None => None
754             };
755
756             let VariantInfo { discr, fields } = VariantInfo::of_node(cx.tcx(), ety, e.id);
757             let cs = fields.iter().enumerate().map(|(ix, &Field(f_name, _))| {
758                 match (fs.iter().find(|f| f_name == f.name.node), base_val) {
759                     (Some(ref f), _) => const_expr(cx, &*f.expr, param_substs, fn_args).0,
760                     (_, Some((bv, _))) => adt::const_get_field(cx, &*repr, bv, discr, ix),
761                     (_, None) => cx.sess().span_bug(e.span, "missing struct field"),
762                 }
763             }).collect::<Vec<_>>();
764             if ety.is_simd() {
765                 C_vector(&cs[..])
766             } else {
767                 adt::trans_const(cx, &*repr, discr, &cs[..])
768             }
769         },
770         hir::ExprVec(ref es) => {
771             let unit_ty = ety.sequence_element_type(cx.tcx());
772             let llunitty = type_of::type_of(cx, unit_ty);
773             let vs = es.iter()
774                        .map(|e| const_expr(cx, &**e, param_substs, fn_args).0)
775                        .collect::<Vec<_>>();
776             // If the vector contains enums, an LLVM array won't work.
777             if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
778                 C_struct(cx, &vs[..], false)
779             } else {
780                 C_array(llunitty, &vs[..])
781             }
782         },
783         hir::ExprRepeat(ref elem, ref count) => {
784             let unit_ty = ety.sequence_element_type(cx.tcx());
785             let llunitty = type_of::type_of(cx, unit_ty);
786             let n = cx.tcx().eval_repeat_count(count);
787             let unit_val = const_expr(cx, &**elem, param_substs, fn_args).0;
788             let vs = vec![unit_val; n];
789             if val_ty(unit_val) != llunitty {
790                 C_struct(cx, &vs[..], false)
791             } else {
792                 C_array(llunitty, &vs[..])
793             }
794         },
795         hir::ExprPath(..) => {
796             let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def();
797             match def {
798                 def::DefLocal(_, id) => {
799                     if let Some(val) = fn_args.and_then(|args| args.get(&id).cloned()) {
800                         val
801                     } else {
802                         cx.sess().span_bug(e.span, "const fn argument not found")
803                     }
804                 }
805                 def::DefFn(..) | def::DefMethod(..) => {
806                     expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
807                 }
808                 def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
809                     const_deref_ptr(cx, get_const_val(cx, def_id, e))
810                 }
811                 def::DefVariant(enum_did, variant_did, _) => {
812                     let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
813                     match vinfo.kind() {
814                         ty::VariantKind::Unit => {
815                             let repr = adt::represent_type(cx, ety);
816                             adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
817                         }
818                         ty::VariantKind::Tuple => {
819                             expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
820                         }
821                         ty::VariantKind::Struct => {
822                             cx.sess().span_bug(e.span, "path-expr refers to a dict variant!")
823                         }
824                     }
825                 }
826                 def::DefStruct(_) => {
827                     if let ty::TyBareFn(..) = ety.sty {
828                         // Tuple struct.
829                         expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
830                     } else {
831                         // Unit struct.
832                         C_null(type_of::type_of(cx, ety))
833                     }
834                 }
835                 _ => {
836                     cx.sess().span_bug(e.span, "expected a const, fn, struct, \
837                                                 or variant def")
838                 }
839             }
840         },
841         hir::ExprCall(ref callee, ref args) => {
842             let mut callee = &**callee;
843             loop {
844                 callee = match callee.node {
845                     hir::ExprBlock(ref block) => match block.expr {
846                         Some(ref tail) => &**tail,
847                         None => break,
848                     },
849                     _ => break,
850                 };
851             }
852             let def = cx.tcx().def_map.borrow()[&callee.id].full_def();
853             let arg_vals = map_list(args);
854             match def {
855                 def::DefFn(did, _) | def::DefMethod(did) => {
856                     const_fn_call(cx, ExprId(callee.id), did, &arg_vals, param_substs)
857                 }
858                 def::DefStruct(_) => {
859                     if ety.is_simd() {
860                         C_vector(&arg_vals[..])
861                     } else {
862                         let repr = adt::represent_type(cx, ety);
863                         adt::trans_const(cx, &*repr, 0, &arg_vals[..])
864                     }
865                 }
866                 def::DefVariant(enum_did, variant_did, _) => {
867                     let repr = adt::represent_type(cx, ety);
868                     let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
869                     adt::trans_const(cx,
870                                      &*repr,
871                                      vinfo.disr_val,
872                                      &arg_vals[..])
873                 }
874                 _ => cx.sess().span_bug(e.span, "expected a struct, variant, or const fn def"),
875             }
876         },
877         hir::ExprMethodCall(_, _, ref args) => {
878             let arg_vals = map_list(args);
879             let method_call = ty::MethodCall::expr(e.id);
880             let method_did = cx.tcx().tables.borrow().method_map[&method_call].def_id;
881             const_fn_call(cx, MethodCallKey(method_call),
882                           method_did, &arg_vals, param_substs)
883         },
884         hir::ExprBlock(ref block) => {
885             match block.expr {
886                 Some(ref expr) => const_expr(cx, &**expr, param_substs, fn_args).0,
887                 None => C_nil(cx),
888             }
889         },
890         hir::ExprClosure(_, ref decl, ref body) => {
891             match ety.sty {
892                 ty::TyClosure(def_id, ref substs) => {
893                     closure::trans_closure_expr(closure::Dest::Ignore(cx), decl,
894                                                 body, e.id, def_id, substs);
895                 }
896                 _ =>
897                     cx.sess().span_bug(
898                         e.span,
899                         &format!("bad type for closure expr: {:?}", ety))
900             }
901             C_null(type_of::type_of(cx, ety))
902         },
903         _ => cx.sess().span_bug(e.span,
904                                 "bad constant expression type in consts::const_expr"),
905     }
906 }
907 pub fn trans_static(ccx: &CrateContext,
908                     m: hir::Mutability,
909                     expr: &hir::Expr,
910                     id: ast::NodeId,
911                     attrs: &Vec<ast::Attribute>)
912                     -> ValueRef {
913     unsafe {
914         let _icx = push_ctxt("trans_static");
915         let g = base::get_item_val(ccx, id);
916
917         let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
918         let (v, _) = const_expr(ccx, expr, empty_substs, None);
919
920         // boolean SSA values are i1, but they have to be stored in i8 slots,
921         // otherwise some LLVM optimization passes don't work as expected
922         let mut val_llty = llvm::LLVMTypeOf(v);
923         let v = if val_llty == Type::i1(ccx).to_ref() {
924             val_llty = Type::i8(ccx).to_ref();
925             llvm::LLVMConstZExt(v, val_llty)
926         } else {
927             v
928         };
929
930         let ty = ccx.tcx().node_id_to_type(id);
931         let llty = type_of::type_of(ccx, ty);
932         let g = if val_llty == llty.to_ref() {
933             g
934         } else {
935             // If we created the global with the wrong type,
936             // correct the type.
937             let empty_string = CString::new("").unwrap();
938             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
939             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
940             llvm::LLVMSetValueName(g, empty_string.as_ptr());
941             let new_g = llvm::LLVMGetOrInsertGlobal(
942                 ccx.llmod(), name_string.as_ptr(), val_llty);
943             // To avoid breaking any invariants, we leave around the old
944             // global for the moment; we'll replace all references to it
945             // with the new global later. (See base::trans_crate.)
946             ccx.statics_to_rauw().borrow_mut().push((g, new_g));
947             new_g
948         };
949         llvm::LLVMSetAlignment(g, type_of::align_of(ccx, ty));
950         llvm::LLVMSetInitializer(g, v);
951
952         // As an optimization, all shared statics which do not have interior
953         // mutability are placed into read-only memory.
954         if m != hir::MutMutable {
955             let tcontents = ty.type_contents(ccx.tcx());
956             if !tcontents.interior_unsafe() {
957                 llvm::LLVMSetGlobalConstant(g, llvm::True);
958             }
959         }
960
961         debuginfo::create_global_var_metadata(ccx, id, g);
962
963         if attr::contains_name(attrs,
964                                "thread_local") {
965             llvm::set_thread_local(g, true);
966         }
967         g
968     }
969 }
970
971
972 fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
973                             did: DefId,
974                             ty: Ty<'tcx>)
975                             -> ValueRef {
976     if let Some(node_id) = ccx.tcx().map.as_local_node_id(did) {
977         base::get_item_val(ccx, node_id)
978     } else {
979         base::trans_external_path(ccx, did, ty)
980     }
981 }