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