1 // Copyright 2012-2013 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.
11 // trans.rs: Translate the completed AST to the LLVM IR.
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
18 // Hopefully useful general knowledge about trans:
20 // * There's no way to find out the ty::t type of a ValueRef. Doing so
21 // would be "trying to get the eggs out of an omelette" (credit:
22 // pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 // but many TypeRefs correspond to one ty::t; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
27 use back::link::{mangle_exported_name};
28 use back::{link, abi};
30 use driver::session::Session;
31 use driver::driver::{CrateAnalysis, CrateTranslation};
32 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
38 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
39 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::base;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::common::*;
47 use middle::trans::consts;
48 use middle::trans::controlflow;
49 use middle::trans::datum;
50 use middle::trans::debuginfo;
51 use middle::trans::expr;
52 use middle::trans::foreign;
53 use middle::trans::glue;
54 use middle::trans::inline;
55 use middle::trans::machine;
56 use middle::trans::machine::{llalign_of_min, llsize_of};
57 use middle::trans::meth;
58 use middle::trans::monomorphize;
59 use middle::trans::tvec;
60 use middle::trans::type_of;
61 use middle::trans::type_of::*;
63 use util::common::indenter;
64 use util::ppaux::{Repr, ty_to_str};
66 use middle::trans::type_::Type;
69 use std::hashmap::HashMap;
71 use std::libc::c_uint;
77 use syntax::ast::ident;
78 use syntax::ast_map::{path, path_elt_to_str, path_name};
79 use syntax::ast_util::{local_def};
81 use syntax::attr::AttrMetaMethods;
82 use syntax::codemap::span;
83 use syntax::parse::token;
84 use syntax::parse::token::{special_idents};
85 use syntax::print::pprust::stmt_to_str;
87 use syntax::{ast, ast_util, codemap, ast_map};
88 use syntax::abi::{X86, X86_64, Arm, Mips};
90 pub use middle::trans::context::task_llcx;
92 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
94 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
95 let opt = local_data::get(task_local_insn_key, |k| k.map_move(|k| *k));
101 pub fn init_insn_ctxt() {
102 local_data::set(task_local_insn_key, @~[]);
105 pub struct _InsnCtxt { _x: () }
108 impl Drop for _InsnCtxt {
110 do local_data::modify(task_local_insn_key) |c| {
111 do c.map_move |ctx| {
112 let mut ctx = (*ctx).clone();
120 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
121 debug!("new InsnCtxt: %s", s);
122 do local_data::modify(task_local_insn_key) |c| {
123 do c.map_move |ctx| {
124 let mut ctx = (*ctx).clone();
132 fn fcx_has_nonzero_span(fcx: &FunctionContext) -> bool {
135 Some(span) => *span.lo != 0 || *span.hi != 0
139 struct StatRecorder<'self> {
140 ccx: @mut CrateContext,
146 impl<'self> StatRecorder<'self> {
147 pub fn new(ccx: @mut CrateContext,
148 name: &'self str) -> StatRecorder<'self> {
149 let start = if ccx.sess.trans_stats() {
150 time::precise_time_ns()
154 let istart = ccx.stats.n_llvm_insns;
165 impl<'self> Drop for StatRecorder<'self> {
167 if self.ccx.sess.trans_stats() {
168 let end = time::precise_time_ns();
169 let elapsed = ((end - self.start) / 1_000_000) as uint;
170 let iend = self.ccx.stats.n_llvm_insns;
171 self.ccx.stats.fn_stats.push((self.name.to_owned(),
173 iend - self.istart));
174 self.ccx.stats.n_fns += 1;
175 // Reset LLVM insn count to avoid compound costs.
176 self.ccx.stats.n_llvm_insns = self.istart;
181 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
182 let llfn: ValueRef = do name.as_c_str |buf| {
184 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
188 lib::llvm::SetFunctionCallConv(llfn, cc);
192 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
193 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
196 // Only use this if you are going to actually define the function. It's
197 // not valid to simply declare a function as internal.
198 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
199 let llfn = decl_cdecl_fn(llmod, name, ty);
200 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
204 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
205 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
206 match externs.find_copy(&name) {
210 let f = decl_fn(llmod, name, cc, ty);
211 externs.insert(name, f);
215 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
216 name: @str, ty: Type) -> ValueRef {
217 match externs.find_copy(&name) {
222 let c = do name.as_c_str |buf| {
223 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
225 externs.insert(name, c);
229 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
230 let _icx = push_ctxt("umax");
231 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
232 return Select(cx, cond, b, a);
235 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
236 let _icx = push_ctxt("umin");
237 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
238 return Select(cx, cond, a, b);
241 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
242 // The type of the returned pointer is always i8*. If you care about the
243 // return type, use bump_ptr().
244 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
245 let _icx = push_ctxt("ptr_offs");
246 let raw = PointerCast(bcx, base, Type::i8p());
247 InBoundsGEP(bcx, raw, [sz])
250 // Increment a pointer by a given amount and then cast it to be a pointer
252 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
254 let _icx = push_ctxt("bump_ptr");
256 let bumped = ptr_offs(bcx, base, sz);
257 let typ = type_of(ccx, t).ptr_to();
258 PointerCast(bcx, bumped, typ)
261 // Returns a pointer to the body for the box. The box may be an opaque
262 // box. The result will be casted to the type of body_t, if it is statically
265 // The runtime equivalent is box_body() in "rust_internal.h".
266 pub fn opaque_box_body(bcx: @mut Block,
268 boxptr: ValueRef) -> ValueRef {
269 let _icx = push_ctxt("opaque_box_body");
271 let ty = type_of(ccx, body_t);
272 let ty = Type::box(ccx, &ty);
273 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
274 GEPi(bcx, boxptr, [0u, abi::box_field_body])
277 // malloc_raw_dyn: allocates a box to contain a given type, but with a
278 // potentially dynamic size.
279 pub fn malloc_raw_dyn(bcx: @mut Block,
282 size: ValueRef) -> Result {
283 let _icx = push_ctxt("malloc_raw");
286 fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::def_id {
287 let li = &bcx.tcx().lang_items;
288 match li.require(it) {
291 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
292 bcx.ty_to_str(t), s));
297 if heap == heap_exchange {
298 let llty_value = type_of::type_of(ccx, t);
302 let r = callee::trans_lang_call(
304 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
307 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
309 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
310 let (mk_fn, langcall) = match heap {
311 heap_managed | heap_managed_unique => {
313 require_alloc_fn(bcx, t, MallocFnLangItem))
315 heap_exchange_closure => {
317 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
319 _ => fail!("heap_exchange already handled")
322 // Grab the TypeRef type of box_ptr_ty.
323 let box_ptr_ty = mk_fn(bcx.tcx(), t);
324 let llty = type_of(ccx, box_ptr_ty);
326 // Get the tydesc for the body:
327 let static_ti = get_tydesc(ccx, t);
328 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
331 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
332 let r = callee::trans_lang_call(
337 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
338 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
343 // malloc_raw: expects an unboxed type and returns a pointer to
344 // enough space for a box of that type. This includes a rust_opaque_box
346 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
347 let ty = type_of(bcx.ccx(), t);
348 let size = llsize_of(bcx.ccx(), ty);
349 malloc_raw_dyn(bcx, t, heap, size)
352 pub struct MallocResult {
358 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
359 // and pulls out the body
360 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
362 assert!(heap != heap_exchange);
363 let _icx = push_ctxt("malloc_general");
364 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
365 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
367 MallocResult { bcx: bcx, box: llbox, body: body }
370 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
371 let ty = type_of(bcx.ccx(), t);
372 assert!(heap != heap_exchange);
373 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
375 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
377 malloc_general(bcx, t, heap_managed)
380 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
381 if ty::type_contents(bcx.tcx(), t).contains_managed() {
388 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
389 assert!(heap != heap_exchange);
390 if heap == heap_managed_unique {
391 // In cases where we are looking at a unique-typed allocation in the
392 // managed heap (thus have refcount 1 from the managed allocator),
393 // such as a ~(@foo) or such. These need to have their refcount forced
394 // to -2 so the annihilator ignores them.
395 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
396 let rc_val = C_int(bcx.ccx(), -2);
397 Store(bcx, rc_val, rc);
401 // Type descriptor and type glue stuff
403 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
404 get_tydesc(ccx, t).tydesc
407 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
408 match ccx.tydescs.find(&t) {
415 ccx.stats.n_static_tydescs += 1u;
416 let inf = glue::declare_tydesc(ccx, t);
417 ccx.tydescs.insert(t, inf);
421 pub fn set_optimize_for_size(f: ValueRef) {
422 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
425 pub fn set_no_inline(f: ValueRef) {
426 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
429 pub fn set_no_unwind(f: ValueRef) {
430 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
433 // Tell LLVM to emit the information necessary to unwind the stack for the
435 pub fn set_uwtable(f: ValueRef) {
436 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
439 pub fn set_inline_hint(f: ValueRef) {
440 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
443 pub fn set_inline_hint_if_appr(attrs: &[ast::Attribute],
446 match find_inline_attr(attrs) {
447 InlineHint => set_inline_hint(llfn),
448 InlineAlways => set_always_inline(llfn),
449 InlineNever => set_no_inline(llfn),
450 InlineNone => { /* fallthrough */ }
454 pub fn set_always_inline(f: ValueRef) {
455 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
458 pub fn set_fixed_stack_segment(f: ValueRef) {
459 lib::llvm::SetFixedStackSegmentAttribute(f);
462 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
463 if ty::type_is_structural(t) {
464 set_optimize_for_size(f);
465 } else { set_always_inline(f); }
468 // Double-check that we never ask LLVM to declare the same symbol twice. It
469 // silently mangles such symbols, breaking our linkage model.
470 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
471 if ccx.all_llvm_symbols.contains(&sym) {
472 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
474 ccx.all_llvm_symbols.insert(sym);
478 pub fn get_res_dtor(ccx: @mut CrateContext,
480 parent_id: ast::def_id,
483 let _icx = push_ctxt("trans_res_dtor");
484 if !substs.is_empty() {
485 let did = if did.crate != ast::LOCAL_CRATE {
486 inline::maybe_instantiate_inline(ccx, did)
490 assert_eq!(did.crate, ast::LOCAL_CRATE);
491 let tsubsts = ty::substs {regions: ty::ErasedRegions,
493 tps: /*bad*/ substs.to_owned() };
494 let (val, _) = monomorphize::monomorphic_fn(ccx,
502 } else if did.crate == ast::LOCAL_CRATE {
503 get_item_val(ccx, did.node)
506 let name = csearch::get_symbol(ccx.sess.cstore, did);
507 let class_ty = ty::subst_tps(tcx,
510 ty::lookup_item_type(tcx, parent_id).ty);
511 let llty = type_of_dtor(ccx, class_ty);
512 let name = name.to_managed(); // :-(
513 get_extern_fn(&mut ccx.externs,
516 lib::llvm::CCallConv,
521 // Structural comparison: a rather involved form of glue.
522 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
523 if cx.sess.opts.save_temps {
524 do s.as_c_str |buf| {
526 llvm::LLVMSetValueName(v, buf)
533 // Used only for creating scalar comparison glue.
534 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
536 // NB: This produces an i1, not a Rust bool (i8).
537 pub fn compare_scalar_types(cx: @mut Block,
543 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
545 match ty::get(t).sty {
546 ty::ty_nil => rslt(cx, f(nil_type)),
547 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
548 ty::ty_int(_) => rslt(cx, f(signed_int)),
549 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
550 ty::ty_float(_) => rslt(cx, f(floating_point)),
553 controlflow::trans_fail(
555 @"attempt to compare values of type type"),
559 // Should never get here, because t is scalar.
560 cx.sess().bug("non-scalar type passed to \
561 compare_scalar_types")
567 // A helper function to do the actual comparison of scalar values.
568 pub fn compare_scalar_values(cx: @mut Block,
574 let _icx = push_ctxt("compare_scalar_values");
575 fn die(cx: @mut Block) -> ! {
576 cx.tcx().sess.bug("compare_scalar_values: must be a\
577 comparison operator");
581 // We don't need to do actual comparisons for nil.
582 // () == () holds but () < () does not.
584 ast::eq | ast::le | ast::ge => return C_i1(true),
585 ast::ne | ast::lt | ast::gt => return C_i1(false),
586 // refinements would be nice
592 ast::eq => lib::llvm::RealOEQ,
593 ast::ne => lib::llvm::RealUNE,
594 ast::lt => lib::llvm::RealOLT,
595 ast::le => lib::llvm::RealOLE,
596 ast::gt => lib::llvm::RealOGT,
597 ast::ge => lib::llvm::RealOGE,
600 return FCmp(cx, cmp, lhs, rhs);
604 ast::eq => lib::llvm::IntEQ,
605 ast::ne => lib::llvm::IntNE,
606 ast::lt => lib::llvm::IntSLT,
607 ast::le => lib::llvm::IntSLE,
608 ast::gt => lib::llvm::IntSGT,
609 ast::ge => lib::llvm::IntSGE,
612 return ICmp(cx, cmp, lhs, rhs);
616 ast::eq => lib::llvm::IntEQ,
617 ast::ne => lib::llvm::IntNE,
618 ast::lt => lib::llvm::IntULT,
619 ast::le => lib::llvm::IntULE,
620 ast::gt => lib::llvm::IntUGT,
621 ast::ge => lib::llvm::IntUGE,
624 return ICmp(cx, cmp, lhs, rhs);
629 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
631 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
632 return Load(cx, GEPi(cx, p, idxs));
635 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
636 Store(cx, v, GEPi(cx, p, idxs));
639 // Iterates through the elements of a structural type.
640 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
641 f: val_and_ty_fn) -> @mut Block {
642 let _icx = push_ctxt("iter_structural_ty");
644 fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
645 variant: @ty::VariantInfo,
646 tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
647 let _icx = push_ctxt("iter_variant");
651 for (i, &arg) in variant.args.iter().enumerate() {
653 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
654 ty::subst_tps(tcx, tps, None, arg));
660 match ty::get(t).sty {
661 ty::ty_struct(*) => {
662 let repr = adt::represent_type(cx.ccx(), t);
663 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
664 for (i, field_ty) in field_tys.iter().enumerate() {
665 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
666 cx = f(cx, llfld_a, field_ty.mt.ty);
670 ty::ty_estr(ty::vstore_fixed(_)) |
671 ty::ty_evec(_, ty::vstore_fixed(_)) => {
672 let (base, len) = tvec::get_base_and_len(cx, av, t);
673 cx = tvec::iter_vec_raw(cx, base, t, len, f);
675 ty::ty_tup(ref args) => {
676 let repr = adt::represent_type(cx.ccx(), t);
677 for (i, arg) in args.iter().enumerate() {
678 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
679 cx = f(cx, llfld_a, *arg);
682 ty::ty_enum(tid, ref substs) => {
685 let repr = adt::represent_type(ccx, t);
686 let variants = ty::enum_variants(ccx.tcx, tid);
687 let n_variants = (*variants).len();
689 // NB: we must hit the discriminant first so that structural
690 // comparison know not to proceed when the discriminants differ.
692 match adt::trans_switch(cx, repr, av) {
693 (_match::single, None) => {
694 cx = iter_variant(cx, repr, av, variants[0],
697 (_match::switch, Some(lldiscrim_a)) => {
698 cx = f(cx, lldiscrim_a, ty::mk_int());
699 let unr_cx = sub_block(cx, "enum-iter-unr");
701 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
703 let next_cx = sub_block(cx, "enum-iter-next");
705 for variant in (*variants).iter() {
707 sub_block(cx, ~"enum-iter-variant-" +
708 uint::to_str(variant.disr_val));
710 iter_variant(variant_cx, repr, av, *variant,
711 substs.tps, |x,y,z| f(x,y,z));
712 match adt::trans_case(cx, repr, variant.disr_val) {
713 _match::single_result(r) => {
714 AddCase(llswitch, r.val, variant_cx.llbb)
716 _ => ccx.sess.unimpl("value from adt::trans_case \
717 in iter_structural_ty")
719 Br(variant_cx, next_cx.llbb);
723 _ => ccx.sess.unimpl("value from adt::trans_switch \
724 in iter_structural_ty")
727 _ => cx.sess().unimpl("type in iter_structural_ty")
732 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::binop,
733 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
734 cast_shift_rhs(op, lhs, rhs,
735 |a,b| Trunc(cx, a, b),
736 |a,b| ZExt(cx, a, b))
739 pub fn cast_shift_const_rhs(op: ast::binop,
740 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
741 cast_shift_rhs(op, lhs, rhs,
742 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
743 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
746 pub fn cast_shift_rhs(op: ast::binop,
747 lhs: ValueRef, rhs: ValueRef,
748 trunc: &fn(ValueRef, Type) -> ValueRef,
749 zext: &fn(ValueRef, Type) -> ValueRef)
751 // Shifts may have any size int on the rhs
753 if ast_util::is_shift_binop(op) {
754 let rhs_llty = val_ty(rhs);
755 let lhs_llty = val_ty(lhs);
756 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
757 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
760 } else if lhs_sz > rhs_sz {
761 // FIXME (#1877: If shifting by negative
762 // values becomes not undefined then this is wrong.
773 pub fn fail_if_zero(cx: @mut Block, span: span, divrem: ast::binop,
774 rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
775 let text = if divrem == ast::div {
776 @"attempted to divide by zero"
778 @"attempted remainder with a divisor of zero"
780 let is_zero = match ty::get(rhs_t).sty {
782 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
783 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
786 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
787 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
790 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
791 ty_to_str(cx.ccx().tcx, rhs_t));
794 do with_cond(cx, is_zero) |bcx| {
795 controlflow::trans_fail(bcx, Some(span), text)
799 pub fn null_env_ptr(bcx: @mut Block) -> ValueRef {
800 C_null(Type::opaque_box(bcx.ccx()).ptr_to())
803 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
805 let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
806 match ty::get(t).sty {
807 ty::ty_bare_fn(_) | ty::ty_closure(_) => {
808 let llty = type_of_fn_from_ty(ccx, t);
809 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
810 lib::llvm::CCallConv, llty);
813 let llty = type_of(ccx, t);
814 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
819 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef])
820 -> (ValueRef, @mut Block) {
821 let _icx = push_ctxt("invoke_");
823 return (C_null(Type::i8()), bcx);
826 match bcx.node_info {
827 None => debug!("invoke at ???"),
829 debug!("invoke at %s",
830 bcx.sess().codemap.span_to_str(node_info.span));
834 if need_invoke(bcx) {
836 debug!("invoking %x at %x",
837 ::std::cast::transmute(llfn),
838 ::std::cast::transmute(bcx.llbb));
839 for &llarg in llargs.iter() {
840 debug!("arg: %x", ::std::cast::transmute(llarg));
843 let normal_bcx = sub_block(bcx, "normal return");
844 let llresult = Invoke(bcx,
848 get_landing_pad(bcx));
849 return (llresult, normal_bcx);
852 debug!("calling %x at %x",
853 ::std::cast::transmute(llfn),
854 ::std::cast::transmute(bcx.llbb));
855 for &llarg in llargs.iter() {
856 debug!("arg: %x", ::std::cast::transmute(llarg));
859 let llresult = Call(bcx, llfn, llargs);
860 return (llresult, bcx);
864 pub fn need_invoke(bcx: @mut Block) -> bool {
865 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
869 // Avoid using invoke if we are already inside a landing pad.
874 if have_cached_lpad(bcx) {
878 // Walk the scopes to look for cleanups
880 let mut cur_scope = cur.scope;
882 cur_scope = match cur_scope {
884 for cleanup in inf.cleanups.iter() {
886 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
887 if cleanup_type == normal_exit_and_unwind {
896 cur = match cur.parent {
906 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
908 do in_lpad_scope_cx(bcx) |inf| {
909 match inf.landing_pad {
910 Some(_) => res = true,
917 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
919 let mut cur_scope = bcx.scope;
921 cur_scope = match cur_scope {
923 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
930 bcx = block_parent(bcx);
937 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
938 let _icx = push_ctxt("get_landing_pad");
940 let mut cached = None;
941 let mut pad_bcx = bcx; // Guaranteed to be set below
942 do in_lpad_scope_cx(bcx) |inf| {
943 // If there is a valid landing pad still around, use it
944 match inf.landing_pad {
945 Some(target) => cached = Some(target),
947 pad_bcx = lpad_block(bcx, "unwind");
948 inf.landing_pad = Some(pad_bcx.llbb);
952 // Can't return from block above
953 match cached { Some(b) => return b, None => () }
954 // The landing pad return type (the type being propagated). Not sure what
955 // this represents but it's determined by the personality function and
956 // this is what the EH proposal example uses.
957 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
958 // The exception handling personality function. This is the C++
959 // personality function __gxx_personality_v0, wrapped in our naming
961 let personality = bcx.ccx().upcalls.rust_personality;
962 // The only landing pad clause will be 'cleanup'
963 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
964 // The landing pad block is a cleanup
965 SetCleanup(pad_bcx, llretval);
967 // Because we may have unwound across a stack boundary, we must call into
968 // the runtime to figure out which stack segment we are on and place the
969 // stack limit back into the TLS.
970 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
972 // We store the retval in a function-central alloca, so that calls to
973 // Resume can find it.
974 match bcx.fcx.personality {
975 Some(addr) => Store(pad_bcx, llretval, addr),
977 let addr = alloca(pad_bcx, val_ty(llretval), "");
978 bcx.fcx.personality = Some(addr);
979 Store(pad_bcx, llretval, addr);
983 // Unwind all parent scopes, and finish with a Resume instr
984 cleanup_and_leave(pad_bcx, None, None);
988 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
989 let mut bcx_sid = bcx;
990 let mut cur_scope = bcx_sid.scope;
992 cur_scope = match cur_scope {
994 match inf.node_info {
995 Some(NodeInfo { id, _ }) if id == scope_id => {
998 // FIXME(#6268, #6248) hacky cleanup for nested method calls
999 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1006 bcx_sid = match bcx_sid.parent {
1007 None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1008 Some(bcx_par) => bcx_par
1017 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1018 if ty::type_is_bot(t) {
1019 return C_null(Type::i8p());
1021 let llptr = alloc_ty(bcx, t, "");
1022 Store(bcx, v, llptr);
1026 // Since this function does *not* root, it is the caller's responsibility to
1027 // ensure that the referent is pointed to by a root.
1028 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1029 let llptr = alloca(cx, val_ty(v), "");
1030 Store(cx, v, llptr);
1034 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1035 let _icx = push_ctxt("spill_if_immediate");
1036 if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1040 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1041 let _icx = push_ctxt("load_if_immediate");
1042 if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1046 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<span>, trace_str: @str) {
1047 if !bcx.sess().trace() { return; }
1048 let _icx = push_ctxt("trans_trace");
1049 add_comment(bcx, trace_str);
1050 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1051 let (V_filename, V_line) = match sp_opt {
1053 let sess = bcx.sess();
1054 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1055 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1058 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1061 let ccx = bcx.ccx();
1062 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1063 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1064 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1065 Call(bcx, ccx.upcalls.trace, args);
1068 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1069 match local.pat.node {
1070 ast::pat_wild => true, _ => false
1074 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1076 debug!("init_local(bcx=%s, local.id=%?)",
1077 bcx.to_str(), local.id);
1078 let _indenter = indenter();
1080 let _icx = push_ctxt("init_local");
1082 if ignore_lhs(bcx, local) {
1083 // Handle let _ = e; just like e;
1086 return expr::trans_into(bcx, init, expr::Ignore);
1088 None => { return bcx; }
1092 _match::store_local(bcx, local.pat, local.init)
1095 pub fn trans_stmt(cx: @mut Block, s: &ast::stmt) -> @mut Block {
1096 let _icx = push_ctxt("trans_stmt");
1097 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1099 if cx.sess().asm_comments() {
1100 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1104 debuginfo::update_source_pos(cx, s.span);
1107 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1108 bcx = expr::trans_into(cx, e, expr::Ignore);
1110 ast::stmt_decl(d, _) => {
1112 ast::decl_local(ref local) => {
1113 bcx = init_local(bcx, *local);
1114 if cx.sess().opts.extra_debuginfo
1115 && fcx_has_nonzero_span(bcx.fcx) {
1116 debuginfo::create_local_var_metadata(bcx, *local);
1119 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1122 ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1128 // You probably don't want to use this one. See the
1129 // next three functions instead.
1130 pub fn new_block(cx: @mut FunctionContext,
1131 parent: Option<@mut Block>,
1132 scope: Option<@mut ScopeInfo>,
1135 opt_node_info: Option<NodeInfo>)
1138 let llbb = do name.as_c_str |buf| {
1139 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1141 let bcx = @mut Block::new(llbb,
1147 for cx in parent.iter() {
1157 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1158 node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1166 node_info: node_info,
1170 // Use this when you're at the top block of a function or the like.
1171 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1173 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1174 "function top level", opt_node_info);
1177 pub fn scope_block(bcx: @mut Block,
1178 opt_node_info: Option<NodeInfo>,
1179 n: &str) -> @mut Block {
1180 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1184 pub fn loop_scope_block(bcx: @mut Block,
1185 loop_break: @mut Block,
1186 loop_label: Option<ident>,
1188 opt_node_info: Option<NodeInfo>) -> @mut Block {
1189 return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1191 loop_break: Some(loop_break),
1192 loop_label: loop_label,
1196 node_info: opt_node_info,
1197 }), bcx.is_lpad, n, opt_node_info);
1200 // Use this when creating a block for the inside of a landing pad.
1201 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1202 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1205 // Use this when you're making a general CFG BB within a scope.
1206 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1207 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1210 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1211 @mut Block::new(llbb, None, is_lpad, None, fcx)
1215 // trans_block_cleanups: Go through all the cleanups attached to this
1216 // block and execute them.
1218 // When translating a block that introduces new variables during its scope, we
1219 // need to make sure those variables go out of scope when the block ends. We
1220 // do that by running a 'cleanup' function for each variable.
1221 // trans_block_cleanups runs all the cleanup functions for the block.
1222 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1223 trans_block_cleanups_(bcx, cleanups, false)
1226 pub fn trans_block_cleanups_(bcx: @mut Block,
1227 cleanups: &[cleanup],
1228 /* cleanup_cx: block, */
1229 is_lpad: bool) -> @mut Block {
1230 let _icx = push_ctxt("trans_block_cleanups");
1231 // NB: Don't short-circuit even if this block is unreachable because
1232 // GC-based cleanup needs to the see that the roots are live.
1234 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1235 if bcx.unreachable && !no_lpads { return bcx; }
1237 for cu in cleanups.rev_iter() {
1239 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1240 // Some types don't need to be cleaned up during
1241 // landing pads because they can be freed en mass later
1242 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1251 // In the last argument, Some(block) mean jump to this block, and none means
1252 // this is a landing pad and leaving should be accomplished with a resume
1254 pub fn cleanup_and_leave(bcx: @mut Block,
1255 upto: Option<BasicBlockRef>,
1256 leave: Option<BasicBlockRef>) {
1257 let _icx = push_ctxt("cleanup_and_leave");
1260 let is_lpad = leave == None;
1262 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1264 if bcx.sess().trace() {
1267 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1270 let mut cur_scope = cur.scope;
1272 cur_scope = match cur_scope {
1273 Some (inf) if !inf.empty_cleanups() => {
1274 let (sub_cx, dest, inf_cleanups) = {
1275 let inf = &mut *inf;
1277 let mut dest = None;
1279 let r = (*inf).cleanup_paths.rev_iter().find_(|cp| cp.target == leave);
1280 for cp in r.iter() {
1281 if cp.size == inf.cleanups.len() {
1287 dest = Some(cp.dest);
1290 let sub_cx = sub_block(bcx, "cleanup");
1291 Br(bcx, sub_cx.llbb);
1292 inf.cleanup_paths.push(cleanup_path {
1294 size: inf.cleanups.len(),
1297 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1299 bcx = trans_block_cleanups_(sub_cx,
1302 for &dest in dest.iter() {
1308 Some(inf) => inf.parent,
1314 Some(bb) => { if cur.llbb == bb { break; } }
1317 cur = match cur.parent {
1319 None => { assert!(upto.is_none()); break; }
1323 Some(target) => Br(bcx, target),
1324 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.unwrap())); }
1328 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1329 let _icx = push_ctxt("cleanup_block");
1333 debug!("cleanup_block: %s", cur.to_str());
1335 if bcx.sess().trace() {
1338 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1341 let mut cur_scope = cur.scope;
1343 cur_scope = match cur_scope {
1345 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1353 Some(bb) => { if cur.llbb == bb { break; } }
1356 cur = match cur.parent {
1358 None => { assert!(upto.is_none()); break; }
1364 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1365 let _icx = push_ctxt("cleanup_and_Br");
1366 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1369 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1370 let _icx = push_ctxt("leave_block");
1371 let next_cx = sub_block(block_parent(out_of), "next");
1372 if bcx.unreachable { Unreachable(next_cx); }
1373 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1377 pub fn with_scope(bcx: @mut Block,
1378 opt_node_info: Option<NodeInfo>,
1380 f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1381 let _icx = push_ctxt("with_scope");
1383 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1384 bcx.to_str(), opt_node_info, name);
1385 let _indenter = indenter();
1387 let scope = simple_block_scope(bcx.scope, opt_node_info);
1388 bcx.scope = Some(scope);
1390 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1391 bcx.scope = scope.parent;
1395 pub fn with_scope_result(bcx: @mut Block,
1396 opt_node_info: Option<NodeInfo>,
1398 f: &fn(@mut Block) -> Result) -> Result {
1399 let _icx = push_ctxt("with_scope_result");
1401 let scope = simple_block_scope(bcx.scope, opt_node_info);
1402 bcx.scope = Some(scope);
1403 let Result { bcx: out_bcx, val } = f(bcx);
1404 let out_bcx = trans_block_cleanups_(out_bcx,
1405 (scope.cleanups).clone(),
1407 bcx.scope = scope.parent;
1412 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1413 name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1414 -> datum::DatumBlock {
1415 use middle::trans::datum::DatumBlock;
1417 let _icx = push_ctxt("with_scope_result");
1418 let scope_cx = scope_block(bcx, opt_node_info, name);
1419 Br(bcx, scope_cx.llbb);
1420 let DatumBlock {bcx, datum} = f(scope_cx);
1421 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1424 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1425 for s in b.stmts.iter() {
1427 ast::stmt_decl(d, _) => {
1429 ast::decl_local(ref local) => it(*local),
1430 _ => {} /* fall through */
1433 _ => {} /* fall through */
1438 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1439 let _icx = push_ctxt("with_cond");
1440 let next_cx = base::sub_block(bcx, "next");
1441 let cond_cx = base::sub_block(bcx, "cond");
1442 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1443 let after_cx = f(cond_cx);
1444 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1448 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1449 let _icx = push_ctxt("call_memcpy");
1451 let key = match ccx.sess.targ_cfg.arch {
1452 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1453 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1455 let memcpy = ccx.intrinsics.get_copy(&key);
1456 let src_ptr = PointerCast(cx, src, Type::i8p());
1457 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1458 let size = IntCast(cx, n_bytes, ccx.int_type);
1459 let align = C_i32(align as i32);
1460 let volatile = C_i1(false);
1461 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1464 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1465 let _icx = push_ctxt("memcpy_ty");
1466 let ccx = bcx.ccx();
1467 if ty::type_is_structural(t) {
1468 let llty = type_of::type_of(ccx, t);
1469 let llsz = llsize_of(ccx, llty);
1470 let llalign = llalign_of_min(ccx, llty);
1471 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1473 Store(bcx, Load(bcx, src), dst);
1477 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1478 if cx.unreachable { return; }
1479 let _icx = push_ctxt("zero_mem");
1482 let llty = type_of::type_of(ccx, t);
1483 memzero(&B(bcx), llptr, llty);
1486 // Always use this function instead of storing a zero constant to the memory
1487 // in question. If you store a zero constant, LLVM will drown in vreg
1488 // allocation for large data structures, and the generated code will be
1489 // awful. (A telltale sign of this is large quantities of
1490 // `mov [byte ptr foo],0` in the generated code.)
1491 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1492 let _icx = push_ctxt("memzero");
1495 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1496 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1497 X86_64 => "llvm.memset.p0i8.i64"
1500 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1501 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1502 let llzeroval = C_u8(0);
1503 let size = machine::llsize_of(ccx, ty);
1504 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1505 let volatile = C_i1(false);
1506 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1509 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1510 let _icx = push_ctxt("alloc_ty");
1511 let ccx = bcx.ccx();
1512 let ty = type_of::type_of(ccx, t);
1513 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1514 let val = alloca(bcx, ty, name);
1518 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1519 alloca_maybe_zeroed(cx, ty, name, false)
1522 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1523 let _icx = push_ctxt("alloca");
1526 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1529 let p = Alloca(cx, ty, name);
1531 let b = cx.fcx.ccx.builder();
1532 b.position_before(cx.fcx.alloca_insert_pt.unwrap());
1538 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1539 let _icx = push_ctxt("arrayalloca");
1542 return llvm::LLVMGetUndef(ty.to_ref());
1545 return ArrayAlloca(cx, ty, v);
1548 pub struct BasicBlocks {
1552 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1554 let cx = task_llcx();
1555 do "static_allocas".as_c_str | buf| {
1556 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1561 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1563 let cx = task_llcx();
1564 do "return".as_c_str |buf| {
1565 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1570 // Creates and returns space for, or returns the argument representing, the
1571 // slot where the return value of the function must go.
1572 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1574 if !ty::type_is_immediate(fcx.ccx.tcx, output_type) {
1575 llvm::LLVMGetParam(fcx.llfn, 0)
1577 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1578 let bcx = fcx.entry_bcx.unwrap();
1579 Alloca(bcx, lloutputtype, "__make_return_pointer")
1584 // NB: must keep 4 fns in sync:
1587 // - create_llargs_for_fn_args.
1590 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1596 param_substs: Option<@param_substs>,
1597 opt_node_info: Option<NodeInfo>,
1599 -> @mut FunctionContext {
1600 for p in param_substs.iter() { p.validate(); }
1602 debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1604 path_str(ccx.sess, path),
1606 param_substs.repr(ccx.tcx));
1608 let substd_output_type = match param_substs {
1609 None => output_type,
1611 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1614 let is_immediate = ty::type_is_immediate(ccx.tcx, substd_output_type);
1615 let fcx = @mut FunctionContext {
1618 llvm::LLVMGetUndef(Type::i8p().to_ref())
1622 alloca_insert_pt: None,
1627 has_immediate_return_value: is_immediate,
1628 llargs: @mut HashMap::new(),
1629 lllocals: @mut HashMap::new(),
1630 llupvars: @mut HashMap::new(),
1632 param_substs: param_substs,
1637 fcx.llenv = unsafe {
1638 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1642 let entry_bcx = top_scope_block(fcx, opt_node_info);
1643 Load(entry_bcx, C_null(Type::i8p()));
1645 fcx.entry_bcx = Some(entry_bcx);
1646 fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1649 if !ty::type_is_nil(substd_output_type) && !(is_immediate && skip_retptr) {
1650 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1655 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1660 -> @mut FunctionContext {
1661 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1664 // NB: must keep 4 fns in sync:
1667 // - create_llargs_for_fn_args.
1671 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1672 // allocas created for them.
1674 // When we translate a function, we need to map its incoming arguments to the
1675 // spaces that have been created for them (by code in the llallocas field of
1676 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1677 // field of the fn_ctxt with
1678 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1682 let _icx = push_ctxt("create_llargs_for_fn_args");
1685 impl_self(tt, self_mode) => {
1686 cx.llself = Some(ValSelfData {
1689 is_copy: self_mode == ty::ByCopy
1695 // Return an array containing the ValueRefs that we get from
1696 // llvm::LLVMGetParam for each argument.
1697 vec::from_fn(args.len(), |i| {
1699 let arg_n = cx.arg_pos(i);
1701 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1703 // FIXME #7260: aliasing should be determined by monomorphized ty::t
1705 // `~` pointers never alias other parameters, because ownership was transferred
1706 ast::ty_uniq(_) => {
1707 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1709 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1710 // those in the other parameters and then mark it as `noalias` if there aren't any
1719 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1722 raw_llargs: &[ValueRef],
1723 arg_tys: &[ty::t]) -> @mut Block {
1724 let _icx = push_ctxt("copy_args_to_allocas");
1729 let self_val = if slf.is_copy
1730 && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1731 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1732 let alloc = alloc_ty(bcx, slf.t, "__self");
1733 Store(bcx, tmp, alloc);
1736 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1739 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1740 add_clean(bcx, self_val, slf.t);
1745 for (arg_n, &arg_ty) in arg_tys.iter().enumerate() {
1746 let raw_llarg = raw_llargs[arg_n];
1748 // For certain mode/type combinations, the raw llarg values are passed
1749 // by value. However, within the fn body itself, we want to always
1750 // have all locals and arguments be by-ref so that we can cancel the
1751 // cleanup and for better interaction with LLVM's debug info. So, if
1752 // the argument would be passed by value, we store it into an alloca.
1753 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1754 // the event it's not truly needed.
1755 // only by value if immediate:
1756 let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1757 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1758 Store(bcx, raw_llarg, alloc);
1763 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1765 if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1766 debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1773 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1774 // and builds the return block.
1775 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1776 let _icx = push_ctxt("finish_fn");
1778 let ret_cx = match fcx.llreturn {
1780 if !last_bcx.terminated {
1781 Br(last_bcx, llreturn);
1783 raw_block(fcx, false, llreturn)
1787 build_return_block(fcx, ret_cx);
1791 // Builds the return block for a function.
1792 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1793 // Return the value if this function immediate; otherwise, return void.
1794 if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1795 Ret(ret_cx, Load(ret_cx, fcx.llretptr.unwrap()))
1801 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1803 // trans_closure: Builds an LLVM function out of a source function.
1804 // If the function closes over its environment a closure will be
1806 pub fn trans_closure(ccx: @mut CrateContext,
1808 decl: &ast::fn_decl,
1812 param_substs: Option<@param_substs>,
1814 attributes: &[ast::Attribute],
1816 maybe_load_env: &fn(@mut FunctionContext),
1817 finish: &fn(@mut Block)) {
1818 ccx.stats.n_closures += 1;
1819 let _icx = push_ctxt("trans_closure");
1820 set_uwtable(llfndecl);
1822 debug!("trans_closure(..., param_substs=%s)",
1823 param_substs.repr(ccx.tcx));
1825 // Set up arguments to the function.
1826 let fcx = new_fn_ctxt_w_id(ccx,
1835 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1837 // Set the fixed stack segment flag if necessary.
1838 if attr::contains_name(attributes, "fixed_stack_segment") {
1839 set_no_inline(fcx.llfn);
1840 set_fixed_stack_segment(fcx.llfn);
1843 // Create the first basic block in the function and keep a handle on it to
1844 // pass to finish_fn later.
1845 let bcx_top = fcx.entry_bcx.unwrap();
1846 let mut bcx = bcx_top;
1847 let block_ty = node_id_type(bcx, body.id);
1849 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1850 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1852 maybe_load_env(fcx);
1854 // This call to trans_block is the place where we bridge between
1855 // translation calls that don't have a return value (trans_crate,
1856 // trans_mod, trans_item, et cetera) and those that do
1857 // (trans_block, trans_expr, et cetera).
1858 if body.expr.is_none() || ty::type_is_bot(block_ty) ||
1859 ty::type_is_nil(block_ty)
1861 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1863 let dest = expr::SaveIn(fcx.llretptr.unwrap());
1864 bcx = controlflow::trans_block(bcx, body, dest);
1868 match fcx.llreturn {
1869 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1870 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1873 // Put return block after all other blocks.
1874 // This somewhat improves single-stepping experience in debugger.
1876 for &llreturn in fcx.llreturn.iter() {
1877 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1881 // Insert the mandatory first few basic blocks before lltop.
1882 finish_fn(fcx, bcx);
1885 // trans_fn: creates an LLVM function corresponding to a source language
1887 pub fn trans_fn(ccx: @mut CrateContext,
1889 decl: &ast::fn_decl,
1893 param_substs: Option<@param_substs>,
1895 attrs: &[ast::Attribute]) {
1897 let the_path_str = path_str(ccx.sess, path);
1898 let _s = StatRecorder::new(ccx, the_path_str);
1899 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1901 param_substs.repr(ccx.tcx));
1902 let _icx = push_ctxt("trans_fn");
1903 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1915 if ccx.sess.opts.extra_debuginfo
1916 && fcx_has_nonzero_span(fcx) {
1917 debuginfo::create_function_metadata(fcx);
1923 fn insert_synthetic_type_entries(bcx: @mut Block,
1924 fn_args: &[ast::arg],
1928 * For tuple-like structs and enum-variants, we generate
1929 * synthetic AST nodes for the arguments. These have no types
1930 * in the type table and no entries in the moves table,
1931 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
1932 * gets upset. This hack of a function bridges the gap by inserting types.
1934 * This feels horrible. I think we should just have a special path
1935 * for these functions and not try to use the generic code, but
1936 * that's not the problem I'm trying to solve right now. - nmatsakis
1939 let tcx = bcx.tcx();
1940 for i in range(0u, fn_args.len()) {
1941 debug!("setting type of argument %u (pat node %d) to %s",
1942 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
1944 let pat_id = fn_args[i].pat.id;
1945 let arg_ty = arg_tys[i];
1946 tcx.node_types.insert(pat_id as uint, arg_ty);
1950 pub fn trans_enum_variant(ccx: @mut CrateContext,
1951 _enum_id: ast::NodeId,
1952 variant: &ast::variant,
1953 args: &[ast::variant_arg],
1955 param_substs: Option<@param_substs>,
1956 llfndecl: ValueRef) {
1957 let _icx = push_ctxt("trans_enum_variant");
1959 trans_enum_variant_or_tuple_like_struct(
1968 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1969 fields: &[@ast::struct_field],
1970 ctor_id: ast::NodeId,
1971 param_substs: Option<@param_substs>,
1972 llfndecl: ValueRef) {
1973 let _icx = push_ctxt("trans_tuple_struct");
1975 trans_enum_variant_or_tuple_like_struct(
1985 fn id(&self) -> ast::NodeId;
1986 fn ty<'a>(&'a self) -> &'a ast::Ty;
1989 impl IdAndTy for ast::variant_arg {
1990 fn id(&self) -> ast::NodeId { self.id }
1991 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
1994 impl IdAndTy for @ast::struct_field {
1995 fn id(&self) -> ast::NodeId { self.node.id }
1996 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
1999 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2000 ccx: @mut CrateContext,
2001 ctor_id: ast::NodeId,
2004 param_substs: Option<@param_substs>,
2007 // Translate variant arguments to function arguments.
2008 let fn_args = do args.map |varg| {
2011 ty: (*varg.ty()).clone(),
2012 pat: ast_util::ident_to_pat(
2013 ccx.tcx.sess.next_node_id(),
2014 codemap::dummy_sp(),
2015 special_idents::arg),
2020 let no_substs: &[ty::t] = [];
2021 let ty_param_substs = match param_substs {
2022 Some(ref substs) => {
2023 let v: &[ty::t] = substs.tys;
2027 let v: &[ty::t] = no_substs;
2032 let ctor_ty = ty::subst_tps(ccx.tcx,
2035 ty::node_id_to_type(ccx.tcx, ctor_id));
2037 let result_ty = match ty::get(ctor_ty).sty {
2038 ty::ty_bare_fn(ref bft) => bft.sig.output,
2040 fmt!("trans_enum_variant_or_tuple_like_struct: \
2041 unexpected ctor return type %s",
2042 ty_to_str(ccx.tcx, ctor_ty)))
2045 let fcx = new_fn_ctxt_w_id(ccx,
2055 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2057 let bcx = fcx.entry_bcx.unwrap();
2058 let arg_tys = ty::ty_fn_args(ctor_ty);
2060 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2061 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2063 let repr = adt::represent_type(ccx, result_ty);
2064 adt::trans_start_init(bcx, repr, fcx.llretptr.unwrap(), disr);
2065 for (i, fn_arg) in fn_args.iter().enumerate() {
2066 let lldestptr = adt::trans_field_ptr(bcx,
2068 fcx.llretptr.unwrap(),
2071 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2072 let arg_ty = arg_tys[i];
2073 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2075 finish_fn(fcx, bcx);
2078 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2079 id: ast::NodeId, vi: @~[@ty::VariantInfo],
2081 for variant in enum_definition.variants.iter() {
2082 let disr_val = vi[*i].disr_val;
2085 match variant.node.kind {
2086 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2087 let llfn = get_item_val(ccx, variant.node.id);
2088 trans_enum_variant(ccx, id, variant, *args,
2089 disr_val, None, llfn);
2091 ast::tuple_variant_kind(_) => {
2094 ast::struct_variant_kind(struct_def) => {
2095 trans_struct_def(ccx, struct_def);
2101 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2102 let _icx = push_ctxt("trans_item");
2103 let path = match ccx.tcx.items.get_copy(&item.id) {
2104 ast_map::node_item(_, p) => p,
2106 _ => fail!("trans_item"),
2109 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2110 if purity == ast::extern_fn {
2111 let llfndecl = get_item_val(ccx, item.id);
2112 foreign::trans_foreign_fn(ccx,
2113 vec::append((*path).clone(),
2114 [path_name(item.ident)]),
2119 } else if !generics.is_type_parameterized() {
2120 let llfndecl = get_item_val(ccx, item.id);
2122 vec::append((*path).clone(), [path_name(item.ident)]),
2131 for stmt in body.stmts.iter() {
2133 ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2142 ast::item_impl(ref generics, _, _, ref ms) => {
2143 meth::trans_impl(ccx,
2150 ast::item_mod(ref m) => {
2153 ast::item_enum(ref enum_definition, ref generics) => {
2154 if !generics.is_type_parameterized() {
2155 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2157 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2160 ast::item_static(_, m, expr) => {
2161 consts::trans_const(ccx, m, item.id);
2162 // Do static_assert checking. It can't really be done much earlier because we need to get
2163 // the value of the bool out of LLVM
2164 for attr in item.attrs.iter() {
2165 if "static_assert" == attr.name() {
2166 if m == ast::m_mutbl {
2167 ccx.sess.span_fatal(expr.span,
2168 "cannot have static_assert on a mutable static");
2170 let v = ccx.const_values.get_copy(&item.id);
2172 if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2173 ccx.sess.span_fatal(expr.span, "static assertion failed");
2179 ast::item_foreign_mod(ref foreign_mod) => {
2180 foreign::trans_foreign_mod(ccx, path, foreign_mod);
2182 ast::item_struct(struct_def, ref generics) => {
2183 if !generics.is_type_parameterized() {
2184 trans_struct_def(ccx, struct_def);
2187 _ => {/* fall through */ }
2191 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2192 // If this is a tuple-like struct, translate the constructor.
2193 match struct_def.ctor_id {
2194 // We only need to translate a constructor if there are fields;
2195 // otherwise this is a unit-like struct.
2196 Some(ctor_id) if struct_def.fields.len() > 0 => {
2197 let llfndecl = get_item_val(ccx, ctor_id);
2198 trans_tuple_struct(ccx, struct_def.fields,
2199 ctor_id, None, llfndecl);
2201 Some(_) | None => {}
2205 // Translate a module. Doing this amounts to translating the items in the
2206 // module; there ends up being no artifact (aside from linkage names) of
2207 // separate modules in the compiled program. That's because modules exist
2208 // only as a convenience for humans working with the code, to organize names
2209 // and control visibility.
2210 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2211 let _icx = push_ctxt("trans_mod");
2212 for item in m.items.iter() {
2213 trans_item(ccx, *item);
2217 pub fn register_fn(ccx: @mut CrateContext,
2220 node_id: ast::NodeId,
2223 let llfty = type_of_fn_from_ty(ccx, node_type);
2224 register_fn_llvmty(ccx, sp, sym, node_id, lib::llvm::CCallConv, llfty)
2227 pub fn register_fn_llvmty(ccx: @mut CrateContext,
2230 node_id: ast::NodeId,
2231 cc: lib::llvm::CallConv,
2234 debug!("register_fn_fuller creating fn for item %d with path %s",
2236 ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2238 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2239 ccx.item_symbols.insert(node_id, sym);
2241 // FIXME #4404 android JNI hacks
2242 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2243 (*ccx.sess.building_library &&
2244 ccx.sess.targ_cfg.os == session::os_android));
2246 create_entry_wrapper(ccx, sp, llfn);
2251 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2252 match *sess.entry_fn {
2253 Some((entry_id, _)) => node_id == entry_id,
2258 // Create a _rust_main(args: ~[str]) function which will be called from the
2259 // runtime rust_start function
2260 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2262 main_llfn: ValueRef) {
2263 let et = ccx.sess.entry_type.unwrap();
2265 session::EntryMain => {
2266 let llfn = create_main(ccx, main_llfn);
2267 create_entry_fn(ccx, llfn, true);
2269 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
2270 session::EntryNone => {} // Do nothing.
2273 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2274 let nt = ty::mk_nil();
2276 let llfty = type_of_fn(ccx, [], nt);
2277 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2278 lib::llvm::CCallConv, llfty);
2280 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2282 // the args vector built in create_entry_fn will need
2283 // be updated if this assertion starts to fail.
2284 assert!(fcx.has_immediate_return_value);
2286 let bcx = fcx.entry_bcx.unwrap();
2288 let llenvarg = unsafe {
2289 let env_arg = fcx.env_arg_pos();
2290 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2292 let args = ~[llenvarg];
2293 Call(bcx, main_llfn, args);
2295 finish_fn(fcx, bcx);
2299 fn create_entry_fn(ccx: @mut CrateContext,
2300 rust_main: ValueRef,
2301 use_start_lang_item: bool) {
2302 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2305 // FIXME #4404 android JNI hacks
2306 let llfn = if *ccx.sess.building_library {
2307 decl_cdecl_fn(ccx.llmod, "amain", llfty)
2309 let main_name = match ccx.sess.targ_cfg.os {
2310 session::os_win32 => ~"WinMain@16",
2313 decl_cdecl_fn(ccx.llmod, main_name, llfty)
2315 let llbb = do "top".as_c_str |buf| {
2317 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2320 let bld = ccx.builder.B;
2322 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2324 let crate_map = ccx.crate_map;
2325 let opaque_crate_map = do "crate_map".as_c_str |buf| {
2326 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2329 let (start_fn, args) = if use_start_lang_item {
2330 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2332 Err(s) => { ccx.tcx.sess.fatal(s); }
2334 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2335 get_item_val(ccx, start_def_id.node)
2337 let start_fn_type = csearch::get_type(ccx.tcx,
2339 trans_external_path(ccx, start_def_id, start_fn_type)
2343 let opaque_rust_main = do "rust_main".as_c_str |buf| {
2344 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2348 C_null(Type::opaque_box(ccx).ptr_to()),
2350 llvm::LLVMGetParam(llfn, 0),
2351 llvm::LLVMGetParam(llfn, 1),
2357 debug!("using user-defined start fn");
2359 C_null(Type::opaque_box(ccx).ptr_to()),
2360 llvm::LLVMGetParam(llfn, 0 as c_uint),
2361 llvm::LLVMGetParam(llfn, 1 as c_uint),
2368 let result = llvm::LLVMBuildCall(bld,
2371 args.len() as c_uint,
2373 llvm::LLVMBuildRet(bld, result);
2378 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2379 llenvptr: ValueRef) {
2380 let ccx = bcx.ccx();
2381 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2382 Store(bcx, llfn, code_cell);
2383 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2384 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2385 Store(bcx, llenvblobptr, env_cell);
2388 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2389 match ccx.tcx.items.get_copy(id) {
2390 ast_map::node_item(i, p) =>
2391 vec::append((*p).clone(), [path_name(i.ident)]),
2392 // separate map for paths?
2393 _ => fail!("item_path")
2397 fn exported_name(ccx: @mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2398 if attr::contains_name(attrs, "no_mangle") {
2399 path_elt_to_str(*path.last(), token::get_ident_interner())
2401 mangle_exported_name(ccx, path, ty)
2405 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2406 debug!("get_item_val(id=`%?`)", id);
2408 let val = ccx.item_vals.find_copy(&id);
2412 let mut exprt = false;
2413 let item = ccx.tcx.items.get_copy(&id);
2414 let val = match item {
2415 ast_map::node_item(i, pth) => {
2417 let my_path = vec::append((*pth).clone(), [path_name(i.ident)]);
2418 let ty = ty::node_id_to_type(ccx.tcx, i.id);
2419 let sym = exported_name(ccx, my_path, ty, i.attrs);
2421 let v = match i.node {
2422 ast::item_static(_, m, expr) => {
2423 // We need the translated value here, because for enums the
2424 // LLVM type is not fully determined by the Rust type.
2425 let v = consts::const_expr(ccx, expr);
2426 ccx.const_values.insert(id, v);
2427 exprt = (m == ast::m_mutbl || i.vis == ast::public);
2430 let llty = llvm::LLVMTypeOf(v);
2431 let g = do sym.as_c_str |buf| {
2432 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2435 ccx.item_symbols.insert(i.id, sym);
2440 ast::item_fn(_, purity, _, _, _) => {
2441 let llfn = if purity != ast::extern_fn {
2442 register_fn(ccx, i.span, sym, i.id, ty)
2444 foreign::register_foreign_fn(ccx, i.span, sym, i.id)
2446 set_inline_hint_if_appr(i.attrs, llfn);
2450 _ => fail!("get_item_val: weird result in table")
2453 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2454 Some(sect) => unsafe {
2455 do sect.as_c_str |buf| {
2456 llvm::LLVMSetSection(v, buf);
2465 ast_map::node_trait_method(trait_method, _, pth) => {
2466 debug!("get_item_val(): processing a node_trait_method");
2467 match *trait_method {
2468 ast::required(_) => {
2469 ccx.sess.bug("unexpected variant: required trait method in \
2472 ast::provided(m) => {
2474 register_method(ccx, id, pth, m)
2479 ast_map::node_method(m, _, pth) => {
2480 register_method(ccx, id, pth, m)
2483 ast_map::node_foreign_item(ni, _, _, pth) => {
2484 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2488 ast::foreign_item_fn(*) => {
2489 let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2490 let sym = exported_name(ccx, path, ty, ni.attrs);
2492 register_fn(ccx, ni.span, sym, ni.id, ty)
2494 ast::foreign_item_static(*) => {
2495 let ident = token::ident_to_str(&ni.ident);
2496 let g = do ident.as_c_str |buf| {
2498 let ty = type_of(ccx, ty);
2499 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2507 ast_map::node_variant(ref v, enm, pth) => {
2510 ast::tuple_variant_kind(ref args) => {
2511 assert!(args.len() != 0u);
2512 let pth = vec::append((*pth).clone(),
2513 [path_name(enm.ident),
2514 path_name((*v).node.name)]);
2515 let ty = ty::node_id_to_type(ccx.tcx, id);
2516 let sym = exported_name(ccx, pth, ty, enm.attrs);
2518 llfn = match enm.node {
2519 ast::item_enum(_, _) => {
2520 register_fn(ccx, (*v).span, sym, id, ty)
2522 _ => fail!("node_variant, shouldn't happen")
2525 ast::struct_variant_kind(_) => {
2526 fail!("struct variant kind unexpected in get_item_val")
2529 set_inline_hint(llfn);
2533 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2534 // Only register the constructor if this is a tuple-like struct.
2535 match struct_def.ctor_id {
2537 ccx.tcx.sess.bug("attempt to register a constructor of \
2538 a non-tuple-like struct")
2541 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2542 let sym = exported_name(ccx, (*struct_path).clone(), ty,
2544 let llfn = register_fn(ccx, struct_item.span,
2546 set_inline_hint(llfn);
2553 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2558 if !exprt && !ccx.reachable.contains(&id) {
2559 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2562 ccx.item_vals.insert(id, val);
2568 pub fn register_method(ccx: @mut CrateContext,
2570 path: @ast_map::path,
2571 m: @ast::method) -> ValueRef {
2572 let mty = ty::node_id_to_type(ccx.tcx, id);
2574 let mut path = (*path).clone();
2575 path.push(path_name(gensym_name("meth")));
2576 path.push(path_name(m.ident));
2578 let sym = exported_name(ccx, path, mty, m.attrs);
2580 let llfn = register_fn(ccx, m.span, sym, id, mty);
2581 set_inline_hint_if_appr(m.attrs, llfn);
2585 // The constant translation pass.
2586 pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) {
2587 let _icx = push_ctxt("trans_constant");
2589 ast::item_enum(ref enum_definition, _) => {
2590 let vi = ty::enum_variants(ccx.tcx,
2591 ast::def_id { crate: ast::LOCAL_CRATE,
2594 let path = item_path(ccx, &it.id);
2595 for variant in (*enum_definition).variants.iter() {
2596 let p = vec::append(path.clone(), [
2597 path_name(variant.node.name),
2598 path_name(special_idents::descrim)
2600 let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2601 let disr_val = vi[i].disr_val;
2602 note_unique_llvm_symbol(ccx, s);
2603 let discrim_gvar = do s.as_c_str |buf| {
2605 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2609 llvm::LLVMSetInitializer(discrim_gvar, C_uint(ccx, disr_val));
2610 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2612 ccx.discrims.insert(
2613 local_def(variant.node.id), discrim_gvar);
2614 ccx.discrim_symbols.insert(variant.node.id, s);
2622 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::Crate) {
2623 oldvisit::visit_crate(
2625 oldvisit::mk_simple_visitor(@oldvisit::SimpleVisitor {
2626 visit_item: |a| trans_constant(ccx, a),
2627 ..*oldvisit::default_simple_visitor()
2631 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2633 return PtrToInt(cx, v, ccx.int_type);
2636 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2638 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2643 ($name:expr, $args:expr, $ret:expr) => ({
2645 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2646 intrinsics.insert(name, f);
2650 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2651 let i8p = Type::i8p();
2652 let mut intrinsics = HashMap::new();
2654 ifn!("llvm.memcpy.p0i8.p0i8.i32",
2655 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2656 ifn!("llvm.memcpy.p0i8.p0i8.i64",
2657 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2658 ifn!("llvm.memmove.p0i8.p0i8.i32",
2659 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2660 ifn!("llvm.memmove.p0i8.p0i8.i64",
2661 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2662 ifn!("llvm.memset.p0i8.i32",
2663 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2664 ifn!("llvm.memset.p0i8.i64",
2665 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2667 ifn!("llvm.trap", [], Type::void());
2668 ifn!("llvm.frameaddress", [Type::i32()], i8p);
2670 ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2671 ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2672 ifn!("llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2673 ifn!("llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2675 ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2676 ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2677 ifn!("llvm.sin.f32", [Type::f32()], Type::f32());
2678 ifn!("llvm.sin.f64", [Type::f64()], Type::f64());
2679 ifn!("llvm.cos.f32", [Type::f32()], Type::f32());
2680 ifn!("llvm.cos.f64", [Type::f64()], Type::f64());
2681 ifn!("llvm.exp.f32", [Type::f32()], Type::f32());
2682 ifn!("llvm.exp.f64", [Type::f64()], Type::f64());
2683 ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2684 ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2685 ifn!("llvm.log.f32", [Type::f32()], Type::f32());
2686 ifn!("llvm.log.f64", [Type::f64()], Type::f64());
2687 ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2688 ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2689 ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2690 ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2692 ifn!("llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2693 ifn!("llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2695 ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2696 ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2697 ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2698 ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2699 ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2700 ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2701 ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2702 ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2704 ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2705 ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2706 ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2707 ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2709 ifn!("llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2710 ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2711 ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2712 ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2714 ifn!("llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2715 ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2716 ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2717 ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2719 ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2720 ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2721 ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2726 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2727 ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2728 ifn!("llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2731 pub fn trap(bcx: @mut Block) {
2732 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2733 Some(&x) => { Call(bcx, x, []); },
2734 _ => bcx.sess().bug("unbound llvm.trap in trap")
2738 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2739 if !ccx.sess.opts.gc || !ccx.uses_gc {
2743 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2744 let gc_metadata = do gc_metadata_name.as_c_str |buf| {
2746 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2750 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2751 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2752 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2756 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2757 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2758 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2759 let map = do "_rust_mod_map".as_c_str |buf| {
2761 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2764 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2765 let mut elts: ~[ValueRef] = ~[];
2767 // This is not ideal, but the borrow checker doesn't
2768 // like the multiple borrows. At least, it doesn't
2769 // like them on the current snapshot. (2013-06-14)
2771 for (k, _) in ccx.module_data.iter() {
2772 keys.push(k.to_managed());
2775 for key in keys.iter() {
2776 let val = *ccx.module_data.find_equiv(key).unwrap();
2777 let s_const = C_cstr(ccx, *key);
2778 let s_ptr = p2i(ccx, s_const);
2779 let v_ptr = p2i(ccx, val);
2780 let elt = C_struct([s_ptr, v_ptr]);
2783 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2786 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2792 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2793 llmod: ModuleRef) -> ValueRef {
2794 let targ_cfg = sess.targ_cfg;
2795 let int_type = Type::int(targ_cfg.arch);
2796 let mut n_subcrates = 1;
2797 let cstore = sess.cstore;
2798 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2799 let mapname = if *sess.building_library {
2800 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2804 let sym_name = ~"_rust_crate_map_" + mapname;
2805 let arrtype = Type::array(&int_type, n_subcrates as u64);
2806 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2807 let map = do sym_name.as_c_str |buf| {
2809 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2812 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2816 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2817 let mut subcrates: ~[ValueRef] = ~[];
2819 let cstore = ccx.sess.cstore;
2820 while cstore::have_crate_data(cstore, i) {
2821 let cdata = cstore::get_crate_data(cstore, i);
2822 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2824 cstore::get_crate_vers(cstore, i),
2825 cstore::get_crate_hash(cstore, i));
2826 let cr = do nm.as_c_str |buf| {
2828 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2831 subcrates.push(p2i(ccx, cr));
2834 subcrates.push(C_int(ccx, 0));
2836 let llannihilatefn = match ccx.tcx.lang_items.annihilate_fn() {
2837 Some(annihilate_def_id) => {
2838 if annihilate_def_id.crate == ast::LOCAL_CRATE {
2839 get_item_val(ccx, annihilate_def_id.node)
2841 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2842 annihilate_def_id).ty;
2843 trans_external_path(ccx, annihilate_def_id, annihilate_fn_type)
2846 None => { C_null(Type::i8p()) }
2850 let mod_map = create_module_map(ccx);
2851 llvm::LLVMSetInitializer(map, C_struct(
2853 lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2855 C_array(ccx.int_type, subcrates)]));
2859 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2860 -> encoder::EncodeParams<'r> {
2862 let diag = cx.sess.diagnostic();
2863 let item_symbols = &cx.item_symbols;
2864 let discrim_symbols = &cx.discrim_symbols;
2865 let link_meta = &cx.link_meta;
2866 encoder::EncodeParams {
2869 reexports2: cx.exp_map2,
2870 item_symbols: item_symbols,
2871 discrim_symbols: discrim_symbols,
2872 link_meta: link_meta,
2873 cstore: cx.sess.cstore,
2874 encode_inlined_item: ie,
2875 reachable: cx.reachable,
2879 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
2880 if !*cx.sess.building_library { return; }
2882 let encode_inlined_item: encoder::encode_inlined_item =
2883 |ecx, ebml_w, path, ii|
2884 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2886 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2887 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2888 let llconst = C_struct([llmeta]);
2889 let mut llglobal = do "rust_metadata".as_c_str |buf| {
2891 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2895 llvm::LLVMSetInitializer(llglobal, llconst);
2896 do cx.sess.targ_cfg.target_strs.meta_sect_name.as_c_str |buf| {
2897 llvm::LLVMSetSection(llglobal, buf)
2899 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2901 let t_ptr_i8 = Type::i8p();
2902 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2903 let llvm_used = do "llvm.used".as_c_str |buf| {
2904 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2906 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2907 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2911 fn mk_global(ccx: &CrateContext,
2917 let llglobal = do name.as_c_str |buf| {
2918 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
2920 llvm::LLVMSetInitializer(llglobal, llval);
2921 llvm::LLVMSetGlobalConstant(llglobal, True);
2924 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2931 // Writes the current ABI version into the crate.
2932 pub fn write_abi_version(ccx: &mut CrateContext) {
2933 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2936 pub fn trans_crate(sess: session::Session,
2938 analysis: &CrateAnalysis,
2939 output: &Path) -> CrateTranslation {
2940 // Before we touch LLVM, make sure that multithreading is enabled.
2941 if unsafe { !llvm::LLVMRustStartMultithreading() } {
2942 //sess.bug("couldn't enable multi-threaded LLVM");
2945 let mut symbol_hasher = hash::default_state();
2946 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2948 // Append ".rc" to crate name as LLVM module identifier.
2950 // LLVM code generator emits a ".file filename" directive
2951 // for ELF backends. Value of the "filename" is set as the
2952 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2953 // crashes if the module identifer is same as other symbols
2954 // such as a function name in the module.
2955 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2956 let llmod_id = link_meta.name.to_owned() + ".rc";
2958 let ccx = @mut CrateContext::new(sess,
2965 analysis.reachable);
2968 let _icx = push_ctxt("data");
2969 trans_constants(ccx, crate);
2973 let _icx = push_ctxt("text");
2974 trans_mod(ccx, &crate.module);
2977 decl_gc_metadata(ccx, llmod_id);
2978 fill_crate_map(ccx, ccx.crate_map);
2979 glue::emit_tydescs(ccx);
2980 write_abi_version(ccx);
2981 if ccx.sess.opts.debuginfo {
2982 debuginfo::finalize(ccx);
2985 // Translate the metadata.
2986 write_metadata(ccx, crate);
2987 if ccx.sess.trans_stats() {
2988 io::println("--- trans stats ---");
2989 printfln!("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
2990 printfln!("n_glues_created: %u", ccx.stats.n_glues_created);
2991 printfln!("n_null_glues: %u", ccx.stats.n_null_glues);
2992 printfln!("n_real_glues: %u", ccx.stats.n_real_glues);
2994 printfln!("n_fns: %u", ccx.stats.n_fns);
2995 printfln!("n_monos: %u", ccx.stats.n_monos);
2996 printfln!("n_inlines: %u", ccx.stats.n_inlines);
2997 printfln!("n_closures: %u", ccx.stats.n_closures);
2998 io::println("fn stats:");
2999 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3002 for tuple in ccx.stats.fn_stats.iter() {
3004 (ref name, ms, insns) => {
3005 printfln!("%u insns, %u ms, %s", insns, ms, *name);
3010 if ccx.sess.count_llvm_insns() {
3011 for (k, v) in ccx.stats.llvm_insns.iter() {
3012 printfln!("%-7u %s", *v, *k);
3016 let llcx = ccx.llcx;
3017 let link_meta = ccx.link_meta;
3018 let llmod = ccx.llmod;
3020 return CrateTranslation {