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