1 // Copyright 2012-2014 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 #[allow(non_camel_case_types)];
13 //! Code that is useful in various trans modules.
15 use driver::session::Session;
16 use lib::llvm::{ValueRef, BasicBlockRef, BuilderRef};
17 use lib::llvm::{True, False, Bool};
20 use middle::lang_items::LangItem;
21 use middle::trans::base;
22 use middle::trans::build;
23 use middle::trans::cleanup;
24 use middle::trans::datum;
25 use middle::trans::datum::{Datum, Lvalue};
26 use middle::trans::debuginfo;
27 use middle::trans::type_::Type;
28 use middle::ty::substs;
31 use util::ppaux::Repr;
32 use util::nodemap::NodeMap;
34 use arena::TypedArena;
35 use collections::HashMap;
36 use std::c_str::ToCStr;
37 use std::cell::{Cell, RefCell};
38 use std::libc::{c_uint, c_longlong, c_ulonglong, c_char};
40 use syntax::ast::Ident;
42 use syntax::ast_map::{PathElem, PathName};
43 use syntax::codemap::Span;
44 use syntax::parse::token::InternedString;
45 use syntax::parse::token;
47 pub use middle::trans::context::CrateContext;
49 fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
50 match ty::get(ty).sty {
51 ty::ty_struct(def_id, ref substs) => {
52 let fields = ty::struct_fields(ccx.tcx, def_id, substs);
54 fields.get(0).ident.name ==
55 token::special_idents::unnamed_field.name &&
56 type_is_immediate(ccx, fields.get(0).mt.ty)
62 pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
63 use middle::trans::machine::llsize_of_alloc;
64 use middle::trans::type_of::sizing_type_of;
66 let simple = ty::type_is_scalar(ty) || ty::type_is_boxed(ty) ||
67 ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
68 type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
69 ty::type_is_simd(tcx, ty);
73 match ty::get(ty).sty {
75 ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) => {
76 let llty = sizing_type_of(ccx, ty);
77 llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type)
79 _ => type_is_zero_size(ccx, ty)
83 pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
85 * Identify types which have size zero at runtime.
88 use middle::trans::machine::llsize_of_alloc;
89 use middle::trans::type_of::sizing_type_of;
90 let llty = sizing_type_of(ccx, ty);
91 llsize_of_alloc(ccx, llty) == 0
94 pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
96 * Identifies types which we declare to be equivalent to `void`
97 * in C for the purpose of function return types. These are
98 * `()`, bot, and uninhabited enums. Note that all such types
99 * are also zero-size, but not all zero-size types use a `void`
100 * return type (in order to aid with C ABI compatibility).
103 ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx, ty)
106 /// Generates a unique symbol based off the name given. This is used to create
107 /// unique symbols for things like closures.
108 pub fn gensym_name(name: &str) -> PathElem {
109 let num = token::gensym(name);
110 // use one colon which will get translated to a period by the mangler, and
111 // we're guaranteed that `num` is globally unique for this crate.
112 PathName(token::gensym(format!("{}:{}", name, num)))
115 pub struct tydesc_info {
121 visit_glue: Cell<Option<ValueRef>>,
125 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
127 * An "extern" is an LLVM symbol we wind up emitting an undefined external
128 * reference to. This means "we don't have the thing in this compilation unit,
129 * please make sure you link it in at runtime". This could be a reference to
130 * C code found in a C library, or rust code found in a rust crate.
132 * Most "externs" are implicitly declared (automatically) as a result of a
133 * user declaring an extern _module_ dependency; this causes the rust driver
134 * to locate an extern crate, scan its compilation metadata, and emit extern
135 * declarations for any symbols used by the declaring crate.
137 * A "foreign" is an extern that references C (or other non-rust ABI) code.
138 * There is no metadata to scan for extern references so in these cases either
139 * a header-digester like bindgen, or manual function prototypes, have to
140 * serve as declarators. So these are usually given explicitly as prototype
141 * declarations, in rust code, with ABI attributes on them noting which ABI to
144 * An "upcall" is a foreign call generated by the compiler (not corresponding
145 * to any user-written call in the code) into the runtime library, to perform
146 * some helper task such as bringing a task to life, allocating memory, etc.
150 pub struct NodeInfo {
155 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
156 NodeInfo { id: expr.id, span: expr.span }
160 n_static_tydescs: Cell<uint>,
161 n_glues_created: Cell<uint>,
162 n_null_glues: Cell<uint>,
163 n_real_glues: Cell<uint>,
166 n_inlines: Cell<uint>,
167 n_closures: Cell<uint>,
168 n_llvm_insns: Cell<uint>,
169 llvm_insns: RefCell<HashMap<~str, uint>>,
170 // (ident, time-in-ms, llvm-instructions)
171 fn_stats: RefCell<Vec<(~str, uint, uint)> >,
174 pub struct BuilderRef_res {
178 impl Drop for BuilderRef_res {
181 llvm::LLVMDisposeBuilder(self.b);
186 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
192 pub type ExternMap = HashMap<~str, ValueRef>;
194 // Here `self_ty` is the real type of the self parameter to this method. It
195 // will only be set in the case of default methods.
196 pub struct param_substs {
198 self_ty: Option<ty::t>,
199 vtables: Option<typeck::vtable_res>,
200 self_vtables: Option<typeck::vtable_param_res>
204 pub fn validate(&self) {
205 for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
206 for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
210 fn param_substs_to_str(this: ¶m_substs, tcx: ty::ctxt) -> ~str {
211 format!("param_substs \\{tys:{}, vtables:{}\\}",
213 this.vtables.repr(tcx))
216 impl Repr for param_substs {
217 fn repr(&self, tcx: ty::ctxt) -> ~str {
218 param_substs_to_str(self, tcx)
222 // work around bizarre resolve errors
223 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
224 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
226 // Function context. Every LLVM function we create will have one of
228 pub struct FunctionContext<'a> {
229 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
230 // address of the first instruction in the sequence of
231 // instructions for this function that will go in the .text
232 // section of the executable we're generating.
235 // The environment argument in a closure.
236 llenv: Option<ValueRef>,
238 // The place to store the return value. If the return type is immediate,
239 // this is an alloca in the function. Otherwise, it's the hidden first
240 // parameter to the function. After function construction, this should
242 llretptr: Cell<Option<ValueRef>>,
244 entry_bcx: RefCell<Option<&'a Block<'a>>>,
246 // These elements: "hoisted basic blocks" containing
247 // administrative activities that have to happen in only one place in
248 // the function, due to LLVM's quirks.
249 // A marker for the place where we want to insert the function's static
250 // allocas, so that LLVM will coalesce them into a single alloca call.
251 alloca_insert_pt: Cell<Option<ValueRef>>,
252 llreturn: Cell<Option<BasicBlockRef>>,
254 // The a value alloca'd for calls to upcalls.rust_personality. Used when
255 // outputting the resume instruction.
256 personality: Cell<Option<ValueRef>>,
258 // True if the caller expects this fn to use the out pointer to
259 // return. Either way, your code should write into llretptr, but if
260 // this value is false, llretptr will be a local alloca.
261 caller_expects_out_pointer: bool,
263 // Maps arguments to allocas created for them in llallocas.
264 llargs: RefCell<NodeMap<LvalueDatum>>,
266 // Maps the def_ids for local variables to the allocas created for
267 // them in llallocas.
268 lllocals: RefCell<NodeMap<LvalueDatum>>,
270 // Same as above, but for closure upvars
271 llupvars: RefCell<NodeMap<ValueRef>>,
273 // The NodeId of the function, or -1 if it doesn't correspond to
274 // a user-defined function.
277 // If this function is being monomorphized, this contains the type
278 // substitutions used.
279 param_substs: Option<@param_substs>,
281 // The source span and nesting context where this function comes from, for
282 // error reporting and symbol generation.
285 // The arena that blocks are allocated from.
286 block_arena: &'a TypedArena<Block<'a>>,
288 // This function's enclosing crate context.
291 // Used and maintained by the debuginfo module.
292 debug_context: debuginfo::FunctionDebugContext,
295 scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
298 impl<'a> FunctionContext<'a> {
299 pub fn arg_pos(&self, arg: uint) -> uint {
300 let arg = self.env_arg_pos() + arg;
301 if self.llenv.is_some() {
308 pub fn out_arg_pos(&self) -> uint {
309 assert!(self.caller_expects_out_pointer);
313 pub fn env_arg_pos(&self) -> uint {
314 if self.caller_expects_out_pointer {
321 pub fn cleanup(&self) {
323 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
327 // Remove the cycle between fcx and bcx, so memory can be freed
328 self.entry_bcx.set(None);
331 pub fn get_llreturn(&self) -> BasicBlockRef {
332 if self.llreturn.get().is_none() {
333 self.llreturn.set(Some(base::mk_return_basic_block(self.llfn)));
336 self.llreturn.get().unwrap()
339 pub fn new_block(&'a self,
342 opt_node_id: Option<ast::NodeId>)
345 let llbb = name.with_c_str(|buf| {
346 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
350 Block::new(llbb, is_lpad, opt_node_id, self)
354 pub fn new_id_block(&'a self,
356 node_id: ast::NodeId)
358 self.new_block(false, name, Some(node_id))
361 pub fn new_temp_block(&'a self,
364 self.new_block(false, name, None)
367 pub fn join_blocks(&'a self,
369 in_cxs: &[&'a Block<'a>])
371 let out = self.new_id_block("join", id);
372 let mut reachable = false;
373 for bcx in in_cxs.iter() {
374 if !bcx.unreachable.get() {
375 build::Br(*bcx, out.llbb);
380 build::Unreachable(out);
386 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
387 if !ccx.do_not_commit_warning_issued.get() {
388 ccx.do_not_commit_warning_issued.set(true);
389 ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
393 // Heap selectors. Indicate which heap something should go on.
398 heap_exchange_closure
401 // Basic block context. We create a block context for each basic block
402 // (single-entry, single-exit sequence of instructions) we generate from Rust
403 // code. Each basic block we generate is attached to a function, typically
404 // with many basic blocks per function. All the basic blocks attached to a
405 // function are organized as a directed graph.
406 pub struct Block<'a> {
407 // The BasicBlockRef returned from a call to
408 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
409 // block to the function pointed to by llfn. We insert
410 // instructions into that block by way of this block context.
411 // The block pointing to this one in the function's digraph.
413 terminated: Cell<bool>,
414 unreachable: Cell<bool>,
416 // Is this block part of a landing pad?
419 // AST node-id associated with this block, if any. Used for
420 // debugging purposes only.
421 opt_node_id: Option<ast::NodeId>,
423 // The function context for the function to which this block is
425 fcx: &'a FunctionContext<'a>,
432 opt_node_id: Option<ast::NodeId>,
433 fcx: &'a FunctionContext<'a>)
435 fcx.block_arena.alloc(Block {
437 terminated: Cell::new(false),
438 unreachable: Cell::new(false),
440 opt_node_id: opt_node_id,
445 pub fn ccx(&self) -> @CrateContext { self.fcx.ccx }
446 pub fn tcx(&self) -> ty::ctxt {
449 pub fn sess(&self) -> Session { self.fcx.ccx.sess }
451 pub fn ident(&self, ident: Ident) -> ~str {
452 token::get_ident(ident).get().to_str()
455 pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
456 self.tcx().map.node_to_str(id)
459 pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
463 pub fn expr_is_lval(&self, e: &ast::Expr) -> bool {
464 ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
467 pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind {
468 ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
471 pub fn def(&self, nid: ast::NodeId) -> ast::Def {
472 let def_map = self.tcx().def_map.borrow();
473 match def_map.get().find(&nid) {
476 self.tcx().sess.bug(format!(
477 "no def associated with node id {:?}", nid));
482 pub fn val_to_str(&self, val: ValueRef) -> ~str {
483 self.ccx().tn.val_to_str(val)
486 pub fn llty_str(&self, ty: Type) -> ~str {
487 self.ccx().tn.type_to_str(ty)
490 pub fn ty_to_str(&self, t: ty::t) -> ~str {
494 pub fn to_str(&self) -> ~str {
495 let blk: *Block = self;
496 format!("[block {}]", blk)
500 pub struct Result<'a> {
505 pub fn rslt<'a>(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
512 impl<'a> Result<'a> {
513 pub fn unpack(&self, bcx: &mut &'a Block<'a>) -> ValueRef {
519 pub fn val_ty(v: ValueRef) -> Type {
521 Type::from_ref(llvm::LLVMTypeOf(v))
525 // LLVM constant constructors.
526 pub fn C_null(t: Type) -> ValueRef {
528 llvm::LLVMConstNull(t.to_ref())
532 pub fn C_undef(t: Type) -> ValueRef {
534 llvm::LLVMGetUndef(t.to_ref())
538 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
540 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
544 pub fn C_floating(s: &str, t: Type) -> ValueRef {
546 s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
550 pub fn C_nil() -> ValueRef {
554 pub fn C_bool(val: bool) -> ValueRef {
555 C_integral(Type::bool(), val as u64, false)
558 pub fn C_i1(val: bool) -> ValueRef {
559 C_integral(Type::i1(), val as u64, false)
562 pub fn C_i32(i: i32) -> ValueRef {
563 return C_integral(Type::i32(), i as u64, true);
566 pub fn C_i64(i: i64) -> ValueRef {
567 return C_integral(Type::i64(), i as u64, true);
570 pub fn C_u64(i: u64) -> ValueRef {
571 return C_integral(Type::i64(), i, false);
574 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
575 return C_integral(cx.int_type, i as u64, true);
578 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
579 return C_integral(cx.int_type, i as u64, false);
582 pub fn C_u8(i: uint) -> ValueRef {
583 return C_integral(Type::i8(), i as u64, false);
587 // This is a 'c-like' raw string, which differs from
588 // our boxed-and-length-annotated strings.
589 pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef {
592 let const_cstr_cache = cx.const_cstr_cache.borrow();
593 match const_cstr_cache.get().find(&s) {
594 Some(&llval) => return llval,
599 let sc = llvm::LLVMConstStringInContext(cx.llcx,
600 s.get().as_ptr() as *c_char,
601 s.get().len() as c_uint,
604 let gsym = token::gensym("str");
605 let g = format!("str{}", gsym).with_c_str(|buf| {
606 llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
608 llvm::LLVMSetInitializer(g, sc);
609 llvm::LLVMSetGlobalConstant(g, True);
610 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
612 let mut const_cstr_cache = cx.const_cstr_cache.borrow_mut();
613 const_cstr_cache.get().insert(s, g);
618 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
619 // you will be kicked off fast isel. See issue #4352 for an example of this.
620 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
622 let len = s.get().len();
623 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
624 C_struct([cs, C_uint(cx, len)], false)
628 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
630 let len = data.len();
631 let lldata = C_bytes(data);
633 let gsym = token::gensym("binary");
634 let g = format!("binary{}", gsym).with_c_str(|buf| {
635 llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
637 llvm::LLVMSetInitializer(g, lldata);
638 llvm::LLVMSetGlobalConstant(g, True);
639 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
641 let cs = llvm::LLVMConstPointerCast(g, Type::i8p().to_ref());
642 C_struct([cs, C_uint(cx, len)], false)
646 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
649 let mut elts: Vec<ValueRef> = Vec::new();
650 while i < size { elts.push(C_u8(0u)); i += 1u; }
651 return llvm::LLVMConstArray(Type::i8().to_ref(),
652 elts.as_ptr(), elts.len() as c_uint);
656 pub fn C_struct(elts: &[ValueRef], packed: bool) -> ValueRef {
659 llvm::LLVMConstStructInContext(base::task_llcx(),
660 elts.as_ptr(), elts.len() as c_uint,
665 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
667 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
671 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
673 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
677 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
679 let ptr = bytes.as_ptr() as *c_char;
680 return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
684 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
686 llvm::LLVMGetParam(fndecl, param as c_uint)
690 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
693 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
695 debug!("const_get_elt(v={}, us={:?}, r={})",
696 cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
702 pub fn is_const(v: ValueRef) -> bool {
704 llvm::LLVMIsConstant(v) == True
708 pub fn const_to_int(v: ValueRef) -> c_longlong {
710 llvm::LLVMConstIntGetSExtValue(v)
714 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
716 llvm::LLVMConstIntGetZExtValue(v)
720 pub fn is_undef(val: ValueRef) -> bool {
722 llvm::LLVMIsUndef(val) != False
726 pub fn is_null(val: ValueRef) -> bool {
728 llvm::LLVMIsNull(val) != False
732 // Used to identify cached monomorphized functions and vtables
733 #[deriving(Eq, Hash)]
734 pub enum mono_param_id {
735 mono_precise(ty::t, Option<@Vec<mono_id> >),
737 mono_repr(uint /* size */,
743 #[deriving(Eq, Hash)]
744 pub enum MonoDataClass {
745 MonoBits, // Anything not treated differently from arbitrary integer data
746 MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
747 // FIXME(#3547)---scalars and floats are
748 // treated differently in most ABIs. But we
749 // should be doing something more detailed
754 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
755 match ty::get(t).sty {
756 ty::ty_float(_) => MonoFloat,
757 ty::ty_rptr(..) | ty::ty_uniq(..) | ty::ty_box(..) |
758 ty::ty_str(ty::vstore_uniq) | ty::ty_vec(_, ty::vstore_uniq) |
759 ty::ty_bare_fn(..) => MonoNonNull,
760 // Is that everything? Would closures or slices qualify?
765 #[deriving(Eq, Hash)]
766 pub struct mono_id_ {
768 params: Vec<mono_param_id> }
770 pub type mono_id = @mono_id_;
772 pub fn umax(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
773 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
774 return build::Select(cx, cond, b, a);
777 pub fn umin(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
778 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
779 return build::Select(cx, cond, a, b);
782 pub fn align_to(cx: &Block, off: ValueRef, align: ValueRef) -> ValueRef {
783 let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
784 let bumped = build::Add(cx, off, mask);
785 return build::And(cx, bumped, build::Not(cx, mask));
788 pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
789 match bcx.fcx.param_substs {
791 ty::subst_tps(bcx.tcx(), substs.tys.as_slice(), substs.self_ty, t)
794 assert!(!ty::type_has_params(t));
795 assert!(!ty::type_has_self(t));
801 pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
803 let t = ty::node_id_to_type(tcx, id);
804 monomorphize_type(bcx, t)
807 pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
808 node_id_type(bcx, ex.id)
811 pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
813 let t = ty::expr_ty_adjusted(tcx, ex, bcx.ccx().maps.method_map.borrow().get());
814 monomorphize_type(bcx, t)
817 // Key used to lookup values supplied for type parameters in an expr.
819 pub enum ExprOrMethodCall {
820 // Type parameters for a path like `None::<int>`
823 // Type parameters for a method call like `a.foo::<int>()`
824 MethodCall(typeck::MethodCall)
827 pub fn node_id_type_params(bcx: &Block, node: ExprOrMethodCall) -> Vec<ty::t> {
829 let params = match node {
830 ExprId(id) => ty::node_id_to_type_params(tcx, id),
831 MethodCall(method_call) => {
832 bcx.ccx().maps.method_map.borrow().get().get(&method_call).substs.tps.clone()
836 if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
838 format!("type parameters for node {:?} include inference types: {}",
839 node, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
842 match bcx.fcx.param_substs {
844 params.iter().map(|t| {
845 ty::subst_tps(tcx, substs.tys.as_slice(), substs.self_ty, *t)
852 pub fn node_vtables(bcx: &Block, id: ast::NodeId)
853 -> Option<typeck::vtable_res> {
854 let vtable_map = bcx.ccx().maps.vtable_map.borrow();
855 let raw_vtables = vtable_map.get().find(&id);
856 raw_vtables.map(|vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
859 // Apply the typaram substitutions in the FunctionContext to some
860 // vtables. This should eliminate any vtable_params.
861 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
862 -> typeck::vtable_res {
863 resolve_vtables_under_param_substs(fcx.ccx.tcx,
868 pub fn resolve_vtables_under_param_substs(tcx: ty::ctxt,
869 param_substs: Option<@param_substs>,
870 vts: typeck::vtable_res)
871 -> typeck::vtable_res {
873 resolve_param_vtables_under_param_substs(tcx,
879 pub fn resolve_param_vtables_under_param_substs(
881 param_substs: Option<@param_substs>,
882 ds: typeck::vtable_param_res)
883 -> typeck::vtable_param_res {
885 |d| resolve_vtable_under_param_substs(tcx,
893 pub fn resolve_vtable_under_param_substs(tcx: ty::ctxt,
894 param_substs: Option<@param_substs>,
895 vt: &typeck::vtable_origin)
896 -> typeck::vtable_origin {
898 typeck::vtable_static(trait_id, ref tys, sub) => {
899 let tys = match param_substs {
903 substs.tys.as_slice(),
908 _ => Vec::from_slice(tys.as_slice())
910 typeck::vtable_static(
912 resolve_vtables_under_param_substs(tcx, param_substs, sub))
914 typeck::vtable_param(n_param, n_bound) => {
917 find_vtable(tcx, substs, n_param, n_bound)
920 tcx.sess.bug(format!(
921 "resolve_vtable_under_param_substs: asked to lookup \
922 but no vtables in the fn_ctxt!"))
929 pub fn find_vtable(tcx: ty::ctxt,
931 n_param: typeck::param_index,
933 -> typeck::vtable_origin {
934 debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
935 n_param, n_bound, ps.repr(tcx));
937 let param_bounds = match n_param {
938 typeck::param_self => ps.self_vtables.expect("self vtables missing"),
939 typeck::param_numbered(n) => {
940 let tables = ps.vtables
941 .expect("vtables missing where they are needed");
945 param_bounds.get(n_bound).clone()
948 pub fn dummy_substs(tps: Vec<ty::t> ) -> ty::substs {
950 regions: ty::ErasedRegions,
956 pub fn filename_and_line_num_from_span(bcx: &Block, span: Span)
957 -> (ValueRef, ValueRef) {
958 let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
959 let filename_cstr = C_cstr(bcx.ccx(),
960 token::intern_and_get_ident(loc.file.name));
961 let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
962 let line = C_int(bcx.ccx(), loc.line as int);
966 // Casts a Rust bool value to an i1.
967 pub fn bool_to_i1(bcx: &Block, llval: ValueRef) -> ValueRef {
968 build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))
971 pub fn langcall(bcx: &Block,
976 match bcx.tcx().lang_items.require(li) {
979 let msg = format!("{} {}", msg, s);
981 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
982 None => { bcx.tcx().sess.fatal(msg); }