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 metadata::cstore::LOCAL_CRATE;
17 use middle::{check_const, def};
18 use middle::const_eval::{self, ConstVal};
19 use middle::const_eval::{const_int_checked_neg, const_uint_checked_neg};
20 use middle::const_eval::{const_int_checked_add, const_uint_checked_add};
21 use middle::const_eval::{const_int_checked_sub, const_uint_checked_sub};
22 use middle::const_eval::{const_int_checked_mul, const_uint_checked_mul};
23 use middle::const_eval::{const_int_checked_div, const_uint_checked_div};
24 use middle::const_eval::{const_int_checked_rem, const_uint_checked_rem};
25 use middle::const_eval::{const_int_checked_shl, const_uint_checked_shl};
26 use middle::const_eval::{const_int_checked_shr, const_uint_checked_shr};
27 use middle::const_eval::EvalHint::ExprTypeChecked;
28 use middle::const_eval::eval_const_expr_partial;
29 use middle::def_id::DefId;
30 use trans::{adt, closure, debuginfo, expr, inline, machine};
31 use trans::base::{self, push_ctxt};
34 use trans::monomorphize;
35 use trans::type_::Type;
37 use middle::subst::Substs;
38 use middle::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
39 use middle::ty::adjustment::AdjustUnsafeFnPointer;
40 use middle::ty::{self, Ty};
41 use middle::ty::cast::{CastTy,IntTy};
42 use util::nodemap::NodeMap;
46 use std::ffi::{CStr, CString};
50 use syntax::parse::token;
53 pub type FnArgMap<'a> = Option<&'a NodeMap<ValueRef>>;
55 pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &ast::Lit)
57 let _icx = push_ctxt("trans_lit");
58 debug!("const_lit: {:?}", lit);
60 ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
61 ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
62 ast::LitInt(i, ast::SignedIntLit(t, _)) => {
63 C_integral(Type::int_from_ty(cx, t), i, true)
65 ast::LitInt(u, ast::UnsignedIntLit(t)) => {
66 C_integral(Type::uint_from_ty(cx, t), u, false)
68 ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
69 let lit_int_ty = cx.tcx().node_id_to_type(e.id);
70 match lit_int_ty.sty {
72 C_integral(Type::int_from_ty(cx, t), i as u64, true)
75 C_integral(Type::uint_from_ty(cx, t), i as u64, false)
77 _ => cx.sess().span_bug(lit.span,
78 &format!("integer literal has type {:?} (expected int \
83 ast::LitFloat(ref fs, t) => {
84 C_floating(&fs, Type::float_from_ty(cx, t))
86 ast::LitFloatUnsuffixed(ref fs) => {
87 let lit_float_ty = cx.tcx().node_id_to_type(e.id);
88 match lit_float_ty.sty {
90 C_floating(&fs, Type::float_from_ty(cx, t))
93 cx.sess().span_bug(lit.span,
94 "floating point literal doesn't have the right type");
98 ast::LitBool(b) => C_bool(cx, b),
99 ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
100 ast::LitByteStr(ref data) => {
101 addr_of(cx, C_bytes(cx, &data[..]), 1, "byte_str")
106 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
108 llvm::LLVMConstPointerCast(val, ty.to_ref())
112 fn addr_of_mut(ccx: &CrateContext,
114 align: machine::llalign,
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));
125 llvm::LLVMSetInitializer(gv, cv);
126 llvm::LLVMSetAlignment(gv, align);
127 SetLinkage(gv, InternalLinkage);
128 SetUnnamedAddr(gv, true);
133 pub fn addr_of(ccx: &CrateContext,
135 align: machine::llalign,
138 match ccx.const_globals().borrow().get(&cv) {
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);
151 let gv = addr_of_mut(ccx, cv, align, kind);
153 llvm::LLVMSetGlobalConstant(gv, True);
155 ccx.const_globals().borrow_mut().insert(cv, gv);
159 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
160 let v = match cx.const_unsized().borrow().get(&v) {
165 llvm::LLVMGetInitializer(v)
169 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
172 -> (ValueRef, Ty<'tcx>) {
173 match ty.builtin_deref(true, ty::NoPreference) {
175 if type_is_sized(cx.tcx(), mt.ty) {
176 (const_deref_ptr(cx, v), mt.ty)
178 // Derefing a fat pointer does not change the representation,
179 // just the type to the unsized contents.
184 cx.sess().bug(&format!("unexpected dereferenceable type {:?}",
190 fn const_fn_call<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
191 node: ExprOrMethodCall,
193 arg_vals: &[ValueRef],
194 param_substs: &'tcx Substs<'tcx>) -> ValueRef {
195 let fn_like = const_eval::lookup_const_fn_by_id(ccx.tcx(), def_id);
196 let fn_like = fn_like.expect("lookup_const_fn_by_id failed in const_fn_call");
198 let args = &fn_like.decl().inputs;
199 assert_eq!(args.len(), arg_vals.len());
201 let arg_ids = args.iter().map(|arg| arg.pat.id);
202 let fn_args = arg_ids.zip(arg_vals.iter().cloned()).collect();
204 let substs = ccx.tcx().mk_substs(node_id_substs(ccx, node, param_substs));
205 match fn_like.body().expr {
207 const_expr(ccx, &**expr, substs, Some(&fn_args)).0
213 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
215 ref_expr: &hir::Expr)
217 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
219 if def_id.krate != LOCAL_CRATE {
220 ccx.sess().span_bug(ref_expr.span,
221 "cross crate constant could not be inlined");
224 match const_eval::lookup_const_by_id(ccx.tcx(), def_id, Some(ref_expr.id)) {
225 Some(ref expr) => expr,
227 ccx.sess().span_bug(ref_expr.span, "constant item not found")
232 fn get_const_val(ccx: &CrateContext,
234 ref_expr: &hir::Expr) -> ValueRef {
235 let expr = get_const_expr(ccx, def_id, ref_expr);
236 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
237 get_const_expr_as_global(ccx, expr, check_const::ConstQualif::empty(), empty_substs)
240 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
242 qualif: check_const::ConstQualif,
243 param_substs: &'tcx Substs<'tcx>)
245 debug!("get_const_expr_as_global: {:?}", expr.id);
246 // Special-case constants to cache a common global for all uses.
248 hir::ExprPath(..) => {
249 let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
251 def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
252 if !ccx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
253 debug!("get_const_expr_as_global ({:?}): found const {:?}",
255 return get_const_val(ccx, def_id, expr);
264 let key = (expr.id, param_substs);
265 match ccx.const_values().borrow().get(&key) {
266 Some(&val) => return val,
269 let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
270 &ccx.tcx().expr_ty(expr));
271 let val = if qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS) {
272 // Avoid autorefs as they would create global instead of stack
273 // references, even when only the latter are correct.
274 const_expr_unadjusted(ccx, expr, ty, param_substs, None)
276 const_expr(ccx, expr, param_substs, None).0
279 // boolean SSA values are i1, but they have to be stored in i8 slots,
280 // otherwise some LLVM optimization passes don't work as expected
282 if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
283 llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
289 let lvalue = addr_of(ccx, val, type_of::align_of(ccx, ty), "const");
290 ccx.const_values().borrow_mut().insert(key, lvalue);
294 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
296 param_substs: &'tcx Substs<'tcx>,
298 -> (ValueRef, Ty<'tcx>) {
299 let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
300 &cx.tcx().expr_ty(e));
301 let llconst = const_expr_unadjusted(cx, e, ety, param_substs, fn_args);
302 let mut llconst = llconst;
303 let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
304 &cx.tcx().expr_ty_adjusted(e));
305 let opt_adj = cx.tcx().tables.borrow().adjustments.get(&e.id).cloned();
307 Some(AdjustReifyFnPointer) => {
308 // FIXME(#19925) once fn item types are
309 // zero-sized, we'll need to do something here
311 Some(AdjustUnsafeFnPointer) => {
312 // purely a type-level thing
314 Some(AdjustDerefRef(adj)) => {
316 // Save the last autoderef in case we can avoid it.
317 if adj.autoderefs > 0 {
318 for _ in 0..adj.autoderefs-1 {
319 let (dv, dt) = const_deref(cx, llconst, ty);
325 if adj.autoref.is_some() {
326 if adj.autoderefs == 0 {
327 // Don't copy data to do a deref+ref
328 // (i.e., skip the last auto-deref).
329 llconst = addr_of(cx, llconst, type_of::align_of(cx, ty), "autoref");
330 ty = cx.tcx().mk_imm_ref(cx.tcx().mk_region(ty::ReStatic), ty);
333 let (dv, dt) = const_deref(cx, llconst, ty);
336 // If we derefed a fat pointer then we will have an
337 // open type here. So we need to update the type with
338 // the one returned from const_deref.
342 if let Some(target) = adj.unsize {
343 let target = monomorphize::apply_param_substs(cx.tcx(),
347 let pointee_ty = ty.builtin_deref(true, ty::NoPreference)
348 .expect("consts: unsizing got non-pointer type").ty;
349 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
350 // Normally, the source is a thin pointer and we are
351 // adding extra info to make a fat pointer. The exception
352 // is when we are upcasting an existing object fat pointer
353 // to use a different vtable. In that case, we want to
354 // load out the original data pointer so we can repackage
356 (const_get_elt(cx, llconst, &[abi::FAT_PTR_ADDR as u32]),
357 Some(const_get_elt(cx, llconst, &[abi::FAT_PTR_EXTRA as u32])))
362 let unsized_ty = target.builtin_deref(true, ty::NoPreference)
363 .expect("consts: unsizing got non-pointer target type").ty;
364 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
365 let base = ptrcast(base, ptr_ty);
366 let info = expr::unsized_info(cx, pointee_ty, unsized_ty,
367 old_info, param_substs);
369 if old_info.is_none() {
370 let prev_const = cx.const_unsized().borrow_mut()
371 .insert(base, llconst);
372 assert!(prev_const.is_none() || prev_const == Some(llconst));
374 assert_eq!(abi::FAT_PTR_ADDR, 0);
375 assert_eq!(abi::FAT_PTR_EXTRA, 1);
376 llconst = C_struct(cx, &[base, info], false);
382 let llty = type_of::sizing_type_of(cx, ety_adjusted);
383 let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
384 let tsize = machine::llsize_of_alloc(cx, llty);
386 cx.sess().abort_if_errors();
388 // FIXME these values could use some context
389 llvm::LLVMDumpValue(llconst);
390 llvm::LLVMDumpValue(C_undef(llty));
392 cx.sess().bug(&format!("const {:?} of type {:?} has size {} instead of {}",
396 (llconst, ety_adjusted)
399 fn check_unary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
401 // The only kind of unary expression that we check for validity
402 // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
403 if let hir::ExprUnary(hir::UnNeg, ref inner_e) = e.node {
405 // An unfortunate special case: we parse e.g. -128 as a
406 // negation of the literal 128, which means if we're expecting
407 // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
408 // 128 will have already overflowed to -128, and so then the
409 // constant evaluator thinks we're trying to negate -128.
411 // Catch this up front by looking for ExprLit directly,
412 // and just accepting it.
413 if let hir::ExprLit(_) = inner_e.node { return; }
415 let result = match t.sty {
416 ty::TyInt(int_type) => {
417 let input = match const_to_opt_int(te) {
421 const_int_checked_neg(
422 input, e, Some(const_eval::IntTy::from(cx.tcx(), int_type)))
424 ty::TyUint(uint_type) => {
425 let input = match const_to_opt_uint(te) {
429 const_uint_checked_neg(
430 input, e, Some(const_eval::UintTy::from(cx.tcx(), uint_type)))
435 // We do not actually care about a successful result.
436 if let Err(err) = result {
437 cx.tcx().sess.span_err(e.span, &err.description());
442 fn check_binary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
443 te1: ValueRef, te2: ValueRef) {
444 let b = if let hir::ExprBinary(b, _, _) = e.node { b } else { return };
446 let result = match t.sty {
447 ty::TyInt(int_type) => {
448 let (lhs, rhs) = match (const_to_opt_int(te1),
449 const_to_opt_int(te2)) {
450 (Some(v1), Some(v2)) => (v1, v2),
454 let opt_ety = Some(const_eval::IntTy::from(cx.tcx(), int_type));
456 hir::BiAdd => const_int_checked_add(lhs, rhs, e, opt_ety),
457 hir::BiSub => const_int_checked_sub(lhs, rhs, e, opt_ety),
458 hir::BiMul => const_int_checked_mul(lhs, rhs, e, opt_ety),
459 hir::BiDiv => const_int_checked_div(lhs, rhs, e, opt_ety),
460 hir::BiRem => const_int_checked_rem(lhs, rhs, e, opt_ety),
461 hir::BiShl => const_int_checked_shl(lhs, rhs, e, opt_ety),
462 hir::BiShr => const_int_checked_shr(lhs, rhs, e, opt_ety),
466 ty::TyUint(uint_type) => {
467 let (lhs, rhs) = match (const_to_opt_uint(te1),
468 const_to_opt_uint(te2)) {
469 (Some(v1), Some(v2)) => (v1, v2),
473 let opt_ety = Some(const_eval::UintTy::from(cx.tcx(), uint_type));
475 hir::BiAdd => const_uint_checked_add(lhs, rhs, e, opt_ety),
476 hir::BiSub => const_uint_checked_sub(lhs, rhs, e, opt_ety),
477 hir::BiMul => const_uint_checked_mul(lhs, rhs, e, opt_ety),
478 hir::BiDiv => const_uint_checked_div(lhs, rhs, e, opt_ety),
479 hir::BiRem => const_uint_checked_rem(lhs, rhs, e, opt_ety),
480 hir::BiShl => const_uint_checked_shl(lhs, rhs, e, opt_ety),
481 hir::BiShr => const_uint_checked_shr(lhs, rhs, e, opt_ety),
487 // We do not actually care about a successful result.
488 if let Err(err) = result {
489 cx.tcx().sess.span_err(e.span, &err.description());
493 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
496 param_substs: &'tcx Substs<'tcx>,
500 debug!("const_expr_unadjusted(e={:?}, ety={:?}, param_substs={:?})",
505 let map_list = |exprs: &[P<hir::Expr>]| -> Vec<ValueRef> {
507 .map(|e| const_expr(cx, &**e, param_substs, fn_args).0)
510 let _icx = push_ctxt("const_expr");
512 hir::ExprLit(ref lit) => {
513 const_lit(cx, e, &**lit)
515 hir::ExprBinary(b, ref e1, ref e2) => {
516 /* Neither type is bottom, and we expect them to be unified
517 * already, so the following is safe. */
518 let (te1, ty) = const_expr(cx, &**e1, param_substs, fn_args);
519 debug!("const_expr_unadjusted: te1={}, ty={:?}",
520 cx.tn().val_to_string(te1),
522 assert!(!ty.is_simd());
523 let is_float = ty.is_fp();
524 let signed = ty.is_signed();
526 let (te2, _) = const_expr(cx, &**e2, param_substs, fn_args);
528 check_binary_expr_validity(cx, e, ty, te1, te2);
530 unsafe { match b.node {
531 hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
532 hir::BiAdd => llvm::LLVMConstAdd(te1, te2),
534 hir::BiSub if is_float => llvm::LLVMConstFSub(te1, te2),
535 hir::BiSub => llvm::LLVMConstSub(te1, te2),
537 hir::BiMul if is_float => llvm::LLVMConstFMul(te1, te2),
538 hir::BiMul => llvm::LLVMConstMul(te1, te2),
540 hir::BiDiv if is_float => llvm::LLVMConstFDiv(te1, te2),
541 hir::BiDiv if signed => llvm::LLVMConstSDiv(te1, te2),
542 hir::BiDiv => llvm::LLVMConstUDiv(te1, te2),
544 hir::BiRem if is_float => llvm::LLVMConstFRem(te1, te2),
545 hir::BiRem if signed => llvm::LLVMConstSRem(te1, te2),
546 hir::BiRem => llvm::LLVMConstURem(te1, te2),
548 hir::BiAnd => llvm::LLVMConstAnd(te1, te2),
549 hir::BiOr => llvm::LLVMConstOr(te1, te2),
550 hir::BiBitXor => llvm::LLVMConstXor(te1, te2),
551 hir::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
552 hir::BiBitOr => llvm::LLVMConstOr(te1, te2),
554 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
555 llvm::LLVMConstShl(te1, te2)
558 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
559 if signed { llvm::LLVMConstAShr(te1, te2) }
560 else { llvm::LLVMConstLShr(te1, te2) }
562 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe => {
564 let cmp = base::bin_op_to_fcmp_predicate(cx, b.node);
565 ConstFCmp(cmp, te1, te2)
567 let cmp = base::bin_op_to_icmp_predicate(cx, b.node, signed);
568 ConstICmp(cmp, te1, te2)
571 } } // unsafe { match b.node {
573 hir::ExprUnary(u, ref inner_e) => {
574 let (te, ty) = const_expr(cx, &**inner_e, param_substs, fn_args);
576 check_unary_expr_validity(cx, e, ty, te);
578 let is_float = ty.is_fp();
580 hir::UnDeref => const_deref(cx, te, ty).0,
581 hir::UnNot => llvm::LLVMConstNot(te),
582 hir::UnNeg if is_float => llvm::LLVMConstFNeg(te),
583 hir::UnNeg => llvm::LLVMConstNeg(te),
586 hir::ExprField(ref base, field) => {
587 let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
588 let brepr = adt::represent_type(cx, bt);
589 let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
590 let ix = vinfo.field_index(field.node);
591 adt::const_get_field(cx, &*brepr, bv, vinfo.discr, ix)
593 hir::ExprTupField(ref base, idx) => {
594 let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
595 let brepr = adt::represent_type(cx, bt);
596 let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
597 adt::const_get_field(cx, &*brepr, bv, vinfo.discr, idx.node)
600 hir::ExprIndex(ref base, ref index) => {
601 let (bv, bt) = const_expr(cx, &**base, param_substs, fn_args);
602 let iv = match eval_const_expr_partial(cx.tcx(), &index, ExprTypeChecked) {
603 Ok(ConstVal::Int(i)) => i as u64,
604 Ok(ConstVal::Uint(u)) => u,
605 _ => cx.sess().span_bug(index.span,
606 "index is not an integer-constant expression")
608 let (arr, len) = match bt.sty {
609 ty::TyArray(_, u) => (bv, C_uint(cx, u)),
610 ty::TySlice(_) | ty::TyStr => {
611 let e1 = const_get_elt(cx, bv, &[0]);
612 (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
614 ty::TyRef(_, mt) => match mt.ty.sty {
615 ty::TyArray(_, u) => {
616 (const_deref_ptr(cx, bv), C_uint(cx, u))
618 _ => cx.sess().span_bug(base.span,
619 &format!("index-expr base must be a vector \
620 or string type, found {:?}",
623 _ => cx.sess().span_bug(base.span,
624 &format!("index-expr base must be a vector \
625 or string type, found {:?}",
629 let len = unsafe { llvm::LLVMConstIntGetZExtValue(len) as u64 };
630 let len = match bt.sty {
631 ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => match ty.sty {
641 // FIXME #3170: report this earlier on in the const-eval
642 // pass. Reporting here is a bit late.
643 span_err!(cx.sess(), e.span, E0515,
644 "const index-expr is out of bounds");
645 C_undef(val_ty(arr).element_type())
647 const_get_elt(cx, arr, &[iv as c_uint])
650 hir::ExprCast(ref base, _) => {
652 let llty = type_of::type_of(cx, t_cast);
653 let (v, t_expr) = const_expr(cx, &**base, param_substs, fn_args);
654 debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
655 if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
658 if type_is_fat_ptr(cx.tcx(), t_expr) {
659 // Fat pointer casts.
661 t_cast.builtin_deref(true, ty::NoPreference).expect("cast to non-pointer").ty;
662 let ptr_ty = type_of::in_memory_type_of(cx, t_cast_inner).ptr_to();
663 let addr = ptrcast(const_get_elt(cx, v, &[abi::FAT_PTR_ADDR as u32]),
665 if type_is_fat_ptr(cx.tcx(), t_cast) {
666 let info = const_get_elt(cx, v, &[abi::FAT_PTR_EXTRA as u32]);
667 return C_struct(cx, &[addr, info], false)
673 CastTy::from_ty(t_expr).expect("bad input type for cast"),
674 CastTy::from_ty(t_cast).expect("bad output type for cast"),
676 (CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
677 let repr = adt::represent_type(cx, t_expr);
678 let discr = adt::const_get_discrim(cx, &*repr, v);
679 let iv = C_integral(cx.int_type(), discr, false);
680 let s = adt::is_discr_signed(&*repr) as Bool;
681 llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
683 (CastTy::Int(_), CastTy::Int(_)) => {
684 let s = t_expr.is_signed() as Bool;
685 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
687 (CastTy::Int(_), CastTy::Float) => {
688 if t_expr.is_signed() {
689 llvm::LLVMConstSIToFP(v, llty.to_ref())
691 llvm::LLVMConstUIToFP(v, llty.to_ref())
694 (CastTy::Float, CastTy::Float) => llvm::LLVMConstFPCast(v, llty.to_ref()),
695 (CastTy::Float, CastTy::Int(IntTy::I)) => llvm::LLVMConstFPToSI(v, llty.to_ref()),
696 (CastTy::Float, CastTy::Int(_)) => llvm::LLVMConstFPToUI(v, llty.to_ref()),
697 (CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FnPtr, CastTy::Ptr(_))
698 | (CastTy::RPtr(_), CastTy::Ptr(_)) => {
701 (CastTy::FnPtr, CastTy::FnPtr) => ptrcast(v, llty), // isn't this a coercion?
702 (CastTy::Int(_), CastTy::Ptr(_)) => llvm::LLVMConstIntToPtr(v, llty.to_ref()),
703 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
704 llvm::LLVMConstPtrToInt(v, llty.to_ref())
707 cx.sess().impossible_case(e.span,
708 "bad combination of types for cast")
710 } } // unsafe { match ( ... ) {
712 hir::ExprAddrOf(hir::MutImmutable, ref sub) => {
713 // If this is the address of some static, then we need to return
714 // the actual address of the static itself (short circuit the rest
719 hir::ExprBlock(ref blk) => {
720 if let Some(ref sub) = blk.expr {
729 let opt_def = cx.tcx().def_map.borrow().get(&cur.id).map(|d| d.full_def());
730 if let Some(def::DefStatic(def_id, _)) = opt_def {
731 get_static_val(cx, def_id, ety)
733 // If this isn't the address of a static, then keep going through
734 // normal constant evaluation.
735 let (v, ty) = const_expr(cx, &**sub, param_substs, fn_args);
736 addr_of(cx, v, type_of::align_of(cx, ty), "ref")
739 hir::ExprAddrOf(hir::MutMutable, ref sub) => {
740 let (v, ty) = const_expr(cx, &**sub, param_substs, fn_args);
741 addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
743 hir::ExprTup(ref es) => {
744 let repr = adt::represent_type(cx, ety);
745 let vals = map_list(&es[..]);
746 adt::trans_const(cx, &*repr, 0, &vals[..])
748 hir::ExprStruct(_, ref fs, ref base_opt) => {
749 let repr = adt::represent_type(cx, ety);
751 let base_val = match *base_opt {
752 Some(ref base) => Some(const_expr(cx, &**base, param_substs, fn_args)),
756 let VariantInfo { discr, fields } = VariantInfo::of_node(cx.tcx(), ety, e.id);
757 let cs = fields.iter().enumerate().map(|(ix, &Field(f_name, _))| {
758 match (fs.iter().find(|f| f_name == f.name.node), base_val) {
759 (Some(ref f), _) => const_expr(cx, &*f.expr, param_substs, fn_args).0,
760 (_, Some((bv, _))) => adt::const_get_field(cx, &*repr, bv, discr, ix),
761 (_, None) => cx.sess().span_bug(e.span, "missing struct field"),
763 }).collect::<Vec<_>>();
767 adt::trans_const(cx, &*repr, discr, &cs[..])
770 hir::ExprVec(ref es) => {
771 let unit_ty = ety.sequence_element_type(cx.tcx());
772 let llunitty = type_of::type_of(cx, unit_ty);
774 .map(|e| const_expr(cx, &**e, param_substs, fn_args).0)
775 .collect::<Vec<_>>();
776 // If the vector contains enums, an LLVM array won't work.
777 if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
778 C_struct(cx, &vs[..], false)
780 C_array(llunitty, &vs[..])
783 hir::ExprRepeat(ref elem, ref count) => {
784 let unit_ty = ety.sequence_element_type(cx.tcx());
785 let llunitty = type_of::type_of(cx, unit_ty);
786 let n = cx.tcx().eval_repeat_count(count);
787 let unit_val = const_expr(cx, &**elem, param_substs, fn_args).0;
788 let vs = vec![unit_val; n];
789 if val_ty(unit_val) != llunitty {
790 C_struct(cx, &vs[..], false)
792 C_array(llunitty, &vs[..])
795 hir::ExprPath(..) => {
796 let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def();
798 def::DefLocal(_, id) => {
799 if let Some(val) = fn_args.and_then(|args| args.get(&id).cloned()) {
802 cx.sess().span_bug(e.span, "const fn argument not found")
805 def::DefFn(..) | def::DefMethod(..) => {
806 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
808 def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
809 const_deref_ptr(cx, get_const_val(cx, def_id, e))
811 def::DefVariant(enum_did, variant_did, _) => {
812 let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
814 ty::VariantKind::Unit => {
815 let repr = adt::represent_type(cx, ety);
816 adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
818 ty::VariantKind::Tuple => {
819 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
821 ty::VariantKind::Struct => {
822 cx.sess().span_bug(e.span, "path-expr refers to a dict variant!")
826 def::DefStruct(_) => {
827 if let ty::TyBareFn(..) = ety.sty {
829 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
832 C_null(type_of::type_of(cx, ety))
836 cx.sess().span_bug(e.span, "expected a const, fn, struct, \
841 hir::ExprCall(ref callee, ref args) => {
842 let mut callee = &**callee;
844 callee = match callee.node {
845 hir::ExprBlock(ref block) => match block.expr {
846 Some(ref tail) => &**tail,
852 let def = cx.tcx().def_map.borrow()[&callee.id].full_def();
853 let arg_vals = map_list(args);
855 def::DefFn(did, _) | def::DefMethod(did) => {
856 const_fn_call(cx, ExprId(callee.id), did, &arg_vals, param_substs)
858 def::DefStruct(_) => {
860 C_vector(&arg_vals[..])
862 let repr = adt::represent_type(cx, ety);
863 adt::trans_const(cx, &*repr, 0, &arg_vals[..])
866 def::DefVariant(enum_did, variant_did, _) => {
867 let repr = adt::represent_type(cx, ety);
868 let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
874 _ => cx.sess().span_bug(e.span, "expected a struct, variant, or const fn def"),
877 hir::ExprMethodCall(_, _, ref args) => {
878 let arg_vals = map_list(args);
879 let method_call = ty::MethodCall::expr(e.id);
880 let method_did = cx.tcx().tables.borrow().method_map[&method_call].def_id;
881 const_fn_call(cx, MethodCallKey(method_call),
882 method_did, &arg_vals, param_substs)
884 hir::ExprBlock(ref block) => {
886 Some(ref expr) => const_expr(cx, &**expr, param_substs, fn_args).0,
890 hir::ExprClosure(_, ref decl, ref body) => {
892 ty::TyClosure(def_id, ref substs) => {
893 closure::trans_closure_expr(closure::Dest::Ignore(cx), decl,
894 body, e.id, def_id, substs);
899 &format!("bad type for closure expr: {:?}", ety))
901 C_null(type_of::type_of(cx, ety))
903 _ => cx.sess().span_bug(e.span,
904 "bad constant expression type in consts::const_expr"),
907 pub fn trans_static(ccx: &CrateContext,
911 attrs: &Vec<ast::Attribute>)
914 let _icx = push_ctxt("trans_static");
915 let g = base::get_item_val(ccx, id);
917 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
918 let (v, _) = const_expr(ccx, expr, empty_substs, None);
920 // boolean SSA values are i1, but they have to be stored in i8 slots,
921 // otherwise some LLVM optimization passes don't work as expected
922 let mut val_llty = llvm::LLVMTypeOf(v);
923 let v = if val_llty == Type::i1(ccx).to_ref() {
924 val_llty = Type::i8(ccx).to_ref();
925 llvm::LLVMConstZExt(v, val_llty)
930 let ty = ccx.tcx().node_id_to_type(id);
931 let llty = type_of::type_of(ccx, ty);
932 let g = if val_llty == llty.to_ref() {
935 // If we created the global with the wrong type,
937 let empty_string = CString::new("").unwrap();
938 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
939 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
940 llvm::LLVMSetValueName(g, empty_string.as_ptr());
941 let new_g = llvm::LLVMGetOrInsertGlobal(
942 ccx.llmod(), name_string.as_ptr(), val_llty);
943 // To avoid breaking any invariants, we leave around the old
944 // global for the moment; we'll replace all references to it
945 // with the new global later. (See base::trans_crate.)
946 ccx.statics_to_rauw().borrow_mut().push((g, new_g));
949 llvm::LLVMSetAlignment(g, type_of::align_of(ccx, ty));
950 llvm::LLVMSetInitializer(g, v);
952 // As an optimization, all shared statics which do not have interior
953 // mutability are placed into read-only memory.
954 if m != hir::MutMutable {
955 let tcontents = ty.type_contents(ccx.tcx());
956 if !tcontents.interior_unsafe() {
957 llvm::LLVMSetGlobalConstant(g, llvm::True);
961 debuginfo::create_global_var_metadata(ccx, id, g);
963 if attr::contains_name(attrs,
965 llvm::set_thread_local(g, true);
972 fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
976 if let Some(node_id) = ccx.tcx().map.as_local_node_id(did) {
977 base::get_item_val(ccx, node_id)
979 base::trans_external_path(ccx, did, ty)