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