]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/common.rs
auto merge of #12764 : Kimundi/rust/partial_typehint, r=nikomatsakis
[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::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;
29 use middle::ty;
30 use middle::typeck;
31 use util::ppaux::Repr;
32 use util::nodemap::NodeMap;
33
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};
39 use std::vec_ng::Vec;
40 use syntax::ast::Ident;
41 use syntax::ast;
42 use syntax::ast_map::{PathElem, PathName};
43 use syntax::codemap::Span;
44 use syntax::parse::token::InternedString;
45 use syntax::parse::token;
46
47 pub use middle::trans::context::CrateContext;
48
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);
53             fields.len() == 1 &&
54                 fields.get(0).ident.name ==
55                     token::special_idents::unnamed_field.name &&
56                 type_is_immediate(ccx, fields.get(0).mt.ty)
57         }
58         _ => false
59     }
60 }
61
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;
65     let tcx = ccx.tcx;
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);
70     if simple {
71         return true;
72     }
73     match ty::get(ty).sty {
74         ty::ty_bot => true,
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)
78         }
79         _ => type_is_zero_size(ccx, ty)
80     }
81 }
82
83 pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
84     /*!
85      * Identify types which have size zero at runtime.
86      */
87
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
92 }
93
94 pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
95     /*!
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).
101      */
102
103     ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx, ty)
104 }
105
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)))
113 }
114
115 pub struct tydesc_info {
116     ty: ty::t,
117     tydesc: ValueRef,
118     size: ValueRef,
119     align: ValueRef,
120     name: ValueRef,
121     visit_glue: Cell<Option<ValueRef>>,
122 }
123
124 /*
125  * A note on nomenclature of linking: "extern", "foreign", and "upcall".
126  *
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.
131  *
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.
136  *
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
142  * link via.
143  *
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.
147  *
148  */
149
150 pub struct NodeInfo {
151     id: ast::NodeId,
152     span: Span,
153 }
154
155 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
156     NodeInfo { id: expr.id, span: expr.span }
157 }
158
159 pub struct Stats {
160     n_static_tydescs: Cell<uint>,
161     n_glues_created: Cell<uint>,
162     n_null_glues: Cell<uint>,
163     n_real_glues: Cell<uint>,
164     n_fns: Cell<uint>,
165     n_monos: 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)> >,
172 }
173
174 pub struct BuilderRef_res {
175     b: BuilderRef,
176 }
177
178 impl Drop for BuilderRef_res {
179     fn drop(&mut self) {
180         unsafe {
181             llvm::LLVMDisposeBuilder(self.b);
182         }
183     }
184 }
185
186 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
187     BuilderRef_res {
188         b: b
189     }
190 }
191
192 pub type ExternMap = HashMap<~str, ValueRef>;
193
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 {
197     tys: Vec<ty::t> ,
198     self_ty: Option<ty::t>,
199     vtables: Option<typeck::vtable_res>,
200     self_vtables: Option<typeck::vtable_param_res>
201 }
202
203 impl param_substs {
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)); }
207     }
208 }
209
210 fn param_substs_to_str(this: &param_substs, tcx: ty::ctxt) -> ~str {
211     format!("param_substs \\{tys:{}, vtables:{}\\}",
212          this.tys.repr(tcx),
213          this.vtables.repr(tcx))
214 }
215
216 impl Repr for param_substs {
217     fn repr(&self, tcx: ty::ctxt) -> ~str {
218         param_substs_to_str(self, tcx)
219     }
220 }
221
222 // work around bizarre resolve errors
223 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
224 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
225
226 // Function context.  Every LLVM function we create will have one of
227 // these.
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.
233     llfn: ValueRef,
234
235     // The environment argument in a closure.
236     llenv: Option<ValueRef>,
237
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
241     // always be Some.
242     llretptr: Cell<Option<ValueRef>>,
243
244     entry_bcx: RefCell<Option<&'a Block<'a>>>,
245
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>>,
253
254     // The a value alloca'd for calls to upcalls.rust_personality. Used when
255     // outputting the resume instruction.
256     personality: Cell<Option<ValueRef>>,
257
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,
262
263     // Maps arguments to allocas created for them in llallocas.
264     llargs: RefCell<NodeMap<LvalueDatum>>,
265
266     // Maps the def_ids for local variables to the allocas created for
267     // them in llallocas.
268     lllocals: RefCell<NodeMap<LvalueDatum>>,
269
270     // Same as above, but for closure upvars
271     llupvars: RefCell<NodeMap<ValueRef>>,
272
273     // The NodeId of the function, or -1 if it doesn't correspond to
274     // a user-defined function.
275     id: ast::NodeId,
276
277     // If this function is being monomorphized, this contains the type
278     // substitutions used.
279     param_substs: Option<@param_substs>,
280
281     // The source span and nesting context where this function comes from, for
282     // error reporting and symbol generation.
283     span: Option<Span>,
284
285     // The arena that blocks are allocated from.
286     block_arena: &'a TypedArena<Block<'a>>,
287
288     // This function's enclosing crate context.
289     ccx: @CrateContext,
290
291     // Used and maintained by the debuginfo module.
292     debug_context: debuginfo::FunctionDebugContext,
293
294     // Cleanup scopes.
295     scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
296 }
297
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() {
302             arg + 1
303         } else {
304             arg
305         }
306     }
307
308     pub fn out_arg_pos(&self) -> uint {
309         assert!(self.caller_expects_out_pointer);
310         0u
311     }
312
313     pub fn env_arg_pos(&self) -> uint {
314         if self.caller_expects_out_pointer {
315             1u
316         } else {
317             0u
318         }
319     }
320
321     pub fn cleanup(&self) {
322         unsafe {
323             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
324                                                      .get()
325                                                      .unwrap());
326         }
327         // Remove the cycle between fcx and bcx, so memory can be freed
328         self.entry_bcx.set(None);
329     }
330
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)));
334         }
335
336         self.llreturn.get().unwrap()
337     }
338
339     pub fn new_block(&'a self,
340                      is_lpad: bool,
341                      name: &str,
342                      opt_node_id: Option<ast::NodeId>)
343                      -> &'a Block<'a> {
344         unsafe {
345             let llbb = name.with_c_str(|buf| {
346                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
347                                                         self.llfn,
348                                                         buf)
349                 });
350             Block::new(llbb, is_lpad, opt_node_id, self)
351         }
352     }
353
354     pub fn new_id_block(&'a self,
355                         name: &str,
356                         node_id: ast::NodeId)
357                         -> &'a Block<'a> {
358         self.new_block(false, name, Some(node_id))
359     }
360
361     pub fn new_temp_block(&'a self,
362                           name: &str)
363                           -> &'a Block<'a> {
364         self.new_block(false, name, None)
365     }
366
367     pub fn join_blocks(&'a self,
368                        id: ast::NodeId,
369                        in_cxs: &[&'a Block<'a>])
370                        -> &'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);
376                 reachable = true;
377             }
378         }
379         if !reachable {
380             build::Unreachable(out);
381         }
382         return out;
383     }
384 }
385
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!");
390     }
391 }
392
393 // Heap selectors. Indicate which heap something should go on.
394 #[deriving(Eq)]
395 pub enum heap {
396     heap_managed,
397     heap_exchange,
398     heap_exchange_closure
399 }
400
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.
412     llbb: BasicBlockRef,
413     terminated: Cell<bool>,
414     unreachable: Cell<bool>,
415
416     // Is this block part of a landing pad?
417     is_lpad: bool,
418
419     // AST node-id associated with this block, if any. Used for
420     // debugging purposes only.
421     opt_node_id: Option<ast::NodeId>,
422
423     // The function context for the function to which this block is
424     // attached.
425     fcx: &'a FunctionContext<'a>,
426 }
427
428 impl<'a> Block<'a> {
429     pub fn new<'a>(
430                llbb: BasicBlockRef,
431                is_lpad: bool,
432                opt_node_id: Option<ast::NodeId>,
433                fcx: &'a FunctionContext<'a>)
434                -> &'a Block<'a> {
435         fcx.block_arena.alloc(Block {
436             llbb: llbb,
437             terminated: Cell::new(false),
438             unreachable: Cell::new(false),
439             is_lpad: is_lpad,
440             opt_node_id: opt_node_id,
441             fcx: fcx
442         })
443     }
444
445     pub fn ccx(&self) -> @CrateContext { self.fcx.ccx }
446     pub fn tcx(&self) -> ty::ctxt {
447         self.fcx.ccx.tcx
448     }
449     pub fn sess(&self) -> Session { self.fcx.ccx.sess }
450
451     pub fn ident(&self, ident: Ident) -> ~str {
452         token::get_ident(ident).get().to_str()
453     }
454
455     pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
456         self.tcx().map.node_to_str(id)
457     }
458
459     pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
460         e.repr(self.tcx())
461     }
462
463     pub fn expr_is_lval(&self, e: &ast::Expr) -> bool {
464         ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
465     }
466
467     pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind {
468         ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
469     }
470
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) {
474             Some(&v) => v,
475             None => {
476                 self.tcx().sess.bug(format!(
477                     "no def associated with node id {:?}", nid));
478             }
479         }
480     }
481
482     pub fn val_to_str(&self, val: ValueRef) -> ~str {
483         self.ccx().tn.val_to_str(val)
484     }
485
486     pub fn llty_str(&self, ty: Type) -> ~str {
487         self.ccx().tn.type_to_str(ty)
488     }
489
490     pub fn ty_to_str(&self, t: ty::t) -> ~str {
491         t.repr(self.tcx())
492     }
493
494     pub fn to_str(&self) -> ~str {
495         let blk: *Block = self;
496         format!("[block {}]", blk)
497     }
498 }
499
500 pub struct Result<'a> {
501     bcx: &'a Block<'a>,
502     val: ValueRef
503 }
504
505 pub fn rslt<'a>(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
506     Result {
507         bcx: bcx,
508         val: val,
509     }
510 }
511
512 impl<'a> Result<'a> {
513     pub fn unpack(&self, bcx: &mut &'a Block<'a>) -> ValueRef {
514         *bcx = self.bcx;
515         return self.val;
516     }
517 }
518
519 pub fn val_ty(v: ValueRef) -> Type {
520     unsafe {
521         Type::from_ref(llvm::LLVMTypeOf(v))
522     }
523 }
524
525 // LLVM constant constructors.
526 pub fn C_null(t: Type) -> ValueRef {
527     unsafe {
528         llvm::LLVMConstNull(t.to_ref())
529     }
530 }
531
532 pub fn C_undef(t: Type) -> ValueRef {
533     unsafe {
534         llvm::LLVMGetUndef(t.to_ref())
535     }
536 }
537
538 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
539     unsafe {
540         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
541     }
542 }
543
544 pub fn C_floating(s: &str, t: Type) -> ValueRef {
545     unsafe {
546         s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
547     }
548 }
549
550 pub fn C_nil() -> ValueRef {
551     C_struct([], false)
552 }
553
554 pub fn C_bool(val: bool) -> ValueRef {
555     C_integral(Type::bool(), val as u64, false)
556 }
557
558 pub fn C_i1(val: bool) -> ValueRef {
559     C_integral(Type::i1(), val as u64, false)
560 }
561
562 pub fn C_i32(i: i32) -> ValueRef {
563     return C_integral(Type::i32(), i as u64, true);
564 }
565
566 pub fn C_i64(i: i64) -> ValueRef {
567     return C_integral(Type::i64(), i as u64, true);
568 }
569
570 pub fn C_u64(i: u64) -> ValueRef {
571     return C_integral(Type::i64(), i, false);
572 }
573
574 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
575     return C_integral(cx.int_type, i as u64, true);
576 }
577
578 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
579     return C_integral(cx.int_type, i as u64, false);
580 }
581
582 pub fn C_u8(i: uint) -> ValueRef {
583     return C_integral(Type::i8(), i as u64, false);
584 }
585
586
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 {
590     unsafe {
591         {
592             let const_cstr_cache = cx.const_cstr_cache.borrow();
593             match const_cstr_cache.get().find(&s) {
594                 Some(&llval) => return llval,
595                 None => ()
596             }
597         }
598
599         let sc = llvm::LLVMConstStringInContext(cx.llcx,
600                                                 s.get().as_ptr() as *c_char,
601                                                 s.get().len() as c_uint,
602                                                 False);
603
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)
607         });
608         llvm::LLVMSetInitializer(g, sc);
609         llvm::LLVMSetGlobalConstant(g, True);
610         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
611
612         let mut const_cstr_cache = cx.const_cstr_cache.borrow_mut();
613         const_cstr_cache.get().insert(s, g);
614         g
615     }
616 }
617
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 {
621     unsafe {
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)
625     }
626 }
627
628 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
629     unsafe {
630         let len = data.len();
631         let lldata = C_bytes(data);
632
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)
636         });
637         llvm::LLVMSetInitializer(g, lldata);
638         llvm::LLVMSetGlobalConstant(g, True);
639         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
640
641         let cs = llvm::LLVMConstPointerCast(g, Type::i8p().to_ref());
642         C_struct([cs, C_uint(cx, len)], false)
643     }
644 }
645
646 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
647     unsafe {
648         let mut i = 0u;
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);
653     }
654 }
655
656 pub fn C_struct(elts: &[ValueRef], packed: bool) -> ValueRef {
657     unsafe {
658
659         llvm::LLVMConstStructInContext(base::task_llcx(),
660                                        elts.as_ptr(), elts.len() as c_uint,
661                                        packed as Bool)
662     }
663 }
664
665 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
666     unsafe {
667         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
668     }
669 }
670
671 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
672     unsafe {
673         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
674     }
675 }
676
677 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
678     unsafe {
679         let ptr = bytes.as_ptr() as *c_char;
680         return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
681     }
682 }
683
684 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
685     unsafe {
686         llvm::LLVMGetParam(fndecl, param as c_uint)
687     }
688 }
689
690 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
691                   -> ValueRef {
692     unsafe {
693         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
694
695         debug!("const_get_elt(v={}, us={:?}, r={})",
696                cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
697
698         return r;
699     }
700 }
701
702 pub fn is_const(v: ValueRef) -> bool {
703     unsafe {
704         llvm::LLVMIsConstant(v) == True
705     }
706 }
707
708 pub fn const_to_int(v: ValueRef) -> c_longlong {
709     unsafe {
710         llvm::LLVMConstIntGetSExtValue(v)
711     }
712 }
713
714 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
715     unsafe {
716         llvm::LLVMConstIntGetZExtValue(v)
717     }
718 }
719
720 pub fn is_undef(val: ValueRef) -> bool {
721     unsafe {
722         llvm::LLVMIsUndef(val) != False
723     }
724 }
725
726 pub fn is_null(val: ValueRef) -> bool {
727     unsafe {
728         llvm::LLVMIsNull(val) != False
729     }
730 }
731
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> >),
736     mono_any,
737     mono_repr(uint /* size */,
738               uint /* align */,
739               MonoDataClass,
740               datum::RvalueMode),
741 }
742
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
750     // here.
751     MonoFloat
752 }
753
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?
761         _ => MonoBits
762     }
763 }
764
765 #[deriving(Eq, Hash)]
766 pub struct mono_id_ {
767     def: ast::DefId,
768     params: Vec<mono_param_id> }
769
770 pub type mono_id = @mono_id_;
771
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);
775 }
776
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);
780 }
781
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));
786 }
787
788 pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
789     match bcx.fcx.param_substs {
790         Some(substs) => {
791             ty::subst_tps(bcx.tcx(), substs.tys.as_slice(), substs.self_ty, t)
792         }
793         _ => {
794             assert!(!ty::type_has_params(t));
795             assert!(!ty::type_has_self(t));
796             t
797         }
798     }
799 }
800
801 pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
802     let tcx = bcx.tcx();
803     let t = ty::node_id_to_type(tcx, id);
804     monomorphize_type(bcx, t)
805 }
806
807 pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
808     node_id_type(bcx, ex.id)
809 }
810
811 pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
812     let tcx = bcx.tcx();
813     let t = ty::expr_ty_adjusted(tcx, ex, bcx.ccx().maps.method_map.borrow().get());
814     monomorphize_type(bcx, t)
815 }
816
817 // Key used to lookup values supplied for type parameters in an expr.
818 #[deriving(Eq)]
819 pub enum ExprOrMethodCall {
820     // Type parameters for a path like `None::<int>`
821     ExprId(ast::NodeId),
822
823     // Type parameters for a method call like `a.foo::<int>()`
824     MethodCall(typeck::MethodCall)
825 }
826
827 pub fn node_id_type_params(bcx: &Block, node: ExprOrMethodCall) -> Vec<ty::t> {
828     let tcx = bcx.tcx();
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()
833         }
834     };
835
836     if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
837         bcx.sess().bug(
838             format!("type parameters for node {:?} include inference types: {}",
839                  node, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
840     }
841
842     match bcx.fcx.param_substs {
843       Some(substs) => {
844         params.iter().map(|t| {
845             ty::subst_tps(tcx, substs.tys.as_slice(), substs.self_ty, *t)
846         }).collect()
847       }
848       _ => params
849     }
850 }
851
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))
857 }
858
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,
864                                        fcx.param_substs,
865                                        vts)
866 }
867
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 {
872     @vts.iter().map(|ds|
873       resolve_param_vtables_under_param_substs(tcx,
874                                                param_substs,
875                                                *ds))
876         .collect()
877 }
878
879 pub fn resolve_param_vtables_under_param_substs(
880     tcx: ty::ctxt,
881     param_substs: Option<@param_substs>,
882     ds: typeck::vtable_param_res)
883     -> typeck::vtable_param_res {
884     @ds.iter().map(
885         |d| resolve_vtable_under_param_substs(tcx,
886                                               param_substs,
887                                               d))
888         .collect()
889 }
890
891
892
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 {
897     match *vt {
898         typeck::vtable_static(trait_id, ref tys, sub) => {
899             let tys = match param_substs {
900                 Some(substs) => {
901                     tys.iter().map(|t| {
902                         ty::subst_tps(tcx,
903                                       substs.tys.as_slice(),
904                                       substs.self_ty,
905                                       *t)
906                     }).collect()
907                 }
908                 _ => Vec::from_slice(tys.as_slice())
909             };
910             typeck::vtable_static(
911                 trait_id, tys,
912                 resolve_vtables_under_param_substs(tcx, param_substs, sub))
913         }
914         typeck::vtable_param(n_param, n_bound) => {
915             match param_substs {
916                 Some(substs) => {
917                     find_vtable(tcx, substs, n_param, n_bound)
918                 }
919                 _ => {
920                     tcx.sess.bug(format!(
921                         "resolve_vtable_under_param_substs: asked to lookup \
922                          but no vtables in the fn_ctxt!"))
923                 }
924             }
925         }
926     }
927 }
928
929 pub fn find_vtable(tcx: ty::ctxt,
930                    ps: &param_substs,
931                    n_param: typeck::param_index,
932                    n_bound: uint)
933                    -> typeck::vtable_origin {
934     debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
935            n_param, n_bound, ps.repr(tcx));
936
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");
942             *tables.get(n)
943         }
944     };
945     param_bounds.get(n_bound).clone()
946 }
947
948 pub fn dummy_substs(tps: Vec<ty::t> ) -> ty::substs {
949     substs {
950         regions: ty::ErasedRegions,
951         self_ty: None,
952         tps: tps
953     }
954 }
955
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);
963     (filename, line)
964 }
965
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))
969 }
970
971 pub fn langcall(bcx: &Block,
972                 span: Option<Span>,
973                 msg: &str,
974                 li: LangItem)
975                 -> ast::DefId {
976     match bcx.tcx().lang_items.require(li) {
977         Ok(id) => id,
978         Err(s) => {
979             let msg = format!("{} {}", msg, s);
980             match span {
981                 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
982                 None => { bcx.tcx().sess.fatal(msg); }
983             }
984         }
985     }
986 }