]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/common.rs
Convert most code to new inner attribute syntax.
[rust.git] / src / librustc / middle / trans / common.rs
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.
4 //
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.
10
11 #![allow(non_camel_case_types)]
12
13 //! Code that is useful in various trans modules.
14
15 use driver::session::Session;
16 use lib::llvm::{ValueRef, BasicBlockRef, BuilderRef};
17 use lib::llvm::{True, False, Bool};
18 use lib::llvm::llvm;
19 use lib;
20 use middle::lang_items::LangItem;
21 use middle::trans::build;
22 use middle::trans::cleanup;
23 use middle::trans::datum;
24 use middle::trans::datum::{Datum, Lvalue};
25 use middle::trans::debuginfo;
26 use middle::trans::type_::Type;
27 use middle::ty::substs;
28 use middle::ty;
29 use middle::typeck;
30 use util::ppaux::Repr;
31 use util::nodemap::NodeMap;
32
33 use arena::TypedArena;
34 use collections::HashMap;
35 use std::c_str::ToCStr;
36 use std::cell::{Cell, RefCell};
37 use std::libc::{c_uint, c_longlong, c_ulonglong, c_char};
38 use syntax::ast::Ident;
39 use syntax::ast;
40 use syntax::ast_map::{PathElem, PathName};
41 use syntax::codemap::Span;
42 use syntax::parse::token::InternedString;
43 use syntax::parse::token;
44
45 pub use middle::trans::context::CrateContext;
46
47 fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
48     match ty::get(ty).sty {
49         ty::ty_struct(def_id, ref substs) => {
50             let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
51             fields.len() == 1 &&
52                 fields.get(0).ident.name ==
53                     token::special_idents::unnamed_field.name &&
54                 type_is_immediate(ccx, fields.get(0).mt.ty)
55         }
56         _ => false
57     }
58 }
59
60 pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
61     use middle::trans::machine::llsize_of_alloc;
62     use middle::trans::type_of::sizing_type_of;
63     let tcx = ccx.tcx();
64     let simple = ty::type_is_scalar(ty) || ty::type_is_boxed(ty) ||
65         ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
66         type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
67         ty::type_is_simd(tcx, ty);
68     if simple {
69         return true;
70     }
71     match ty::get(ty).sty {
72         ty::ty_bot => true,
73         ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) => {
74             let llty = sizing_type_of(ccx, ty);
75             llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type)
76         }
77         _ => type_is_zero_size(ccx, ty)
78     }
79 }
80
81 pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
82     /*!
83      * Identify types which have size zero at runtime.
84      */
85
86     use middle::trans::machine::llsize_of_alloc;
87     use middle::trans::type_of::sizing_type_of;
88     let llty = sizing_type_of(ccx, ty);
89     llsize_of_alloc(ccx, llty) == 0
90 }
91
92 pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
93     /*!
94      * Identifies types which we declare to be equivalent to `void`
95      * in C for the purpose of function return types. These are
96      * `()`, bot, and uninhabited enums. Note that all such types
97      * are also zero-size, but not all zero-size types use a `void`
98      * return type (in order to aid with C ABI compatibility).
99      */
100
101     ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx(), ty)
102 }
103
104 /// Generates a unique symbol based off the name given. This is used to create
105 /// unique symbols for things like closures.
106 pub fn gensym_name(name: &str) -> PathElem {
107     let num = token::gensym(name);
108     // use one colon which will get translated to a period by the mangler, and
109     // we're guaranteed that `num` is globally unique for this crate.
110     PathName(token::gensym(format!("{}:{}", name, num)))
111 }
112
113 pub struct tydesc_info {
114     ty: ty::t,
115     tydesc: ValueRef,
116     size: ValueRef,
117     align: ValueRef,
118     name: ValueRef,
119     visit_glue: Cell<Option<ValueRef>>,
120 }
121
122 /*
123  * A note on nomenclature of linking: "extern", "foreign", and "upcall".
124  *
125  * An "extern" is an LLVM symbol we wind up emitting an undefined external
126  * reference to. This means "we don't have the thing in this compilation unit,
127  * please make sure you link it in at runtime". This could be a reference to
128  * C code found in a C library, or rust code found in a rust crate.
129  *
130  * Most "externs" are implicitly declared (automatically) as a result of a
131  * user declaring an extern _module_ dependency; this causes the rust driver
132  * to locate an extern crate, scan its compilation metadata, and emit extern
133  * declarations for any symbols used by the declaring crate.
134  *
135  * A "foreign" is an extern that references C (or other non-rust ABI) code.
136  * There is no metadata to scan for extern references so in these cases either
137  * a header-digester like bindgen, or manual function prototypes, have to
138  * serve as declarators. So these are usually given explicitly as prototype
139  * declarations, in rust code, with ABI attributes on them noting which ABI to
140  * link via.
141  *
142  * An "upcall" is a foreign call generated by the compiler (not corresponding
143  * to any user-written call in the code) into the runtime library, to perform
144  * some helper task such as bringing a task to life, allocating memory, etc.
145  *
146  */
147
148 pub struct NodeInfo {
149     id: ast::NodeId,
150     span: Span,
151 }
152
153 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
154     NodeInfo { id: expr.id, span: expr.span }
155 }
156
157 pub struct Stats {
158     n_static_tydescs: Cell<uint>,
159     n_glues_created: Cell<uint>,
160     n_null_glues: Cell<uint>,
161     n_real_glues: Cell<uint>,
162     n_fns: Cell<uint>,
163     n_monos: Cell<uint>,
164     n_inlines: Cell<uint>,
165     n_closures: Cell<uint>,
166     n_llvm_insns: Cell<uint>,
167     llvm_insns: RefCell<HashMap<~str, uint>>,
168     // (ident, time-in-ms, llvm-instructions)
169     fn_stats: RefCell<Vec<(~str, uint, uint)> >,
170 }
171
172 pub struct BuilderRef_res {
173     b: BuilderRef,
174 }
175
176 impl Drop for BuilderRef_res {
177     fn drop(&mut self) {
178         unsafe {
179             llvm::LLVMDisposeBuilder(self.b);
180         }
181     }
182 }
183
184 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
185     BuilderRef_res {
186         b: b
187     }
188 }
189
190 pub type ExternMap = HashMap<~str, ValueRef>;
191
192 // Here `self_ty` is the real type of the self parameter to this method. It
193 // will only be set in the case of default methods.
194 pub struct param_substs {
195     tys: Vec<ty::t> ,
196     self_ty: Option<ty::t>,
197     vtables: Option<typeck::vtable_res>,
198     self_vtables: Option<typeck::vtable_param_res>
199 }
200
201 impl param_substs {
202     pub fn validate(&self) {
203         for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
204         for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
205     }
206 }
207
208 fn param_substs_to_str(this: &param_substs, tcx: &ty::ctxt) -> ~str {
209     format!("param_substs \\{tys:{}, vtables:{}\\}",
210          this.tys.repr(tcx),
211          this.vtables.repr(tcx))
212 }
213
214 impl Repr for param_substs {
215     fn repr(&self, tcx: &ty::ctxt) -> ~str {
216         param_substs_to_str(self, tcx)
217     }
218 }
219
220 // work around bizarre resolve errors
221 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
222 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
223
224 // Function context.  Every LLVM function we create will have one of
225 // these.
226 pub struct FunctionContext<'a> {
227     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
228     // address of the first instruction in the sequence of
229     // instructions for this function that will go in the .text
230     // section of the executable we're generating.
231     llfn: ValueRef,
232
233     // The environment argument in a closure.
234     llenv: Option<ValueRef>,
235
236     // The place to store the return value. If the return type is immediate,
237     // this is an alloca in the function. Otherwise, it's the hidden first
238     // parameter to the function. After function construction, this should
239     // always be Some.
240     llretptr: Cell<Option<ValueRef>>,
241
242     entry_bcx: RefCell<Option<&'a Block<'a>>>,
243
244     // These elements: "hoisted basic blocks" containing
245     // administrative activities that have to happen in only one place in
246     // the function, due to LLVM's quirks.
247     // A marker for the place where we want to insert the function's static
248     // allocas, so that LLVM will coalesce them into a single alloca call.
249     alloca_insert_pt: Cell<Option<ValueRef>>,
250     llreturn: Cell<Option<BasicBlockRef>>,
251
252     // The a value alloca'd for calls to upcalls.rust_personality. Used when
253     // outputting the resume instruction.
254     personality: Cell<Option<ValueRef>>,
255
256     // True if the caller expects this fn to use the out pointer to
257     // return. Either way, your code should write into llretptr, but if
258     // this value is false, llretptr will be a local alloca.
259     caller_expects_out_pointer: bool,
260
261     // Maps arguments to allocas created for them in llallocas.
262     llargs: RefCell<NodeMap<LvalueDatum>>,
263
264     // Maps the def_ids for local variables to the allocas created for
265     // them in llallocas.
266     lllocals: RefCell<NodeMap<LvalueDatum>>,
267
268     // Same as above, but for closure upvars
269     llupvars: RefCell<NodeMap<ValueRef>>,
270
271     // The NodeId of the function, or -1 if it doesn't correspond to
272     // a user-defined function.
273     id: ast::NodeId,
274
275     // If this function is being monomorphized, this contains the type
276     // substitutions used.
277     param_substs: Option<@param_substs>,
278
279     // The source span and nesting context where this function comes from, for
280     // error reporting and symbol generation.
281     span: Option<Span>,
282
283     // The arena that blocks are allocated from.
284     block_arena: &'a TypedArena<Block<'a>>,
285
286     // This function's enclosing crate context.
287     ccx: &'a CrateContext,
288
289     // Used and maintained by the debuginfo module.
290     debug_context: debuginfo::FunctionDebugContext,
291
292     // Cleanup scopes.
293     scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
294 }
295
296 impl<'a> FunctionContext<'a> {
297     pub fn arg_pos(&self, arg: uint) -> uint {
298         let arg = self.env_arg_pos() + arg;
299         if self.llenv.is_some() {
300             arg + 1
301         } else {
302             arg
303         }
304     }
305
306     pub fn out_arg_pos(&self) -> uint {
307         assert!(self.caller_expects_out_pointer);
308         0u
309     }
310
311     pub fn env_arg_pos(&self) -> uint {
312         if self.caller_expects_out_pointer {
313             1u
314         } else {
315             0u
316         }
317     }
318
319     pub fn cleanup(&self) {
320         unsafe {
321             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
322                                                      .get()
323                                                      .unwrap());
324         }
325         // Remove the cycle between fcx and bcx, so memory can be freed
326         self.entry_bcx.set(None);
327     }
328
329     pub fn get_llreturn(&self) -> BasicBlockRef {
330         if self.llreturn.get().is_none() {
331
332             self.llreturn.set(Some(unsafe {
333                 "return".with_c_str(|buf| {
334                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx, self.llfn, buf)
335                 })
336             }))
337         }
338
339         self.llreturn.get().unwrap()
340     }
341
342     pub fn new_block(&'a self,
343                      is_lpad: bool,
344                      name: &str,
345                      opt_node_id: Option<ast::NodeId>)
346                      -> &'a Block<'a> {
347         unsafe {
348             let llbb = name.with_c_str(|buf| {
349                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
350                                                         self.llfn,
351                                                         buf)
352                 });
353             Block::new(llbb, is_lpad, opt_node_id, self)
354         }
355     }
356
357     pub fn new_id_block(&'a self,
358                         name: &str,
359                         node_id: ast::NodeId)
360                         -> &'a Block<'a> {
361         self.new_block(false, name, Some(node_id))
362     }
363
364     pub fn new_temp_block(&'a self,
365                           name: &str)
366                           -> &'a Block<'a> {
367         self.new_block(false, name, None)
368     }
369
370     pub fn join_blocks(&'a self,
371                        id: ast::NodeId,
372                        in_cxs: &[&'a Block<'a>])
373                        -> &'a Block<'a> {
374         let out = self.new_id_block("join", id);
375         let mut reachable = false;
376         for bcx in in_cxs.iter() {
377             if !bcx.unreachable.get() {
378                 build::Br(*bcx, out.llbb);
379                 reachable = true;
380             }
381         }
382         if !reachable {
383             build::Unreachable(out);
384         }
385         return out;
386     }
387 }
388
389 // Heap selectors. Indicate which heap something should go on.
390 #[deriving(Eq)]
391 pub enum heap {
392     heap_managed,
393     heap_exchange,
394     heap_exchange_closure
395 }
396
397 // Basic block context.  We create a block context for each basic block
398 // (single-entry, single-exit sequence of instructions) we generate from Rust
399 // code.  Each basic block we generate is attached to a function, typically
400 // with many basic blocks per function.  All the basic blocks attached to a
401 // function are organized as a directed graph.
402 pub struct Block<'a> {
403     // The BasicBlockRef returned from a call to
404     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
405     // block to the function pointed to by llfn.  We insert
406     // instructions into that block by way of this block context.
407     // The block pointing to this one in the function's digraph.
408     llbb: BasicBlockRef,
409     terminated: Cell<bool>,
410     unreachable: Cell<bool>,
411
412     // Is this block part of a landing pad?
413     is_lpad: bool,
414
415     // AST node-id associated with this block, if any. Used for
416     // debugging purposes only.
417     opt_node_id: Option<ast::NodeId>,
418
419     // The function context for the function to which this block is
420     // attached.
421     fcx: &'a FunctionContext<'a>,
422 }
423
424 impl<'a> Block<'a> {
425     pub fn new<'a>(
426                llbb: BasicBlockRef,
427                is_lpad: bool,
428                opt_node_id: Option<ast::NodeId>,
429                fcx: &'a FunctionContext<'a>)
430                -> &'a Block<'a> {
431         fcx.block_arena.alloc(Block {
432             llbb: llbb,
433             terminated: Cell::new(false),
434             unreachable: Cell::new(false),
435             is_lpad: is_lpad,
436             opt_node_id: opt_node_id,
437             fcx: fcx
438         })
439     }
440
441     pub fn ccx(&self) -> &'a CrateContext { self.fcx.ccx }
442     pub fn tcx(&self) -> &'a ty::ctxt {
443         &self.fcx.ccx.tcx
444     }
445     pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
446
447     pub fn ident(&self, ident: Ident) -> ~str {
448         token::get_ident(ident).get().to_str()
449     }
450
451     pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
452         self.tcx().map.node_to_str(id)
453     }
454
455     pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
456         e.repr(self.tcx())
457     }
458
459     pub fn expr_is_lval(&self, e: &ast::Expr) -> bool {
460         ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
461     }
462
463     pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind {
464         ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
465     }
466
467     pub fn def(&self, nid: ast::NodeId) -> ast::Def {
468         match self.tcx().def_map.borrow().find(&nid) {
469             Some(&v) => v,
470             None => {
471                 self.tcx().sess.bug(format!(
472                     "no def associated with node id {:?}", nid));
473             }
474         }
475     }
476
477     pub fn val_to_str(&self, val: ValueRef) -> ~str {
478         self.ccx().tn.val_to_str(val)
479     }
480
481     pub fn llty_str(&self, ty: Type) -> ~str {
482         self.ccx().tn.type_to_str(ty)
483     }
484
485     pub fn ty_to_str(&self, t: ty::t) -> ~str {
486         t.repr(self.tcx())
487     }
488
489     pub fn to_str(&self) -> ~str {
490         let blk: *Block = self;
491         format!("[block {}]", blk)
492     }
493 }
494
495 pub struct Result<'a> {
496     bcx: &'a Block<'a>,
497     val: ValueRef
498 }
499
500 pub fn rslt<'a>(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
501     Result {
502         bcx: bcx,
503         val: val,
504     }
505 }
506
507 impl<'a> Result<'a> {
508     pub fn unpack(&self, bcx: &mut &'a Block<'a>) -> ValueRef {
509         *bcx = self.bcx;
510         return self.val;
511     }
512 }
513
514 pub fn val_ty(v: ValueRef) -> Type {
515     unsafe {
516         Type::from_ref(llvm::LLVMTypeOf(v))
517     }
518 }
519
520 // LLVM constant constructors.
521 pub fn C_null(t: Type) -> ValueRef {
522     unsafe {
523         llvm::LLVMConstNull(t.to_ref())
524     }
525 }
526
527 pub fn C_undef(t: Type) -> ValueRef {
528     unsafe {
529         llvm::LLVMGetUndef(t.to_ref())
530     }
531 }
532
533 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
534     unsafe {
535         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
536     }
537 }
538
539 pub fn C_floating(s: &str, t: Type) -> ValueRef {
540     unsafe {
541         s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
542     }
543 }
544
545 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
546     C_struct(ccx, [], false)
547 }
548
549 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
550     C_integral(Type::bool(ccx), val as u64, false)
551 }
552
553 pub fn C_i1(ccx: &CrateContext, val: bool) -> ValueRef {
554     C_integral(Type::i1(ccx), val as u64, false)
555 }
556
557 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
558     C_integral(Type::i32(ccx), i as u64, true)
559 }
560
561 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
562     C_integral(Type::i64(ccx), i as u64, true)
563 }
564
565 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
566     C_integral(Type::i64(ccx), i, false)
567 }
568
569 pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
570     C_integral(ccx.int_type, i as u64, true)
571 }
572
573 pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
574     C_integral(ccx.int_type, i as u64, false)
575 }
576
577 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
578     C_integral(Type::i8(ccx), i as u64, false)
579 }
580
581
582 // This is a 'c-like' raw string, which differs from
583 // our boxed-and-length-annotated strings.
584 pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef {
585     unsafe {
586         match cx.const_cstr_cache.borrow().find(&s) {
587             Some(&llval) => return llval,
588             None => ()
589         }
590
591         let sc = llvm::LLVMConstStringInContext(cx.llcx,
592                                                 s.get().as_ptr() as *c_char,
593                                                 s.get().len() as c_uint,
594                                                 False);
595
596         let gsym = token::gensym("str");
597         let g = format!("str{}", gsym).with_c_str(|buf| {
598             llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
599         });
600         llvm::LLVMSetInitializer(g, sc);
601         llvm::LLVMSetGlobalConstant(g, True);
602         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
603
604         cx.const_cstr_cache.borrow_mut().insert(s, g);
605         g
606     }
607 }
608
609 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
610 // you will be kicked off fast isel. See issue #4352 for an example of this.
611 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
612     unsafe {
613         let len = s.get().len();
614         let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p(cx).to_ref());
615         C_struct(cx, [cs, C_uint(cx, len)], false)
616     }
617 }
618
619 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
620     unsafe {
621         let len = data.len();
622         let lldata = C_bytes(cx, data);
623
624         let gsym = token::gensym("binary");
625         let g = format!("binary{}", gsym).with_c_str(|buf| {
626             llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
627         });
628         llvm::LLVMSetInitializer(g, lldata);
629         llvm::LLVMSetGlobalConstant(g, True);
630         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
631
632         let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
633         C_struct(cx, [cs, C_uint(cx, len)], false)
634     }
635 }
636
637 pub fn C_struct(ccx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
638     unsafe {
639         llvm::LLVMConstStructInContext(ccx.llcx,
640                                        elts.as_ptr(), elts.len() as c_uint,
641                                        packed as Bool)
642     }
643 }
644
645 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
646     unsafe {
647         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
648     }
649 }
650
651 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
652     unsafe {
653         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
654     }
655 }
656
657 pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef {
658     unsafe {
659         let ptr = bytes.as_ptr() as *c_char;
660         return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True);
661     }
662 }
663
664 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
665     unsafe {
666         llvm::LLVMGetParam(fndecl, param as c_uint)
667     }
668 }
669
670 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
671                   -> ValueRef {
672     unsafe {
673         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
674
675         debug!("const_get_elt(v={}, us={:?}, r={})",
676                cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
677
678         return r;
679     }
680 }
681
682 pub fn is_const(v: ValueRef) -> bool {
683     unsafe {
684         llvm::LLVMIsConstant(v) == True
685     }
686 }
687
688 pub fn const_to_int(v: ValueRef) -> c_longlong {
689     unsafe {
690         llvm::LLVMConstIntGetSExtValue(v)
691     }
692 }
693
694 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
695     unsafe {
696         llvm::LLVMConstIntGetZExtValue(v)
697     }
698 }
699
700 pub fn is_undef(val: ValueRef) -> bool {
701     unsafe {
702         llvm::LLVMIsUndef(val) != False
703     }
704 }
705
706 pub fn is_null(val: ValueRef) -> bool {
707     unsafe {
708         llvm::LLVMIsNull(val) != False
709     }
710 }
711
712 // Used to identify cached monomorphized functions and vtables
713 #[deriving(Eq, TotalEq, Hash)]
714 pub enum mono_param_id {
715     mono_precise(ty::t, Option<@Vec<mono_id> >),
716     mono_any,
717     mono_repr(uint /* size */,
718               uint /* align */,
719               MonoDataClass,
720               datum::RvalueMode),
721 }
722
723 #[deriving(Eq, TotalEq, Hash)]
724 pub enum MonoDataClass {
725     MonoBits,    // Anything not treated differently from arbitrary integer data
726     MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
727     // FIXME(#3547)---scalars and floats are
728     // treated differently in most ABIs.  But we
729     // should be doing something more detailed
730     // here.
731     MonoFloat
732 }
733
734 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
735     match ty::get(t).sty {
736         ty::ty_float(_) => MonoFloat,
737         ty::ty_rptr(..) | ty::ty_uniq(..) | ty::ty_box(..) |
738         ty::ty_str(ty::vstore_uniq) | ty::ty_vec(_, ty::vstore_uniq) |
739         ty::ty_bare_fn(..) => MonoNonNull,
740         // Is that everything?  Would closures or slices qualify?
741         _ => MonoBits
742     }
743 }
744
745 #[deriving(Eq, TotalEq, Hash)]
746 pub struct mono_id_ {
747     def: ast::DefId,
748     params: Vec<mono_param_id> }
749
750 pub type mono_id = @mono_id_;
751
752 pub fn umax(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
753     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
754     return build::Select(cx, cond, b, a);
755 }
756
757 pub fn umin(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
758     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
759     return build::Select(cx, cond, a, b);
760 }
761
762 pub fn align_to(cx: &Block, off: ValueRef, align: ValueRef) -> ValueRef {
763     let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
764     let bumped = build::Add(cx, off, mask);
765     return build::And(cx, bumped, build::Not(cx, mask));
766 }
767
768 pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
769     match bcx.fcx.param_substs {
770         Some(substs) => {
771             ty::subst_tps(bcx.tcx(), substs.tys.as_slice(), substs.self_ty, t)
772         }
773         _ => {
774             assert!(!ty::type_has_params(t));
775             assert!(!ty::type_has_self(t));
776             t
777         }
778     }
779 }
780
781 pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
782     let tcx = bcx.tcx();
783     let t = ty::node_id_to_type(tcx, id);
784     monomorphize_type(bcx, t)
785 }
786
787 pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
788     node_id_type(bcx, ex.id)
789 }
790
791 pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
792     let tcx = bcx.tcx();
793     let t = ty::expr_ty_adjusted(tcx, ex, &*bcx.ccx().maps.method_map.borrow());
794     monomorphize_type(bcx, t)
795 }
796
797 // Key used to lookup values supplied for type parameters in an expr.
798 #[deriving(Eq)]
799 pub enum ExprOrMethodCall {
800     // Type parameters for a path like `None::<int>`
801     ExprId(ast::NodeId),
802
803     // Type parameters for a method call like `a.foo::<int>()`
804     MethodCall(typeck::MethodCall)
805 }
806
807 pub fn node_id_type_params(bcx: &Block, node: ExprOrMethodCall) -> Vec<ty::t> {
808     let tcx = bcx.tcx();
809     let params = match node {
810         ExprId(id) => ty::node_id_to_type_params(tcx, id),
811         MethodCall(method_call) => {
812             bcx.ccx().maps.method_map.borrow().get(&method_call).substs.tps.clone()
813         }
814     };
815
816     if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
817         bcx.sess().bug(
818             format!("type parameters for node {:?} include inference types: {}",
819                  node, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
820     }
821
822     match bcx.fcx.param_substs {
823       Some(substs) => {
824         params.iter().map(|t| {
825             ty::subst_tps(tcx, substs.tys.as_slice(), substs.self_ty, *t)
826         }).collect()
827       }
828       _ => params
829     }
830 }
831
832 pub fn node_vtables(bcx: &Block, id: typeck::MethodCall)
833                  -> Option<typeck::vtable_res> {
834     let vtable_map = bcx.ccx().maps.vtable_map.borrow();
835     let raw_vtables = vtable_map.find(&id);
836     raw_vtables.map(|vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
837 }
838
839 // Apply the typaram substitutions in the FunctionContext to some
840 // vtables. This should eliminate any vtable_params.
841 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
842     -> typeck::vtable_res {
843     resolve_vtables_under_param_substs(fcx.ccx.tcx(),
844                                        fcx.param_substs,
845                                        vts)
846 }
847
848 pub fn resolve_vtables_under_param_substs(tcx: &ty::ctxt,
849                                           param_substs: Option<@param_substs>,
850                                           vts: typeck::vtable_res)
851     -> typeck::vtable_res {
852     @vts.iter().map(|ds|
853       resolve_param_vtables_under_param_substs(tcx,
854                                                param_substs,
855                                                *ds))
856         .collect()
857 }
858
859 pub fn resolve_param_vtables_under_param_substs(
860     tcx: &ty::ctxt,
861     param_substs: Option<@param_substs>,
862     ds: typeck::vtable_param_res)
863     -> typeck::vtable_param_res {
864     @ds.iter().map(
865         |d| resolve_vtable_under_param_substs(tcx,
866                                               param_substs,
867                                               d))
868         .collect()
869 }
870
871
872
873 pub fn resolve_vtable_under_param_substs(tcx: &ty::ctxt,
874                                          param_substs: Option<@param_substs>,
875                                          vt: &typeck::vtable_origin)
876                                          -> typeck::vtable_origin {
877     match *vt {
878         typeck::vtable_static(trait_id, ref tys, sub) => {
879             let tys = match param_substs {
880                 Some(substs) => {
881                     tys.iter().map(|t| {
882                         ty::subst_tps(tcx,
883                                       substs.tys.as_slice(),
884                                       substs.self_ty,
885                                       *t)
886                     }).collect()
887                 }
888                 _ => Vec::from_slice(tys.as_slice())
889             };
890             typeck::vtable_static(
891                 trait_id, tys,
892                 resolve_vtables_under_param_substs(tcx, param_substs, sub))
893         }
894         typeck::vtable_param(n_param, n_bound) => {
895             match param_substs {
896                 Some(substs) => {
897                     find_vtable(tcx, substs, n_param, n_bound)
898                 }
899                 _ => {
900                     tcx.sess.bug(format!(
901                         "resolve_vtable_under_param_substs: asked to lookup \
902                          but no vtables in the fn_ctxt!"))
903                 }
904             }
905         }
906     }
907 }
908
909 pub fn find_vtable(tcx: &ty::ctxt,
910                    ps: &param_substs,
911                    n_param: typeck::param_index,
912                    n_bound: uint)
913                    -> typeck::vtable_origin {
914     debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
915            n_param, n_bound, ps.repr(tcx));
916
917     let param_bounds = match n_param {
918         typeck::param_self => ps.self_vtables.expect("self vtables missing"),
919         typeck::param_numbered(n) => {
920             let tables = ps.vtables
921                 .expect("vtables missing where they are needed");
922             *tables.get(n)
923         }
924     };
925     param_bounds.get(n_bound).clone()
926 }
927
928 pub fn dummy_substs(tps: Vec<ty::t> ) -> ty::substs {
929     substs {
930         regions: ty::ErasedRegions,
931         self_ty: None,
932         tps: tps
933     }
934 }
935
936 pub fn filename_and_line_num_from_span(bcx: &Block, span: Span)
937                                        -> (ValueRef, ValueRef) {
938     let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
939     let filename_cstr = C_cstr(bcx.ccx(),
940                                token::intern_and_get_ident(loc.file.name));
941     let filename = build::PointerCast(bcx, filename_cstr, Type::i8p(bcx.ccx()));
942     let line = C_int(bcx.ccx(), loc.line as int);
943     (filename, line)
944 }
945
946 // Casts a Rust bool value to an i1.
947 pub fn bool_to_i1(bcx: &Block, llval: ValueRef) -> ValueRef {
948     build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(bcx.ccx(), false))
949 }
950
951 pub fn langcall(bcx: &Block,
952                 span: Option<Span>,
953                 msg: &str,
954                 li: LangItem)
955                 -> ast::DefId {
956     match bcx.tcx().lang_items.require(li) {
957         Ok(id) => id,
958         Err(s) => {
959             let msg = format!("{} {}", msg, s);
960             match span {
961                 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
962                 None => { bcx.tcx().sess.fatal(msg); }
963             }
964         }
965     }
966 }