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