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.
13 use lib::llvm::{llvm, ConstFCmp, ConstICmp, SetLinkage, PrivateLinkage, ValueRef, Bool, True};
14 use lib::llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE,
15 RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE};
17 use metadata::csearch;
18 use middle::const_eval;
19 use middle::trans::adt;
20 use middle::trans::base;
21 use middle::trans::base::push_ctxt;
22 use middle::trans::common::*;
23 use middle::trans::consts;
24 use middle::trans::expr;
25 use middle::trans::inline;
26 use middle::trans::machine;
27 use middle::trans::type_of;
29 use util::ppaux::{Repr, ty_to_str};
31 use middle::trans::type_::Type;
33 use std::c_str::ToCStr;
34 use std::libc::c_uint;
36 use syntax::{ast, ast_util, ast_map};
38 pub fn const_lit(cx: &mut CrateContext, e: &ast::Expr, lit: ast::lit)
40 let _icx = push_ctxt("trans_lit");
42 ast::lit_char(i) => C_integral(Type::char(), i as u64, false),
43 ast::lit_int(i, t) => C_integral(Type::int_from_ty(cx, t), i as u64, true),
44 ast::lit_uint(u, t) => C_integral(Type::uint_from_ty(cx, t), u, false),
45 ast::lit_int_unsuffixed(i) => {
46 let lit_int_ty = ty::node_id_to_type(cx.tcx, e.id);
47 match ty::get(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 or uint)",
56 ty_to_str(cx.tcx, lit_int_ty)))
59 ast::lit_float(fs, t) => C_floating(fs, Type::float_from_ty(t)),
60 ast::lit_float_unsuffixed(fs) => {
61 let lit_float_ty = ty::node_id_to_type(cx.tcx, e.id);
62 match ty::get(lit_float_ty).sty {
64 C_floating(fs, Type::float_from_ty(t))
67 cx.sess.span_bug(lit.span,
68 "floating point literal doesn't have the right type");
72 ast::lit_bool(b) => C_bool(b),
73 ast::lit_nil => C_nil(),
74 ast::lit_str(s, _) => C_estr_slice(cx, s)
78 pub fn const_ptrcast(cx: &mut CrateContext, a: ValueRef, t: Type) -> ValueRef {
80 let b = llvm::LLVMConstPointerCast(a, t.ptr_to().to_ref());
81 assert!(cx.const_globals.insert(b as int, a));
86 pub fn const_vec(cx: @mut CrateContext, e: &ast::Expr, es: &[@ast::Expr])
87 -> (ValueRef, ValueRef, Type, bool) {
89 let vec_ty = ty::expr_ty(cx.tcx, e);
90 let unit_ty = ty::sequence_element_type(cx.tcx, vec_ty);
91 let llunitty = type_of::type_of(cx, unit_ty);
92 let unit_sz = machine::llsize_of(cx, llunitty);
93 let sz = llvm::LLVMConstMul(C_uint(cx, es.len()), unit_sz);
94 let (vs, inlineable) = vec::unzip(es.iter().map(|e| const_expr(cx, *e)));
95 // If the vector contains enums, an LLVM array won't work.
96 let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
101 return (v, sz, llunitty, inlineable.iter().fold(true, |a, &b| a && b));
105 fn const_addr_of(cx: &mut CrateContext, cv: ValueRef) -> ValueRef {
107 let gv = do "const".with_c_str |name| {
108 llvm::LLVMAddGlobal(cx.llmod, val_ty(cv).to_ref(), name)
110 llvm::LLVMSetInitializer(gv, cv);
111 llvm::LLVMSetGlobalConstant(gv, True);
112 SetLinkage(gv, PrivateLinkage);
117 fn const_deref_ptr(cx: &mut CrateContext, v: ValueRef) -> ValueRef {
118 let v = match cx.const_globals.find(&(v as int)) {
123 assert_eq!(llvm::LLVMIsGlobalConstant(v), True);
124 llvm::LLVMGetInitializer(v)
128 fn const_deref_newtype(cx: &mut CrateContext, v: ValueRef, t: ty::t)
130 let repr = adt::represent_type(cx, t);
131 adt::const_get_field(cx, repr, v, 0, 0)
134 fn const_deref(cx: &mut CrateContext, v: ValueRef, t: ty::t, explicit: bool)
135 -> (ValueRef, ty::t) {
136 match ty::deref(cx.tcx, t, explicit) {
138 assert!(mt.mutbl != ast::MutMutable);
139 let dv = match ty::get(t).sty {
140 ty::ty_ptr(*) | ty::ty_rptr(*) => {
141 const_deref_ptr(cx, v)
143 ty::ty_enum(*) | ty::ty_struct(*) => {
144 const_deref_newtype(cx, v, t)
147 cx.sess.bug(format!("Unexpected dereferenceable type {}",
148 ty_to_str(cx.tcx, t)))
154 cx.sess.bug(format!("Can't dereference const of type {}",
155 ty_to_str(cx.tcx, t)))
160 pub fn get_const_val(cx: @mut CrateContext,
161 mut def_id: ast::DefId) -> (ValueRef, bool) {
162 let contains_key = cx.const_values.contains_key(&def_id.node);
163 if !ast_util::is_local(def_id) || !contains_key {
164 if !ast_util::is_local(def_id) {
165 def_id = inline::maybe_instantiate_inline(cx, def_id);
167 match cx.tcx.items.get_copy(&def_id.node) {
168 ast_map::node_item(@ast::item {
169 node: ast::item_static(_, ast::MutImmutable, _), _
171 trans_const(cx, ast::MutImmutable, def_id.node);
173 _ => cx.tcx.sess.bug("expected a const to be an item")
176 (cx.const_values.get_copy(&def_id.node),
177 !cx.non_inlineable_statics.contains(&def_id.node))
180 pub fn const_expr(cx: @mut CrateContext, e: &ast::Expr) -> (ValueRef, bool) {
181 let (llconst, inlineable) = const_expr_unadjusted(cx, e);
182 let mut llconst = llconst;
183 let mut inlineable = inlineable;
184 let ety = ty::expr_ty(cx.tcx, e);
185 let adjustment = cx.tcx.adjustments.find_copy(&e.id);
188 Some(@ty::AutoAddEnv(ty::re_static, ast::BorrowedSigil)) => {
189 llconst = C_struct([llconst, C_null(Type::opaque_box(cx).ptr_to())], false)
191 Some(@ty::AutoAddEnv(ref r, ref s)) => {
192 cx.sess.span_bug(e.span, format!("unexpected static function: \
193 region {:?} sigil {:?}", *r, *s))
195 Some(@ty::AutoDerefRef(ref adj)) => {
197 let mut maybe_ptr = None;
198 do adj.autoderefs.times {
199 let (dv, dt) = const_deref(cx, llconst, ty, false);
200 maybe_ptr = Some(llconst);
207 Some(ref autoref) => {
208 // Don't copy data to do a deref+ref.
209 let llptr = match maybe_ptr {
213 const_addr_of(cx, llconst)
218 ty::AutoPtr(ty::re_static, m) => {
219 assert!(m != ast::MutMutable);
222 ty::AutoBorrowVec(ty::re_static, m) => {
223 assert!(m != ast::MutMutable);
224 assert_eq!(abi::slice_elt_base, 0);
225 assert_eq!(abi::slice_elt_len, 1);
227 match ty::get(ty).sty {
228 ty::ty_evec(_, ty::vstore_fixed(*)) => {
229 let size = machine::llsize_of(cx, val_ty(llconst));
230 llconst = C_struct([llptr, size], false);
236 cx.sess.span_bug(e.span,
237 format!("unimplemented const \
238 autoref {:?}", autoref))
246 let ety_adjusted = ty::expr_ty_adjusted(cx.tcx, e);
247 let llty = type_of::sizing_type_of(cx, ety_adjusted);
248 let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
249 let tsize = machine::llsize_of_alloc(cx, llty);
252 // XXX these values could use some context
253 llvm::LLVMDumpValue(llconst);
254 llvm::LLVMDumpValue(C_undef(llty));
256 cx.sess.bug(format!("const {} of type {} has size {} instead of {}",
257 e.repr(cx.tcx), ty_to_str(cx.tcx, ety),
260 (llconst, inlineable)
263 // the bool returned is whether this expression can be inlined into other crates
264 // if it's assigned to a static.
265 fn const_expr_unadjusted(cx: @mut CrateContext,
266 e: &ast::Expr) -> (ValueRef, bool) {
267 fn map_list(cx: @mut CrateContext,
268 exprs: &[@ast::Expr]) -> (~[ValueRef], bool) {
269 exprs.iter().map(|&e| const_expr(cx, e))
270 .fold((~[], true), |(L, all_inlineable), (val, inlineable)| {
271 (vec::append_one(L, val), all_inlineable && inlineable)
275 let _icx = push_ctxt("const_expr");
276 return match e.node {
277 ast::ExprLit(lit) => (consts::const_lit(cx, e, *lit), true),
278 ast::ExprBinary(_, b, e1, e2) => {
279 let (te1, _) = const_expr(cx, e1);
280 let (te2, _) = const_expr(cx, e2);
282 let te2 = base::cast_shift_const_rhs(b, te1, te2);
284 /* Neither type is bottom, and we expect them to be unified
285 * already, so the following is safe. */
286 let ty = ty::expr_ty(cx.tcx, e1);
287 let is_float = ty::type_is_fp(ty);
288 let signed = ty::type_is_signed(ty);
291 if is_float { llvm::LLVMConstFAdd(te1, te2) }
292 else { llvm::LLVMConstAdd(te1, te2) }
295 if is_float { llvm::LLVMConstFSub(te1, te2) }
296 else { llvm::LLVMConstSub(te1, te2) }
299 if is_float { llvm::LLVMConstFMul(te1, te2) }
300 else { llvm::LLVMConstMul(te1, te2) }
303 if is_float { llvm::LLVMConstFDiv(te1, te2) }
304 else if signed { llvm::LLVMConstSDiv(te1, te2) }
305 else { llvm::LLVMConstUDiv(te1, te2) }
308 if is_float { llvm::LLVMConstFRem(te1, te2) }
309 else if signed { llvm::LLVMConstSRem(te1, te2) }
310 else { llvm::LLVMConstURem(te1, te2) }
312 ast::BiAnd => llvm::LLVMConstAnd(te1, te2),
313 ast::BiOr => llvm::LLVMConstOr(te1, te2),
314 ast::BiBitXor => llvm::LLVMConstXor(te1, te2),
315 ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
316 ast::BiBitOr => llvm::LLVMConstOr(te1, te2),
317 ast::BiShl => llvm::LLVMConstShl(te1, te2),
319 if signed { llvm::LLVMConstAShr(te1, te2) }
320 else { llvm::LLVMConstLShr(te1, te2) }
323 if is_float { ConstFCmp(RealOEQ, te1, te2) }
324 else { ConstICmp(IntEQ, te1, te2) }
327 if is_float { ConstFCmp(RealOLT, te1, te2) }
329 if signed { ConstICmp(IntSLT, te1, te2) }
330 else { ConstICmp(IntULT, te1, te2) }
334 if is_float { ConstFCmp(RealOLE, te1, te2) }
336 if signed { ConstICmp(IntSLE, te1, te2) }
337 else { ConstICmp(IntULE, te1, te2) }
341 if is_float { ConstFCmp(RealONE, te1, te2) }
342 else { ConstICmp(IntNE, te1, te2) }
345 if is_float { ConstFCmp(RealOGE, te1, te2) }
347 if signed { ConstICmp(IntSGE, te1, te2) }
348 else { ConstICmp(IntUGE, te1, te2) }
352 if is_float { ConstFCmp(RealOGT, te1, te2) }
354 if signed { ConstICmp(IntSGT, te1, te2) }
355 else { ConstICmp(IntUGT, te1, te2) }
360 ast::ExprUnary(_, u, e) => {
361 let (te, _) = const_expr(cx, e);
362 let ty = ty::expr_ty(cx.tcx, e);
363 let is_float = ty::type_is_fp(ty);
368 let (dv, _dt) = const_deref(cx, te, ty, true);
372 match ty::get(ty).sty {
374 // Somewhat questionable, but I believe this is
376 let te = llvm::LLVMConstTrunc(te, Type::i1().to_ref());
377 let te = llvm::LLVMConstNot(te);
378 llvm::LLVMConstZExt(te, Type::bool().to_ref())
380 _ => llvm::LLVMConstNot(te),
384 if is_float { llvm::LLVMConstFNeg(te) }
385 else { llvm::LLVMConstNeg(te) }
389 ast::ExprField(base, field, _) => {
390 let bt = ty::expr_ty_adjusted(cx.tcx, base);
391 let brepr = adt::represent_type(cx, bt);
392 let (bv, inlineable) = const_expr(cx, base);
393 do expr::with_field_tys(cx.tcx, bt, None) |discr, field_tys| {
394 let ix = ty::field_idx_strict(cx.tcx, field.name, field_tys);
395 (adt::const_get_field(cx, brepr, bv, discr, ix), inlineable)
399 ast::ExprIndex(_, base, index) => {
400 let bt = ty::expr_ty_adjusted(cx.tcx, base);
401 let (bv, inlineable) = const_expr(cx, base);
402 let iv = match const_eval::eval_const_expr(cx.tcx, index) {
403 const_eval::const_int(i) => i as u64,
404 const_eval::const_uint(u) => u,
405 _ => cx.sess.span_bug(index.span,
406 "index is not an integer-constant expression")
408 let (arr, len) = match ty::get(bt).sty {
409 ty::ty_evec(_, vstore) | ty::ty_estr(vstore) =>
411 ty::vstore_fixed(u) =>
414 ty::vstore_slice(_) => {
415 let unit_ty = ty::sequence_element_type(cx.tcx, bt);
416 let llunitty = type_of::type_of(cx, unit_ty);
417 let unit_sz = machine::llsize_of(cx, llunitty);
419 let e1 = const_get_elt(cx, bv, [0]);
420 (const_deref_ptr(cx, e1),
421 llvm::LLVMConstUDiv(const_get_elt(cx, bv, [1]),
424 _ => cx.sess.span_bug(base.span,
425 "index-expr base must be fixed-size or slice")
427 _ => cx.sess.span_bug(base.span,
428 "index-expr base must be a vector or string type")
431 let len = llvm::LLVMConstIntGetZExtValue(len) as u64;
432 let len = match ty::get(bt).sty {
433 ty::ty_estr(*) => {assert!(len > 0); len - 1},
437 // FIXME #3170: report this earlier on in the const-eval
438 // pass. Reporting here is a bit late.
439 cx.sess.span_err(e.span,
440 "const index-expr is out of bounds");
442 (const_get_elt(cx, arr, [iv as c_uint]), inlineable)
444 ast::ExprCast(base, _) => {
445 let ety = ty::expr_ty(cx.tcx, e);
446 let llty = type_of::type_of(cx, ety);
447 let basety = ty::expr_ty(cx.tcx, base);
448 let (v, inlineable) = const_expr(cx, base);
449 return (match (expr::cast_type_kind(basety),
450 expr::cast_type_kind(ety)) {
452 (expr::cast_integral, expr::cast_integral) => {
453 let s = ty::type_is_signed(basety) as Bool;
454 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
456 (expr::cast_integral, expr::cast_float) => {
457 if ty::type_is_signed(basety) {
458 llvm::LLVMConstSIToFP(v, llty.to_ref())
460 llvm::LLVMConstUIToFP(v, llty.to_ref())
463 (expr::cast_float, expr::cast_float) => {
464 llvm::LLVMConstFPCast(v, llty.to_ref())
466 (expr::cast_float, expr::cast_integral) => {
467 if ty::type_is_signed(ety) { llvm::LLVMConstFPToSI(v, llty.to_ref()) }
468 else { llvm::LLVMConstFPToUI(v, llty.to_ref()) }
470 (expr::cast_enum, expr::cast_integral) |
471 (expr::cast_enum, expr::cast_float) => {
472 let repr = adt::represent_type(cx, basety);
473 let discr = adt::const_get_discrim(cx, repr, v);
474 let iv = C_integral(cx.int_type, discr, false);
475 let ety_cast = expr::cast_type_kind(ety);
477 expr::cast_integral => {
478 let s = ty::type_is_signed(ety) as Bool;
479 llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
481 expr::cast_float => llvm::LLVMConstUIToFP(iv, llty.to_ref()),
482 _ => cx.sess.bug("enum cast destination is not \
486 (expr::cast_pointer, expr::cast_pointer) => {
487 llvm::LLVMConstPointerCast(v, llty.to_ref())
489 (expr::cast_integral, expr::cast_pointer) => {
490 llvm::LLVMConstIntToPtr(v, llty.to_ref())
493 cx.sess.impossible_case(e.span,
494 "bad combination of types for cast")
498 ast::ExprAddrOf(ast::MutImmutable, sub) => {
499 let (e, _) = const_expr(cx, sub);
500 (const_addr_of(cx, e), false)
502 ast::ExprTup(ref es) => {
503 let ety = ty::expr_ty(cx.tcx, e);
504 let repr = adt::represent_type(cx, ety);
505 let (vals, inlineable) = map_list(cx, *es);
506 (adt::trans_const(cx, repr, 0, vals), inlineable)
508 ast::ExprStruct(_, ref fs, ref base_opt) => {
509 let ety = ty::expr_ty(cx.tcx, e);
510 let repr = adt::represent_type(cx, ety);
513 let base_val = match *base_opt {
514 Some(base) => Some(const_expr(cx, base)),
518 do expr::with_field_tys(tcx, ety, Some(e.id))
520 let cs = field_tys.iter().enumerate()
521 .map(|(ix, &field_ty)| {
522 match fs.iter().find(|f| field_ty.ident.name == f.ident.name) {
523 Some(f) => const_expr(cx, (*f).expr),
526 Some((bv, inlineable)) => {
527 (adt::const_get_field(cx, repr, bv, discr, ix),
530 None => cx.tcx.sess.span_bug(e.span, "missing struct field")
535 let (cs, inlineable) = vec::unzip(cs.move_iter());
536 (adt::trans_const(cx, repr, discr, cs),
537 inlineable.iter().fold(true, |a, &b| a && b))
540 ast::ExprVec(ref es, ast::MutImmutable) => {
541 let (v, _, _, inlineable) = const_vec(cx, e, *es);
544 ast::ExprVstore(sub, ast::ExprVstoreSlice) => {
546 ast::ExprLit(ref lit) => {
548 ast::lit_str(*) => { const_expr(cx, sub) }
549 _ => { cx.sess.span_bug(e.span, "bad const-slice lit") }
552 ast::ExprVec(ref es, ast::MutImmutable) => {
553 let (cv, sz, llunitty, _) = const_vec(cx, e, *es);
554 let llty = val_ty(cv);
555 let gv = do "const".with_c_str |name| {
556 llvm::LLVMAddGlobal(cx.llmod, llty.to_ref(), name)
558 llvm::LLVMSetInitializer(gv, cv);
559 llvm::LLVMSetGlobalConstant(gv, True);
560 SetLinkage(gv, PrivateLinkage);
561 let p = const_ptrcast(cx, gv, llunitty);
562 (C_struct([p, sz], false), false)
564 _ => cx.sess.span_bug(e.span, "bad const-slice expr")
567 ast::ExprRepeat(elem, count, _) => {
568 let vec_ty = ty::expr_ty(cx.tcx, e);
569 let unit_ty = ty::sequence_element_type(cx.tcx, vec_ty);
570 let llunitty = type_of::type_of(cx, unit_ty);
571 let n = match const_eval::eval_const_expr(cx.tcx, count) {
572 const_eval::const_int(i) => i as uint,
573 const_eval::const_uint(i) => i as uint,
574 _ => cx.sess.span_bug(count.span, "count must be integral const expression.")
576 let vs = vec::from_elem(n, const_expr(cx, elem).first());
577 let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
580 C_array(llunitty, vs)
584 ast::ExprPath(ref pth) => {
585 // Assert that there are no type parameters in this path.
586 assert!(pth.segments.iter().all(|seg| seg.types.is_empty()));
589 match tcx.def_map.find(&e.id) {
590 Some(&ast::DefFn(def_id, _purity)) => {
591 if !ast_util::is_local(def_id) {
592 let ty = csearch::get_type(cx.tcx, def_id).ty;
593 (base::trans_external_path(cx, def_id, ty), true)
595 assert!(ast_util::is_local(def_id));
596 (base::get_item_val(cx, def_id.node), true)
599 Some(&ast::DefStatic(def_id, false)) => {
600 get_const_val(cx, def_id)
602 Some(&ast::DefVariant(enum_did, variant_did, _)) => {
603 let ety = ty::expr_ty(cx.tcx, e);
604 let repr = adt::represent_type(cx, ety);
605 let vinfo = ty::enum_variant_with_id(cx.tcx,
608 (adt::trans_const(cx, repr, vinfo.disr_val, []), true)
610 Some(&ast::DefStruct(_)) => {
611 let ety = ty::expr_ty(cx.tcx, e);
612 let llty = type_of::type_of(cx, ety);
616 cx.sess.span_bug(e.span, "expected a const, fn, struct, or variant def")
620 ast::ExprCall(callee, ref args, _) => {
622 match tcx.def_map.find(&callee.id) {
623 Some(&ast::DefStruct(_)) => {
624 let ety = ty::expr_ty(cx.tcx, e);
625 let repr = adt::represent_type(cx, ety);
626 let (arg_vals, inlineable) = map_list(cx, *args);
627 (adt::trans_const(cx, repr, 0, arg_vals), inlineable)
629 Some(&ast::DefVariant(enum_did, variant_did, _)) => {
630 let ety = ty::expr_ty(cx.tcx, e);
631 let repr = adt::represent_type(cx, ety);
632 let vinfo = ty::enum_variant_with_id(cx.tcx,
635 let (arg_vals, inlineable) = map_list(cx, *args);
636 (adt::trans_const(cx, repr, vinfo.disr_val, arg_vals),
639 _ => cx.sess.span_bug(e.span, "expected a struct or variant def")
642 ast::ExprParen(e) => { const_expr(cx, e) }
643 _ => cx.sess.span_bug(e.span,
644 "bad constant expression type in consts::const_expr")
649 pub fn trans_const(ccx: @mut CrateContext, m: ast::Mutability, id: ast::NodeId) {
651 let _icx = push_ctxt("trans_const");
652 let g = base::get_item_val(ccx, id);
653 // At this point, get_item_val has already translated the
654 // constant's initializer to determine its LLVM type.
655 let v = ccx.const_values.get_copy(&id);
656 llvm::LLVMSetInitializer(g, v);
657 if m != ast::MutMutable {
658 llvm::LLVMSetGlobalConstant(g, True);