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