]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/consts.rs
lower blanket unsafe block to actual cases of unsafe and adjust indents
[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 trans::{adt, closure, debuginfo, expr, inline, machine};
27 use trans::base::{self, push_ctxt};
28 use trans::common::*;
29 use trans::declare;
30 use trans::monomorphize;
31 use trans::type_::Type;
32 use trans::type_of;
33 use middle::cast::{CastTy,IntTy};
34 use middle::subst::Substs;
35 use middle::ty::{self, Ty};
36 use util::nodemap::NodeMap;
37
38 use std::iter::repeat;
39 use libc::c_uint;
40 use syntax::{ast, ast_util};
41 use syntax::parse::token;
42 use syntax::ptr::P;
43
44 pub type FnArgMap<'a> = Option<&'a NodeMap<ValueRef>>;
45
46 pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit)
47     -> ValueRef {
48     let _icx = push_ctxt("trans_lit");
49     debug!("const_lit: {:?}", lit);
50     match lit.node {
51         ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
52         ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
53         ast::LitInt(i, ast::SignedIntLit(t, _)) => {
54             C_integral(Type::int_from_ty(cx, t), i, true)
55         }
56         ast::LitInt(u, ast::UnsignedIntLit(t)) => {
57             C_integral(Type::uint_from_ty(cx, t), u, false)
58         }
59         ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
60             let lit_int_ty = cx.tcx().node_id_to_type(e.id);
61             match lit_int_ty.sty {
62                 ty::TyInt(t) => {
63                     C_integral(Type::int_from_ty(cx, t), i as u64, true)
64                 }
65                 ty::TyUint(t) => {
66                     C_integral(Type::uint_from_ty(cx, t), i as u64, false)
67                 }
68                 _ => cx.sess().span_bug(lit.span,
69                         &format!("integer literal has type {:?} (expected int \
70                                  or usize)",
71                                 lit_int_ty))
72             }
73         }
74         ast::LitFloat(ref fs, t) => {
75             C_floating(&fs, Type::float_from_ty(cx, t))
76         }
77         ast::LitFloatUnsuffixed(ref fs) => {
78             let lit_float_ty = cx.tcx().node_id_to_type(e.id);
79             match lit_float_ty.sty {
80                 ty::TyFloat(t) => {
81                     C_floating(&fs, Type::float_from_ty(cx, t))
82                 }
83                 _ => {
84                     cx.sess().span_bug(lit.span,
85                         "floating point literal doesn't have the right type");
86                 }
87             }
88         }
89         ast::LitBool(b) => C_bool(cx, b),
90         ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
91         ast::LitBinary(ref data) => {
92             addr_of(cx, C_bytes(cx, &data[..]), "binary")
93         }
94     }
95 }
96
97 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
98     unsafe {
99         llvm::LLVMConstPointerCast(val, ty.to_ref())
100     }
101 }
102
103 fn addr_of_mut(ccx: &CrateContext,
104                cv: ValueRef,
105                kind: &str)
106                -> ValueRef {
107     unsafe {
108         // FIXME: this totally needs a better name generation scheme, perhaps a simple global
109         // counter? Also most other uses of gensym in trans.
110         let gsym = token::gensym("_");
111         let name = format!("{}{}", kind, gsym.usize());
112         let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
113             ccx.sess().bug(&format!("symbol `{}` is already defined", name));
114         });
115         llvm::LLVMSetInitializer(gv, cv);
116         SetLinkage(gv, InternalLinkage);
117         SetUnnamedAddr(gv, true);
118         gv
119     }
120 }
121
122 pub fn addr_of(ccx: &CrateContext,
123                cv: ValueRef,
124                kind: &str)
125                -> ValueRef {
126     match ccx.const_globals().borrow().get(&cv) {
127         Some(&gv) => return gv,
128         None => {}
129     }
130     let gv = addr_of_mut(ccx, cv, kind);
131     unsafe {
132         llvm::LLVMSetGlobalConstant(gv, True);
133     }
134     ccx.const_globals().borrow_mut().insert(cv, gv);
135     gv
136 }
137
138 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
139     let v = match cx.const_unsized().borrow().get(&v) {
140         Some(&v) => v,
141         None => v
142     };
143     unsafe {
144         llvm::LLVMGetInitializer(v)
145     }
146 }
147
148 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
149                          v: ValueRef,
150                          ty: Ty<'tcx>)
151                          -> (ValueRef, Ty<'tcx>) {
152     match ty.builtin_deref(true) {
153         Some(mt) => {
154             if type_is_sized(cx.tcx(), mt.ty) {
155                 (const_deref_ptr(cx, v), mt.ty)
156             } else {
157                 // Derefing a fat pointer does not change the representation,
158                 // just the type to the unsized contents.
159                 (v, mt.ty)
160             }
161         }
162         None => {
163             cx.sess().bug(&format!("unexpected dereferenceable type {:?}",
164                                    ty))
165         }
166     }
167 }
168
169 fn const_fn_call<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
170                            node: ExprOrMethodCall,
171                            def_id: ast::DefId,
172                            arg_vals: &[ValueRef],
173                            param_substs: &'tcx Substs<'tcx>) -> ValueRef {
174     let fn_like = const_eval::lookup_const_fn_by_id(ccx.tcx(), def_id);
175     let fn_like = fn_like.expect("lookup_const_fn_by_id failed in const_fn_call");
176
177     let args = &fn_like.decl().inputs;
178     assert_eq!(args.len(), arg_vals.len());
179
180     let arg_ids = args.iter().map(|arg| arg.pat.id);
181     let fn_args = arg_ids.zip(arg_vals.iter().cloned()).collect();
182
183     let substs = ccx.tcx().mk_substs(node_id_substs(ccx, node, param_substs));
184     match fn_like.body().expr {
185         Some(ref expr) => {
186             const_expr(ccx, &**expr, substs, Some(&fn_args)).0
187         }
188         None => C_nil(ccx)
189     }
190 }
191
192 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
193                                 def_id: ast::DefId,
194                                 ref_expr: &ast::Expr)
195                                 -> &'tcx ast::Expr {
196     let def_id = inline::maybe_instantiate_inline(ccx, def_id);
197
198     if def_id.krate != ast::LOCAL_CRATE {
199         ccx.sess().span_bug(ref_expr.span,
200                             "cross crate constant could not be inlined");
201     }
202
203     match const_eval::lookup_const_by_id(ccx.tcx(), def_id, Some(ref_expr.id)) {
204         Some(ref expr) => expr,
205         None => {
206             ccx.sess().span_bug(ref_expr.span, "constant item not found")
207         }
208     }
209 }
210
211 fn get_const_val(ccx: &CrateContext,
212                  def_id: ast::DefId,
213                  ref_expr: &ast::Expr) -> ValueRef {
214     let expr = get_const_expr(ccx, def_id, ref_expr);
215     let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
216     get_const_expr_as_global(ccx, expr, check_const::ConstQualif::empty(), empty_substs)
217 }
218
219 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
220                                           expr: &ast::Expr,
221                                           qualif: check_const::ConstQualif,
222                                           param_substs: &'tcx Substs<'tcx>)
223                                           -> ValueRef {
224     debug!("get_const_expr_as_global: {:?}", expr.id);
225     // Special-case constants to cache a common global for all uses.
226     match expr.node {
227         ast::ExprPath(..) => {
228             let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
229             match def {
230                 def::DefConst(def_id) | def::DefAssociatedConst(def_id, _) => {
231                     if !ccx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
232                         debug!("get_const_expr_as_global ({:?}): found const {:?}",
233                                expr.id, def_id);
234                         return get_const_val(ccx, def_id, expr);
235                     }
236                 }
237                 _ => {}
238             }
239         }
240         _ => {}
241     }
242
243     let key = (expr.id, param_substs);
244     match ccx.const_values().borrow().get(&key) {
245         Some(&val) => return val,
246         None => {}
247     }
248     let val = if qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS) {
249         // Avoid autorefs as they would create global instead of stack
250         // references, even when only the latter are correct.
251         let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
252                                                   &ccx.tcx().expr_ty(expr));
253         const_expr_unadjusted(ccx, expr, ty, param_substs, None)
254     } else {
255         const_expr(ccx, expr, param_substs, None).0
256     };
257
258     // boolean SSA values are i1, but they have to be stored in i8 slots,
259     // otherwise some LLVM optimization passes don't work as expected
260     let val = unsafe {
261         if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
262             llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
263         } else {
264             val
265         }
266     };
267
268     let lvalue = addr_of(ccx, val, "const");
269     ccx.const_values().borrow_mut().insert(key, lvalue);
270     lvalue
271 }
272
273 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
274                             e: &ast::Expr,
275                             param_substs: &'tcx Substs<'tcx>,
276                             fn_args: FnArgMap)
277                             -> (ValueRef, Ty<'tcx>) {
278     let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
279                                                &cx.tcx().expr_ty(e));
280     let llconst = const_expr_unadjusted(cx, e, ety, param_substs, fn_args);
281     let mut llconst = llconst;
282     let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
283                                                             &cx.tcx().expr_ty_adjusted(e));
284     let opt_adj = cx.tcx().tables.borrow().adjustments.get(&e.id).cloned();
285     match opt_adj {
286         Some(ty::AdjustReifyFnPointer) => {
287             // FIXME(#19925) once fn item types are
288             // zero-sized, we'll need to do something here
289         }
290         Some(ty::AdjustUnsafeFnPointer) => {
291             // purely a type-level thing
292         }
293         Some(ty::AdjustDerefRef(adj)) => {
294             let mut ty = ety;
295             // Save the last autoderef in case we can avoid it.
296             if adj.autoderefs > 0 {
297                 for _ in 0..adj.autoderefs-1 {
298                     let (dv, dt) = const_deref(cx, llconst, ty);
299                     llconst = dv;
300                     ty = dt;
301                 }
302             }
303
304             if adj.autoref.is_some() {
305                 if adj.autoderefs == 0 {
306                     // Don't copy data to do a deref+ref
307                     // (i.e., skip the last auto-deref).
308                     llconst = addr_of(cx, llconst, "autoref");
309                     ty = cx.tcx().mk_imm_ref(cx.tcx().mk_region(ty::ReStatic), ty);
310                 }
311             } else {
312                 let (dv, dt) = const_deref(cx, llconst, ty);
313                 llconst = dv;
314
315                 // If we derefed a fat pointer then we will have an
316                 // open type here. So we need to update the type with
317                 // the one returned from const_deref.
318                 ety_adjusted = dt;
319             }
320
321             if let Some(target) = adj.unsize {
322                 let target = monomorphize::apply_param_substs(cx.tcx(),
323                                                               param_substs,
324                                                               &target);
325
326                 let pointee_ty = ty.builtin_deref(true)
327                     .expect("consts: unsizing got non-pointer type").ty;
328                 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
329                     // Normally, the source is a thin pointer and we are
330                     // adding extra info to make a fat pointer. The exception
331                     // is when we are upcasting an existing object fat pointer
332                     // to use a different vtable. In that case, we want to
333                     // load out the original data pointer so we can repackage
334                     // it.
335                     (const_get_elt(cx, llconst, &[abi::FAT_PTR_ADDR as u32]),
336                      Some(const_get_elt(cx, llconst, &[abi::FAT_PTR_EXTRA as u32])))
337                 } else {
338                     (llconst, None)
339                 };
340
341                 let unsized_ty = target.builtin_deref(true)
342                     .expect("consts: unsizing got non-pointer target type").ty;
343                 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
344                 let base = ptrcast(base, ptr_ty);
345                 let info = expr::unsized_info(cx, pointee_ty, unsized_ty,
346                                               old_info, param_substs);
347
348                 if old_info.is_none() {
349                     let prev_const = cx.const_unsized().borrow_mut()
350                                        .insert(base, llconst);
351                     assert!(prev_const.is_none() || prev_const == Some(llconst));
352                 }
353                 assert_eq!(abi::FAT_PTR_ADDR, 0);
354                 assert_eq!(abi::FAT_PTR_EXTRA, 1);
355                 llconst = C_struct(cx, &[base, info], false);
356             }
357         }
358         None => {}
359     };
360
361     let llty = type_of::sizing_type_of(cx, ety_adjusted);
362     let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
363     let tsize = machine::llsize_of_alloc(cx, llty);
364     if csize != tsize {
365         cx.sess().abort_if_errors();
366         unsafe {
367             // FIXME these values could use some context
368             llvm::LLVMDumpValue(llconst);
369             llvm::LLVMDumpValue(C_undef(llty));
370         }
371         cx.sess().bug(&format!("const {:?} of type {:?} has size {} instead of {}",
372                          e, ety_adjusted,
373                          csize, tsize));
374     }
375     (llconst, ety_adjusted)
376 }
377
378 fn check_unary_expr_validity(cx: &CrateContext, e: &ast::Expr, t: Ty,
379                              te: ValueRef) {
380     // The only kind of unary expression that we check for validity
381     // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
382     if let ast::ExprUnary(ast::UnNeg, ref inner_e) = e.node {
383
384         // An unfortunate special case: we parse e.g. -128 as a
385         // negation of the literal 128, which means if we're expecting
386         // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
387         // 128 will have already overflowed to -128, and so then the
388         // constant evaluator thinks we're trying to negate -128.
389         //
390         // Catch this up front by looking for ExprLit directly,
391         // and just accepting it.
392         if let ast::ExprLit(_) = inner_e.node { return; }
393
394         let result = match t.sty {
395             ty::TyInt(int_type) => {
396                 let input = match const_to_opt_int(te) {
397                     Some(v) => v,
398                     None => return,
399                 };
400                 const_int_checked_neg(
401                     input, e, Some(const_eval::IntTy::from(cx.tcx(), int_type)))
402             }
403             ty::TyUint(uint_type) => {
404                 let input = match const_to_opt_uint(te) {
405                     Some(v) => v,
406                     None => return,
407                 };
408                 const_uint_checked_neg(
409                     input, e, Some(const_eval::UintTy::from(cx.tcx(), uint_type)))
410             }
411             _ => return,
412         };
413
414         // We do not actually care about a successful result.
415         if let Err(err) = result {
416             cx.tcx().sess.span_err(e.span, &err.description());
417         }
418     }
419 }
420
421 fn check_binary_expr_validity(cx: &CrateContext, e: &ast::Expr, t: Ty,
422                               te1: ValueRef, te2: ValueRef) {
423     let b = if let ast::ExprBinary(b, _, _) = e.node { b } else { return };
424
425     let result = match t.sty {
426         ty::TyInt(int_type) => {
427             let (lhs, rhs) = match (const_to_opt_int(te1),
428                                     const_to_opt_int(te2)) {
429                 (Some(v1), Some(v2)) => (v1, v2),
430                 _ => return,
431             };
432
433             let opt_ety = Some(const_eval::IntTy::from(cx.tcx(), int_type));
434             match b.node {
435                 ast::BiAdd => const_int_checked_add(lhs, rhs, e, opt_ety),
436                 ast::BiSub => const_int_checked_sub(lhs, rhs, e, opt_ety),
437                 ast::BiMul => const_int_checked_mul(lhs, rhs, e, opt_ety),
438                 ast::BiDiv => const_int_checked_div(lhs, rhs, e, opt_ety),
439                 ast::BiRem => const_int_checked_rem(lhs, rhs, e, opt_ety),
440                 ast::BiShl => const_int_checked_shl(lhs, rhs, e, opt_ety),
441                 ast::BiShr => const_int_checked_shr(lhs, rhs, e, opt_ety),
442                 _ => return,
443             }
444         }
445         ty::TyUint(uint_type) => {
446             let (lhs, rhs) = match (const_to_opt_uint(te1),
447                                     const_to_opt_uint(te2)) {
448                 (Some(v1), Some(v2)) => (v1, v2),
449                 _ => return,
450             };
451
452             let opt_ety = Some(const_eval::UintTy::from(cx.tcx(), uint_type));
453             match b.node {
454                 ast::BiAdd => const_uint_checked_add(lhs, rhs, e, opt_ety),
455                 ast::BiSub => const_uint_checked_sub(lhs, rhs, e, opt_ety),
456                 ast::BiMul => const_uint_checked_mul(lhs, rhs, e, opt_ety),
457                 ast::BiDiv => const_uint_checked_div(lhs, rhs, e, opt_ety),
458                 ast::BiRem => const_uint_checked_rem(lhs, rhs, e, opt_ety),
459                 ast::BiShl => const_uint_checked_shl(lhs, rhs, e, opt_ety),
460                 ast::BiShr => const_uint_checked_shr(lhs, rhs, e, opt_ety),
461                 _ => return,
462             }
463         }
464         _ => return,
465     };
466     // We do not actually care about a successful result.
467     if let Err(err) = result {
468         cx.tcx().sess.span_err(e.span, &err.description());
469     }
470 }
471
472 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
473                                    e: &ast::Expr,
474                                    ety: Ty<'tcx>,
475                                    param_substs: &'tcx Substs<'tcx>,
476                                    fn_args: FnArgMap)
477                                    -> ValueRef
478 {
479     debug!("const_expr_unadjusted(e={:?}, ety={:?}, param_substs={:?})",
480            e,
481            ety,
482            param_substs);
483
484     let map_list = |exprs: &[P<ast::Expr>]| -> Vec<ValueRef> {
485         exprs.iter()
486              .map(|e| const_expr(cx, &**e, param_substs, fn_args).0)
487              .collect()
488     };
489     let _icx = push_ctxt("const_expr");
490     match e.node {
491         ast::ExprLit(ref lit) => {
492             const_lit(cx, e, &**lit)
493         },
494         ast::ExprBinary(b, ref e1, ref e2) => {
495             /* Neither type is bottom, and we expect them to be unified
496              * already, so the following is safe. */
497             let (te1, ty) = const_expr(cx, &**e1, param_substs, fn_args);
498             debug!("const_expr_unadjusted: te1={}, ty={:?}",
499                    cx.tn().val_to_string(te1),
500                    ty);
501             let is_simd = ty.is_simd(cx.tcx());
502             let intype = if is_simd {
503                 ty.simd_type(cx.tcx())
504             } else {
505                 ty
506             };
507             let is_float = intype.is_fp();
508             let signed = intype.is_signed();
509
510             let (te2, _) = const_expr(cx, &**e2, param_substs, fn_args);
511
512             check_binary_expr_validity(cx, e, ty, te1, te2);
513
514             unsafe { match b.node {
515                 ast::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
516                 ast::BiAdd             => llvm::LLVMConstAdd(te1, te2),
517
518                 ast::BiSub if is_float => llvm::LLVMConstFSub(te1, te2),
519                 ast::BiSub             => llvm::LLVMConstSub(te1, te2),
520
521                 ast::BiMul if is_float => llvm::LLVMConstFMul(te1, te2),
522                 ast::BiMul             => llvm::LLVMConstMul(te1, te2),
523
524                 ast::BiDiv if is_float => llvm::LLVMConstFDiv(te1, te2),
525                 ast::BiDiv if signed   => llvm::LLVMConstSDiv(te1, te2),
526                 ast::BiDiv             => llvm::LLVMConstUDiv(te1, te2),
527
528                 ast::BiRem if is_float => llvm::LLVMConstFRem(te1, te2),
529                 ast::BiRem if signed   => llvm::LLVMConstSRem(te1, te2),
530                 ast::BiRem             => llvm::LLVMConstURem(te1, te2),
531
532                 ast::BiAnd    => llvm::LLVMConstAnd(te1, te2),
533                 ast::BiOr     => llvm::LLVMConstOr(te1, te2),
534                 ast::BiBitXor => llvm::LLVMConstXor(te1, te2),
535                 ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
536                 ast::BiBitOr  => llvm::LLVMConstOr(te1, te2),
537                 ast::BiShl    => {
538                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
539                     llvm::LLVMConstShl(te1, te2)
540                 },
541                 ast::BiShr    => {
542                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
543                     if signed { llvm::LLVMConstAShr(te1, te2) }
544                     else      { llvm::LLVMConstLShr(te1, te2) }
545                 },
546                 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiLe | ast::BiGt | ast::BiGe => {
547                     if is_float {
548                         let cmp = base::bin_op_to_fcmp_predicate(cx, b.node);
549                         ConstFCmp(cmp, te1, te2)
550                     } else {
551                         let cmp = base::bin_op_to_icmp_predicate(cx, b.node, signed);
552                         let bool_val = ConstICmp(cmp, te1, te2);
553                         if is_simd {
554                             // LLVM outputs an `< size x i1 >`, so we need to perform
555                             // a sign extension to get the correctly sized type.
556                             llvm::LLVMConstIntCast(bool_val, val_ty(te1).to_ref(), True)
557                         } else {
558                             bool_val
559                         }
560                     }
561                 },
562             } } // unsafe { match b.node {
563         },
564         ast::ExprUnary(u, ref inner_e) => {
565             let (te, ty) = const_expr(cx, &**inner_e, param_substs, fn_args);
566
567             check_unary_expr_validity(cx, e, ty, te);
568
569             let is_float = ty.is_fp();
570             unsafe { match u {
571                 ast::UnUniq | ast::UnDeref => const_deref(cx, te, ty).0,
572                 ast::UnNot                 => llvm::LLVMConstNot(te),
573                 ast::UnNeg if is_float     => llvm::LLVMConstFNeg(te),
574                 ast::UnNeg                 => llvm::LLVMConstNeg(te),
575             } }
576         },
577         ast::ExprField(ref base, field) => {
578             let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
579             let brepr = adt::represent_type(cx, bt);
580             expr::with_field_tys(cx.tcx(), bt, None, |discr, field_tys| {
581                 let ix = cx.tcx().field_idx_strict(field.node.name, field_tys);
582                 adt::const_get_field(cx, &*brepr, bv, discr, ix)
583             })
584         },
585         ast::ExprTupField(ref base, idx) => {
586             let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
587             let brepr = adt::represent_type(cx, bt);
588             expr::with_field_tys(cx.tcx(), bt, None, |discr, _| {
589                 adt::const_get_field(cx, &*brepr, bv, discr, idx.node)
590             })
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 const_eval::eval_const_expr_partial(cx.tcx(), &**index, None) {
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::mt{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(cx.tcx(), t_expr).expect("bad input type for cast"),
666                 CastTy::from_ty(cx.tcx(), 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             expr::with_field_tys(cx.tcx(), ety, Some(e.id), |discr, field_tys| {
750                 let cs = field_tys.iter().enumerate()
751                                   .map(|(ix, &field_ty)| {
752                     match (fs.iter().find(|f| field_ty.name == f.ident.node.name), base_val) {
753                         (Some(ref f), _) => const_expr(cx, &*f.expr, param_substs, fn_args).0,
754                         (_, Some((bv, _))) => adt::const_get_field(cx, &*repr, bv, discr, ix),
755                         (_, None) => cx.sess().span_bug(e.span, "missing struct field"),
756                     }
757                 }).collect::<Vec<_>>();
758                 if ety.is_simd(cx.tcx()) {
759                     C_vector(&cs[..])
760                 } else {
761                     adt::trans_const(cx, &*repr, discr, &cs[..])
762                 }
763             })
764         },
765         ast::ExprVec(ref es) => {
766             let unit_ty = ety.sequence_element_type(cx.tcx());
767             let llunitty = type_of::type_of(cx, unit_ty);
768             let vs = es.iter()
769                        .map(|e| const_expr(cx, &**e, param_substs, fn_args).0)
770                        .collect::<Vec<_>>();
771             // If the vector contains enums, an LLVM array won't work.
772             if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
773                 C_struct(cx, &vs[..], false)
774             } else {
775                 C_array(llunitty, &vs[..])
776             }
777         },
778         ast::ExprRepeat(ref elem, ref count) => {
779             let unit_ty = ety.sequence_element_type(cx.tcx());
780             let llunitty = type_of::type_of(cx, unit_ty);
781             let n = cx.tcx().eval_repeat_count(count);
782             let unit_val = const_expr(cx, &**elem, param_substs, fn_args).0;
783             let vs: Vec<_> = repeat(unit_val).take(n).collect();
784             if val_ty(unit_val) != llunitty {
785                 C_struct(cx, &vs[..], false)
786             } else {
787                 C_array(llunitty, &vs[..])
788             }
789         },
790         ast::ExprPath(..) => {
791             let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def();
792             match def {
793                 def::DefLocal(id) => {
794                     if let Some(val) = fn_args.and_then(|args| args.get(&id).cloned()) {
795                         val
796                     } else {
797                         cx.sess().span_bug(e.span, "const fn argument not found")
798                     }
799                 }
800                 def::DefFn(..) | def::DefMethod(..) => {
801                     expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
802                 }
803                 def::DefConst(def_id) | def::DefAssociatedConst(def_id, _) => {
804                     const_deref_ptr(cx, get_const_val(cx, def_id, e))
805                 }
806                 def::DefVariant(enum_did, variant_did, _) => {
807                     let vinfo = cx.tcx().enum_variant_with_id(enum_did, variant_did);
808                     if !vinfo.args.is_empty() {
809                         // N-ary variant.
810                         expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
811                     } else {
812                         // Nullary variant.
813                         let repr = adt::represent_type(cx, ety);
814                         adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
815                     }
816                 }
817                 def::DefStruct(_) => {
818                     if let ty::TyBareFn(..) = ety.sty {
819                         // Tuple struct.
820                         expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
821                     } else {
822                         // Unit struct.
823                         C_null(type_of::type_of(cx, ety))
824                     }
825                 }
826                 _ => {
827                     cx.sess().span_bug(e.span, "expected a const, fn, struct, \
828                                                 or variant def")
829                 }
830             }
831         },
832         ast::ExprCall(ref callee, ref args) => {
833             let mut callee = &**callee;
834             loop {
835                 callee = match callee.node {
836                     ast::ExprParen(ref inner) => &**inner,
837                     ast::ExprBlock(ref block) => match block.expr {
838                         Some(ref tail) => &**tail,
839                         None => break,
840                     },
841                     _ => break,
842                 };
843             }
844             let def = cx.tcx().def_map.borrow()[&callee.id].full_def();
845             let arg_vals = map_list(args);
846             match def {
847                 def::DefFn(did, _) | def::DefMethod(did, _) => {
848                     const_fn_call(cx, ExprId(callee.id), did, &arg_vals, param_substs)
849                 },
850                 def::DefStruct(_) => {
851                     if ety.is_simd(cx.tcx()) {
852                         C_vector(&arg_vals[..])
853                     } else {
854                         let repr = adt::represent_type(cx, ety);
855                         adt::trans_const(cx, &*repr, 0, &arg_vals[..])
856                     }
857                 },
858                 def::DefVariant(enum_did, variant_did, _) => {
859                     let repr = adt::represent_type(cx, ety);
860                     let vinfo = cx.tcx().enum_variant_with_id(enum_did, variant_did);
861                     adt::trans_const(cx,
862                                      &*repr,
863                                      vinfo.disr_val,
864                                      &arg_vals[..])
865                 },
866                 _ => cx.sess().span_bug(e.span, "expected a struct, variant, or const fn def"),
867             }
868         },
869         ast::ExprMethodCall(_, _, ref args) => {
870             let arg_vals = map_list(args);
871             let method_call = ty::MethodCall::expr(e.id);
872               let method_did = cx.tcx().tables.borrow().method_map[&method_call].def_id;
873             const_fn_call(cx, MethodCallKey(method_call),
874                           method_did, &arg_vals, param_substs)
875         },
876         ast::ExprParen(ref e) => const_expr(cx, &**e, param_substs, fn_args).0,
877         ast::ExprBlock(ref block) => {
878             match block.expr {
879                 Some(ref expr) => const_expr(cx, &**expr, param_substs, fn_args).0,
880                 None => C_nil(cx),
881             }
882         },
883         ast::ExprClosure(_, ref decl, ref body) => {
884             closure::trans_closure_expr(closure::Dest::Ignore(cx),
885                                         decl,
886                                         body,
887                                         e.id,
888                                         param_substs);
889             C_null(type_of::type_of(cx, ety))
890         },
891         _ => cx.sess().span_bug(e.span,
892                                 "bad constant expression type in consts::const_expr"),
893     }
894 }
895
896 pub fn trans_static(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) -> ValueRef {
897     unsafe {
898         let _icx = push_ctxt("trans_static");
899         let g = base::get_item_val(ccx, id);
900         // At this point, get_item_val has already translated the
901         // constant's initializer to determine its LLVM type.
902         let v = ccx.static_values().borrow().get(&id).unwrap().clone();
903         // boolean SSA values are i1, but they have to be stored in i8 slots,
904         // otherwise some LLVM optimization passes don't work as expected
905         let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() {
906             llvm::LLVMConstZExt(v, Type::i8(ccx).to_ref())
907         } else {
908             v
909         };
910         llvm::LLVMSetInitializer(g, v);
911
912         // As an optimization, all shared statics which do not have interior
913         // mutability are placed into read-only memory.
914         if m != ast::MutMutable {
915             let node_ty = ccx.tcx().node_id_to_type(id);
916             let tcontents = node_ty.type_contents(ccx.tcx());
917             if !tcontents.interior_unsafe() {
918                 llvm::LLVMSetGlobalConstant(g, True);
919             }
920         }
921         debuginfo::create_global_var_metadata(ccx, id, g);
922         g
923     }
924 }
925
926 fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
927                             ty: Ty<'tcx>) -> ValueRef {
928     if ast_util::is_local(did) { return base::get_item_val(ccx, did.node) }
929     base::trans_external_path(ccx, did, ty)
930 }