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 //! Code that is useful in various trans modules.
16 use driver::session::Session;
17 use lib::llvm::{ValueRef, BasicBlockRef, BuilderRef};
18 use lib::llvm::{True, False, Bool};
19 use lib::llvm::{llvm};
21 use middle::trans::base;
22 use middle::trans::build;
23 use middle::trans::datum;
24 use middle::trans::glue;
25 use middle::trans::write_guard;
26 use middle::ty::substs;
29 use middle::borrowck::root_map_key;
30 use util::ppaux::{Repr};
32 use middle::trans::type_::Type;
34 use core::cast::transmute;
36 use core::hashmap::{HashMap};
37 use core::libc::{c_uint, c_longlong, c_ulonglong};
40 use syntax::ast::ident;
41 use syntax::ast_map::{path, path_elt};
42 use syntax::codemap::span;
43 use syntax::parse::token;
44 use syntax::{ast, ast_map};
46 pub use middle::trans::context::CrateContext;
48 // NOTE: this thunk is totally pointless now that we're not passing
49 // interners around...
50 pub type namegen = @fn(s: &str) -> ident;
51 pub fn new_namegen() -> namegen {
52 let f: @fn(s: &str) -> ident = |prefix| {
53 token::str_to_ident(fmt!("%s_%u", prefix, token::gensym(prefix)))
58 pub struct tydesc_info {
63 take_glue: Option<ValueRef>,
64 drop_glue: Option<ValueRef>,
65 free_glue: Option<ValueRef>,
66 visit_glue: Option<ValueRef>
70 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
72 * An "extern" is an LLVM symbol we wind up emitting an undefined external
73 * reference to. This means "we don't have the thing in this compilation unit,
74 * please make sure you link it in at runtime". This could be a reference to
75 * C code found in a C library, or rust code found in a rust crate.
77 * Most "externs" are implicitly declared (automatically) as a result of a
78 * user declaring an extern _module_ dependency; this causes the rust driver
79 * to locate an extern crate, scan its compilation metadata, and emit extern
80 * declarations for any symbols used by the declaring crate.
82 * A "foreign" is an extern that references C (or other non-rust ABI) code.
83 * There is no metadata to scan for extern references so in these cases either
84 * a header-digester like bindgen, or manual function prototypes, have to
85 * serve as declarators. So these are usually given explicitly as prototype
86 * declarations, in rust code, with ABI attributes on them noting which ABI to
89 * An "upcall" is a foreign call generated by the compiler (not corresponding
90 * to any user-written call in the code) into the runtime library, to perform
91 * some helper task such as bringing a task to life, allocating memory, etc.
96 n_static_tydescs: uint,
97 n_glues_created: uint,
104 llvm_insns: HashMap<~str, uint>,
105 fn_times: ~[(~str, int)] // (ident, time)
108 pub struct BuilderRef_res {
112 impl Drop for BuilderRef_res {
115 llvm::LLVMDisposeBuilder(self.B);
120 pub fn BuilderRef_res(B: BuilderRef) -> BuilderRef_res {
126 pub type ExternMap = HashMap<@str, ValueRef>;
128 // Types used for llself.
129 pub struct ValSelfData {
135 // Here `self_ty` is the real type of the self parameter to this method. It
136 // will only be set in the case of default methods.
137 pub struct param_substs {
139 vtables: Option<typeck::vtable_res>,
140 type_param_defs: @~[ty::TypeParameterDef],
141 self_ty: Option<ty::t>
145 pub fn validate(&self) {
146 for self.tys.iter().advance |t| { assert!(!ty::type_needs_infer(*t)); }
147 for self.self_ty.iter().advance |t| { assert!(!ty::type_needs_infer(*t)); }
151 fn param_substs_to_str(this: ¶m_substs, tcx: ty::ctxt) -> ~str {
152 fmt!("param_substs {tys:%s, vtables:%s, type_param_defs:%s}",
154 this.vtables.repr(tcx),
155 this.type_param_defs.repr(tcx))
158 impl Repr for param_substs {
159 fn repr(&self, tcx: ty::ctxt) -> ~str {
160 param_substs_to_str(self, tcx)
164 impl Repr for @param_substs {
165 fn repr(&self, tcx: ty::ctxt) -> ~str {
166 param_substs_to_str(*self, tcx)
170 // Function context. Every LLVM function we create will have one of
172 pub struct fn_ctxt_ {
173 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
174 // address of the first instruction in the sequence of
175 // instructions for this function that will go in the .text
176 // section of the executable we're generating.
179 // The implicit environment argument that arrives in the function we're
183 // The place to store the return value. If the return type is immediate,
184 // this is an alloca in the function. Otherwise, it's the hidden first
185 // parameter to the function. After function construction, this should
187 llretptr: Option<ValueRef>,
189 // These elements: "hoisted basic blocks" containing
190 // administrative activities that have to happen in only one place in
191 // the function, due to LLVM's quirks.
192 // A block for all the function's static allocas, so that LLVM
193 // will coalesce them into a single alloca call.
194 llstaticallocas: BasicBlockRef,
195 // A block containing code that copies incoming arguments to space
196 // already allocated by code in one of the llallocas blocks.
197 // (LLVM requires that arguments be copied to local allocas before
198 // allowing most any operation to be performed on them.)
199 llloadenv: Option<BasicBlockRef>,
200 llreturn: BasicBlockRef,
201 // The 'self' value currently in use in this function, if there
204 // NB: This is the type of the self *variable*, not the self *type*. The
205 // self type is set only for default methods, while the self variable is
206 // set for all methods.
207 llself: Option<ValSelfData>,
208 // The a value alloca'd for calls to upcalls.rust_personality. Used when
209 // outputting the resume instruction.
210 personality: Option<ValueRef>,
211 // If this is a for-loop body that returns, this holds the pointers needed
212 // for that (flagptr, retptr)
213 loop_ret: Option<(ValueRef, ValueRef)>,
215 // True if this function has an immediate return value, false otherwise.
216 // If this is false, the llretptr will alias the first argument of the
218 has_immediate_return_value: bool,
220 // Maps arguments to allocas created for them in llallocas.
221 llargs: @mut HashMap<ast::node_id, ValueRef>,
222 // Maps the def_ids for local variables to the allocas created for
223 // them in llallocas.
224 lllocals: @mut HashMap<ast::node_id, ValueRef>,
225 // Same as above, but for closure upvars
226 llupvars: @mut HashMap<ast::node_id, ValueRef>,
228 // The node_id of the function, or -1 if it doesn't correspond to
229 // a user-defined function.
232 // The def_id of the impl we're inside, or None if we aren't inside one.
233 impl_id: Option<ast::def_id>,
235 // If this function is being monomorphized, this contains the type
236 // substitutions used.
237 param_substs: Option<@param_substs>,
239 // The source span and nesting context where this function comes from, for
240 // error reporting and symbol generation.
244 // This function's enclosing crate context.
245 ccx: @mut CrateContext
249 pub fn arg_pos(&self, arg: uint) -> uint {
250 if self.has_immediate_return_value {
257 pub fn out_arg_pos(&self) -> uint {
258 assert!(self.has_immediate_return_value);
262 pub fn env_arg_pos(&self) -> uint {
263 if !self.has_immediate_return_value {
272 pub type fn_ctxt = @mut fn_ctxt_;
274 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
275 if !ccx.do_not_commit_warning_issued {
276 ccx.do_not_commit_warning_issued = true;
277 ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
281 // Heap selectors. Indicate which heap something should go on.
292 normal_exit_and_unwind
296 clean(@fn(block) -> block, cleantype),
297 clean_temp(ValueRef, @fn(block) -> block, cleantype),
300 // Used to remember and reuse existing cleanup paths
301 // target: none means the path ends in an resume instruction
302 pub struct cleanup_path {
303 target: Option<BasicBlockRef>,
308 pub fn shrink_scope_clean(scope_info: &mut scope_info, size: uint) {
309 scope_info.landing_pad = None;
310 scope_info.cleanup_paths = scope_info.cleanup_paths.iter()
311 .take_while(|&cu| cu.size <= size).transform(|&x|x).collect();
314 pub fn grow_scope_clean(scope_info: &mut scope_info) {
315 scope_info.landing_pad = None;
318 pub fn cleanup_type(cx: ty::ctxt, ty: ty::t) -> cleantype {
319 if ty::type_needs_unwind_cleanup(cx, ty) {
320 normal_exit_and_unwind
326 pub fn add_clean(bcx: block, val: ValueRef, t: ty::t) {
327 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
329 debug!("add_clean(%s, %s, %s)", bcx.to_str(), bcx.val_to_str(val), t.repr(bcx.tcx()));
331 let cleanup_type = cleanup_type(bcx.tcx(), t);
332 do in_scope_cx(bcx) |scope_info| {
333 scope_info.cleanups.push(clean(|a| glue::drop_ty(a, val, t), cleanup_type));
334 grow_scope_clean(scope_info);
338 pub fn add_clean_temp_immediate(cx: block, val: ValueRef, ty: ty::t) {
339 if !ty::type_needs_drop(cx.tcx(), ty) { return; }
340 debug!("add_clean_temp_immediate(%s, %s, %s)",
341 cx.to_str(), cx.val_to_str(val),
343 let cleanup_type = cleanup_type(cx.tcx(), ty);
344 do in_scope_cx(cx) |scope_info| {
345 scope_info.cleanups.push(
346 clean_temp(val, |a| glue::drop_ty_immediate(a, val, ty),
348 grow_scope_clean(scope_info);
351 pub fn add_clean_temp_mem(bcx: block, val: ValueRef, t: ty::t) {
352 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
353 debug!("add_clean_temp_mem(%s, %s, %s)",
354 bcx.to_str(), bcx.val_to_str(val),
356 let cleanup_type = cleanup_type(bcx.tcx(), t);
357 do in_scope_cx(bcx) |scope_info| {
358 scope_info.cleanups.push(clean_temp(val, |a| glue::drop_ty(a, val, t), cleanup_type));
359 grow_scope_clean(scope_info);
362 pub fn add_clean_return_to_mut(bcx: block,
363 root_key: root_map_key,
364 frozen_val_ref: ValueRef,
365 bits_val_ref: ValueRef,
366 filename_val: ValueRef,
367 line_val: ValueRef) {
368 //! When an `@mut` has been frozen, we have to
369 //! call the lang-item `return_to_mut` when the
370 //! freeze goes out of scope. We need to pass
371 //! in both the value which was frozen (`frozen_val`) and
372 //! the value (`bits_val_ref`) which was returned when the
373 //! box was frozen initially. Here, both `frozen_val_ref` and
374 //! `bits_val_ref` are in fact pointers to stack slots.
376 debug!("add_clean_return_to_mut(%s, %s, %s)",
378 bcx.val_to_str(frozen_val_ref),
379 bcx.val_to_str(bits_val_ref));
380 do in_scope_cx(bcx) |scope_info| {
381 scope_info.cleanups.push(
384 |bcx| write_guard::return_to_mut(bcx, root_key, frozen_val_ref, bits_val_ref,
385 filename_val, line_val),
387 grow_scope_clean(scope_info);
390 pub fn add_clean_free(cx: block, ptr: ValueRef, heap: heap) {
391 let free_fn = match heap {
392 heap_managed | heap_managed_unique => {
393 let f: @fn(block) -> block = |a| glue::trans_free(a, ptr);
397 let f: @fn(block) -> block = |a| glue::trans_exchange_free(a, ptr);
401 do in_scope_cx(cx) |scope_info| {
402 scope_info.cleanups.push(clean_temp(ptr, free_fn,
403 normal_exit_and_unwind));
404 grow_scope_clean(scope_info);
408 // Note that this only works for temporaries. We should, at some point, move
409 // to a system where we can also cancel the cleanup on local variables, but
410 // this will be more involved. For now, we simply zero out the local, and the
411 // drop glue checks whether it is zero.
412 pub fn revoke_clean(cx: block, val: ValueRef) {
413 do in_scope_cx(cx) |scope_info| {
414 let scope_info = &mut *scope_info; // FIXME(#5074) workaround borrowck
415 let cleanup_pos = scope_info.cleanups.iter().position_(
417 clean_temp(v, _, _) if v == val => true,
420 for cleanup_pos.iter().advance |i| {
421 scope_info.cleanups =
422 vec::append(vec::slice(scope_info.cleanups, 0u, *i).to_owned(),
423 vec::slice(scope_info.cleanups,
425 scope_info.cleanups.len()));
426 shrink_scope_clean(scope_info, *i);
431 pub fn block_cleanups(bcx: block) -> ~[cleanup] {
433 block_non_scope => ~[],
434 block_scope(inf) => /*bad*/copy inf.cleanups
438 pub enum block_kind {
439 // A scope at the end of which temporary values created inside of it are
440 // cleaned up. May correspond to an actual block in the language, but also
441 // to an implicit scope, for example, calls introduce an implicit scope in
442 // which the arguments are evaluated and cleaned up.
443 block_scope(@mut scope_info),
445 // A non-scope block is a basic block created as a translation artifact
446 // from translating code that expresses conditional logic rather than by
447 // explicit { ... } block structure in the source language. It's called a
448 // non-scope block because it doesn't introduce a new variable scope.
452 pub struct scope_info {
453 loop_break: Option<block>,
454 loop_label: Option<ident>,
455 // A list of functions that must be run at when leaving this
456 // block, cleaning up any variables that were introduced in the
458 cleanups: ~[cleanup],
459 // Existing cleanup paths that may be reused, indexed by destination and
460 // cleared when the set of cleanups changes.
461 cleanup_paths: ~[cleanup_path],
462 // Unwinding landing pad. Also cleared when cleanups change.
463 landing_pad: Option<BasicBlockRef>,
467 pub fn empty_cleanups(&mut self) -> bool {
468 self.cleanups.is_empty()
472 pub trait get_node_info {
473 fn info(&self) -> Option<NodeInfo>;
476 impl get_node_info for @ast::expr {
477 fn info(&self) -> Option<NodeInfo> {
478 Some(NodeInfo {id: self.id,
479 callee_id: self.get_callee_id(),
484 impl get_node_info for ast::blk {
485 fn info(&self) -> Option<NodeInfo> {
486 Some(NodeInfo {id: self.node.id,
492 impl get_node_info for Option<@ast::expr> {
493 fn info(&self) -> Option<NodeInfo> {
494 self.chain_ref(|s| s.info())
498 pub struct NodeInfo {
500 callee_id: Option<ast::node_id>,
504 // Basic block context. We create a block context for each basic block
505 // (single-entry, single-exit sequence of instructions) we generate from Rust
506 // code. Each basic block we generate is attached to a function, typically
507 // with many basic blocks per function. All the basic blocks attached to a
508 // function are organized as a directed graph.
510 // The BasicBlockRef returned from a call to
511 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
512 // block to the function pointed to by llfn. We insert
513 // instructions into that block by way of this block context.
514 // The block pointing to this one in the function's digraph.
518 parent: Option<block>,
519 // The 'kind' of basic block this is.
521 // Is this block part of a landing pad?
523 // info about the AST node this block originated from, if any
524 node_info: Option<NodeInfo>,
525 // The function context for the function to which this block is
530 pub fn block_(llbb: BasicBlockRef, parent: Option<block>, kind: block_kind,
531 is_lpad: bool, node_info: Option<NodeInfo>, fcx: fn_ctxt)
541 node_info: node_info,
546 pub type block = @mut block_;
548 pub fn mk_block(llbb: BasicBlockRef, parent: Option<block>, kind: block_kind,
549 is_lpad: bool, node_info: Option<NodeInfo>, fcx: fn_ctxt)
551 @mut block_(llbb, parent, kind, is_lpad, node_info, fcx)
559 pub fn rslt(bcx: block, val: ValueRef) -> Result {
560 Result {bcx: bcx, val: val}
564 pub fn unpack(&self, bcx: &mut block) -> ValueRef {
570 pub fn val_ty(v: ValueRef) -> Type {
572 Type::from_ref(llvm::LLVMTypeOf(v))
576 pub fn in_scope_cx(cx: block, f: &fn(si: @mut scope_info)) {
580 block_scope(inf) => {
581 debug!("in_scope_cx: selected cur=%s (cx=%s)",
582 cur.to_str(), cx.to_str());
588 cur = block_parent(cur);
592 pub fn block_parent(cx: block) -> block {
595 None => cx.sess().bug(fmt!("block_parent called on root block %?",
603 pub fn ccx(&self) -> @mut CrateContext { self.fcx.ccx }
604 pub fn tcx(&self) -> ty::ctxt { self.fcx.ccx.tcx }
605 pub fn sess(&self) -> Session { self.fcx.ccx.sess }
607 pub fn node_id_to_str(&self, id: ast::node_id) -> ~str {
608 ast_map::node_id_to_str(self.tcx().items, id, self.sess().intr())
611 pub fn expr_to_str(&self, e: @ast::expr) -> ~str {
615 pub fn expr_is_lval(&self, e: @ast::expr) -> bool {
616 ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
619 pub fn expr_kind(&self, e: @ast::expr) -> ty::ExprKind {
620 ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
623 pub fn def(&self, nid: ast::node_id) -> ast::def {
624 match self.tcx().def_map.find(&nid) {
627 self.tcx().sess.bug(fmt!(
628 "No def associated with node id %?", nid));
633 pub fn val_to_str(&self, val: ValueRef) -> ~str {
634 self.ccx().tn.val_to_str(val)
637 pub fn llty_str(&self, ty: Type) -> ~str {
638 self.ccx().tn.type_to_str(ty)
641 pub fn ty_to_str(&self, t: ty::t) -> ~str {
645 pub fn to_str(&self) -> ~str {
647 match self.node_info {
648 Some(node_info) => fmt!("[block %d]", node_info.id),
649 None => fmt!("[block %x]", transmute(&*self)),
655 // Let T be the content of a box @T. tuplify_box_ty(t) returns the
656 // representation of @T as a tuple (i.e., the ty::t version of what T_box()
658 pub fn tuplify_box_ty(tcx: ty::ctxt, t: ty::t) -> ty::t {
659 let ptr = ty::mk_ptr(
661 ty::mt {ty: ty::mk_nil(), mutbl: ast::m_imm}
663 return ty::mk_tup(tcx, ~[ty::mk_uint(), ty::mk_type(tcx),
669 // LLVM constant constructors.
670 pub fn C_null(t: Type) -> ValueRef {
672 llvm::LLVMConstNull(t.to_ref())
676 pub fn C_undef(t: Type) -> ValueRef {
678 llvm::LLVMGetUndef(t.to_ref())
682 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
684 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
688 pub fn C_floating(s: &str, t: Type) -> ValueRef {
690 do s.as_c_str |buf| {
691 llvm::LLVMConstRealOfString(t.to_ref(), buf)
696 pub fn C_nil() -> ValueRef {
700 pub fn C_bool(val: bool) -> ValueRef {
701 C_integral(Type::bool(), val as u64, false)
704 pub fn C_i1(val: bool) -> ValueRef {
705 C_integral(Type::i1(), val as u64, false)
708 pub fn C_i32(i: i32) -> ValueRef {
709 return C_integral(Type::i32(), i as u64, true);
712 pub fn C_i64(i: i64) -> ValueRef {
713 return C_integral(Type::i64(), i as u64, true);
716 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
717 return C_integral(cx.int_type, i as u64, true);
720 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
721 return C_integral(cx.int_type, i as u64, false);
724 pub fn C_u8(i: uint) -> ValueRef {
725 return C_integral(Type::i8(), i as u64, false);
729 // This is a 'c-like' raw string, which differs from
730 // our boxed-and-length-annotated strings.
731 pub fn C_cstr(cx: &mut CrateContext, s: @str) -> ValueRef {
733 match cx.const_cstr_cache.find_equiv(&s) {
734 Some(&llval) => return llval,
738 let sc = do s.as_c_str |buf| {
739 llvm::LLVMConstStringInContext(cx.llcx, buf, s.len() as c_uint, False)
742 let gsym = token::gensym("str");
743 let g = do fmt!("str%u", gsym).as_c_str |buf| {
744 llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
746 llvm::LLVMSetInitializer(g, sc);
747 llvm::LLVMSetGlobalConstant(g, True);
748 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
750 cx.const_cstr_cache.insert(s, g);
756 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
757 // you will be kicked off fast isel. See issue #4352 for an example of this.
758 pub fn C_estr_slice(cx: &mut CrateContext, s: @str) -> ValueRef {
761 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
762 C_struct([cs, C_uint(cx, len + 1u /* +1 for null */)])
766 // Returns a Plain Old LLVM String:
767 pub fn C_postr(s: &str) -> ValueRef {
769 do s.as_c_str |buf| {
770 llvm::LLVMConstStringInContext(base::task_llcx(), buf, s.len() as c_uint, False)
775 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
778 let mut elts: ~[ValueRef] = ~[];
779 while i < size { elts.push(C_u8(0u)); i += 1u; }
780 return llvm::LLVMConstArray(Type::i8().to_ref(),
781 vec::raw::to_ptr(elts), elts.len() as c_uint);
785 pub fn C_struct(elts: &[ValueRef]) -> ValueRef {
787 do vec::as_imm_buf(elts) |ptr, len| {
788 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, False)
793 pub fn C_packed_struct(elts: &[ValueRef]) -> ValueRef {
795 do vec::as_imm_buf(elts) |ptr, len| {
796 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, True)
801 pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef {
803 do vec::as_imm_buf(elts) |ptr, len| {
804 llvm::LLVMConstNamedStruct(T.to_ref(), ptr, len as c_uint)
809 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
811 return llvm::LLVMConstArray(ty.to_ref(), vec::raw::to_ptr(elts), elts.len() as c_uint);
815 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
817 let ptr = cast::transmute(vec::raw::to_ptr(bytes));
818 return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
822 pub fn C_bytes_plus_null(bytes: &[u8]) -> ValueRef {
824 let ptr = cast::transmute(vec::raw::to_ptr(bytes));
825 return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint,False);
829 pub fn C_shape(ccx: &CrateContext, bytes: ~[u8]) -> ValueRef {
831 let llshape = C_bytes_plus_null(bytes);
832 let name = fmt!("shape%u", token::gensym("shape"));
833 let llglobal = do name.as_c_str |buf| {
834 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llshape).to_ref(), buf)
836 llvm::LLVMSetInitializer(llglobal, llshape);
837 llvm::LLVMSetGlobalConstant(llglobal, True);
838 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
839 return llvm::LLVMConstPointerCast(llglobal, Type::i8p().to_ref());
843 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
845 llvm::LLVMGetParam(fndecl, param as c_uint)
849 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
852 let r = do vec::as_imm_buf(us) |p, len| {
853 llvm::LLVMConstExtractValue(v, p, len as c_uint)
856 debug!("const_get_elt(v=%s, us=%?, r=%s)",
857 cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
863 pub fn const_to_int(v: ValueRef) -> c_longlong {
865 llvm::LLVMConstIntGetSExtValue(v)
869 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
871 llvm::LLVMConstIntGetZExtValue(v)
875 pub fn is_undef(val: ValueRef) -> bool {
877 llvm::LLVMIsUndef(val) != False
881 pub fn is_null(val: ValueRef) -> bool {
883 llvm::LLVMIsNull(val) != False
887 // Used to identify cached monomorphized functions and vtables
889 pub enum mono_param_id {
890 mono_precise(ty::t, Option<@~[mono_id]>),
892 mono_repr(uint /* size */,
899 pub enum MonoDataClass {
900 MonoBits, // Anything not treated differently from arbitrary integer data
901 MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
902 // FIXME(#3547)---scalars and floats are
903 // treated differently in most ABIs. But we
904 // should be doing something more detailed
909 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
910 match ty::get(t).sty {
911 ty::ty_float(_) => MonoFloat,
912 ty::ty_rptr(*) | ty::ty_uniq(*) |
913 ty::ty_box(*) | ty::ty_opaque_box(*) |
914 ty::ty_estr(ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_uniq) |
915 ty::ty_estr(ty::vstore_box) | ty::ty_evec(_, ty::vstore_box) |
916 ty::ty_bare_fn(*) => MonoNonNull,
917 // Is that everything? Would closures or slices qualify?
924 pub struct mono_id_ {
926 params: ~[mono_param_id],
927 impl_did_opt: Option<ast::def_id>
930 pub type mono_id = @mono_id_;
932 impl to_bytes::IterBytes for mono_param_id {
933 fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
935 mono_precise(t, ref mids) => {
936 0u8.iter_bytes(lsb0, f) &&
937 ty::type_id(t).iter_bytes(lsb0, f) &&
938 mids.iter_bytes(lsb0, f)
941 mono_any => 1u8.iter_bytes(lsb0, f),
943 mono_repr(ref a, ref b, ref c, ref d) => {
944 2u8.iter_bytes(lsb0, f) &&
945 a.iter_bytes(lsb0, f) &&
946 b.iter_bytes(lsb0, f) &&
947 c.iter_bytes(lsb0, f) &&
948 d.iter_bytes(lsb0, f)
954 impl to_bytes::IterBytes for MonoDataClass {
955 fn iter_bytes(&self, lsb0: bool, f:to_bytes::Cb) -> bool {
956 (*self as u8).iter_bytes(lsb0, f)
960 impl to_bytes::IterBytes for mono_id_ {
961 fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
962 self.def.iter_bytes(lsb0, f) && self.params.iter_bytes(lsb0, f)
966 pub fn umax(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
967 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
968 return build::Select(cx, cond, b, a);
971 pub fn umin(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
972 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
973 return build::Select(cx, cond, a, b);
976 pub fn align_to(cx: block, off: ValueRef, align: ValueRef) -> ValueRef {
977 let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
978 let bumped = build::Add(cx, off, mask);
979 return build::And(cx, bumped, build::Not(cx, mask));
982 pub fn path_str(sess: session::Session, p: &[path_elt]) -> ~str {
984 let mut first = true;
985 for p.iter().advance |e| {
987 ast_map::path_name(s) | ast_map::path_mod(s) => {
988 if first { first = false; }
997 pub fn monomorphize_type(bcx: block, t: ty::t) -> ty::t {
998 match bcx.fcx.param_substs {
1000 ty::subst_tps(bcx.tcx(), substs.tys, substs.self_ty, t)
1002 _ => { assert!(!ty::type_has_params(t)); t }
1006 pub fn node_id_type(bcx: block, id: ast::node_id) -> ty::t {
1007 let tcx = bcx.tcx();
1008 let t = ty::node_id_to_type(tcx, id);
1009 monomorphize_type(bcx, t)
1012 pub fn expr_ty(bcx: block, ex: @ast::expr) -> ty::t {
1013 node_id_type(bcx, ex.id)
1016 pub fn expr_ty_adjusted(bcx: block, ex: @ast::expr) -> ty::t {
1017 let tcx = bcx.tcx();
1018 let t = ty::expr_ty_adjusted(tcx, ex);
1019 monomorphize_type(bcx, t)
1022 pub fn node_id_type_params(bcx: block, id: ast::node_id) -> ~[ty::t] {
1023 let tcx = bcx.tcx();
1024 let params = ty::node_id_to_type_params(tcx, id);
1026 if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
1028 fmt!("Type parameters for node %d include inference types: %s",
1029 id, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
1032 match bcx.fcx.param_substs {
1034 do vec::map(params) |t| {
1035 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1042 pub fn node_vtables(bcx: block, id: ast::node_id)
1043 -> Option<typeck::vtable_res> {
1044 let raw_vtables = bcx.ccx().maps.vtable_map.find(&id);
1046 |&vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
1049 pub fn resolve_vtables_in_fn_ctxt(fcx: fn_ctxt, vts: typeck::vtable_res)
1050 -> typeck::vtable_res {
1051 @vec::map(*vts, |d| resolve_vtable_in_fn_ctxt(fcx, copy *d))
1054 // Apply the typaram substitutions in the fn_ctxt to a vtable. This should
1055 // eliminate any vtable_params.
1056 pub fn resolve_vtable_in_fn_ctxt(fcx: fn_ctxt, vt: typeck::vtable_origin)
1057 -> typeck::vtable_origin {
1058 let tcx = fcx.ccx.tcx;
1060 typeck::vtable_static(trait_id, tys, sub) => {
1061 let tys = match fcx.param_substs {
1063 do vec::map(tys) |t| {
1064 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1069 typeck::vtable_static(trait_id, tys,
1070 resolve_vtables_in_fn_ctxt(fcx, sub))
1072 typeck::vtable_param(n_param, n_bound) => {
1073 match fcx.param_substs {
1075 find_vtable(tcx, substs, n_param, n_bound)
1079 "resolve_vtable_in_fn_ctxt: asked to lookup but \
1080 no vtables in the fn_ctxt!"))
1087 pub fn find_vtable(tcx: ty::ctxt, ps: ¶m_substs,
1088 n_param: uint, n_bound: uint)
1089 -> typeck::vtable_origin {
1090 debug!("find_vtable(n_param=%u, n_bound=%u, ps=%s)",
1091 n_param, n_bound, ps.repr(tcx));
1093 // Vtables are stored in a flat array, finding the right one is
1095 let first_n_type_param_defs = ps.type_param_defs.slice(0, n_param);
1096 let vtables_to_skip =
1097 ty::count_traits_and_supertraits(tcx, first_n_type_param_defs);
1098 let vtable_off = vtables_to_skip + n_bound;
1099 /*bad*/ copy ps.vtables.get()[vtable_off]
1102 pub fn dummy_substs(tps: ~[ty::t]) -> ty::substs {
1104 self_r: Some(ty::re_bound(ty::br_self)),
1110 pub fn filename_and_line_num_from_span(bcx: block,
1111 span: span) -> (ValueRef, ValueRef) {
1112 let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
1113 let filename_cstr = C_cstr(bcx.ccx(), loc.file.name);
1114 let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
1115 let line = C_int(bcx.ccx(), loc.line as int);
1119 // Casts a Rust bool value to an i1.
1120 pub fn bool_to_i1(bcx: block, llval: ValueRef) -> ValueRef {
1121 build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))