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