]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/consts.rs
3f18c61fbd26caada391283588bcc08ebfb6ae20
[rust.git] / src / librustc_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 llvm;
13 use llvm::{ConstFCmp, ConstICmp, SetLinkage, SetUnnamedAddr};
14 use llvm::{InternalLinkage, ValueRef, Bool, True};
15 use middle::const_qualif::ConstQualif;
16 use rustc_const_eval::{ConstEvalErr, lookup_const_fn_by_id, lookup_const_by_id, ErrKind};
17 use rustc_const_eval::eval_repeat_count;
18 use rustc::hir::def::Def;
19 use rustc::hir::def_id::DefId;
20 use rustc::hir::map as hir_map;
21 use {abi, adt, closure, debuginfo, expr, machine};
22 use base::{self, push_ctxt};
23 use callee::Callee;
24 use collector;
25 use trans_item::TransItem;
26 use common::{type_is_sized, C_nil, const_get_elt};
27 use common::{CrateContext, C_integral, C_floating, C_bool, C_str_slice, C_bytes, val_ty};
28 use common::{C_struct, C_undef, const_to_opt_int, const_to_opt_uint, VariantInfo, C_uint};
29 use common::{type_is_fat_ptr, Field, C_vector, C_array, C_null};
30 use datum::{Datum, Lvalue};
31 use declare;
32 use monomorphize::{self, Instance};
33 use type_::Type;
34 use type_of;
35 use value::Value;
36 use Disr;
37 use rustc::ty::subst::Substs;
38 use rustc::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
39 use rustc::ty::adjustment::{AdjustUnsafeFnPointer, AdjustMutToConstPointer};
40 use rustc::ty::{self, Ty, TyCtxt};
41 use rustc::ty::cast::{CastTy,IntTy};
42 use util::nodemap::NodeMap;
43 use rustc_const_math::{ConstInt, ConstUsize, ConstIsize};
44
45 use rustc::hir;
46
47 use std::ffi::{CStr, CString};
48 use std::borrow::Cow;
49 use libc::c_uint;
50 use syntax::ast::{self, LitKind};
51 use syntax::attr::{self, AttrMetaMethods};
52 use syntax::parse::token;
53 use syntax::ptr::P;
54 use syntax_pos::Span;
55
56 pub type FnArgMap<'a> = Option<&'a NodeMap<ValueRef>>;
57
58 pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &ast::Lit)
59     -> ValueRef {
60     let _icx = push_ctxt("trans_lit");
61     debug!("const_lit: {:?}", lit);
62     match lit.node {
63         LitKind::Byte(b) => C_integral(Type::uint_from_ty(cx, ast::UintTy::U8), b as u64, false),
64         LitKind::Char(i) => C_integral(Type::char(cx), i as u64, false),
65         LitKind::Int(i, ast::LitIntType::Signed(t)) => {
66             C_integral(Type::int_from_ty(cx, t), i, true)
67         }
68         LitKind::Int(u, ast::LitIntType::Unsigned(t)) => {
69             C_integral(Type::uint_from_ty(cx, t), u, false)
70         }
71         LitKind::Int(i, ast::LitIntType::Unsuffixed) => {
72             let lit_int_ty = cx.tcx().node_id_to_type(e.id);
73             match lit_int_ty.sty {
74                 ty::TyInt(t) => {
75                     C_integral(Type::int_from_ty(cx, t), i as u64, true)
76                 }
77                 ty::TyUint(t) => {
78                     C_integral(Type::uint_from_ty(cx, t), i as u64, false)
79                 }
80                 _ => span_bug!(lit.span,
81                         "integer literal has type {:?} (expected int \
82                          or usize)",
83                         lit_int_ty)
84             }
85         }
86         LitKind::Float(ref fs, t) => {
87             C_floating(&fs, Type::float_from_ty(cx, t))
88         }
89         LitKind::FloatUnsuffixed(ref fs) => {
90             let lit_float_ty = cx.tcx().node_id_to_type(e.id);
91             match lit_float_ty.sty {
92                 ty::TyFloat(t) => {
93                     C_floating(&fs, Type::float_from_ty(cx, t))
94                 }
95                 _ => {
96                     span_bug!(lit.span,
97                         "floating point literal doesn't have the right type");
98                 }
99             }
100         }
101         LitKind::Bool(b) => C_bool(cx, b),
102         LitKind::Str(ref s, _) => C_str_slice(cx, (*s).clone()),
103         LitKind::ByteStr(ref data) => {
104             addr_of(cx, C_bytes(cx, &data[..]), 1, "byte_str")
105         }
106     }
107 }
108
109 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
110     unsafe {
111         llvm::LLVMConstPointerCast(val, ty.to_ref())
112     }
113 }
114
115 pub fn addr_of_mut(ccx: &CrateContext,
116                    cv: ValueRef,
117                    align: machine::llalign,
118                    kind: &str)
119                     -> ValueRef {
120     unsafe {
121         // FIXME: this totally needs a better name generation scheme, perhaps a simple global
122         // counter? Also most other uses of gensym in trans.
123         let gsym = token::gensym("_");
124         let name = format!("{}{}", kind, gsym.0);
125         let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
126             bug!("symbol `{}` is already defined", name);
127         });
128         llvm::LLVMSetInitializer(gv, cv);
129         llvm::LLVMSetAlignment(gv, align);
130         SetLinkage(gv, InternalLinkage);
131         SetUnnamedAddr(gv, true);
132         gv
133     }
134 }
135
136 pub fn addr_of(ccx: &CrateContext,
137                cv: ValueRef,
138                align: machine::llalign,
139                kind: &str)
140                -> ValueRef {
141     if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
142         unsafe {
143             // Upgrade the alignment in cases where the same constant is used with different
144             // alignment requirements
145             if align > llvm::LLVMGetAlignment(gv) {
146                 llvm::LLVMSetAlignment(gv, align);
147             }
148         }
149         return gv;
150     }
151     let gv = addr_of_mut(ccx, cv, align, kind);
152     unsafe {
153         llvm::LLVMSetGlobalConstant(gv, True);
154     }
155     ccx.const_globals().borrow_mut().insert(cv, gv);
156     gv
157 }
158
159 /// Deref a constant pointer
160 pub fn load_const(cx: &CrateContext, v: ValueRef, t: Ty) -> ValueRef {
161     let v = match cx.const_unsized().borrow().get(&v) {
162         Some(&v) => v,
163         None => v
164     };
165     let d = unsafe { llvm::LLVMGetInitializer(v) };
166     if !d.is_null() && t.is_bool() {
167         unsafe { llvm::LLVMConstTrunc(d, Type::i1(cx).to_ref()) }
168     } else {
169         d
170     }
171 }
172
173 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
174                          v: ValueRef,
175                          ty: Ty<'tcx>)
176                          -> (ValueRef, Ty<'tcx>) {
177     match ty.builtin_deref(true, ty::NoPreference) {
178         Some(mt) => {
179             if type_is_sized(cx.tcx(), mt.ty) {
180                 (load_const(cx, v, mt.ty), mt.ty)
181             } else {
182                 // Derefing a fat pointer does not change the representation,
183                 // just the type to the unsized contents.
184                 (v, mt.ty)
185             }
186         }
187         None => {
188             bug!("unexpected dereferenceable type {:?}", ty)
189         }
190     }
191 }
192
193 fn const_fn_call<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
194                            def_id: DefId,
195                            substs: &'tcx Substs<'tcx>,
196                            arg_vals: &[ValueRef],
197                            param_substs: &'tcx Substs<'tcx>,
198                            trueconst: TrueConst) -> Result<ValueRef, ConstEvalFailure> {
199     let fn_like = lookup_const_fn_by_id(ccx.tcx(), def_id);
200     let fn_like = fn_like.expect("lookup_const_fn_by_id failed in const_fn_call");
201
202     let body = match fn_like.body().expr {
203         Some(ref expr) => expr,
204         None => return Ok(C_nil(ccx))
205     };
206
207     let args = &fn_like.decl().inputs;
208     assert_eq!(args.len(), arg_vals.len());
209
210     let arg_ids = args.iter().map(|arg| arg.pat.id);
211     let fn_args = arg_ids.zip(arg_vals.iter().cloned()).collect();
212
213     let substs = ccx.tcx().mk_substs(substs.clone().erase_regions());
214     let substs = monomorphize::apply_param_substs(ccx.tcx(),
215                                                   param_substs,
216                                                   &substs);
217
218     const_expr(ccx, body, substs, Some(&fn_args), trueconst).map(|(res, _)| res)
219 }
220
221 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
222                                 def_id: DefId,
223                                 ref_expr: &hir::Expr,
224                                 param_substs: &'tcx Substs<'tcx>)
225                                 -> &'tcx hir::Expr {
226     let substs = ccx.tcx().node_id_item_substs(ref_expr.id).substs;
227     let substs = ccx.tcx().mk_substs(substs.clone().erase_regions());
228     let substs = monomorphize::apply_param_substs(ccx.tcx(),
229                                                   param_substs,
230                                                   &substs);
231     match lookup_const_by_id(ccx.tcx(), def_id, Some(substs)) {
232         Some((ref expr, _ty)) => expr,
233         None => {
234             span_bug!(ref_expr.span, "constant item not found")
235         }
236     }
237 }
238
239 pub enum ConstEvalFailure {
240     /// in case the const evaluator failed on something that panic at runtime
241     /// as defined in RFC 1229
242     Runtime(ConstEvalErr),
243     // in case we found a true constant
244     Compiletime(ConstEvalErr),
245 }
246
247 impl ConstEvalFailure {
248     fn into_inner(self) -> ConstEvalErr {
249         match self {
250             Runtime(e) => e,
251             Compiletime(e) => e,
252         }
253     }
254     pub fn description(&self) -> Cow<str> {
255         match self {
256             &Runtime(ref e) => e.description(),
257             &Compiletime(ref e) => e.description(),
258         }
259     }
260 }
261
262 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
263 pub enum TrueConst {
264     Yes, No
265 }
266
267 use self::ConstEvalFailure::*;
268
269 fn get_const_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
270                            def_id: DefId,
271                            ref_expr: &hir::Expr,
272                            param_substs: &'tcx Substs<'tcx>)
273                            -> Result<ValueRef, ConstEvalFailure> {
274     let expr = get_const_expr(ccx, def_id, ref_expr, param_substs);
275     let empty_substs = ccx.tcx().mk_substs(Substs::empty());
276     match get_const_expr_as_global(ccx, expr, ConstQualif::empty(), empty_substs, TrueConst::Yes) {
277         Err(Runtime(err)) => {
278             ccx.tcx().sess.span_err(expr.span, &err.description());
279             Err(Compiletime(err))
280         },
281         other => other,
282     }
283 }
284
285 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
286                                           expr: &hir::Expr,
287                                           qualif: ConstQualif,
288                                           param_substs: &'tcx Substs<'tcx>,
289                                           trueconst: TrueConst)
290                                           -> Result<ValueRef, ConstEvalFailure> {
291     debug!("get_const_expr_as_global: {:?}", expr.id);
292     // Special-case constants to cache a common global for all uses.
293     if let hir::ExprPath(..) = expr.node {
294         // `def` must be its own statement and cannot be in the `match`
295         // otherwise the `def_map` will be borrowed for the entire match instead
296         // of just to get the `def` value
297         match ccx.tcx().expect_def(expr.id) {
298             Def::Const(def_id) | Def::AssociatedConst(def_id) => {
299                 if !ccx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
300                     debug!("get_const_expr_as_global ({:?}): found const {:?}",
301                            expr.id, def_id);
302                     return get_const_val(ccx, def_id, expr, param_substs);
303                 }
304             },
305             _ => {},
306         }
307     }
308
309     let key = (expr.id, param_substs);
310     if let Some(&val) = ccx.const_values().borrow().get(&key) {
311         return Ok(val);
312     }
313     let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
314                                               &ccx.tcx().expr_ty(expr));
315     let val = if qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
316         // Avoid autorefs as they would create global instead of stack
317         // references, even when only the latter are correct.
318         const_expr_unadjusted(ccx, expr, ty, param_substs, None, trueconst)?
319     } else {
320         const_expr(ccx, expr, param_substs, None, trueconst)?.0
321     };
322
323     // boolean SSA values are i1, but they have to be stored in i8 slots,
324     // otherwise some LLVM optimization passes don't work as expected
325     let val = unsafe {
326         if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
327             llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
328         } else {
329             val
330         }
331     };
332
333     let lvalue = addr_of(ccx, val, type_of::align_of(ccx, ty), "const");
334     ccx.const_values().borrow_mut().insert(key, lvalue);
335     Ok(lvalue)
336 }
337
338 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
339                             e: &hir::Expr,
340                             param_substs: &'tcx Substs<'tcx>,
341                             fn_args: FnArgMap,
342                             trueconst: TrueConst)
343                             -> Result<(ValueRef, Ty<'tcx>), ConstEvalFailure> {
344     let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
345                                                &cx.tcx().expr_ty(e));
346     let llconst = const_expr_unadjusted(cx, e, ety, param_substs, fn_args, trueconst)?;
347     let mut llconst = llconst;
348     let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
349                                                             &cx.tcx().expr_ty_adjusted(e));
350     let opt_adj = cx.tcx().tables.borrow().adjustments.get(&e.id).cloned();
351     match opt_adj {
352         Some(AdjustReifyFnPointer) => {
353             match ety.sty {
354                 ty::TyFnDef(def_id, substs, _) => {
355                     llconst = Callee::def(cx, def_id, substs).reify(cx).val;
356                 }
357                 _ => {
358                     bug!("{} cannot be reified to a fn ptr", ety)
359                 }
360             }
361         }
362         Some(AdjustUnsafeFnPointer) | Some(AdjustMutToConstPointer) => {
363             // purely a type-level thing
364         }
365         Some(AdjustDerefRef(adj)) => {
366             let mut ty = ety;
367             // Save the last autoderef in case we can avoid it.
368             if adj.autoderefs > 0 {
369                 for _ in 0..adj.autoderefs-1 {
370                     let (dv, dt) = const_deref(cx, llconst, ty);
371                     llconst = dv;
372                     ty = dt;
373                 }
374             }
375
376             if adj.autoref.is_some() {
377                 if adj.autoderefs == 0 {
378                     // Don't copy data to do a deref+ref
379                     // (i.e., skip the last auto-deref).
380                     llconst = addr_of(cx, llconst, type_of::align_of(cx, ty), "autoref");
381                     ty = cx.tcx().mk_imm_ref(cx.tcx().mk_region(ty::ReErased), ty);
382                 }
383             } else if adj.autoderefs > 0 {
384                 let (dv, dt) = const_deref(cx, llconst, ty);
385                 llconst = dv;
386
387                 // If we derefed a fat pointer then we will have an
388                 // open type here. So we need to update the type with
389                 // the one returned from const_deref.
390                 ety_adjusted = dt;
391             }
392
393             if let Some(target) = adj.unsize {
394                 let target = monomorphize::apply_param_substs(cx.tcx(),
395                                                               param_substs,
396                                                               &target);
397
398                 let pointee_ty = ty.builtin_deref(true, ty::NoPreference)
399                     .expect("consts: unsizing got non-pointer type").ty;
400                 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
401                     // Normally, the source is a thin pointer and we are
402                     // adding extra info to make a fat pointer. The exception
403                     // is when we are upcasting an existing object fat pointer
404                     // to use a different vtable. In that case, we want to
405                     // load out the original data pointer so we can repackage
406                     // it.
407                     (const_get_elt(llconst, &[abi::FAT_PTR_ADDR as u32]),
408                      Some(const_get_elt(llconst, &[abi::FAT_PTR_EXTRA as u32])))
409                 } else {
410                     (llconst, None)
411                 };
412
413                 let unsized_ty = target.builtin_deref(true, ty::NoPreference)
414                     .expect("consts: unsizing got non-pointer target type").ty;
415                 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
416                 let base = ptrcast(base, ptr_ty);
417                 let info = base::unsized_info(cx, pointee_ty, unsized_ty, old_info);
418
419                 if old_info.is_none() {
420                     let prev_const = cx.const_unsized().borrow_mut()
421                                        .insert(base, llconst);
422                     assert!(prev_const.is_none() || prev_const == Some(llconst));
423                 }
424                 assert_eq!(abi::FAT_PTR_ADDR, 0);
425                 assert_eq!(abi::FAT_PTR_EXTRA, 1);
426                 llconst = C_struct(cx, &[base, info], false);
427             }
428         }
429         None => {}
430     };
431
432     let llty = type_of::sizing_type_of(cx, ety_adjusted);
433     let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
434     let tsize = machine::llsize_of_alloc(cx, llty);
435     if csize != tsize {
436         cx.sess().abort_if_errors();
437         unsafe {
438             // FIXME these values could use some context
439             llvm::LLVMDumpValue(llconst);
440             llvm::LLVMDumpValue(C_undef(llty));
441         }
442         bug!("const {:?} of type {:?} has size {} instead of {}",
443              e, ety_adjusted,
444              csize, tsize);
445     }
446     Ok((llconst, ety_adjusted))
447 }
448
449 fn check_unary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
450                              te: ValueRef, trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
451     // The only kind of unary expression that we check for validity
452     // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
453     if let hir::ExprUnary(hir::UnNeg, ref inner_e) = e.node {
454
455         // An unfortunate special case: we parse e.g. -128 as a
456         // negation of the literal 128, which means if we're expecting
457         // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
458         // 128 will have already overflowed to -128, and so then the
459         // constant evaluator thinks we're trying to negate -128.
460         //
461         // Catch this up front by looking for ExprLit directly,
462         // and just accepting it.
463         if let hir::ExprLit(_) = inner_e.node { return Ok(()); }
464         let cval = match to_const_int(te, t, cx.tcx()) {
465             Some(v) => v,
466             None => return Ok(()),
467         };
468         const_err(cx, e.span, (-cval).map_err(ErrKind::Math), trueconst)?;
469     }
470     Ok(())
471 }
472
473 pub fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
474     match t.sty {
475         ty::TyInt(int_type) => const_to_opt_int(value).and_then(|input| match int_type {
476             ast::IntTy::I8 => {
477                 assert_eq!(input as i8 as i64, input);
478                 Some(ConstInt::I8(input as i8))
479             },
480             ast::IntTy::I16 => {
481                 assert_eq!(input as i16 as i64, input);
482                 Some(ConstInt::I16(input as i16))
483             },
484             ast::IntTy::I32 => {
485                 assert_eq!(input as i32 as i64, input);
486                 Some(ConstInt::I32(input as i32))
487             },
488             ast::IntTy::I64 => {
489                 Some(ConstInt::I64(input))
490             },
491             ast::IntTy::Is => {
492                 ConstIsize::new(input, tcx.sess.target.int_type)
493                     .ok().map(ConstInt::Isize)
494             },
495         }),
496         ty::TyUint(uint_type) => const_to_opt_uint(value).and_then(|input| match uint_type {
497             ast::UintTy::U8 => {
498                 assert_eq!(input as u8 as u64, input);
499                 Some(ConstInt::U8(input as u8))
500             },
501             ast::UintTy::U16 => {
502                 assert_eq!(input as u16 as u64, input);
503                 Some(ConstInt::U16(input as u16))
504             },
505             ast::UintTy::U32 => {
506                 assert_eq!(input as u32 as u64, input);
507                 Some(ConstInt::U32(input as u32))
508             },
509             ast::UintTy::U64 => {
510                 Some(ConstInt::U64(input))
511             },
512             ast::UintTy::Us => {
513                 ConstUsize::new(input, tcx.sess.target.uint_type)
514                     .ok().map(ConstInt::Usize)
515             },
516         }),
517         _ => None,
518     }
519 }
520
521 pub fn const_err<T>(cx: &CrateContext,
522                     span: Span,
523                     result: Result<T, ErrKind>,
524                     trueconst: TrueConst)
525                     -> Result<T, ConstEvalFailure> {
526     match (result, trueconst) {
527         (Ok(x), _) => Ok(x),
528         (Err(err), TrueConst::Yes) => {
529             let err = ConstEvalErr{ span: span, kind: err };
530             cx.tcx().sess.span_err(span, &err.description());
531             Err(Compiletime(err))
532         },
533         (Err(err), TrueConst::No) => {
534             let err = ConstEvalErr{ span: span, kind: err };
535             cx.tcx().sess.span_warn(span, &err.description());
536             Err(Runtime(err))
537         },
538     }
539 }
540
541 fn check_binary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
542                               te1: ValueRef, te2: ValueRef,
543                               trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
544     let b = if let hir::ExprBinary(b, _, _) = e.node { b } else { bug!() };
545     let (lhs, rhs) = match (to_const_int(te1, t, cx.tcx()), to_const_int(te2, t, cx.tcx())) {
546         (Some(v1), Some(v2)) => (v1, v2),
547         _ => return Ok(()),
548     };
549     let result = match b.node {
550         hir::BiAdd => lhs + rhs,
551         hir::BiSub => lhs - rhs,
552         hir::BiMul => lhs * rhs,
553         hir::BiDiv => lhs / rhs,
554         hir::BiRem => lhs % rhs,
555         hir::BiShl => lhs << rhs,
556         hir::BiShr => lhs >> rhs,
557         _ => return Ok(()),
558     };
559     const_err(cx, e.span, result.map_err(ErrKind::Math), trueconst)?;
560     Ok(())
561 }
562
563 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
564                                    e: &hir::Expr,
565                                    ety: Ty<'tcx>,
566                                    param_substs: &'tcx Substs<'tcx>,
567                                    fn_args: FnArgMap,
568                                    trueconst: TrueConst)
569                                    -> Result<ValueRef, ConstEvalFailure>
570 {
571     debug!("const_expr_unadjusted(e={:?}, ety={:?}, param_substs={:?})",
572            e,
573            ety,
574            param_substs);
575
576     let map_list = |exprs: &[P<hir::Expr>]| -> Result<Vec<ValueRef>, ConstEvalFailure> {
577         exprs.iter()
578              .map(|e| const_expr(cx, &e, param_substs, fn_args, trueconst).map(|(l, _)| l))
579              .collect::<Vec<Result<ValueRef, ConstEvalFailure>>>()
580              .into_iter()
581              .collect()
582          // this dance is necessary to eagerly run const_expr so all errors are reported
583     };
584     let _icx = push_ctxt("const_expr");
585     Ok(match e.node {
586         hir::ExprLit(ref lit) => const_lit(cx, e, &lit),
587         hir::ExprBinary(b, ref e1, ref e2) => {
588             /* Neither type is bottom, and we expect them to be unified
589              * already, so the following is safe. */
590             let (te1, ty) = const_expr(cx, &e1, param_substs, fn_args, trueconst)?;
591             debug!("const_expr_unadjusted: te1={:?}, ty={:?}",
592                    Value(te1), ty);
593             assert!(!ty.is_simd());
594             let is_float = ty.is_fp();
595             let signed = ty.is_signed();
596
597             let (te2, ty2) = const_expr(cx, &e2, param_substs, fn_args, trueconst)?;
598             debug!("const_expr_unadjusted: te2={:?}, ty={:?}",
599                    Value(te2), ty2);
600
601             check_binary_expr_validity(cx, e, ty, te1, te2, trueconst)?;
602
603             unsafe { match b.node {
604                 hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
605                 hir::BiAdd             => llvm::LLVMConstAdd(te1, te2),
606
607                 hir::BiSub if is_float => llvm::LLVMConstFSub(te1, te2),
608                 hir::BiSub             => llvm::LLVMConstSub(te1, te2),
609
610                 hir::BiMul if is_float => llvm::LLVMConstFMul(te1, te2),
611                 hir::BiMul             => llvm::LLVMConstMul(te1, te2),
612
613                 hir::BiDiv if is_float => llvm::LLVMConstFDiv(te1, te2),
614                 hir::BiDiv if signed   => llvm::LLVMConstSDiv(te1, te2),
615                 hir::BiDiv             => llvm::LLVMConstUDiv(te1, te2),
616
617                 hir::BiRem if is_float => llvm::LLVMConstFRem(te1, te2),
618                 hir::BiRem if signed   => llvm::LLVMConstSRem(te1, te2),
619                 hir::BiRem             => llvm::LLVMConstURem(te1, te2),
620
621                 hir::BiAnd    => llvm::LLVMConstAnd(te1, te2),
622                 hir::BiOr     => llvm::LLVMConstOr(te1, te2),
623                 hir::BiBitXor => llvm::LLVMConstXor(te1, te2),
624                 hir::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
625                 hir::BiBitOr  => llvm::LLVMConstOr(te1, te2),
626                 hir::BiShl    => {
627                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
628                     llvm::LLVMConstShl(te1, te2)
629                 },
630                 hir::BiShr    => {
631                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
632                     if signed { llvm::LLVMConstAShr(te1, te2) }
633                     else      { llvm::LLVMConstLShr(te1, te2) }
634                 },
635                 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe => {
636                     if is_float {
637                         let cmp = base::bin_op_to_fcmp_predicate(b.node);
638                         ConstFCmp(cmp, te1, te2)
639                     } else {
640                         let cmp = base::bin_op_to_icmp_predicate(b.node, signed);
641                         ConstICmp(cmp, te1, te2)
642                     }
643                 },
644             } } // unsafe { match b.node {
645         },
646         hir::ExprUnary(u, ref inner_e) => {
647             let (te, ty) = const_expr(cx, &inner_e, param_substs, fn_args, trueconst)?;
648
649             check_unary_expr_validity(cx, e, ty, te, trueconst)?;
650
651             let is_float = ty.is_fp();
652             unsafe { match u {
653                 hir::UnDeref           => const_deref(cx, te, ty).0,
654                 hir::UnNot             => llvm::LLVMConstNot(te),
655                 hir::UnNeg if is_float => llvm::LLVMConstFNeg(te),
656                 hir::UnNeg             => llvm::LLVMConstNeg(te),
657             } }
658         },
659         hir::ExprField(ref base, field) => {
660             let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
661             let brepr = adt::represent_type(cx, bt);
662             let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
663             let ix = vinfo.field_index(field.node);
664             adt::const_get_field(&brepr, bv, vinfo.discr, ix)
665         },
666         hir::ExprTupField(ref base, idx) => {
667             let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
668             let brepr = adt::represent_type(cx, bt);
669             let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
670             adt::const_get_field(&brepr, bv, vinfo.discr, idx.node)
671         },
672         hir::ExprIndex(ref base, ref index) => {
673             let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
674             let iv = const_expr(cx, &index, param_substs, fn_args, TrueConst::Yes)?.0;
675             let iv = if let Some(iv) = const_to_opt_uint(iv) {
676                 iv
677             } else {
678                 span_bug!(index.span, "index is not an integer-constant expression");
679             };
680             let (arr, len) = match bt.sty {
681                 ty::TyArray(_, u) => (bv, C_uint(cx, u)),
682                 ty::TySlice(..) | ty::TyStr => {
683                     let e1 = const_get_elt(bv, &[0]);
684                     (load_const(cx, e1, bt), const_get_elt(bv, &[1]))
685                 },
686                 ty::TyRef(_, mt) => match mt.ty.sty {
687                     ty::TyArray(_, u) => {
688                         (load_const(cx, bv, mt.ty), C_uint(cx, u))
689                     },
690                     _ => span_bug!(base.span,
691                                    "index-expr base must be a vector \
692                                     or string type, found {:?}",
693                                    bt),
694                 },
695                 _ => span_bug!(base.span,
696                                "index-expr base must be a vector \
697                                 or string type, found {:?}",
698                                bt),
699             };
700
701             let len = unsafe { llvm::LLVMConstIntGetZExtValue(len) as u64 };
702             let len = match bt.sty {
703                 ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => match ty.sty {
704                     ty::TyStr => {
705                         assert!(len > 0);
706                         len - 1
707                     },
708                     _ => len,
709                 },
710                 _ => len,
711             };
712             if iv >= len {
713                 // FIXME #3170: report this earlier on in the const-eval
714                 // pass. Reporting here is a bit late.
715                 const_err(cx, e.span, Err(ErrKind::IndexOutOfBounds {
716                     len: len,
717                     index: iv
718                 }), trueconst)?;
719                 C_undef(val_ty(arr).element_type())
720             } else {
721                 const_get_elt(arr, &[iv as c_uint])
722             }
723         },
724         hir::ExprCast(ref base, _) => {
725             let t_cast = ety;
726             let llty = type_of::type_of(cx, t_cast);
727             let (v, t_expr) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
728             debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
729             if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
730                 return Ok(v);
731             }
732             if type_is_fat_ptr(cx.tcx(), t_expr) {
733                 // Fat pointer casts.
734                 let t_cast_inner =
735                     t_cast.builtin_deref(true, ty::NoPreference).expect("cast to non-pointer").ty;
736                 let ptr_ty = type_of::in_memory_type_of(cx, t_cast_inner).ptr_to();
737                 let addr = ptrcast(const_get_elt(v, &[abi::FAT_PTR_ADDR as u32]),
738                                    ptr_ty);
739                 if type_is_fat_ptr(cx.tcx(), t_cast) {
740                     let info = const_get_elt(v, &[abi::FAT_PTR_EXTRA as u32]);
741                     return Ok(C_struct(cx, &[addr, info], false))
742                 } else {
743                     return Ok(addr);
744                 }
745             }
746             unsafe { match (
747                 CastTy::from_ty(t_expr).expect("bad input type for cast"),
748                 CastTy::from_ty(t_cast).expect("bad output type for cast"),
749             ) {
750                 (CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
751                     let repr = adt::represent_type(cx, t_expr);
752                     let discr = adt::const_get_discrim(&repr, v);
753                     let iv = C_integral(cx.int_type(), discr.0, false);
754                     let s = adt::is_discr_signed(&repr) as Bool;
755                     llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
756                 },
757                 (CastTy::Int(_), CastTy::Int(_)) => {
758                     let s = t_expr.is_signed() as Bool;
759                     llvm::LLVMConstIntCast(v, llty.to_ref(), s)
760                 },
761                 (CastTy::Int(_), CastTy::Float) => {
762                     if t_expr.is_signed() {
763                         llvm::LLVMConstSIToFP(v, llty.to_ref())
764                     } else {
765                         llvm::LLVMConstUIToFP(v, llty.to_ref())
766                     }
767                 },
768                 (CastTy::Float, CastTy::Float) => llvm::LLVMConstFPCast(v, llty.to_ref()),
769                 (CastTy::Float, CastTy::Int(IntTy::I)) => llvm::LLVMConstFPToSI(v, llty.to_ref()),
770                 (CastTy::Float, CastTy::Int(_)) => llvm::LLVMConstFPToUI(v, llty.to_ref()),
771                 (CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FnPtr, CastTy::Ptr(_))
772                 | (CastTy::RPtr(_), CastTy::Ptr(_)) => {
773                     ptrcast(v, llty)
774                 },
775                 (CastTy::FnPtr, CastTy::FnPtr) => ptrcast(v, llty), // isn't this a coercion?
776                 (CastTy::Int(_), CastTy::Ptr(_)) => llvm::LLVMConstIntToPtr(v, llty.to_ref()),
777                 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
778                   llvm::LLVMConstPtrToInt(v, llty.to_ref())
779                 },
780                 _ => {
781                   span_bug!(e.span, "bad combination of types for cast")
782                 },
783             } } // unsafe { match ( ... ) {
784         },
785         hir::ExprAddrOf(hir::MutImmutable, ref sub) => {
786             // If this is the address of some static, then we need to return
787             // the actual address of the static itself (short circuit the rest
788             // of const eval).
789             let mut cur = sub;
790             loop {
791                 match cur.node {
792                     hir::ExprBlock(ref blk) => {
793                         if let Some(ref sub) = blk.expr {
794                             cur = sub;
795                         } else {
796                             break;
797                         }
798                     },
799                     _ => break,
800                 }
801             }
802             if let Some(Def::Static(def_id, _)) = cx.tcx().expect_def_or_none(cur.id) {
803                 get_static(cx, def_id).val
804             } else {
805                 // If this isn't the address of a static, then keep going through
806                 // normal constant evaluation.
807                 let (v, ty) = const_expr(cx, &sub, param_substs, fn_args, trueconst)?;
808                 addr_of(cx, v, type_of::align_of(cx, ty), "ref")
809             }
810         },
811         hir::ExprAddrOf(hir::MutMutable, ref sub) => {
812             let (v, ty) = const_expr(cx, &sub, param_substs, fn_args, trueconst)?;
813             addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
814         },
815         hir::ExprTup(ref es) => {
816             let repr = adt::represent_type(cx, ety);
817             let vals = map_list(&es[..])?;
818             adt::trans_const(cx, &repr, Disr(0), &vals[..])
819         },
820         hir::ExprStruct(_, ref fs, ref base_opt) => {
821             let repr = adt::represent_type(cx, ety);
822
823             let base_val = match *base_opt {
824                 Some(ref base) => Some(const_expr(
825                     cx,
826                     &base,
827                     param_substs,
828                     fn_args,
829                     trueconst,
830                 )?),
831                 None => None
832             };
833
834             let VariantInfo { discr, fields } = VariantInfo::of_node(cx.tcx(), ety, e.id);
835             let cs = fields.iter().enumerate().map(|(ix, &Field(f_name, _))| {
836                 match (fs.iter().find(|f| f_name == f.name.node), base_val) {
837                     (Some(ref f), _) => {
838                         const_expr(cx, &f.expr, param_substs, fn_args, trueconst).map(|(l, _)| l)
839                     },
840                     (_, Some((bv, _))) => Ok(adt::const_get_field(&repr, bv, discr, ix)),
841                     (_, None) => span_bug!(e.span, "missing struct field"),
842                 }
843             })
844             .collect::<Vec<Result<_, ConstEvalFailure>>>()
845             .into_iter()
846             .collect::<Result<Vec<_>,ConstEvalFailure>>();
847             let cs = cs?;
848             if ety.is_simd() {
849                 C_vector(&cs[..])
850             } else {
851                 adt::trans_const(cx, &repr, discr, &cs[..])
852             }
853         },
854         hir::ExprVec(ref es) => {
855             let unit_ty = ety.sequence_element_type(cx.tcx());
856             let llunitty = type_of::type_of(cx, unit_ty);
857             let vs = es.iter()
858                        .map(|e| const_expr(
859                            cx,
860                            &e,
861                            param_substs,
862                            fn_args,
863                            trueconst,
864                        ).map(|(l, _)| l))
865                        .collect::<Vec<Result<_, ConstEvalFailure>>>()
866                        .into_iter()
867                        .collect::<Result<Vec<_>, ConstEvalFailure>>();
868             let vs = vs?;
869             // If the vector contains enums, an LLVM array won't work.
870             if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
871                 C_struct(cx, &vs[..], false)
872             } else {
873                 C_array(llunitty, &vs[..])
874             }
875         },
876         hir::ExprRepeat(ref elem, ref count) => {
877             let unit_ty = ety.sequence_element_type(cx.tcx());
878             let llunitty = type_of::type_of(cx, unit_ty);
879             let n = eval_repeat_count(cx.tcx(), count);
880             let unit_val = const_expr(cx, &elem, param_substs, fn_args, trueconst)?.0;
881             let vs = vec![unit_val; n];
882             if val_ty(unit_val) != llunitty {
883                 C_struct(cx, &vs[..], false)
884             } else {
885                 C_array(llunitty, &vs[..])
886             }
887         },
888         hir::ExprPath(..) => {
889             match cx.tcx().expect_def(e.id) {
890                 Def::Local(_, id) => {
891                     if let Some(val) = fn_args.and_then(|args| args.get(&id).cloned()) {
892                         val
893                     } else {
894                         span_bug!(e.span, "const fn argument not found")
895                     }
896                 }
897                 Def::Fn(..) | Def::Method(..) => C_nil(cx),
898                 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
899                     load_const(cx, get_const_val(cx, def_id, e, param_substs)?,
900                                ety)
901                 }
902                 Def::Variant(enum_did, variant_did) => {
903                     let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
904                     match vinfo.kind() {
905                         ty::VariantKind::Unit => {
906                             let repr = adt::represent_type(cx, ety);
907                             adt::trans_const(cx, &repr, Disr::from(vinfo.disr_val), &[])
908                         }
909                         ty::VariantKind::Tuple => C_nil(cx),
910                         ty::VariantKind::Struct => {
911                             span_bug!(e.span, "path-expr refers to a dict variant!")
912                         }
913                     }
914                 }
915                 // Unit struct or ctor.
916                 Def::Struct(..) => C_null(type_of::type_of(cx, ety)),
917                 _ => {
918                     span_bug!(e.span, "expected a const, fn, struct, \
919                                        or variant def")
920                 }
921             }
922         },
923         hir::ExprCall(ref callee, ref args) => {
924             let mut callee = &**callee;
925             loop {
926                 callee = match callee.node {
927                     hir::ExprBlock(ref block) => match block.expr {
928                         Some(ref tail) => &tail,
929                         None => break,
930                     },
931                     _ => break,
932                 };
933             }
934             let arg_vals = map_list(args)?;
935             match cx.tcx().expect_def(callee.id) {
936                 Def::Fn(did) | Def::Method(did) => {
937                     const_fn_call(
938                         cx,
939                         did,
940                         cx.tcx().node_id_item_substs(callee.id).substs,
941                         &arg_vals,
942                         param_substs,
943                         trueconst,
944                     )?
945                 }
946                 Def::Struct(..) => {
947                     if ety.is_simd() {
948                         C_vector(&arg_vals[..])
949                     } else {
950                         let repr = adt::represent_type(cx, ety);
951                         adt::trans_const(cx, &repr, Disr(0), &arg_vals[..])
952                     }
953                 }
954                 Def::Variant(enum_did, variant_did) => {
955                     let repr = adt::represent_type(cx, ety);
956                     let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
957                     adt::trans_const(cx,
958                                      &repr,
959                                      Disr::from(vinfo.disr_val),
960                                      &arg_vals[..])
961                 }
962                 _ => span_bug!(e.span, "expected a struct, variant, or const fn def"),
963             }
964         },
965         hir::ExprMethodCall(_, _, ref args) => {
966             let arg_vals = map_list(args)?;
967             let method_call = ty::MethodCall::expr(e.id);
968             let method = cx.tcx().tables.borrow().method_map[&method_call];
969             const_fn_call(cx, method.def_id, method.substs,
970                           &arg_vals, param_substs, trueconst)?
971         },
972         hir::ExprType(ref e, _) => const_expr(cx, &e, param_substs, fn_args, trueconst)?.0,
973         hir::ExprBlock(ref block) => {
974             match block.expr {
975                 Some(ref expr) => const_expr(
976                     cx,
977                     &expr,
978                     param_substs,
979                     fn_args,
980                     trueconst,
981                 )?.0,
982                 None => C_nil(cx),
983             }
984         },
985         hir::ExprClosure(_, ref decl, ref body, _) => {
986             match ety.sty {
987                 ty::TyClosure(def_id, substs) => {
988                     closure::trans_closure_expr(closure::Dest::Ignore(cx),
989                                                 decl,
990                                                 body,
991                                                 e.id,
992                                                 def_id,
993                                                 substs);
994                 }
995                 _ =>
996                     span_bug!(
997                         e.span,
998                         "bad type for closure expr: {:?}", ety)
999             }
1000             C_null(type_of::type_of(cx, ety))
1001         },
1002         _ => span_bug!(e.span,
1003                        "bad constant expression type in consts::const_expr"),
1004     })
1005 }
1006
1007 pub fn get_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, def_id: DefId)
1008                             -> Datum<'tcx, Lvalue> {
1009     let ty = ccx.tcx().lookup_item_type(def_id).ty;
1010
1011     let instance = Instance::mono(ccx.shared(), def_id);
1012     if let Some(&g) = ccx.instances().borrow().get(&instance) {
1013         return Datum::new(g, ty, Lvalue::new("static"));
1014     }
1015
1016     let g = if let Some(id) = ccx.tcx().map.as_local_node_id(def_id) {
1017
1018         let llty = type_of::type_of(ccx, ty);
1019         let (g, attrs) = match ccx.tcx().map.get(id) {
1020             hir_map::NodeItem(&hir::Item {
1021                 ref attrs, span, node: hir::ItemStatic(..), ..
1022             }) => {
1023                 let sym = ccx.symbol_map()
1024                              .get(TransItem::Static(id))
1025                              .expect("Local statics should always be in the SymbolMap");
1026                 // Make sure that this is never executed for something inlined.
1027                 assert!(!ccx.external_srcs().borrow().contains_key(&id));
1028
1029                 let defined_in_current_codegen_unit = ccx.codegen_unit()
1030                                                          .items
1031                                                          .contains_key(&TransItem::Static(id));
1032                 if defined_in_current_codegen_unit {
1033                     if declare::get_declared_value(ccx, sym).is_none() {
1034                         span_bug!(span, "trans: Static not properly pre-defined?");
1035                     }
1036                 } else {
1037                     if declare::get_declared_value(ccx, sym).is_some() {
1038                         span_bug!(span, "trans: Conflicting symbol names for static?");
1039                     }
1040                 }
1041
1042                 let g = declare::define_global(ccx, sym, llty).unwrap();
1043
1044                 (g, attrs)
1045             }
1046
1047             hir_map::NodeForeignItem(&hir::ForeignItem {
1048                 ref attrs, span, node: hir::ForeignItemStatic(..), ..
1049             }) => {
1050                 let sym = instance.symbol_name(ccx.shared());
1051                 let g = if let Some(name) =
1052                         attr::first_attr_value_str_by_name(&attrs, "linkage") {
1053                     // If this is a static with a linkage specified, then we need to handle
1054                     // it a little specially. The typesystem prevents things like &T and
1055                     // extern "C" fn() from being non-null, so we can't just declare a
1056                     // static and call it a day. Some linkages (like weak) will make it such
1057                     // that the static actually has a null value.
1058                     let linkage = match base::llvm_linkage_by_name(&name) {
1059                         Some(linkage) => linkage,
1060                         None => {
1061                             ccx.sess().span_fatal(span, "invalid linkage specified");
1062                         }
1063                     };
1064                     let llty2 = match ty.sty {
1065                         ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
1066                         _ => {
1067                             ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
1068                         }
1069                     };
1070                     unsafe {
1071                         // Declare a symbol `foo` with the desired linkage.
1072                         let g1 = declare::declare_global(ccx, &sym, llty2);
1073                         llvm::SetLinkage(g1, linkage);
1074
1075                         // Declare an internal global `extern_with_linkage_foo` which
1076                         // is initialized with the address of `foo`.  If `foo` is
1077                         // discarded during linking (for example, if `foo` has weak
1078                         // linkage and there are no definitions), then
1079                         // `extern_with_linkage_foo` will instead be initialized to
1080                         // zero.
1081                         let mut real_name = "_rust_extern_with_linkage_".to_string();
1082                         real_name.push_str(&sym);
1083                         let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
1084                             ccx.sess().span_fatal(span,
1085                                 &format!("symbol `{}` is already defined", &sym))
1086                         });
1087                         llvm::SetLinkage(g2, llvm::InternalLinkage);
1088                         llvm::LLVMSetInitializer(g2, g1);
1089                         g2
1090                     }
1091                 } else {
1092                     // Generate an external declaration.
1093                     declare::declare_global(ccx, &sym, llty)
1094                 };
1095
1096                 (g, attrs)
1097             }
1098
1099             item => bug!("get_static: expected static, found {:?}", item)
1100         };
1101
1102         for attr in attrs {
1103             if attr.check_name("thread_local") {
1104                 llvm::set_thread_local(g, true);
1105             }
1106         }
1107
1108         g
1109     } else {
1110         let sym = instance.symbol_name(ccx.shared());
1111
1112         // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
1113         // FIXME(nagisa): investigate whether it can be changed into define_global
1114         let g = declare::declare_global(ccx, &sym, type_of::type_of(ccx, ty));
1115         // Thread-local statics in some other crate need to *always* be linked
1116         // against in a thread-local fashion, so we need to be sure to apply the
1117         // thread-local attribute locally if it was present remotely. If we
1118         // don't do this then linker errors can be generated where the linker
1119         // complains that one object files has a thread local version of the
1120         // symbol and another one doesn't.
1121         for attr in ccx.tcx().get_attrs(def_id).iter() {
1122             if attr.check_name("thread_local") {
1123                 llvm::set_thread_local(g, true);
1124             }
1125         }
1126         if ccx.use_dll_storage_attrs() {
1127             llvm::SetDLLStorageClass(g, llvm::DLLImportStorageClass);
1128         }
1129         g
1130     };
1131
1132     ccx.instances().borrow_mut().insert(instance, g);
1133     ccx.statics().borrow_mut().insert(g, def_id);
1134     Datum::new(g, ty, Lvalue::new("static"))
1135 }
1136
1137 pub fn trans_static(ccx: &CrateContext,
1138                     m: hir::Mutability,
1139                     expr: &hir::Expr,
1140                     id: ast::NodeId,
1141                     attrs: &[ast::Attribute])
1142                     -> Result<ValueRef, ConstEvalErr> {
1143
1144     if collector::collecting_debug_information(ccx.shared()) {
1145         ccx.record_translation_item_as_generated(TransItem::Static(id));
1146     }
1147
1148     unsafe {
1149         let _icx = push_ctxt("trans_static");
1150         let def_id = ccx.tcx().map.local_def_id(id);
1151         let datum = get_static(ccx, def_id);
1152
1153         let check_attrs = |attrs: &[ast::Attribute]| {
1154             let default_to_mir = ccx.sess().opts.debugging_opts.orbit;
1155             let invert = if default_to_mir { "rustc_no_mir" } else { "rustc_mir" };
1156             default_to_mir ^ attrs.iter().any(|item| item.check_name(invert))
1157         };
1158         let use_mir = check_attrs(ccx.tcx().map.attrs(id));
1159
1160         let v = if use_mir {
1161             ::mir::trans_static_initializer(ccx, def_id)
1162         } else {
1163             let empty_substs = ccx.tcx().mk_substs(Substs::empty());
1164             const_expr(ccx, expr, empty_substs, None, TrueConst::Yes)
1165                 .map(|(v, _)| v)
1166         }.map_err(|e| e.into_inner())?;
1167
1168         // boolean SSA values are i1, but they have to be stored in i8 slots,
1169         // otherwise some LLVM optimization passes don't work as expected
1170         let mut val_llty = val_ty(v);
1171         let v = if val_llty == Type::i1(ccx) {
1172             val_llty = Type::i8(ccx);
1173             llvm::LLVMConstZExt(v, val_llty.to_ref())
1174         } else {
1175             v
1176         };
1177
1178         let llty = type_of::type_of(ccx, datum.ty);
1179         let g = if val_llty == llty {
1180             datum.val
1181         } else {
1182             // If we created the global with the wrong type,
1183             // correct the type.
1184             let empty_string = CString::new("").unwrap();
1185             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(datum.val));
1186             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
1187             llvm::LLVMSetValueName(datum.val, empty_string.as_ptr());
1188             let new_g = llvm::LLVMGetOrInsertGlobal(
1189                 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
1190             // To avoid breaking any invariants, we leave around the old
1191             // global for the moment; we'll replace all references to it
1192             // with the new global later. (See base::trans_crate.)
1193             ccx.statics_to_rauw().borrow_mut().push((datum.val, new_g));
1194             new_g
1195         };
1196         llvm::LLVMSetAlignment(g, type_of::align_of(ccx, datum.ty));
1197         llvm::LLVMSetInitializer(g, v);
1198
1199         // As an optimization, all shared statics which do not have interior
1200         // mutability are placed into read-only memory.
1201         if m != hir::MutMutable {
1202             let tcontents = datum.ty.type_contents(ccx.tcx());
1203             if !tcontents.interior_unsafe() {
1204                 llvm::LLVMSetGlobalConstant(g, llvm::True);
1205             }
1206         }
1207
1208         debuginfo::create_global_var_metadata(ccx, id, g);
1209
1210         if attr::contains_name(attrs,
1211                                "thread_local") {
1212             llvm::set_thread_local(g, true);
1213         }
1214
1215         base::set_link_section(ccx, g, attrs);
1216
1217         Ok(g)
1218     }
1219 }