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