]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/common.rs
9aa18bc05f8fa884ff22abb255dcebb2cc8e24fe
[rust.git] / src / librustc / middle / trans / common.rs
1 // Copyright 2012-2013 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 //! Code that is useful in various trans modules.
12
13
14 use driver::session;
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::datum;
24 use middle::trans::glue;
25 use middle::trans::write_guard;
26 use middle::trans::debuginfo;
27 use middle::ty::substs;
28 use middle::ty;
29 use middle::typeck;
30 use middle::borrowck::root_map_key;
31 use util::ppaux::{Repr};
32
33 use middle::trans::type_::Type;
34
35 use std::c_str::ToCStr;
36 use std::cast::transmute;
37 use std::cast;
38 use std::hashmap::{HashMap};
39 use std::libc::{c_uint, c_longlong, c_ulonglong};
40 use std::vec;
41 use syntax::ast::ident;
42 use syntax::ast_map::{path, path_elt};
43 use syntax::codemap::span;
44 use syntax::parse::token;
45 use syntax::{ast, ast_map};
46
47 pub use middle::trans::context::CrateContext;
48
49 pub fn gensym_name(name: &str) -> ident {
50     token::str_to_ident(fmt!("%s_%u", name, token::gensym(name)))
51 }
52
53 pub struct tydesc_info {
54     ty: ty::t,
55     tydesc: ValueRef,
56     size: ValueRef,
57     align: ValueRef,
58     borrow_offset: ValueRef,
59     take_glue: Option<ValueRef>,
60     drop_glue: Option<ValueRef>,
61     free_glue: Option<ValueRef>,
62     visit_glue: Option<ValueRef>
63 }
64
65 /*
66  * A note on nomenclature of linking: "extern", "foreign", and "upcall".
67  *
68  * An "extern" is an LLVM symbol we wind up emitting an undefined external
69  * reference to. This means "we don't have the thing in this compilation unit,
70  * please make sure you link it in at runtime". This could be a reference to
71  * C code found in a C library, or rust code found in a rust crate.
72  *
73  * Most "externs" are implicitly declared (automatically) as a result of a
74  * user declaring an extern _module_ dependency; this causes the rust driver
75  * to locate an extern crate, scan its compilation metadata, and emit extern
76  * declarations for any symbols used by the declaring crate.
77  *
78  * A "foreign" is an extern that references C (or other non-rust ABI) code.
79  * There is no metadata to scan for extern references so in these cases either
80  * a header-digester like bindgen, or manual function prototypes, have to
81  * serve as declarators. So these are usually given explicitly as prototype
82  * declarations, in rust code, with ABI attributes on them noting which ABI to
83  * link via.
84  *
85  * An "upcall" is a foreign call generated by the compiler (not corresponding
86  * to any user-written call in the code) into the runtime library, to perform
87  * some helper task such as bringing a task to life, allocating memory, etc.
88  *
89  */
90
91 pub struct Stats {
92     n_static_tydescs: uint,
93     n_glues_created: uint,
94     n_null_glues: uint,
95     n_real_glues: uint,
96     n_fns: uint,
97     n_monos: uint,
98     n_inlines: uint,
99     n_closures: uint,
100     n_llvm_insns: uint,
101     llvm_insn_ctxt: ~[~str],
102     llvm_insns: HashMap<~str, uint>,
103     fn_stats: ~[(~str, uint, uint)] // (ident, time-in-ms, llvm-instructions)
104 }
105
106 pub struct BuilderRef_res {
107     B: BuilderRef,
108 }
109
110 impl Drop for BuilderRef_res {
111     fn drop(&self) {
112         unsafe {
113             llvm::LLVMDisposeBuilder(self.B);
114         }
115     }
116 }
117
118 pub fn BuilderRef_res(B: BuilderRef) -> BuilderRef_res {
119     BuilderRef_res {
120         B: B
121     }
122 }
123
124 pub type ExternMap = HashMap<@str, ValueRef>;
125
126 // Types used for llself.
127 pub struct ValSelfData {
128     v: ValueRef,
129     t: ty::t,
130     is_copy: bool,
131 }
132
133 // Here `self_ty` is the real type of the self parameter to this method. It
134 // will only be set in the case of default methods.
135 pub struct param_substs {
136     tys: ~[ty::t],
137     self_ty: Option<ty::t>,
138     vtables: Option<typeck::vtable_res>,
139     self_vtables: Option<typeck::vtable_param_res>
140 }
141
142 impl param_substs {
143     pub fn validate(&self) {
144         for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
145         for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
146     }
147 }
148
149 fn param_substs_to_str(this: &param_substs, tcx: ty::ctxt) -> ~str {
150     fmt!("param_substs {tys:%s, vtables:%s}",
151          this.tys.repr(tcx),
152          this.vtables.repr(tcx))
153 }
154
155 impl Repr for param_substs {
156     fn repr(&self, tcx: ty::ctxt) -> ~str {
157         param_substs_to_str(self, tcx)
158     }
159 }
160
161 // Function context.  Every LLVM function we create will have one of
162 // these.
163 pub struct FunctionContext {
164     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
165     // address of the first instruction in the sequence of
166     // instructions for this function that will go in the .text
167     // section of the executable we're generating.
168     llfn: ValueRef,
169
170     // The implicit environment argument that arrives in the function we're
171     // creating.
172     llenv: ValueRef,
173
174     // The place to store the return value. If the return type is immediate,
175     // this is an alloca in the function. Otherwise, it's the hidden first
176     // parameter to the function. After function construction, this should
177     // always be Some.
178     llretptr: Option<ValueRef>,
179
180     entry_bcx: Option<@mut Block>,
181
182     // These elements: "hoisted basic blocks" containing
183     // administrative activities that have to happen in only one place in
184     // the function, due to LLVM's quirks.
185     // A marker for the place where we want to insert the function's static
186     // allocas, so that LLVM will coalesce them into a single alloca call.
187     alloca_insert_pt: Option<ValueRef>,
188     llreturn: Option<BasicBlockRef>,
189     // The 'self' value currently in use in this function, if there
190     // is one.
191     //
192     // NB: This is the type of the self *variable*, not the self *type*. The
193     // self type is set only for default methods, while the self variable is
194     // set for all methods.
195     llself: Option<ValSelfData>,
196     // The a value alloca'd for calls to upcalls.rust_personality. Used when
197     // outputting the resume instruction.
198     personality: Option<ValueRef>,
199     // If this is a for-loop body that returns, this holds the pointers needed
200     // for that (flagptr, retptr)
201     loop_ret: Option<(ValueRef, ValueRef)>,
202
203     // True if this function has an immediate return value, false otherwise.
204     // If this is false, the llretptr will alias the first argument of the
205     // function.
206     has_immediate_return_value: bool,
207
208     // Maps arguments to allocas created for them in llallocas.
209     llargs: @mut HashMap<ast::NodeId, ValueRef>,
210     // Maps the def_ids for local variables to the allocas created for
211     // them in llallocas.
212     lllocals: @mut HashMap<ast::NodeId, ValueRef>,
213     // Same as above, but for closure upvars
214     llupvars: @mut HashMap<ast::NodeId, ValueRef>,
215
216     // The NodeId of the function, or -1 if it doesn't correspond to
217     // a user-defined function.
218     id: ast::NodeId,
219
220     // If this function is being monomorphized, this contains the type
221     // substitutions used.
222     param_substs: Option<@param_substs>,
223
224     // The source span and nesting context where this function comes from, for
225     // error reporting and symbol generation.
226     span: Option<span>,
227     path: path,
228
229     // This function's enclosing crate context.
230     ccx: @mut CrateContext,
231
232     // Used and maintained by the debuginfo module.
233     debug_context: Option<~debuginfo::FunctionDebugContext>
234 }
235
236 impl FunctionContext {
237     pub fn arg_pos(&self, arg: uint) -> uint {
238         if self.has_immediate_return_value {
239             arg + 1u
240         } else {
241             arg + 2u
242         }
243     }
244
245     pub fn out_arg_pos(&self) -> uint {
246         assert!(!self.has_immediate_return_value);
247         0u
248     }
249
250     pub fn env_arg_pos(&self) -> uint {
251         if !self.has_immediate_return_value {
252             1u
253         } else {
254             0u
255         }
256     }
257
258     pub fn cleanup(&mut self) {
259         unsafe {
260             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt.unwrap());
261         }
262         // Remove the cycle between fcx and bcx, so memory can be freed
263         self.entry_bcx = None;
264     }
265
266     pub fn get_llreturn(&mut self) -> BasicBlockRef {
267         if self.llreturn.is_none() {
268             self.llreturn = Some(base::mk_return_basic_block(self.llfn));
269         }
270
271         self.llreturn.unwrap()
272     }
273 }
274
275 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
276     if !ccx.do_not_commit_warning_issued {
277         ccx.do_not_commit_warning_issued = true;
278         ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
279     }
280 }
281
282 // Heap selectors. Indicate which heap something should go on.
283 #[deriving(Eq)]
284 pub enum heap {
285     heap_managed,
286     heap_managed_unique,
287     heap_exchange,
288     heap_exchange_closure
289 }
290
291 #[deriving(Clone, Eq)]
292 pub enum cleantype {
293     normal_exit_only,
294     normal_exit_and_unwind
295 }
296
297 pub enum cleanup {
298     clean(@fn(@mut Block) -> @mut Block, cleantype),
299     clean_temp(ValueRef, @fn(@mut Block) -> @mut Block, cleantype),
300 }
301
302 // Can't use deriving(Clone) because of the managed closure.
303 impl Clone for cleanup {
304     fn clone(&self) -> cleanup {
305         match *self {
306             clean(f, ct) => clean(f, ct),
307             clean_temp(v, f, ct) => clean_temp(v, f, ct),
308         }
309     }
310 }
311
312 // Used to remember and reuse existing cleanup paths
313 // target: none means the path ends in an resume instruction
314 #[deriving(Clone)]
315 pub struct cleanup_path {
316     target: Option<BasicBlockRef>,
317     size: uint,
318     dest: BasicBlockRef
319 }
320
321 pub fn shrink_scope_clean(scope_info: &mut ScopeInfo, size: uint) {
322     scope_info.landing_pad = None;
323     scope_info.cleanup_paths = scope_info.cleanup_paths.iter()
324             .take_while(|&cu| cu.size <= size).map(|&x|x).collect();
325 }
326
327 pub fn grow_scope_clean(scope_info: &mut ScopeInfo) {
328     scope_info.landing_pad = None;
329 }
330
331 pub fn cleanup_type(cx: ty::ctxt, ty: ty::t) -> cleantype {
332     if ty::type_needs_unwind_cleanup(cx, ty) {
333         normal_exit_and_unwind
334     } else {
335         normal_exit_only
336     }
337 }
338
339 pub fn add_clean(bcx: @mut Block, val: ValueRef, t: ty::t) {
340     if !ty::type_needs_drop(bcx.tcx(), t) { return; }
341
342     debug!("add_clean(%s, %s, %s)", bcx.to_str(), bcx.val_to_str(val), t.repr(bcx.tcx()));
343
344     let cleanup_type = cleanup_type(bcx.tcx(), t);
345     do in_scope_cx(bcx, None) |scope_info| {
346         scope_info.cleanups.push(clean(|a| glue::drop_ty(a, val, t), cleanup_type));
347         grow_scope_clean(scope_info);
348     }
349 }
350
351 pub fn add_clean_temp_immediate(cx: @mut Block, val: ValueRef, ty: ty::t) {
352     if !ty::type_needs_drop(cx.tcx(), ty) { return; }
353     debug!("add_clean_temp_immediate(%s, %s, %s)",
354            cx.to_str(), cx.val_to_str(val),
355            ty.repr(cx.tcx()));
356     let cleanup_type = cleanup_type(cx.tcx(), ty);
357     do in_scope_cx(cx, None) |scope_info| {
358         scope_info.cleanups.push(
359             clean_temp(val, |a| glue::drop_ty_immediate(a, val, ty),
360                        cleanup_type));
361         grow_scope_clean(scope_info);
362     }
363 }
364
365 pub fn add_clean_temp_mem(bcx: @mut Block, val: ValueRef, t: ty::t) {
366     add_clean_temp_mem_in_scope_(bcx, None, val, t);
367 }
368
369 pub fn add_clean_temp_mem_in_scope(bcx: @mut Block,
370                                    scope_id: ast::NodeId,
371                                    val: ValueRef,
372                                    t: ty::t) {
373     add_clean_temp_mem_in_scope_(bcx, Some(scope_id), val, t);
374 }
375
376 pub fn add_clean_temp_mem_in_scope_(bcx: @mut Block, scope_id: Option<ast::NodeId>,
377                                     val: ValueRef, t: ty::t) {
378     if !ty::type_needs_drop(bcx.tcx(), t) { return; }
379     debug!("add_clean_temp_mem(%s, %s, %s)",
380            bcx.to_str(), bcx.val_to_str(val),
381            t.repr(bcx.tcx()));
382     let cleanup_type = cleanup_type(bcx.tcx(), t);
383     do in_scope_cx(bcx, scope_id) |scope_info| {
384         scope_info.cleanups.push(clean_temp(val, |a| glue::drop_ty(a, val, t), cleanup_type));
385         grow_scope_clean(scope_info);
386     }
387 }
388 pub fn add_clean_return_to_mut(bcx: @mut Block,
389                                scope_id: ast::NodeId,
390                                root_key: root_map_key,
391                                frozen_val_ref: ValueRef,
392                                bits_val_ref: ValueRef,
393                                filename_val: ValueRef,
394                                line_val: ValueRef) {
395     //! When an `@mut` has been frozen, we have to
396     //! call the lang-item `return_to_mut` when the
397     //! freeze goes out of scope. We need to pass
398     //! in both the value which was frozen (`frozen_val`) and
399     //! the value (`bits_val_ref`) which was returned when the
400     //! box was frozen initially. Here, both `frozen_val_ref` and
401     //! `bits_val_ref` are in fact pointers to stack slots.
402
403     debug!("add_clean_return_to_mut(%s, %s, %s)",
404            bcx.to_str(),
405            bcx.val_to_str(frozen_val_ref),
406            bcx.val_to_str(bits_val_ref));
407     do in_scope_cx(bcx, Some(scope_id)) |scope_info| {
408         scope_info.cleanups.push(
409             clean_temp(
410                 frozen_val_ref,
411                 |bcx| write_guard::return_to_mut(bcx, root_key, frozen_val_ref, bits_val_ref,
412                                                  filename_val, line_val),
413                 normal_exit_only));
414         grow_scope_clean(scope_info);
415     }
416 }
417 pub fn add_clean_free(cx: @mut Block, ptr: ValueRef, heap: heap) {
418     let free_fn = match heap {
419       heap_managed | heap_managed_unique => {
420         let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_free(a, ptr);
421         f
422       }
423       heap_exchange | heap_exchange_closure => {
424         let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_exchange_free(a, ptr);
425         f
426       }
427     };
428     do in_scope_cx(cx, None) |scope_info| {
429         scope_info.cleanups.push(clean_temp(ptr, free_fn,
430                                       normal_exit_and_unwind));
431         grow_scope_clean(scope_info);
432     }
433 }
434
435 // Note that this only works for temporaries. We should, at some point, move
436 // to a system where we can also cancel the cleanup on local variables, but
437 // this will be more involved. For now, we simply zero out the local, and the
438 // drop glue checks whether it is zero.
439 pub fn revoke_clean(cx: @mut Block, val: ValueRef) {
440     do in_scope_cx(cx, None) |scope_info| {
441         let cleanup_pos = scope_info.cleanups.iter().position(
442             |cu| match *cu {
443                 clean_temp(v, _, _) if v == val => true,
444                 _ => false
445             });
446         for i in cleanup_pos.iter() {
447             scope_info.cleanups =
448                 vec::append(scope_info.cleanups.slice(0u, *i).to_owned(),
449                             scope_info.cleanups.slice(*i + 1u,
450                                                       scope_info.cleanups.len()));
451             shrink_scope_clean(scope_info, *i);
452         }
453     }
454 }
455
456 pub fn block_cleanups(bcx: @mut Block) -> ~[cleanup] {
457     match bcx.scope {
458        None  => ~[],
459        Some(inf) => inf.cleanups.clone(),
460     }
461 }
462
463 pub struct ScopeInfo {
464     parent: Option<@mut ScopeInfo>,
465     loop_break: Option<@mut Block>,
466     loop_label: Option<ident>,
467     // A list of functions that must be run at when leaving this
468     // block, cleaning up any variables that were introduced in the
469     // block.
470     cleanups: ~[cleanup],
471     // Existing cleanup paths that may be reused, indexed by destination and
472     // cleared when the set of cleanups changes.
473     cleanup_paths: ~[cleanup_path],
474     // Unwinding landing pad. Also cleared when cleanups change.
475     landing_pad: Option<BasicBlockRef>,
476     // info about the AST node this scope originated from, if any
477     node_info: Option<NodeInfo>,
478 }
479
480 impl ScopeInfo {
481     pub fn empty_cleanups(&mut self) -> bool {
482         self.cleanups.is_empty()
483     }
484 }
485
486 pub trait get_node_info {
487     fn info(&self) -> Option<NodeInfo>;
488 }
489
490 impl get_node_info for ast::expr {
491     fn info(&self) -> Option<NodeInfo> {
492         Some(NodeInfo {id: self.id,
493                        callee_id: self.get_callee_id(),
494                        span: self.span})
495     }
496 }
497
498 impl get_node_info for ast::Block {
499     fn info(&self) -> Option<NodeInfo> {
500         Some(NodeInfo {id: self.id,
501                        callee_id: None,
502                        span: self.span})
503     }
504 }
505
506 impl get_node_info for Option<@ast::expr> {
507     fn info(&self) -> Option<NodeInfo> {
508         self.chain_ref(|s| s.info())
509     }
510 }
511
512 pub struct NodeInfo {
513     id: ast::NodeId,
514     callee_id: Option<ast::NodeId>,
515     span: span
516 }
517
518 // Basic block context.  We create a block context for each basic block
519 // (single-entry, single-exit sequence of instructions) we generate from Rust
520 // code.  Each basic block we generate is attached to a function, typically
521 // with many basic blocks per function.  All the basic blocks attached to a
522 // function are organized as a directed graph.
523 pub struct Block {
524     // The BasicBlockRef returned from a call to
525     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
526     // block to the function pointed to by llfn.  We insert
527     // instructions into that block by way of this block context.
528     // The block pointing to this one in the function's digraph.
529     llbb: BasicBlockRef,
530     terminated: bool,
531     unreachable: bool,
532     parent: Option<@mut Block>,
533     // The current scope within this basic block
534     scope: Option<@mut ScopeInfo>,
535     // Is this block part of a landing pad?
536     is_lpad: bool,
537     // info about the AST node this block originated from, if any
538     node_info: Option<NodeInfo>,
539     // The function context for the function to which this block is
540     // attached.
541     fcx: @mut FunctionContext
542 }
543
544 impl Block {
545
546     pub fn new(llbb: BasicBlockRef,
547                parent: Option<@mut Block>,
548                is_lpad: bool,
549                node_info: Option<NodeInfo>,
550                fcx: @mut FunctionContext)
551             -> Block {
552         Block {
553             llbb: llbb,
554             terminated: false,
555             unreachable: false,
556             parent: parent,
557             scope: None,
558             is_lpad: is_lpad,
559             node_info: node_info,
560             fcx: fcx
561         }
562     }
563
564     pub fn ccx(&self) -> @mut CrateContext { self.fcx.ccx }
565     pub fn tcx(&self) -> ty::ctxt { self.fcx.ccx.tcx }
566     pub fn sess(&self) -> Session { self.fcx.ccx.sess }
567
568     pub fn ident(&self, ident: ident) -> @str {
569         token::ident_to_str(&ident)
570     }
571
572     pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
573         ast_map::node_id_to_str(self.tcx().items, id, self.sess().intr())
574     }
575
576     pub fn expr_to_str(&self, e: @ast::expr) -> ~str {
577         e.repr(self.tcx())
578     }
579
580     pub fn expr_is_lval(&self, e: &ast::expr) -> bool {
581         ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
582     }
583
584     pub fn expr_kind(&self, e: &ast::expr) -> ty::ExprKind {
585         ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
586     }
587
588     pub fn def(&self, nid: ast::NodeId) -> ast::def {
589         match self.tcx().def_map.find(&nid) {
590             Some(&v) => v,
591             None => {
592                 self.tcx().sess.bug(fmt!(
593                     "No def associated with node id %?", nid));
594             }
595         }
596     }
597
598     pub fn val_to_str(&self, val: ValueRef) -> ~str {
599         self.ccx().tn.val_to_str(val)
600     }
601
602     pub fn llty_str(&self, ty: Type) -> ~str {
603         self.ccx().tn.type_to_str(ty)
604     }
605
606     pub fn ty_to_str(&self, t: ty::t) -> ~str {
607         t.repr(self.tcx())
608     }
609
610     pub fn to_str(&self) -> ~str {
611         unsafe {
612             match self.node_info {
613                 Some(node_info) => fmt!("[block %d]", node_info.id),
614                 None => fmt!("[block %x]", transmute(&*self)),
615             }
616         }
617     }
618 }
619
620 pub struct Result {
621     bcx: @mut Block,
622     val: ValueRef
623 }
624
625 pub fn rslt(bcx: @mut Block, val: ValueRef) -> Result {
626     Result {bcx: bcx, val: val}
627 }
628
629 impl Result {
630     pub fn unpack(&self, bcx: &mut @mut Block) -> ValueRef {
631         *bcx = self.bcx;
632         return self.val;
633     }
634 }
635
636 pub fn val_ty(v: ValueRef) -> Type {
637     unsafe {
638         Type::from_ref(llvm::LLVMTypeOf(v))
639     }
640 }
641
642 pub fn in_scope_cx(cx: @mut Block, scope_id: Option<ast::NodeId>, f: &fn(si: &mut ScopeInfo)) {
643     let mut cur = cx;
644     let mut cur_scope = cur.scope;
645     loop {
646         cur_scope = match cur_scope {
647             Some(inf) => match scope_id {
648                 Some(wanted) => match inf.node_info {
649                     Some(NodeInfo { id: actual, _ }) if wanted == actual => {
650                         debug!("in_scope_cx: selected cur=%s (cx=%s)",
651                                cur.to_str(), cx.to_str());
652                         f(inf);
653                         return;
654                     },
655                     _ => inf.parent,
656                 },
657                 None => {
658                     debug!("in_scope_cx: selected cur=%s (cx=%s)",
659                            cur.to_str(), cx.to_str());
660                     f(inf);
661                     return;
662                 }
663             },
664             None => {
665                 cur = block_parent(cur);
666                 cur.scope
667             }
668         }
669     }
670 }
671
672 pub fn block_parent(cx: @mut Block) -> @mut Block {
673     match cx.parent {
674       Some(b) => b,
675       None    => cx.sess().bug(fmt!("block_parent called on root block %?",
676                                    cx))
677     }
678 }
679
680
681 // Let T be the content of a box @T.  tuplify_box_ty(t) returns the
682 // representation of @T as a tuple (i.e., the ty::t version of what T_box()
683 // returns).
684 pub fn tuplify_box_ty(tcx: ty::ctxt, t: ty::t) -> ty::t {
685     let ptr = ty::mk_ptr(
686         tcx,
687         ty::mt {ty: ty::mk_i8(), mutbl: ast::m_imm}
688     );
689     return ty::mk_tup(tcx, ~[ty::mk_uint(), ty::mk_type(tcx),
690                          ptr, ptr,
691                          t]);
692 }
693
694 // LLVM constant constructors.
695 pub fn C_null(t: Type) -> ValueRef {
696     unsafe {
697         llvm::LLVMConstNull(t.to_ref())
698     }
699 }
700
701 pub fn C_undef(t: Type) -> ValueRef {
702     unsafe {
703         llvm::LLVMGetUndef(t.to_ref())
704     }
705 }
706
707 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
708     unsafe {
709         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
710     }
711 }
712
713 pub fn C_floating(s: &str, t: Type) -> ValueRef {
714     unsafe {
715         do s.to_c_str().with_ref |buf| {
716             llvm::LLVMConstRealOfString(t.to_ref(), buf)
717         }
718     }
719 }
720
721 pub fn C_nil() -> ValueRef {
722     return C_struct([]);
723 }
724
725 pub fn C_bool(val: bool) -> ValueRef {
726     C_integral(Type::bool(), val as u64, false)
727 }
728
729 pub fn C_i1(val: bool) -> ValueRef {
730     C_integral(Type::i1(), val as u64, false)
731 }
732
733 pub fn C_i32(i: i32) -> ValueRef {
734     return C_integral(Type::i32(), i as u64, true);
735 }
736
737 pub fn C_i64(i: i64) -> ValueRef {
738     return C_integral(Type::i64(), i as u64, true);
739 }
740
741 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
742     return C_integral(cx.int_type, i as u64, true);
743 }
744
745 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
746     return C_integral(cx.int_type, i as u64, false);
747 }
748
749 pub fn C_u8(i: uint) -> ValueRef {
750     return C_integral(Type::i8(), i as u64, false);
751 }
752
753
754 // This is a 'c-like' raw string, which differs from
755 // our boxed-and-length-annotated strings.
756 pub fn C_cstr(cx: &mut CrateContext, s: @str) -> ValueRef {
757     unsafe {
758         match cx.const_cstr_cache.find_equiv(&s) {
759             Some(&llval) => return llval,
760             None => ()
761         }
762
763         let sc = do s.to_c_str().with_ref |buf| {
764             llvm::LLVMConstStringInContext(cx.llcx, buf, s.len() as c_uint, False)
765         };
766
767         let gsym = token::gensym("str");
768         let g = do fmt!("str%u", gsym).to_c_str().with_ref |buf| {
769             llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
770         };
771         llvm::LLVMSetInitializer(g, sc);
772         llvm::LLVMSetGlobalConstant(g, True);
773         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
774
775         cx.const_cstr_cache.insert(s, g);
776
777         return g;
778     }
779 }
780
781 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
782 // you will be kicked off fast isel. See issue #4352 for an example of this.
783 pub fn C_estr_slice(cx: &mut CrateContext, s: @str) -> ValueRef {
784     unsafe {
785         let len = s.len();
786         let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
787         C_struct([cs, C_uint(cx, len)])
788     }
789 }
790
791 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
792     unsafe {
793         let mut i = 0u;
794         let mut elts: ~[ValueRef] = ~[];
795         while i < size { elts.push(C_u8(0u)); i += 1u; }
796         return llvm::LLVMConstArray(Type::i8().to_ref(),
797                                     vec::raw::to_ptr(elts), elts.len() as c_uint);
798     }
799 }
800
801 pub fn C_struct(elts: &[ValueRef]) -> ValueRef {
802     unsafe {
803         do elts.as_imm_buf |ptr, len| {
804             llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, False)
805         }
806     }
807 }
808
809 pub fn C_packed_struct(elts: &[ValueRef]) -> ValueRef {
810     unsafe {
811         do elts.as_imm_buf |ptr, len| {
812             llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, True)
813         }
814     }
815 }
816
817 pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef {
818     unsafe {
819         do elts.as_imm_buf |ptr, len| {
820             llvm::LLVMConstNamedStruct(T.to_ref(), ptr, len as c_uint)
821         }
822     }
823 }
824
825 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
826     unsafe {
827         return llvm::LLVMConstArray(ty.to_ref(), vec::raw::to_ptr(elts), elts.len() as c_uint);
828     }
829 }
830
831 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
832     unsafe {
833         let ptr = cast::transmute(vec::raw::to_ptr(bytes));
834         return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
835     }
836 }
837
838 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
839     unsafe {
840         llvm::LLVMGetParam(fndecl, param as c_uint)
841     }
842 }
843
844 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
845                   -> ValueRef {
846     unsafe {
847         let r = do us.as_imm_buf |p, len| {
848             llvm::LLVMConstExtractValue(v, p, len as c_uint)
849         };
850
851         debug!("const_get_elt(v=%s, us=%?, r=%s)",
852                cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
853
854         return r;
855     }
856 }
857
858 pub fn is_const(v: ValueRef) -> bool {
859     unsafe {
860         llvm::LLVMIsConstant(v) == True
861     }
862 }
863
864 pub fn const_to_int(v: ValueRef) -> c_longlong {
865     unsafe {
866         llvm::LLVMConstIntGetSExtValue(v)
867     }
868 }
869
870 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
871     unsafe {
872         llvm::LLVMConstIntGetZExtValue(v)
873     }
874 }
875
876 pub fn is_undef(val: ValueRef) -> bool {
877     unsafe {
878         llvm::LLVMIsUndef(val) != False
879     }
880 }
881
882 pub fn is_null(val: ValueRef) -> bool {
883     unsafe {
884         llvm::LLVMIsNull(val) != False
885     }
886 }
887
888 // Used to identify cached monomorphized functions and vtables
889 #[deriving(Eq,IterBytes)]
890 pub enum mono_param_id {
891     mono_precise(ty::t, Option<@~[mono_id]>),
892     mono_any,
893     mono_repr(uint /* size */,
894               uint /* align */,
895               MonoDataClass,
896               datum::DatumMode),
897 }
898
899 #[deriving(Eq,IterBytes)]
900 pub enum MonoDataClass {
901     MonoBits,    // Anything not treated differently from arbitrary integer data
902     MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
903     // FIXME(#3547)---scalars and floats are
904     // treated differently in most ABIs.  But we
905     // should be doing something more detailed
906     // here.
907     MonoFloat
908 }
909
910 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
911     match ty::get(t).sty {
912         ty::ty_float(_) => MonoFloat,
913         ty::ty_rptr(*) | ty::ty_uniq(*) |
914         ty::ty_box(*) | ty::ty_opaque_box(*) |
915         ty::ty_estr(ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_uniq) |
916         ty::ty_estr(ty::vstore_box) | ty::ty_evec(_, ty::vstore_box) |
917         ty::ty_bare_fn(*) => MonoNonNull,
918         // Is that everything?  Would closures or slices qualify?
919         _ => MonoBits
920     }
921 }
922
923
924 #[deriving(Eq,IterBytes)]
925 pub struct mono_id_ {
926     def: ast::def_id,
927     params: ~[mono_param_id]
928 }
929
930 pub type mono_id = @mono_id_;
931
932 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
933     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
934     return build::Select(cx, cond, b, a);
935 }
936
937 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
938     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
939     return build::Select(cx, cond, a, b);
940 }
941
942 pub fn align_to(cx: @mut Block, off: ValueRef, align: ValueRef) -> ValueRef {
943     let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
944     let bumped = build::Add(cx, off, mask);
945     return build::And(cx, bumped, build::Not(cx, mask));
946 }
947
948 pub fn path_str(sess: session::Session, p: &[path_elt]) -> ~str {
949     let mut r = ~"";
950     let mut first = true;
951     for e in p.iter() {
952         match *e {
953             ast_map::path_name(s) | ast_map::path_mod(s) => {
954                 if first {
955                     first = false
956                 } else {
957                     r.push_str("::")
958                 }
959                 r.push_str(sess.str_of(s));
960             }
961         }
962     }
963     r
964 }
965
966 pub fn monomorphize_type(bcx: @mut Block, t: ty::t) -> ty::t {
967     match bcx.fcx.param_substs {
968         Some(substs) => {
969             ty::subst_tps(bcx.tcx(), substs.tys, substs.self_ty, t)
970         }
971         _ => {
972             assert!(!ty::type_has_params(t));
973             assert!(!ty::type_has_self(t));
974             t
975         }
976     }
977 }
978
979 pub fn node_id_type(bcx: @mut Block, id: ast::NodeId) -> ty::t {
980     let tcx = bcx.tcx();
981     let t = ty::node_id_to_type(tcx, id);
982     monomorphize_type(bcx, t)
983 }
984
985 pub fn expr_ty(bcx: @mut Block, ex: &ast::expr) -> ty::t {
986     node_id_type(bcx, ex.id)
987 }
988
989 pub fn expr_ty_adjusted(bcx: @mut Block, ex: &ast::expr) -> ty::t {
990     let tcx = bcx.tcx();
991     let t = ty::expr_ty_adjusted(tcx, ex);
992     monomorphize_type(bcx, t)
993 }
994
995 pub fn node_id_type_params(bcx: @mut Block, id: ast::NodeId) -> ~[ty::t] {
996     let tcx = bcx.tcx();
997     let params = ty::node_id_to_type_params(tcx, id);
998
999     if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
1000         bcx.sess().bug(
1001             fmt!("Type parameters for node %d include inference types: %s",
1002                  id, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
1003     }
1004
1005     match bcx.fcx.param_substs {
1006       Some(substs) => {
1007         do params.iter().map |t| {
1008             ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1009         }.collect()
1010       }
1011       _ => params
1012     }
1013 }
1014
1015 pub fn node_vtables(bcx: @mut Block, id: ast::NodeId)
1016                  -> Option<typeck::vtable_res> {
1017     let raw_vtables = bcx.ccx().maps.vtable_map.find(&id);
1018     raw_vtables.map_move(|vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
1019 }
1020
1021 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
1022     -> typeck::vtable_res {
1023     resolve_vtables_under_param_substs(fcx.ccx.tcx,
1024                                        fcx.param_substs,
1025                                        vts)
1026 }
1027
1028 pub fn resolve_vtables_under_param_substs(tcx: ty::ctxt,
1029                                           param_substs: Option<@param_substs>,
1030                                           vts: typeck::vtable_res)
1031     -> typeck::vtable_res {
1032     @vts.iter().map(|ds|
1033       resolve_param_vtables_under_param_substs(tcx,
1034                                                param_substs,
1035                                                *ds))
1036         .collect()
1037 }
1038
1039 pub fn resolve_param_vtables_under_param_substs(
1040     tcx: ty::ctxt,
1041     param_substs: Option<@param_substs>,
1042     ds: typeck::vtable_param_res)
1043     -> typeck::vtable_param_res {
1044     @ds.iter().map(
1045         |d| resolve_vtable_under_param_substs(tcx,
1046                                               param_substs,
1047                                               d))
1048         .collect()
1049 }
1050
1051
1052
1053 // Apply the typaram substitutions in the FunctionContext to a vtable. This should
1054 // eliminate any vtable_params.
1055 pub fn resolve_vtable_in_fn_ctxt(fcx: &FunctionContext, vt: &typeck::vtable_origin)
1056     -> typeck::vtable_origin {
1057     resolve_vtable_under_param_substs(fcx.ccx.tcx,
1058                                       fcx.param_substs,
1059                                       vt)
1060 }
1061
1062 pub fn resolve_vtable_under_param_substs(tcx: ty::ctxt,
1063                                          param_substs: Option<@param_substs>,
1064                                          vt: &typeck::vtable_origin)
1065                                          -> typeck::vtable_origin {
1066     match *vt {
1067         typeck::vtable_static(trait_id, ref tys, sub) => {
1068             let tys = match param_substs {
1069                 Some(substs) => {
1070                     do tys.iter().map |t| {
1071                         ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1072                     }.collect()
1073                 }
1074                 _ => tys.to_owned()
1075             };
1076             typeck::vtable_static(
1077                 trait_id, tys,
1078                 resolve_vtables_under_param_substs(tcx, param_substs, sub))
1079         }
1080         typeck::vtable_param(n_param, n_bound) => {
1081             match param_substs {
1082                 Some(substs) => {
1083                     find_vtable(tcx, substs, n_param, n_bound)
1084                 }
1085                 _ => {
1086                     tcx.sess.bug(fmt!(
1087                         "resolve_vtable_in_fn_ctxt: asked to lookup but \
1088                          no vtables in the fn_ctxt!"))
1089                 }
1090             }
1091         }
1092     }
1093 }
1094
1095 pub fn find_vtable(tcx: ty::ctxt,
1096                    ps: &param_substs,
1097                    n_param: typeck::param_index,
1098                    n_bound: uint)
1099                    -> typeck::vtable_origin {
1100     debug!("find_vtable(n_param=%?, n_bound=%u, ps=%s)",
1101            n_param, n_bound, ps.repr(tcx));
1102
1103     let param_bounds = match n_param {
1104         typeck::param_self => ps.self_vtables.expect("self vtables missing"),
1105         typeck::param_numbered(n) => {
1106             let tables = ps.vtables
1107                 .expect("vtables missing where they are needed");
1108             tables[n]
1109         }
1110     };
1111     param_bounds[n_bound].clone()
1112 }
1113
1114 pub fn dummy_substs(tps: ~[ty::t]) -> ty::substs {
1115     substs {
1116         regions: ty::ErasedRegions,
1117         self_ty: None,
1118         tps: tps
1119     }
1120 }
1121
1122 pub fn filename_and_line_num_from_span(bcx: @mut Block,
1123                                        span: span) -> (ValueRef, ValueRef) {
1124     let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
1125     let filename_cstr = C_cstr(bcx.ccx(), loc.file.name);
1126     let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
1127     let line = C_int(bcx.ccx(), loc.line as int);
1128     (filename, line)
1129 }
1130
1131 // Casts a Rust bool value to an i1.
1132 pub fn bool_to_i1(bcx: @mut Block, llval: ValueRef) -> ValueRef {
1133     build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))
1134 }
1135
1136 pub fn langcall(bcx: @mut Block, span: Option<span>, msg: &str,
1137                 li: LangItem) -> ast::def_id {
1138     match bcx.tcx().lang_items.require(li) {
1139         Ok(id) => id,
1140         Err(s) => {
1141             let msg = fmt!("%s %s", msg, s);
1142             match span {
1143                 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
1144                 None => { bcx.tcx().sess.fatal(msg); }
1145             }
1146         }
1147     }
1148 }