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, non_snake_case_functions)]
13 //! Code that is useful in various trans modules.
15 use driver::session::Session;
17 use llvm::{ValueRef, BasicBlockRef, BuilderRef};
18 use llvm::{True, False, Bool};
20 use middle::lang_items::LangItem;
22 use middle::subst::Subst;
23 use middle::trans::build;
24 use middle::trans::cleanup;
25 use middle::trans::datum;
26 use middle::trans::debuginfo;
27 use middle::trans::type_::Type;
30 use util::ppaux::Repr;
31 use util::nodemap::NodeMap;
33 use arena::TypedArena;
34 use std::collections::HashMap;
35 use libc::{c_uint, c_longlong, c_ulonglong, c_char};
36 use std::c_str::ToCStr;
37 use std::cell::{Cell, RefCell};
39 use syntax::ast::Ident;
41 use syntax::ast_map::{PathElem, PathName};
42 use syntax::codemap::Span;
43 use syntax::parse::token::InternedString;
44 use syntax::parse::token;
46 pub use middle::trans::context::CrateContext;
48 fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
49 match ty::get(ty).sty {
50 ty::ty_struct(def_id, ref substs) => {
51 let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
53 fields.get(0).ident.name ==
54 token::special_idents::unnamed_field.name &&
55 type_is_immediate(ccx, fields.get(0).mt.ty)
61 pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
62 use middle::trans::machine::llsize_of_alloc;
63 use middle::trans::type_of::sizing_type_of;
65 let simple = ty::type_is_scalar(ty) || ty::type_is_boxed(ty) ||
66 ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
67 type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
68 ty::type_is_simd(tcx, ty);
69 if simple && !ty::type_is_trait(ty) {
72 match ty::get(ty).sty {
74 ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) |
75 ty::ty_unboxed_closure(..) => {
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).as_slice()))
115 pub struct tydesc_info {
117 pub tydesc: ValueRef,
121 pub 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 }
159 pub struct BuilderRef_res {
163 impl Drop for BuilderRef_res {
166 llvm::LLVMDisposeBuilder(self.b);
171 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
177 pub type ExternMap = HashMap<String, ValueRef>;
179 // Here `self_ty` is the real type of the self parameter to this method. It
180 // will only be set in the case of default methods.
181 pub struct param_substs {
182 pub substs: subst::Substs,
183 pub vtables: typeck::vtable_res,
187 pub fn empty() -> param_substs {
189 substs: subst::Substs::trans_empty(),
190 vtables: subst::VecPerParamSpace::empty(),
194 pub fn validate(&self) {
195 assert!(self.substs.types.all(|t| !ty::type_needs_infer(*t)));
199 fn param_substs_to_string(this: ¶m_substs, tcx: &ty::ctxt) -> String {
200 format!("param_substs({})", this.substs.repr(tcx))
203 impl Repr for param_substs {
204 fn repr(&self, tcx: &ty::ctxt) -> String {
205 param_substs_to_string(self, tcx)
210 fn substp(&self, tcx: &ty::ctxt, param_substs: ¶m_substs)
214 impl<T:Subst+Clone> SubstP for T {
215 fn substp(&self, tcx: &ty::ctxt, substs: ¶m_substs) -> T {
216 self.subst(tcx, &substs.substs)
220 // work around bizarre resolve errors
221 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
222 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
224 #[deriving(Clone, Eq, PartialEq)]
225 pub enum HandleItemsFlag {
230 // Function context. Every LLVM function we create will have one of
232 pub struct FunctionContext<'a> {
233 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
234 // address of the first instruction in the sequence of
235 // instructions for this function that will go in the .text
236 // section of the executable we're generating.
239 // The environment argument in a closure.
240 pub llenv: Option<ValueRef>,
242 // The place to store the return value. If the return type is immediate,
243 // this is an alloca in the function. Otherwise, it's the hidden first
244 // parameter to the function. After function construction, this should
246 pub llretptr: Cell<Option<ValueRef>>,
248 // These pub elements: "hoisted basic blocks" containing
249 // administrative activities that have to happen in only one place in
250 // the function, due to LLVM's quirks.
251 // A marker for the place where we want to insert the function's static
252 // allocas, so that LLVM will coalesce them into a single alloca call.
253 pub alloca_insert_pt: Cell<Option<ValueRef>>,
254 pub llreturn: Cell<Option<BasicBlockRef>>,
256 // The a value alloca'd for calls to upcalls.rust_personality. Used when
257 // outputting the resume instruction.
258 pub personality: Cell<Option<ValueRef>>,
260 // True if the caller expects this fn to use the out pointer to
261 // return. Either way, your code should write into llretptr, but if
262 // this value is false, llretptr will be a local alloca.
263 pub caller_expects_out_pointer: bool,
265 // Maps arguments to allocas created for them in llallocas.
266 pub llargs: RefCell<NodeMap<LvalueDatum>>,
268 // Maps the def_ids for local variables to the allocas created for
269 // them in llallocas.
270 pub lllocals: RefCell<NodeMap<LvalueDatum>>,
272 // Same as above, but for closure upvars
273 pub llupvars: RefCell<NodeMap<ValueRef>>,
275 // The NodeId of the function, or -1 if it doesn't correspond to
276 // a user-defined function.
279 // If this function is being monomorphized, this contains the type
280 // substitutions used.
281 pub param_substs: &'a param_substs,
283 // The source span and nesting context where this function comes from, for
284 // error reporting and symbol generation.
285 pub span: Option<Span>,
287 // The arena that blocks are allocated from.
288 pub block_arena: &'a TypedArena<Block<'a>>,
290 // This function's enclosing crate context.
291 pub ccx: &'a CrateContext,
293 // Used and maintained by the debuginfo module.
294 pub debug_context: debuginfo::FunctionDebugContext,
297 pub scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
299 // How to handle items encountered during translation of this function.
300 pub handle_items: HandleItemsFlag,
303 impl<'a> FunctionContext<'a> {
304 pub fn arg_pos(&self, arg: uint) -> uint {
305 let arg = self.env_arg_pos() + arg;
306 if self.llenv.is_some() {
313 pub fn out_arg_pos(&self) -> uint {
314 assert!(self.caller_expects_out_pointer);
318 pub fn env_arg_pos(&self) -> uint {
319 if self.caller_expects_out_pointer {
326 pub fn cleanup(&self) {
328 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
334 pub fn get_llreturn(&self) -> BasicBlockRef {
335 if self.llreturn.get().is_none() {
337 self.llreturn.set(Some(unsafe {
338 "return".with_c_str(|buf| {
339 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx, self.llfn, buf)
344 self.llreturn.get().unwrap()
347 pub fn new_block(&'a self,
350 opt_node_id: Option<ast::NodeId>)
353 let llbb = name.with_c_str(|buf| {
354 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
358 Block::new(llbb, is_lpad, opt_node_id, self)
362 pub fn new_id_block(&'a self,
364 node_id: ast::NodeId)
366 self.new_block(false, name, Some(node_id))
369 pub fn new_temp_block(&'a self,
372 self.new_block(false, name, None)
375 pub fn join_blocks(&'a self,
377 in_cxs: &[&'a Block<'a>])
379 let out = self.new_id_block("join", id);
380 let mut reachable = false;
381 for bcx in in_cxs.iter() {
382 if !bcx.unreachable.get() {
383 build::Br(*bcx, out.llbb);
388 build::Unreachable(out);
394 // Basic block context. We create a block context for each basic block
395 // (single-entry, single-exit sequence of instructions) we generate from Rust
396 // code. Each basic block we generate is attached to a function, typically
397 // with many basic blocks per function. All the basic blocks attached to a
398 // function are organized as a directed graph.
399 pub struct Block<'a> {
400 // The BasicBlockRef returned from a call to
401 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
402 // block to the function pointed to by llfn. We insert
403 // instructions into that block by way of this block context.
404 // The block pointing to this one in the function's digraph.
405 pub llbb: BasicBlockRef,
406 pub terminated: Cell<bool>,
407 pub unreachable: Cell<bool>,
409 // Is this block part of a landing pad?
412 // AST node-id associated with this block, if any. Used for
413 // debugging purposes only.
414 pub opt_node_id: Option<ast::NodeId>,
416 // The function context for the function to which this block is
418 pub fcx: &'a FunctionContext<'a>,
425 opt_node_id: Option<ast::NodeId>,
426 fcx: &'a FunctionContext<'a>)
428 fcx.block_arena.alloc(Block {
430 terminated: Cell::new(false),
431 unreachable: Cell::new(false),
433 opt_node_id: opt_node_id,
438 pub fn ccx(&self) -> &'a CrateContext { self.fcx.ccx }
439 pub fn tcx(&self) -> &'a ty::ctxt {
442 pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
444 pub fn ident(&self, ident: Ident) -> String {
445 token::get_ident(ident).get().to_string()
448 pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
449 self.tcx().map.node_to_string(id).to_string()
452 pub fn expr_to_string(&self, e: &ast::Expr) -> String {
456 pub fn def(&self, nid: ast::NodeId) -> def::Def {
457 match self.tcx().def_map.borrow().find(&nid) {
460 self.tcx().sess.bug(format!(
461 "no def associated with node id {:?}", nid).as_slice());
466 pub fn val_to_string(&self, val: ValueRef) -> String {
467 self.ccx().tn.val_to_string(val)
470 pub fn llty_str(&self, ty: Type) -> String {
471 self.ccx().tn.type_to_string(ty)
474 pub fn ty_to_string(&self, t: ty::t) -> String {
478 pub fn to_str(&self) -> String {
479 let blk: *const Block = self;
480 format!("[block {}]", blk)
484 pub struct Result<'a> {
485 pub bcx: &'a Block<'a>,
489 impl<'a> Result<'a> {
490 pub fn new(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
498 pub fn val_ty(v: ValueRef) -> Type {
500 Type::from_ref(llvm::LLVMTypeOf(v))
504 // LLVM constant constructors.
505 pub fn C_null(t: Type) -> ValueRef {
507 llvm::LLVMConstNull(t.to_ref())
511 pub fn C_undef(t: Type) -> ValueRef {
513 llvm::LLVMGetUndef(t.to_ref())
517 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
519 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
523 pub fn C_floating(s: &str, t: Type) -> ValueRef {
525 s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
529 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
530 C_struct(ccx, [], false)
533 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
534 C_integral(Type::i1(ccx), val as u64, false)
537 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
538 C_integral(Type::i32(ccx), i as u64, true)
541 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
542 C_integral(Type::i64(ccx), i as u64, true)
545 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
546 C_integral(Type::i64(ccx), i, false)
549 pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
550 C_integral(ccx.int_type, i as u64, true)
553 pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
554 C_integral(ccx.int_type, i as u64, false)
557 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
558 C_integral(Type::i8(ccx), i as u64, false)
562 // This is a 'c-like' raw string, which differs from
563 // our boxed-and-length-annotated strings.
564 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
566 match cx.const_cstr_cache.borrow().find(&s) {
567 Some(&llval) => return llval,
571 let sc = llvm::LLVMConstStringInContext(cx.llcx,
572 s.get().as_ptr() as *const c_char,
573 s.get().len() as c_uint,
574 !null_terminated as Bool);
576 let gsym = token::gensym("str");
577 let g = format!("str{}", gsym).with_c_str(|buf| {
578 llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
580 llvm::LLVMSetInitializer(g, sc);
581 llvm::LLVMSetGlobalConstant(g, True);
582 llvm::SetLinkage(g, llvm::InternalLinkage);
584 cx.const_cstr_cache.borrow_mut().insert(s, g);
589 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
590 // you will be kicked off fast isel. See issue #4352 for an example of this.
591 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
593 let len = s.get().len();
594 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s, false),
595 Type::i8p(cx).to_ref());
596 C_named_struct(cx.tn.find_type("str_slice").unwrap(), [cs, C_uint(cx, len)])
600 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
602 let len = data.len();
603 let lldata = C_bytes(cx, data);
605 let gsym = token::gensym("binary");
606 let g = format!("binary{}", gsym).with_c_str(|buf| {
607 llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
609 llvm::LLVMSetInitializer(g, lldata);
610 llvm::LLVMSetGlobalConstant(g, True);
611 llvm::SetLinkage(g, llvm::InternalLinkage);
613 let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
614 C_struct(cx, [cs, C_uint(cx, len)], false)
618 pub fn C_struct(ccx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
620 llvm::LLVMConstStructInContext(ccx.llcx,
621 elts.as_ptr(), elts.len() as c_uint,
626 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
628 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
632 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
634 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
638 pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef {
640 let ptr = bytes.as_ptr() as *const c_char;
641 return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True);
645 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
648 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
650 debug!("const_get_elt(v={}, us={:?}, r={})",
651 cx.tn.val_to_string(v), us, cx.tn.val_to_string(r));
657 pub fn is_const(v: ValueRef) -> bool {
659 llvm::LLVMIsConstant(v) == True
663 pub fn const_to_int(v: ValueRef) -> c_longlong {
665 llvm::LLVMConstIntGetSExtValue(v)
669 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
671 llvm::LLVMConstIntGetZExtValue(v)
675 pub fn is_undef(val: ValueRef) -> bool {
677 llvm::LLVMIsUndef(val) != False
681 pub fn is_null(val: ValueRef) -> bool {
683 llvm::LLVMIsNull(val) != False
687 pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
688 t.subst(bcx.tcx(), &bcx.fcx.param_substs.substs)
691 pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
693 let t = ty::node_id_to_type(tcx, id);
694 monomorphize_type(bcx, t)
697 pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
698 node_id_type(bcx, ex.id)
701 pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
702 monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
705 // Key used to lookup values supplied for type parameters in an expr.
706 #[deriving(PartialEq)]
707 pub enum ExprOrMethodCall {
708 // Type parameters for a path like `None::<int>`
711 // Type parameters for a method call like `a.foo::<int>()`
712 MethodCall(typeck::MethodCall)
715 pub fn node_id_substs(bcx: &Block,
716 node: ExprOrMethodCall)
720 let substs = match node {
722 ty::node_id_item_substs(tcx, id).substs
724 MethodCall(method_call) => {
725 tcx.method_map.borrow().get(&method_call).substs.clone()
729 if substs.types.any(|t| ty::type_needs_infer(*t)) {
731 format!("type parameters for node {:?} include inference types: \
734 substs.repr(bcx.tcx())).as_slice());
737 substs.substp(tcx, bcx.fcx.param_substs)
740 pub fn node_vtables(bcx: &Block, id: typeck::MethodCall)
741 -> typeck::vtable_res {
742 bcx.tcx().vtable_map.borrow().find(&id).map(|vts| {
743 resolve_vtables_in_fn_ctxt(bcx.fcx, vts)
744 }).unwrap_or_else(|| subst::VecPerParamSpace::empty())
747 // Apply the typaram substitutions in the FunctionContext to some
748 // vtables. This should eliminate any vtable_params.
749 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext,
750 vts: &typeck::vtable_res)
751 -> typeck::vtable_res {
752 resolve_vtables_under_param_substs(fcx.ccx.tcx(),
757 pub fn resolve_vtables_under_param_substs(tcx: &ty::ctxt,
758 param_substs: ¶m_substs,
759 vts: &typeck::vtable_res)
760 -> typeck::vtable_res
763 resolve_param_vtables_under_param_substs(tcx,
769 pub fn resolve_param_vtables_under_param_substs(tcx: &ty::ctxt,
770 param_substs: ¶m_substs,
771 ds: &typeck::vtable_param_res)
772 -> typeck::vtable_param_res
775 resolve_vtable_under_param_substs(tcx,
783 pub fn resolve_vtable_under_param_substs(tcx: &ty::ctxt,
784 param_substs: ¶m_substs,
785 vt: &typeck::vtable_origin)
786 -> typeck::vtable_origin
789 typeck::vtable_static(trait_id, ref vtable_substs, ref sub) => {
790 let vtable_substs = vtable_substs.substp(tcx, param_substs);
791 typeck::vtable_static(
794 resolve_vtables_under_param_substs(tcx, param_substs, sub))
796 typeck::vtable_param(n_param, n_bound) => {
797 find_vtable(tcx, param_substs, n_param, n_bound)
799 typeck::vtable_unboxed_closure(def_id) => {
800 typeck::vtable_unboxed_closure(def_id)
802 typeck::vtable_error => typeck::vtable_error
806 pub fn find_vtable(tcx: &ty::ctxt,
808 n_param: typeck::param_index,
810 -> typeck::vtable_origin {
811 debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
812 n_param, n_bound, ps.repr(tcx));
814 let param_bounds = ps.vtables.get(n_param.space,
816 param_bounds.get(n_bound).clone()
819 pub fn langcall(bcx: &Block,
824 match bcx.tcx().lang_items.require(li) {
827 let msg = format!("{} {}", msg, s);
829 Some(span) => bcx.tcx().sess.span_fatal(span, msg.as_slice()),
830 None => bcx.tcx().sess.fatal(msg.as_slice()),