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)]
13 //! Code that is useful in various trans modules.
15 pub use self::ExprOrMethodCall::*;
19 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ContextRef};
20 use llvm::{True, False, Bool};
24 use middle::lang_items::LangItem;
25 use middle::mem_categorization as mc;
27 use middle::subst::{self, Subst, Substs};
33 use trans::debuginfo::{self, DebugLoc};
36 use trans::monomorphize;
37 use trans::type_::Type;
40 use middle::ty::{self, HasProjectionTypes, Ty};
42 use middle::ty_fold::{TypeFolder, TypeFoldable};
43 use util::ppaux::Repr;
44 use util::nodemap::{FnvHashMap, NodeMap};
46 use arena::TypedArena;
47 use libc::{c_uint, c_char};
48 use std::ffi::CString;
49 use std::cell::{Cell, RefCell};
50 use std::result::Result as StdResult;
53 use syntax::ast_map::{PathElem, PathName};
54 use syntax::codemap::{DUMMY_SP, Span};
55 use syntax::parse::token::InternedString;
56 use syntax::parse::token;
57 use util::common::memoized;
58 use util::nodemap::FnvHashSet;
60 pub use trans::context::CrateContext;
62 /// Returns an equivalent value with all free regions removed (note
63 /// that late-bound regions remain, because they are important for
64 /// subtyping, but they are anonymized and normalized as well). This
65 /// is a stronger, caching version of `ty_fold::erase_regions`.
66 pub fn erase_regions<'tcx,T>(cx: &ty::ctxt<'tcx>, value: &T) -> T
67 where T : TypeFoldable<'tcx> + Repr<'tcx>
69 let value1 = value.fold_with(&mut RegionEraser(cx));
70 debug!("erase_regions({}) = {}",
71 value.repr(cx), value1.repr(cx));
74 struct RegionEraser<'a, 'tcx: 'a>(&'a ty::ctxt<'tcx>);
76 impl<'a, 'tcx> TypeFolder<'tcx> for RegionEraser<'a, 'tcx> {
77 fn tcx(&self) -> &ty::ctxt<'tcx> { self.0 }
79 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
80 match self.tcx().normalized_cache.borrow().get(&ty).cloned() {
85 let t_norm = ty_fold::super_fold_ty(self, ty);
86 self.tcx().normalized_cache.borrow_mut().insert(ty, t_norm);
90 fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
91 where T : TypeFoldable<'tcx> + Repr<'tcx>
93 let u = ty::anonymize_late_bound_regions(self.tcx(), t);
94 ty_fold::super_fold_binder(self, &u)
97 fn fold_region(&mut self, r: ty::Region) -> ty::Region {
98 // because late-bound regions affect subtyping, we can't
99 // erase the bound/free distinction, but we can replace
100 // all free regions with 'static.
102 // Note that we *CAN* replace early-bound regions -- the
103 // type system never "sees" those, they get substituted
104 // away. In trans, they will always be erased to 'static
105 // whenever a substitution occurs.
107 ty::ReLateBound(..) => r,
112 fn fold_substs(&mut self,
113 substs: &subst::Substs<'tcx>)
114 -> subst::Substs<'tcx> {
115 subst::Substs { regions: subst::ErasedRegions,
116 types: substs.types.fold_with(self) }
121 // Is the type's representation size known at compile time?
122 pub fn type_is_sized<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
123 let param_env = ty::empty_parameter_environment(tcx);
124 // FIXME(#4287) This can cause errors due to polymorphic recursion,
125 // a better span should be provided, if available.
126 let err_count = tcx.sess.err_count();
127 let is_sized = ty::type_is_sized(¶m_env, DUMMY_SP, ty);
128 // Those errors aren't fatal, but an incorrect result can later
129 // trip over asserts in both rustc's trans and LLVM.
130 if err_count < tcx.sess.err_count() {
131 tcx.sess.abort_if_errors();
136 pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
138 ty::ty_ptr(ty::mt{ty, ..}) |
139 ty::ty_rptr(_, ty::mt{ty, ..}) |
141 !type_is_sized(cx, ty)
149 // Some things don't need cleanups during unwinding because the
150 // thread can free them all at once later. Currently only things
151 // that only contain scalars and shared boxes can avoid unwind
153 pub fn type_needs_unwind_cleanup<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
154 return memoized(ccx.needs_unwind_cleanup_cache(), ty, |ty| {
155 type_needs_unwind_cleanup_(ccx.tcx(), ty, &mut FnvHashSet())
158 fn type_needs_unwind_cleanup_<'tcx>(tcx: &ty::ctxt<'tcx>,
160 tycache: &mut FnvHashSet<Ty<'tcx>>)
163 // Prevent infinite recursion
164 if !tycache.insert(ty) {
168 let mut needs_unwind_cleanup = false;
169 ty::maybe_walk_ty(ty, |ty| {
170 needs_unwind_cleanup |= match ty.sty {
171 ty::ty_bool | ty::ty_int(_) | ty::ty_uint(_) |
172 ty::ty_float(_) | ty::ty_tup(_) | ty::ty_ptr(_) => false,
174 ty::ty_enum(did, substs) =>
175 ty::enum_variants(tcx, did).iter().any(|v|
176 v.args.iter().any(|&aty| {
177 let t = aty.subst(tcx, substs);
178 type_needs_unwind_cleanup_(tcx, t, tycache)
184 !needs_unwind_cleanup
190 /// If `type_needs_drop` returns true, then `ty` is definitely
191 /// non-copy and *might* have a destructor attached; if it returns
192 /// false, then `ty` definitely has no destructor (i.e. no drop glue).
194 /// (Note that this implies that if `ty` has a destructor attached,
195 /// then `type_needs_drop` will definitely return `true` for `ty`.)
196 pub fn type_needs_drop<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
197 type_needs_drop_given_env(cx, ty, &ty::empty_parameter_environment(cx))
200 /// Core implementation of type_needs_drop, potentially making use of
201 /// and/or updating caches held in the `param_env`.
202 fn type_needs_drop_given_env<'a,'tcx>(cx: &ty::ctxt<'tcx>,
204 param_env: &ty::ParameterEnvironment<'a,'tcx>) -> bool {
205 // Issue #22536: We first query type_moves_by_default. It sees a
206 // normalized version of the type, and therefore will definitely
207 // know whether the type implements Copy (and thus needs no
208 // cleanup/drop/zeroing) ...
209 let implements_copy = !ty::type_moves_by_default(¶m_env, DUMMY_SP, ty);
211 if implements_copy { return false; }
213 // ... (issue #22536 continued) but as an optimization, still use
214 // prior logic of asking if the `needs_drop` bit is set; we need
215 // not zero non-Copy types if they have no destructor.
217 // FIXME(#22815): Note that calling `ty::type_contents` is a
218 // conservative heuristic; it may report that `needs_drop` is set
219 // when actual type does not actually have a destructor associated
220 // with it. But since `ty` absolutely did not have the `Copy`
221 // bound attached (see above), it is sound to treat it as having a
222 // destructor (e.g. zero its memory on move).
224 let contents = ty::type_contents(cx, ty);
225 debug!("type_needs_drop ty={} contents={:?}", ty.repr(cx), contents);
226 contents.needs_drop(cx)
229 fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
231 ty::ty_struct(def_id, substs) => {
232 let fields = ty::lookup_struct_fields(ccx.tcx(), def_id);
233 fields.len() == 1 && {
234 let ty = ty::lookup_field_type(ccx.tcx(), def_id, fields[0].id, substs);
235 let ty = monomorphize::normalize_associated_type(ccx.tcx(), &ty);
236 type_is_immediate(ccx, ty)
243 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
244 use trans::machine::llsize_of_alloc;
245 use trans::type_of::sizing_type_of;
248 let simple = ty::type_is_scalar(ty) ||
249 ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
250 type_is_newtype_immediate(ccx, ty) ||
251 ty::type_is_simd(tcx, ty);
252 if simple && !type_is_fat_ptr(tcx, ty) {
255 if !type_is_sized(tcx, ty) {
259 ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) | ty::ty_vec(_, Some(_)) |
260 ty::ty_closure(..) => {
261 let llty = sizing_type_of(ccx, ty);
262 llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
264 _ => type_is_zero_size(ccx, ty)
268 /// Identify types which have size zero at runtime.
269 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
270 use trans::machine::llsize_of_alloc;
271 use trans::type_of::sizing_type_of;
272 let llty = sizing_type_of(ccx, ty);
273 llsize_of_alloc(ccx, llty) == 0
276 /// Identifies types which we declare to be equivalent to `void` in C for the purpose of function
277 /// return types. These are `()`, bot, and uninhabited enums. Note that all such types are also
278 /// zero-size, but not all zero-size types use a `void` return type (in order to aid with C ABI
280 pub fn return_type_is_void(ccx: &CrateContext, ty: Ty) -> bool {
281 ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty)
284 /// Generates a unique symbol based off the name given. This is used to create
285 /// unique symbols for things like closures.
286 pub fn gensym_name(name: &str) -> PathElem {
287 let num = token::gensym(name).usize();
288 // use one colon which will get translated to a period by the mangler, and
289 // we're guaranteed that `num` is globally unique for this crate.
290 PathName(token::gensym(&format!("{}:{}", name, num)))
294 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
296 * An "extern" is an LLVM symbol we wind up emitting an undefined external
297 * reference to. This means "we don't have the thing in this compilation unit,
298 * please make sure you link it in at runtime". This could be a reference to
299 * C code found in a C library, or rust code found in a rust crate.
301 * Most "externs" are implicitly declared (automatically) as a result of a
302 * user declaring an extern _module_ dependency; this causes the rust driver
303 * to locate an extern crate, scan its compilation metadata, and emit extern
304 * declarations for any symbols used by the declaring crate.
306 * A "foreign" is an extern that references C (or other non-rust ABI) code.
307 * There is no metadata to scan for extern references so in these cases either
308 * a header-digester like bindgen, or manual function prototypes, have to
309 * serve as declarators. So these are usually given explicitly as prototype
310 * declarations, in rust code, with ABI attributes on them noting which ABI to
313 * An "upcall" is a foreign call generated by the compiler (not corresponding
314 * to any user-written call in the code) into the runtime library, to perform
315 * some helper task such as bringing a task to life, allocating memory, etc.
319 #[derive(Copy, Clone)]
320 pub struct NodeIdAndSpan {
325 pub fn expr_info(expr: &ast::Expr) -> NodeIdAndSpan {
326 NodeIdAndSpan { id: expr.id, span: expr.span }
329 pub struct BuilderRef_res {
333 impl Drop for BuilderRef_res {
336 llvm::LLVMDisposeBuilder(self.b);
341 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
347 pub type ExternMap = FnvHashMap<String, ValueRef>;
349 pub fn validate_substs(substs: &Substs) {
350 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
353 // work around bizarre resolve errors
354 type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
355 pub type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
357 // Function context. Every LLVM function we create will have one of
359 pub struct FunctionContext<'a, 'tcx: 'a> {
360 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
361 // address of the first instruction in the sequence of
362 // instructions for this function that will go in the .text
363 // section of the executable we're generating.
366 // always an empty parameter-environment
367 pub param_env: ty::ParameterEnvironment<'a, 'tcx>,
369 // The environment argument in a closure.
370 pub llenv: Option<ValueRef>,
372 // A pointer to where to store the return value. If the return type is
373 // immediate, this points to an alloca in the function. Otherwise, it's a
374 // pointer to the hidden first parameter of the function. After function
375 // construction, this should always be Some.
376 pub llretslotptr: Cell<Option<ValueRef>>,
378 // These pub elements: "hoisted basic blocks" containing
379 // administrative activities that have to happen in only one place in
380 // the function, due to LLVM's quirks.
381 // A marker for the place where we want to insert the function's static
382 // allocas, so that LLVM will coalesce them into a single alloca call.
383 pub alloca_insert_pt: Cell<Option<ValueRef>>,
384 pub llreturn: Cell<Option<BasicBlockRef>>,
386 // If the function has any nested return's, including something like:
387 // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then
388 // we use a separate alloca for each return
389 pub needs_ret_allocas: bool,
391 // The a value alloca'd for calls to upcalls.rust_personality. Used when
392 // outputting the resume instruction.
393 pub personality: Cell<Option<ValueRef>>,
395 // True if the caller expects this fn to use the out pointer to
396 // return. Either way, your code should write into the slot llretslotptr
397 // points to, but if this value is false, that slot will be a local alloca.
398 pub caller_expects_out_pointer: bool,
400 // Maps the DefId's for local variables to the allocas created for
401 // them in llallocas.
402 pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>,
404 // Same as above, but for closure upvars
405 pub llupvars: RefCell<NodeMap<ValueRef>>,
407 // The NodeId of the function, or -1 if it doesn't correspond to
408 // a user-defined function.
411 // If this function is being monomorphized, this contains the type
412 // substitutions used.
413 pub param_substs: &'tcx Substs<'tcx>,
415 // The source span and nesting context where this function comes from, for
416 // error reporting and symbol generation.
417 pub span: Option<Span>,
419 // The arena that blocks are allocated from.
420 pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
422 // This function's enclosing crate context.
423 pub ccx: &'a CrateContext<'a, 'tcx>,
425 // Used and maintained by the debuginfo module.
426 pub debug_context: debuginfo::FunctionDebugContext,
429 pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
431 pub cfg: Option<cfg::CFG>,
434 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
435 pub fn arg_pos(&self, arg: usize) -> usize {
436 let arg = self.env_arg_pos() + arg;
437 if self.llenv.is_some() {
444 pub fn env_arg_pos(&self) -> usize {
445 if self.caller_expects_out_pointer {
452 pub fn cleanup(&self) {
454 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
460 pub fn get_llreturn(&self) -> BasicBlockRef {
461 if self.llreturn.get().is_none() {
463 self.llreturn.set(Some(unsafe {
464 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn,
465 "return\0".as_ptr() as *const _)
469 self.llreturn.get().unwrap()
472 pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>,
473 output: ty::FnOutput<'tcx>,
474 name: &str) -> ValueRef {
475 if self.needs_ret_allocas {
476 base::alloca_no_lifetime(bcx, match output {
477 ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type),
478 ty::FnDiverging => Type::void(bcx.ccx())
481 self.llretslotptr.get().unwrap()
485 pub fn new_block(&'a self,
488 opt_node_id: Option<ast::NodeId>)
491 let name = CString::new(name).unwrap();
492 let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
495 BlockS::new(llbb, is_lpad, opt_node_id, self)
499 pub fn new_id_block(&'a self,
501 node_id: ast::NodeId)
503 self.new_block(false, name, Some(node_id))
506 pub fn new_temp_block(&'a self,
509 self.new_block(false, name, None)
512 pub fn join_blocks(&'a self,
514 in_cxs: &[Block<'a, 'tcx>])
516 let out = self.new_id_block("join", id);
517 let mut reachable = false;
519 if !bcx.unreachable.get() {
520 build::Br(*bcx, out.llbb, DebugLoc::None);
525 build::Unreachable(out);
530 pub fn monomorphize<T>(&self, value: &T) -> T
531 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
533 monomorphize::apply_param_substs(self.ccx.tcx(),
538 /// This is the same as `common::type_needs_drop`, except that it
539 /// may use or update caches within this `FunctionContext`.
540 pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
541 type_needs_drop_given_env(self.ccx.tcx(), ty, &self.param_env)
545 // Basic block context. We create a block context for each basic block
546 // (single-entry, single-exit sequence of instructions) we generate from Rust
547 // code. Each basic block we generate is attached to a function, typically
548 // with many basic blocks per function. All the basic blocks attached to a
549 // function are organized as a directed graph.
550 pub struct BlockS<'blk, 'tcx: 'blk> {
551 // The BasicBlockRef returned from a call to
552 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
553 // block to the function pointed to by llfn. We insert
554 // instructions into that block by way of this block context.
555 // The block pointing to this one in the function's digraph.
556 pub llbb: BasicBlockRef,
557 pub terminated: Cell<bool>,
558 pub unreachable: Cell<bool>,
560 // Is this block part of a landing pad?
563 // AST node-id associated with this block, if any. Used for
564 // debugging purposes only.
565 pub opt_node_id: Option<ast::NodeId>,
567 // The function context for the function to which this block is
569 pub fcx: &'blk FunctionContext<'blk, 'tcx>,
572 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
574 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
575 pub fn new(llbb: BasicBlockRef,
577 opt_node_id: Option<ast::NodeId>,
578 fcx: &'blk FunctionContext<'blk, 'tcx>)
579 -> Block<'blk, 'tcx> {
580 fcx.block_arena.alloc(BlockS {
582 terminated: Cell::new(false),
583 unreachable: Cell::new(false),
585 opt_node_id: opt_node_id,
590 pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
593 pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
596 pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
598 pub fn name(&self, name: ast::Name) -> String {
599 token::get_name(name).to_string()
602 pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
603 self.tcx().map.node_to_string(id).to_string()
606 pub fn expr_to_string(&self, e: &ast::Expr) -> String {
610 pub fn def(&self, nid: ast::NodeId) -> def::Def {
611 match self.tcx().def_map.borrow().get(&nid) {
612 Some(v) => v.full_def(),
614 self.tcx().sess.bug(&format!(
615 "no def associated with node id {}", nid));
620 pub fn val_to_string(&self, val: ValueRef) -> String {
621 self.ccx().tn().val_to_string(val)
624 pub fn llty_str(&self, ty: Type) -> String {
625 self.ccx().tn().type_to_string(ty)
628 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
632 pub fn to_str(&self) -> String {
633 format!("[block {:p}]", self)
636 pub fn monomorphize<T>(&self, value: &T) -> T
637 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
639 monomorphize::apply_param_substs(self.tcx(),
640 self.fcx.param_substs,
645 impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> {
646 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
647 Ok(node_id_type(self, id))
650 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
651 Ok(expr_ty_adjusted(self, expr))
654 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
659 .map(|method| monomorphize_type(self, method.ty))
662 fn node_method_origin(&self, method_call: ty::MethodCall)
663 -> Option<ty::MethodOrigin<'tcx>>
669 .map(|method| method.origin.clone())
672 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
673 &self.tcx().adjustments
676 fn is_method_call(&self, id: ast::NodeId) -> bool {
677 self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id))
680 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
681 self.tcx().region_maps.temporary_scope(rvalue_id)
684 fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
685 Some(self.tcx().upvar_capture_map.borrow().get(&upvar_id).unwrap().clone())
688 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
689 self.fcx.param_env.type_moves_by_default(span, ty)
693 impl<'blk, 'tcx> ty::ClosureTyper<'tcx> for BlockS<'blk, 'tcx> {
694 fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> {
698 fn closure_kind(&self,
700 -> Option<ty::ClosureKind>
702 let typer = NormalizingClosureTyper::new(self.tcx());
703 typer.closure_kind(def_id)
706 fn closure_type(&self,
708 substs: &subst::Substs<'tcx>)
709 -> ty::ClosureTy<'tcx>
711 let typer = NormalizingClosureTyper::new(self.tcx());
712 typer.closure_type(def_id, substs)
715 fn closure_upvars(&self,
717 substs: &Substs<'tcx>)
718 -> Option<Vec<ty::ClosureUpvar<'tcx>>>
720 let typer = NormalizingClosureTyper::new(self.tcx());
721 typer.closure_upvars(def_id, substs)
725 pub struct Result<'blk, 'tcx: 'blk> {
726 pub bcx: Block<'blk, 'tcx>,
730 impl<'b, 'tcx> Result<'b, 'tcx> {
731 pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
739 pub fn val_ty(v: ValueRef) -> Type {
741 Type::from_ref(llvm::LLVMTypeOf(v))
745 // LLVM constant constructors.
746 pub fn C_null(t: Type) -> ValueRef {
748 llvm::LLVMConstNull(t.to_ref())
752 pub fn C_undef(t: Type) -> ValueRef {
754 llvm::LLVMGetUndef(t.to_ref())
758 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
760 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
764 pub fn C_floating(s: &str, t: Type) -> ValueRef {
766 let s = CString::new(s).unwrap();
767 llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr())
771 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
772 C_struct(ccx, &[], false)
775 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
776 C_integral(Type::i1(ccx), val as u64, false)
779 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
780 C_integral(Type::i32(ccx), i as u64, true)
783 pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef {
784 C_integral(Type::i32(ccx), i as u64, false)
787 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
788 C_integral(Type::i64(ccx), i, false)
791 pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef {
794 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
795 32 => assert!(v < (1<<31) && v >= -(1<<31)),
797 n => panic!("unsupported target size: {}", n)
800 C_integral(ccx.int_type(), v as u64, true)
803 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
806 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
807 32 => assert!(v < (1<<32)),
809 n => panic!("unsupported target size: {}", n)
812 C_integral(ccx.int_type(), v, false)
815 pub trait AsI64 { fn as_i64(self) -> i64; }
816 pub trait AsU64 { fn as_u64(self) -> u64; }
818 // FIXME: remove the intptr conversions, because they
819 // are host-architecture-dependent
820 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
821 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
822 impl AsI64 for isize { fn as_i64(self) -> i64 { self as i64 }}
824 impl AsU64 for u64 { fn as_u64(self) -> u64 { self as u64 }}
825 impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }}
826 impl AsU64 for usize { fn as_u64(self) -> u64 { self as u64 }}
828 pub fn C_u8(ccx: &CrateContext, i: usize) -> ValueRef {
829 C_integral(Type::i8(ccx), i as u64, false)
833 // This is a 'c-like' raw string, which differs from
834 // our boxed-and-length-annotated strings.
835 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
837 match cx.const_cstr_cache().borrow().get(&s) {
838 Some(&llval) => return llval,
842 let sc = llvm::LLVMConstStringInContext(cx.llcx(),
843 s.as_ptr() as *const c_char,
845 !null_terminated as Bool);
847 let gsym = token::gensym("str");
848 let sym = format!("str{}", gsym.usize());
849 let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
850 cx.sess().bug(&format!("symbol `{}` is already defined", sym));
852 llvm::LLVMSetInitializer(g, sc);
853 llvm::LLVMSetGlobalConstant(g, True);
854 llvm::SetLinkage(g, llvm::InternalLinkage);
856 cx.const_cstr_cache().borrow_mut().insert(s, g);
861 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
862 // you will be kicked off fast isel. See issue #4352 for an example of this.
863 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
865 let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
866 C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
869 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
870 C_struct_in_context(cx.llcx(), elts, packed)
873 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
875 llvm::LLVMConstStructInContext(llcx,
876 elts.as_ptr(), elts.len() as c_uint,
881 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
883 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
887 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
889 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
893 pub fn C_vector(elts: &[ValueRef]) -> ValueRef {
895 return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
899 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
900 C_bytes_in_context(cx.llcx(), bytes)
903 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
905 let ptr = bytes.as_ptr() as *const c_char;
906 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
910 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
913 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
915 debug!("const_get_elt(v={}, us={:?}, r={})",
916 cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
922 pub fn is_const(v: ValueRef) -> bool {
924 llvm::LLVMIsConstant(v) == True
928 pub fn const_to_int(v: ValueRef) -> i64 {
930 llvm::LLVMConstIntGetSExtValue(v)
934 pub fn const_to_uint(v: ValueRef) -> u64 {
936 llvm::LLVMConstIntGetZExtValue(v)
940 fn is_const_integral(v: ValueRef) -> bool {
942 !llvm::LLVMIsAConstantInt(v).is_null()
946 pub fn const_to_opt_int(v: ValueRef) -> Option<i64> {
948 if is_const_integral(v) {
949 Some(llvm::LLVMConstIntGetSExtValue(v))
956 pub fn const_to_opt_uint(v: ValueRef) -> Option<u64> {
958 if is_const_integral(v) {
959 Some(llvm::LLVMConstIntGetZExtValue(v))
966 pub fn is_undef(val: ValueRef) -> bool {
968 llvm::LLVMIsUndef(val) != False
972 #[allow(dead_code)] // potentially useful
973 pub fn is_null(val: ValueRef) -> bool {
975 llvm::LLVMIsNull(val) != False
979 pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
980 bcx.fcx.monomorphize(&t)
983 pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> {
985 let t = ty::node_id_to_type(tcx, id);
986 monomorphize_type(bcx, t)
989 pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
990 node_id_type(bcx, ex.id)
993 pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
994 monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
997 /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
998 /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
999 /// guarantee to us that all nested obligations *could be* resolved if we wanted to.
1000 pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1002 trait_ref: ty::PolyTraitRef<'tcx>)
1003 -> traits::Vtable<'tcx, ()>
1005 let tcx = ccx.tcx();
1007 // Remove any references to regions; this helps improve caching.
1008 let trait_ref = erase_regions(tcx, &trait_ref);
1010 // First check the cache.
1011 match ccx.trait_cache().borrow().get(&trait_ref) {
1013 info!("Cache hit: {}", trait_ref.repr(ccx.tcx()));
1014 return (*vtable).clone();
1019 debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx()));
1021 ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id());
1022 let infcx = infer::new_infer_ctxt(tcx);
1024 // Do the initial selection for the obligation. This yields the
1025 // shallow result we are looking for -- that is, what specific impl.
1026 let typer = NormalizingClosureTyper::new(tcx);
1027 let mut selcx = traits::SelectionContext::new(&infcx, &typer);
1029 traits::Obligation::new(traits::ObligationCause::misc(span, ast::DUMMY_NODE_ID),
1030 trait_ref.to_poly_trait_predicate());
1031 let selection = match selcx.select(&obligation) {
1032 Ok(Some(selection)) => selection,
1034 // Ambiguity can happen when monomorphizing during trans
1035 // expands to some humongo type that never occurred
1036 // statically -- this humongo type can then overflow,
1037 // leading to an ambiguous result. So report this as an
1038 // overflow bug, since I believe this is the only case
1039 // where ambiguity can result.
1040 debug!("Encountered ambiguity selecting `{}` during trans, \
1041 presuming due to overflow",
1042 trait_ref.repr(tcx));
1043 ccx.sess().span_fatal(
1045 "reached the recursion limit during monomorphization");
1050 &format!("Encountered error `{}` selecting `{}` during trans",
1052 trait_ref.repr(tcx)))
1056 // Currently, we use a fulfillment context to completely resolve
1057 // all nested obligations. This is because they can inform the
1058 // inference of the impl's type parameters.
1059 let mut fulfill_cx = traits::FulfillmentContext::new();
1060 let vtable = selection.map_move_nested(|predicate| {
1061 fulfill_cx.register_predicate_obligation(&infcx, predicate);
1063 let vtable = drain_fulfillment_cx_or_panic(span, &infcx, &mut fulfill_cx, &vtable);
1065 info!("Cache miss: {}", trait_ref.repr(ccx.tcx()));
1066 ccx.trait_cache().borrow_mut().insert(trait_ref,
1072 /// Normalizes the predicates and checks whether they hold. If this
1073 /// returns false, then either normalize encountered an error or one
1074 /// of the predicates did not hold. Used when creating vtables to
1075 /// check for unsatisfiable methods.
1076 pub fn normalize_and_test_predicates<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1077 predicates: Vec<ty::Predicate<'tcx>>)
1080 debug!("normalize_and_test_predicates(predicates={})",
1081 predicates.repr(ccx.tcx()));
1083 let tcx = ccx.tcx();
1084 let infcx = infer::new_infer_ctxt(tcx);
1085 let typer = NormalizingClosureTyper::new(tcx);
1086 let mut selcx = traits::SelectionContext::new(&infcx, &typer);
1087 let mut fulfill_cx = traits::FulfillmentContext::new();
1088 let cause = traits::ObligationCause::dummy();
1089 let traits::Normalized { value: predicates, obligations } =
1090 traits::normalize(&mut selcx, cause.clone(), &predicates);
1091 for obligation in obligations {
1092 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1094 for predicate in predicates {
1095 let obligation = traits::Obligation::new(cause.clone(), predicate);
1096 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1098 drain_fulfillment_cx(&infcx, &mut fulfill_cx, &()).is_ok()
1101 pub struct NormalizingClosureTyper<'a,'tcx:'a> {
1102 param_env: ty::ParameterEnvironment<'a, 'tcx>
1105 impl<'a,'tcx> NormalizingClosureTyper<'a,'tcx> {
1106 pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingClosureTyper<'a,'tcx> {
1107 // Parameter environment is used to give details about type parameters,
1108 // but since we are in trans, everything is fully monomorphized.
1109 NormalizingClosureTyper { param_env: ty::empty_parameter_environment(tcx) }
1113 impl<'a,'tcx> ty::ClosureTyper<'tcx> for NormalizingClosureTyper<'a,'tcx> {
1114 fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1118 fn closure_kind(&self,
1120 -> Option<ty::ClosureKind>
1122 self.param_env.closure_kind(def_id)
1125 fn closure_type(&self,
1127 substs: &subst::Substs<'tcx>)
1128 -> ty::ClosureTy<'tcx>
1130 // the substitutions in `substs` are already monomorphized,
1131 // but we still must normalize associated types
1132 let closure_ty = self.param_env.tcx.closure_type(def_id, substs);
1133 monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty)
1136 fn closure_upvars(&self,
1138 substs: &Substs<'tcx>)
1139 -> Option<Vec<ty::ClosureUpvar<'tcx>>>
1141 // the substitutions in `substs` are already monomorphized,
1142 // but we still must normalize associated types
1143 let result = ty::closure_upvars(&self.param_env, def_id, substs);
1144 monomorphize::normalize_associated_type(self.param_env.tcx, &result)
1148 pub fn drain_fulfillment_cx_or_panic<'a,'tcx,T>(span: Span,
1149 infcx: &infer::InferCtxt<'a,'tcx>,
1150 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
1153 where T : TypeFoldable<'tcx> + Repr<'tcx>
1155 match drain_fulfillment_cx(infcx, fulfill_cx, result) {
1158 infcx.tcx.sess.span_bug(
1160 &format!("Encountered errors `{}` fulfilling during trans",
1161 errors.repr(infcx.tcx)));
1166 /// Finishes processes any obligations that remain in the fulfillment
1167 /// context, and then "freshens" and returns `result`. This is
1168 /// primarily used during normalization and other cases where
1169 /// processing the obligations in `fulfill_cx` may cause type
1170 /// inference variables that appear in `result` to be unified, and
1171 /// hence we need to process those obligations to get the complete
1172 /// picture of the type.
1173 pub fn drain_fulfillment_cx<'a,'tcx,T>(infcx: &infer::InferCtxt<'a,'tcx>,
1174 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
1176 -> StdResult<T,Vec<traits::FulfillmentError<'tcx>>>
1177 where T : TypeFoldable<'tcx> + Repr<'tcx>
1179 debug!("drain_fulfillment_cx(result={})",
1180 result.repr(infcx.tcx));
1182 // In principle, we only need to do this so long as `result`
1183 // contains unbound type parameters. It could be a slight
1184 // optimization to stop iterating early.
1185 let typer = NormalizingClosureTyper::new(infcx.tcx);
1186 match fulfill_cx.select_all_or_error(infcx, &typer) {
1193 // Use freshen to simultaneously replace all type variables with
1194 // their bindings and replace all regions with 'static. This is
1195 // sort of overkill because we do not expect there to be any
1196 // unbound type variables, hence no `TyFresh` types should ever be
1198 Ok(result.fold_with(&mut infcx.freshener()))
1201 // Key used to lookup values supplied for type parameters in an expr.
1202 #[derive(Copy, Clone, PartialEq, Debug)]
1203 pub enum ExprOrMethodCall {
1204 // Type parameters for a path like `None::<int>`
1205 ExprId(ast::NodeId),
1207 // Type parameters for a method call like `a.foo::<int>()`
1208 MethodCallKey(ty::MethodCall)
1211 pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1212 node: ExprOrMethodCall,
1213 param_substs: &subst::Substs<'tcx>)
1214 -> subst::Substs<'tcx> {
1215 let tcx = ccx.tcx();
1217 let substs = match node {
1219 ty::node_id_item_substs(tcx, id).substs
1221 MethodCallKey(method_call) => {
1222 tcx.method_map.borrow().get(&method_call).unwrap().substs.clone()
1226 if substs.types.any(|t| ty::type_needs_infer(*t)) {
1227 tcx.sess.bug(&format!("type parameters for node {:?} include inference types: {:?}",
1228 node, substs.repr(tcx)));
1231 monomorphize::apply_param_substs(tcx,
1233 &substs.erase_regions())
1236 pub fn langcall(bcx: Block,
1241 match bcx.tcx().lang_items.require(li) {
1244 let msg = format!("{} {}", msg, s);
1246 Some(span) => bcx.tcx().sess.span_fatal(span, &msg[..]),
1247 None => bcx.tcx().sess.fatal(&msg[..]),