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.
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.
14 use llvm::{ConstFCmp, ConstICmp, SetLinkage, SetUnnamedAddr};
15 use llvm::{InternalLinkage, ValueRef, Bool, True};
16 use middle::{check_const, const_eval, def};
17 use trans::{adt, closure, debuginfo, expr, inline, machine};
18 use trans::base::{self, push_ctxt};
20 use trans::monomorphize;
21 use trans::type_::Type;
23 use middle::subst::Substs;
24 use middle::ty::{self, Ty};
25 use util::ppaux::{Repr, ty_to_string};
27 use std::iter::repeat;
29 use syntax::{ast, ast_util};
32 pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit)
34 let _icx = push_ctxt("trans_lit");
35 debug!("const_lit: {:?}", lit);
37 ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
38 ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
39 ast::LitInt(i, ast::SignedIntLit(t, _)) => {
40 C_integral(Type::int_from_ty(cx, t), i, true)
42 ast::LitInt(u, ast::UnsignedIntLit(t)) => {
43 C_integral(Type::uint_from_ty(cx, t), u, false)
45 ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
46 let lit_int_ty = ty::node_id_to_type(cx.tcx(), e.id);
47 match lit_int_ty.sty {
49 C_integral(Type::int_from_ty(cx, t), i as u64, true)
52 C_integral(Type::uint_from_ty(cx, t), i as u64, false)
54 _ => cx.sess().span_bug(lit.span,
55 &format!("integer literal has type {} (expected int \
57 ty_to_string(cx.tcx(), lit_int_ty))[])
60 ast::LitFloat(ref fs, t) => {
61 C_floating(&fs, Type::float_from_ty(cx, t))
63 ast::LitFloatUnsuffixed(ref fs) => {
64 let lit_float_ty = ty::node_id_to_type(cx.tcx(), e.id);
65 match lit_float_ty.sty {
67 C_floating(&fs, Type::float_from_ty(cx, t))
70 cx.sess().span_bug(lit.span,
71 "floating point literal doesn't have the right type");
75 ast::LitBool(b) => C_bool(cx, b),
76 ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
77 ast::LitBinary(ref data) => {
78 let g = addr_of(cx, C_bytes(cx, &data[..]), "binary", e.id);
79 let base = ptrcast(g, Type::i8p(cx));
80 let prev_const = cx.const_unsized().borrow_mut()
82 assert!(prev_const.is_none() || prev_const == Some(g));
83 assert_eq!(abi::FAT_PTR_ADDR, 0);
84 assert_eq!(abi::FAT_PTR_EXTRA, 1);
85 C_struct(cx, &[base, C_uint(cx, data.len())], false)
90 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
92 llvm::LLVMConstPointerCast(val, ty.to_ref())
96 fn addr_of_mut(ccx: &CrateContext,
102 let name = format!("{}{}\0", kind, id);
103 let gv = llvm::LLVMAddGlobal(ccx.llmod(), val_ty(cv).to_ref(),
104 name.as_ptr() as *const _);
105 llvm::LLVMSetInitializer(gv, cv);
106 SetLinkage(gv, InternalLinkage);
107 SetUnnamedAddr(gv, true);
112 pub fn addr_of(ccx: &CrateContext,
117 match ccx.const_globals().borrow().get(&cv) {
118 Some(&gv) => return gv,
121 let gv = addr_of_mut(ccx, cv, kind, id);
123 llvm::LLVMSetGlobalConstant(gv, True);
125 ccx.const_globals().borrow_mut().insert(cv, gv);
129 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
130 let v = match cx.const_unsized().borrow().get(&v) {
135 llvm::LLVMGetInitializer(v)
139 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
142 -> (ValueRef, Ty<'tcx>) {
143 match ty::deref(ty, true) {
145 if type_is_sized(cx.tcx(), mt.ty) {
146 (const_deref_ptr(cx, v), mt.ty)
148 // Derefing a fat pointer does not change the representation,
149 // just the type to ty_open.
150 (v, ty::mk_open(cx.tcx(), mt.ty))
154 cx.sess().bug(&format!("unexpected dereferenceable type {}",
155 ty_to_string(cx.tcx(), ty))[])
160 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
162 ref_expr: &ast::Expr)
164 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
166 if def_id.krate != ast::LOCAL_CRATE {
167 ccx.sess().span_bug(ref_expr.span,
168 "cross crate constant could not be inlined");
171 let item = ccx.tcx().map.expect_item(def_id.node);
172 if let ast::ItemConst(_, ref expr) = item.node {
175 ccx.sess().span_bug(ref_expr.span,
176 &format!("get_const_val given non-constant item {}",
177 item.repr(ccx.tcx()))[]);
181 fn get_const_val(ccx: &CrateContext,
183 ref_expr: &ast::Expr) -> ValueRef {
184 let expr = get_const_expr(ccx, def_id, ref_expr);
185 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
186 get_const_expr_as_global(ccx, expr, check_const::PURE_CONST, empty_substs)
189 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
191 qualif: check_const::ConstQualif,
192 param_substs: &'tcx Substs<'tcx>)
194 // Special-case constants to cache a common global for all uses.
196 ast::ExprPath(_) => {
197 let def = ccx.tcx().def_map.borrow()[expr.id];
199 def::DefConst(def_id) => {
200 if !ccx.tcx().adjustments.borrow().contains_key(&expr.id) {
201 return get_const_val(ccx, def_id, expr);
210 let key = (expr.id, param_substs);
211 match ccx.const_values().borrow().get(&key) {
212 Some(&val) => return val,
215 let val = if qualif.intersects(check_const::NON_STATIC_BORROWS) {
216 // Avoid autorefs as they would create global instead of stack
217 // references, even when only the latter are correct.
218 let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
219 &ty::expr_ty(ccx.tcx(), expr));
220 const_expr_unadjusted(ccx, expr, ty, param_substs)
222 const_expr(ccx, expr, param_substs).0
225 // boolean SSA values are i1, but they have to be stored in i8 slots,
226 // otherwise some LLVM optimization passes don't work as expected
228 if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
229 llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
235 let lvalue = addr_of(ccx, val, "const", expr.id);
236 ccx.const_values().borrow_mut().insert(key, lvalue);
240 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
242 param_substs: &'tcx Substs<'tcx>)
243 -> (ValueRef, Ty<'tcx>) {
244 let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
245 &ty::expr_ty(cx.tcx(), e));
246 let llconst = const_expr_unadjusted(cx, e, ety, param_substs);
247 let mut llconst = llconst;
248 let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
249 &ty::expr_ty_adjusted(cx.tcx(), e));
250 let opt_adj = cx.tcx().adjustments.borrow().get(&e.id).cloned();
252 Some(ty::AdjustReifyFnPointer(_def_id)) => {
253 // FIXME(#19925) once fn item types are
254 // zero-sized, we'll need to do something here
256 Some(ty::AdjustDerefRef(adj)) => {
258 // Save the last autoderef in case we can avoid it.
259 if adj.autoderefs > 0 {
260 for _ in 0..adj.autoderefs-1 {
261 let (dv, dt) = const_deref(cx, llconst, ty);
267 let second_autoref = match adj.autoref {
269 let (dv, dt) = const_deref(cx, llconst, ty);
272 // If we derefed a fat pointer then we will have an
273 // open type here. So we need to update the type with
274 // the one returned from const_deref.
278 Some(ty::AutoUnsafe(_, opt_autoref)) |
279 Some(ty::AutoPtr(_, _, opt_autoref)) => {
280 if adj.autoderefs == 0 {
281 // Don't copy data to do a deref+ref
282 // (i.e., skip the last auto-deref).
283 llconst = addr_of(cx, llconst, "autoref", e.id);
285 // Seeing as we are deref'ing here and take a reference
286 // again to make the pointer part of the far pointer below,
287 // we just skip the whole thing. We still need the type
288 // though. This works even if we don't need to deref
289 // because of byref semantics. Note that this is not just
290 // an optimisation, it is necessary for mutable vectors to
292 ty = match ty::deref(ty, true) {
294 if type_is_sized(cx.tcx(), mt.ty) {
297 // Derefing a fat pointer does not change the representation,
298 // just the type to ty_open.
299 ty::mk_open(cx.tcx(), mt.ty)
303 cx.sess().bug(&format!("unexpected dereferenceable type {}",
304 ty_to_string(cx.tcx(), ty))[])
311 cx.sess().span_bug(e.span,
312 &format!("unimplemented const first autoref {:?}", autoref)[])
315 match second_autoref {
317 Some(box ty::AutoUnsafe(_, None)) |
318 Some(box ty::AutoPtr(_, _, None)) => {
319 llconst = addr_of(cx, llconst, "autoref", e.id);
321 Some(box ty::AutoUnsize(ref k)) => {
322 let unsized_ty = ty::unsize_ty(cx.tcx(), ty, k, e.span);
323 let info = expr::unsized_info(cx, k, e.id, ty, param_substs,
324 |t| ty::mk_imm_rptr(cx.tcx(), cx.tcx().mk_region(ty::ReStatic), t));
326 let base = ptrcast(llconst, type_of::type_of(cx, unsized_ty).ptr_to());
327 let prev_const = cx.const_unsized().borrow_mut()
328 .insert(base, llconst);
329 assert!(prev_const.is_none() || prev_const == Some(llconst));
330 assert_eq!(abi::FAT_PTR_ADDR, 0);
331 assert_eq!(abi::FAT_PTR_EXTRA, 1);
332 llconst = C_struct(cx, &[base, info], false);
335 cx.sess().span_bug(e.span,
336 &format!("unimplemented const second autoref {:?}", autoref)[])
343 let llty = type_of::sizing_type_of(cx, ety_adjusted);
344 let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
345 let tsize = machine::llsize_of_alloc(cx, llty);
348 // FIXME these values could use some context
349 llvm::LLVMDumpValue(llconst);
350 llvm::LLVMDumpValue(C_undef(llty));
352 cx.sess().bug(&format!("const {} of type {} has size {} instead of {}",
353 e.repr(cx.tcx()), ty_to_string(cx.tcx(), ety_adjusted),
356 (llconst, ety_adjusted)
359 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
362 param_substs: &'tcx Substs<'tcx>) -> ValueRef {
363 let map_list = |exprs: &[P<ast::Expr>]| {
364 exprs.iter().map(|e| const_expr(cx, &**e, param_substs).0)
365 .fold(Vec::new(), |mut l, val| { l.push(val); l })
368 let _icx = push_ctxt("const_expr");
369 return match e.node {
370 ast::ExprLit(ref lit) => {
371 const_lit(cx, e, &**lit)
373 ast::ExprBinary(b, ref e1, ref e2) => {
374 /* Neither type is bottom, and we expect them to be unified
375 * already, so the following is safe. */
376 let (te1, ty) = const_expr(cx, &**e1, param_substs);
377 let is_simd = ty::type_is_simd(cx.tcx(), ty);
378 let intype = if is_simd {
379 ty::simd_type(cx.tcx(), ty)
383 let is_float = ty::type_is_fp(intype);
384 let signed = ty::type_is_signed(intype);
386 let (te2, _) = const_expr(cx, &**e2, param_substs);
387 let te2 = base::cast_shift_const_rhs(b, te1, te2);
389 return match b.node {
391 if is_float { llvm::LLVMConstFAdd(te1, te2) }
392 else { llvm::LLVMConstAdd(te1, te2) }
395 if is_float { llvm::LLVMConstFSub(te1, te2) }
396 else { llvm::LLVMConstSub(te1, te2) }
399 if is_float { llvm::LLVMConstFMul(te1, te2) }
400 else { llvm::LLVMConstMul(te1, te2) }
403 if is_float { llvm::LLVMConstFDiv(te1, te2) }
404 else if signed { llvm::LLVMConstSDiv(te1, te2) }
405 else { llvm::LLVMConstUDiv(te1, te2) }
408 if is_float { llvm::LLVMConstFRem(te1, te2) }
409 else if signed { llvm::LLVMConstSRem(te1, te2) }
410 else { llvm::LLVMConstURem(te1, te2) }
412 ast::BiAnd => llvm::LLVMConstAnd(te1, te2),
413 ast::BiOr => llvm::LLVMConstOr(te1, te2),
414 ast::BiBitXor => llvm::LLVMConstXor(te1, te2),
415 ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
416 ast::BiBitOr => llvm::LLVMConstOr(te1, te2),
417 ast::BiShl => llvm::LLVMConstShl(te1, te2),
419 if signed { llvm::LLVMConstAShr(te1, te2) }
420 else { llvm::LLVMConstLShr(te1, te2) }
422 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiLe | ast::BiGt | ast::BiGe => {
424 let cmp = base::bin_op_to_fcmp_predicate(cx, b.node);
425 ConstFCmp(cmp, te1, te2)
427 let cmp = base::bin_op_to_icmp_predicate(cx, b.node, signed);
428 let bool_val = ConstICmp(cmp, te1, te2);
430 // LLVM outputs an `< size x i1 >`, so we need to perform
431 // a sign extension to get the correctly sized type.
432 llvm::LLVMConstIntCast(bool_val, val_ty(te1).to_ref(), True)
440 ast::ExprUnary(u, ref e) => {
441 let (te, ty) = const_expr(cx, &**e, param_substs);
442 let is_float = ty::type_is_fp(ty);
444 ast::UnUniq | ast::UnDeref => {
445 const_deref(cx, te, ty).0
447 ast::UnNot => llvm::LLVMConstNot(te),
449 if is_float { llvm::LLVMConstFNeg(te) }
450 else { llvm::LLVMConstNeg(te) }
454 ast::ExprField(ref base, field) => {
455 let (bv, bt) = const_expr(cx, &**base, param_substs);
456 let brepr = adt::represent_type(cx, bt);
457 expr::with_field_tys(cx.tcx(), bt, None, |discr, field_tys| {
458 let ix = ty::field_idx_strict(cx.tcx(), field.node.name, field_tys);
459 adt::const_get_field(cx, &*brepr, bv, discr, ix)
462 ast::ExprTupField(ref base, idx) => {
463 let (bv, bt) = const_expr(cx, &**base, param_substs);
464 let brepr = adt::represent_type(cx, bt);
465 expr::with_field_tys(cx.tcx(), bt, None, |discr, _| {
466 adt::const_get_field(cx, &*brepr, bv, discr, idx.node)
470 ast::ExprIndex(ref base, ref index) => {
471 let (bv, bt) = const_expr(cx, &**base, param_substs);
472 let iv = match const_eval::eval_const_expr(cx.tcx(), &**index) {
473 const_eval::const_int(i) => i as u64,
474 const_eval::const_uint(u) => u,
475 _ => cx.sess().span_bug(index.span,
476 "index is not an integer-constant expression")
478 let (arr, len) = match bt.sty {
479 ty::ty_vec(_, Some(u)) => (bv, C_uint(cx, u)),
480 ty::ty_open(ty) => match ty.sty {
481 ty::ty_vec(_, None) | ty::ty_str => {
482 let e1 = const_get_elt(cx, bv, &[0]);
483 (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
485 _ => cx.sess().span_bug(base.span,
486 &format!("index-expr base must be a vector \
487 or string type, found {}",
488 ty_to_string(cx.tcx(), bt))[])
490 ty::ty_rptr(_, mt) => match mt.ty.sty {
491 ty::ty_vec(_, Some(u)) => {
492 (const_deref_ptr(cx, bv), C_uint(cx, u))
494 _ => cx.sess().span_bug(base.span,
495 &format!("index-expr base must be a vector \
496 or string type, found {}",
497 ty_to_string(cx.tcx(), bt))[])
499 _ => cx.sess().span_bug(base.span,
500 &format!("index-expr base must be a vector \
501 or string type, found {}",
502 ty_to_string(cx.tcx(), bt))[])
505 let len = llvm::LLVMConstIntGetZExtValue(len) as u64;
506 let len = match bt.sty {
507 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) => match ty.sty {
517 // FIXME #3170: report this earlier on in the const-eval
518 // pass. Reporting here is a bit late.
519 cx.sess().span_err(e.span,
520 "const index-expr is out of bounds");
522 const_get_elt(cx, arr, &[iv as c_uint])
524 ast::ExprCast(ref base, _) => {
525 let llty = type_of::type_of(cx, ety);
526 let (v, basety) = const_expr(cx, &**base, param_substs);
527 if expr::cast_is_noop(basety, ety) {
530 return match (expr::cast_type_kind(cx.tcx(), basety),
531 expr::cast_type_kind(cx.tcx(), ety)) {
533 (expr::cast_integral, expr::cast_integral) => {
534 let s = ty::type_is_signed(basety) as Bool;
535 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
537 (expr::cast_integral, expr::cast_float) => {
538 if ty::type_is_signed(basety) {
539 llvm::LLVMConstSIToFP(v, llty.to_ref())
541 llvm::LLVMConstUIToFP(v, llty.to_ref())
544 (expr::cast_float, expr::cast_float) => {
545 llvm::LLVMConstFPCast(v, llty.to_ref())
547 (expr::cast_float, expr::cast_integral) => {
548 if ty::type_is_signed(ety) { llvm::LLVMConstFPToSI(v, llty.to_ref()) }
549 else { llvm::LLVMConstFPToUI(v, llty.to_ref()) }
551 (expr::cast_enum, expr::cast_integral) => {
552 let repr = adt::represent_type(cx, basety);
553 let discr = adt::const_get_discrim(cx, &*repr, v);
554 let iv = C_integral(cx.int_type(), discr, false);
555 let ety_cast = expr::cast_type_kind(cx.tcx(), ety);
557 expr::cast_integral => {
558 let s = ty::type_is_signed(ety) as Bool;
559 llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
561 _ => cx.sess().bug("enum cast destination is not \
565 (expr::cast_pointer, expr::cast_pointer) => {
568 (expr::cast_integral, expr::cast_pointer) => {
569 llvm::LLVMConstIntToPtr(v, llty.to_ref())
571 (expr::cast_pointer, expr::cast_integral) => {
572 llvm::LLVMConstPtrToInt(v, llty.to_ref())
575 cx.sess().impossible_case(e.span,
576 "bad combination of types for cast")
580 ast::ExprAddrOf(ast::MutImmutable, ref sub) => {
581 // If this is the address of some static, then we need to return
582 // the actual address of the static itself (short circuit the rest
587 ast::ExprParen(ref sub) => cur = sub,
588 ast::ExprBlock(ref blk) => {
589 if let Some(ref sub) = blk.expr {
598 let opt_def = cx.tcx().def_map.borrow().get(&cur.id).cloned();
599 if let Some(def::DefStatic(def_id, _)) = opt_def {
600 return get_static_val(cx, def_id, ety);
603 // If this isn't the address of a static, then keep going through
604 // normal constant evaluation.
605 let (v, _) = const_expr(cx, &**sub, param_substs);
606 addr_of(cx, v, "ref", e.id)
608 ast::ExprAddrOf(ast::MutMutable, ref sub) => {
609 let (v, _) = const_expr(cx, &**sub, param_substs);
610 addr_of_mut(cx, v, "ref_mut_slice", e.id)
612 ast::ExprTup(ref es) => {
613 let repr = adt::represent_type(cx, ety);
614 let vals = map_list(&es[..]);
615 adt::trans_const(cx, &*repr, 0, &vals[..])
617 ast::ExprStruct(_, ref fs, ref base_opt) => {
618 let repr = adt::represent_type(cx, ety);
620 let base_val = match *base_opt {
621 Some(ref base) => Some(const_expr(cx, &**base, param_substs)),
625 expr::with_field_tys(cx.tcx(), ety, Some(e.id), |discr, field_tys| {
626 let cs = field_tys.iter().enumerate()
627 .map(|(ix, &field_ty)| {
628 match fs.iter().find(|f| field_ty.name == f.ident.node.name) {
629 Some(ref f) => const_expr(cx, &*f.expr, param_substs).0,
633 adt::const_get_field(cx, &*repr, bv,
637 cx.sess().span_bug(e.span,
638 "missing struct field")
643 }).collect::<Vec<_>>();
644 if ty::type_is_simd(cx.tcx(), ety) {
647 adt::trans_const(cx, &*repr, discr, &cs[..])
651 ast::ExprVec(ref es) => {
652 let unit_ty = ty::sequence_element_type(cx.tcx(), ety);
653 let llunitty = type_of::type_of(cx, unit_ty);
654 let vs = es.iter().map(|e| const_expr(cx, &**e, param_substs).0)
655 .collect::<Vec<_>>();
656 // If the vector contains enums, an LLVM array won't work.
657 if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
658 C_struct(cx, &vs[..], false)
660 C_array(llunitty, &vs[..])
663 ast::ExprRepeat(ref elem, ref count) => {
664 let unit_ty = ty::sequence_element_type(cx.tcx(), ety);
665 let llunitty = type_of::type_of(cx, unit_ty);
666 let n = match const_eval::eval_const_expr(cx.tcx(), &**count) {
667 const_eval::const_int(i) => i as uint,
668 const_eval::const_uint(i) => i as uint,
669 _ => cx.sess().span_bug(count.span, "count must be integral const expression.")
671 let unit_val = const_expr(cx, &**elem, param_substs).0;
672 let vs: Vec<_> = repeat(unit_val).take(n).collect();
673 if val_ty(unit_val) != llunitty {
674 C_struct(cx, &vs[..], false)
676 C_array(llunitty, &vs[..])
679 ast::ExprPath(_) | ast::ExprQPath(_) => {
680 let def = cx.tcx().def_map.borrow()[e.id];
682 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => {
683 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
685 def::DefConst(def_id) => {
686 const_deref_ptr(cx, get_const_val(cx, def_id, e))
688 def::DefVariant(enum_did, variant_did, _) => {
689 let vinfo = ty::enum_variant_with_id(cx.tcx(),
692 if vinfo.args.len() > 0 {
694 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
697 let repr = adt::represent_type(cx, ety);
698 adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
701 def::DefStruct(_) => {
702 if let ty::ty_bare_fn(..) = ety.sty {
704 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
707 C_null(type_of::type_of(cx, ety))
711 cx.sess().span_bug(e.span, "expected a const, fn, struct, \
716 ast::ExprCall(ref callee, ref args) => {
717 let opt_def = cx.tcx().def_map.borrow().get(&callee.id).cloned();
718 let arg_vals = map_list(&args[..]);
720 Some(def::DefStruct(_)) => {
721 if ty::type_is_simd(cx.tcx(), ety) {
722 C_vector(&arg_vals[..])
724 let repr = adt::represent_type(cx, ety);
725 adt::trans_const(cx, &*repr, 0, &arg_vals[..])
728 Some(def::DefVariant(enum_did, variant_did, _)) => {
729 let repr = adt::represent_type(cx, ety);
730 let vinfo = ty::enum_variant_with_id(cx.tcx(),
738 _ => cx.sess().span_bug(e.span, "expected a struct or variant def")
741 ast::ExprParen(ref e) => const_expr(cx, &**e, param_substs).0,
742 ast::ExprBlock(ref block) => {
744 Some(ref expr) => const_expr(cx, &**expr, param_substs).0,
748 ast::ExprClosure(_, ref decl, ref body) => {
749 closure::trans_closure_expr(closure::Dest::Ignore(cx),
750 &**decl, &**body, e.id,
752 C_null(type_of::type_of(cx, ety))
754 _ => cx.sess().span_bug(e.span,
755 "bad constant expression type in consts::const_expr")
760 pub fn trans_static(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) {
762 let _icx = push_ctxt("trans_static");
763 let g = base::get_item_val(ccx, id);
764 // At this point, get_item_val has already translated the
765 // constant's initializer to determine its LLVM type.
766 let v = ccx.static_values().borrow()[id].clone();
767 // boolean SSA values are i1, but they have to be stored in i8 slots,
768 // otherwise some LLVM optimization passes don't work as expected
769 let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() {
770 llvm::LLVMConstZExt(v, Type::i8(ccx).to_ref())
774 llvm::LLVMSetInitializer(g, v);
776 // As an optimization, all shared statics which do not have interior
777 // mutability are placed into read-only memory.
778 if m != ast::MutMutable {
779 let node_ty = ty::node_id_to_type(ccx.tcx(), id);
780 let tcontents = ty::type_contents(ccx.tcx(), node_ty);
781 if !tcontents.interior_unsafe() {
782 llvm::LLVMSetGlobalConstant(g, True);
785 debuginfo::create_global_var_metadata(ccx, id, g);
789 fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
790 ty: Ty<'tcx>) -> ValueRef {
791 if ast_util::is_local(did) { return base::get_item_val(ccx, did.node) }
792 base::trans_external_path(ccx, did, ty)