]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
f838bcf9c5ec25406784650ca8e50e3c76ef9581
[rust.git] / src / librustc / middle / trans / base.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 // trans.rs: Translate the completed AST to the LLVM IR.
12 //
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
17 //
18 // Hopefully useful general knowledge about trans:
19 //
20 //   * There's no way to find out the ty::t type of a ValueRef.  Doing so
21 //     would be "trying to get the eggs out of an omelette" (credit:
22 //     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
23 //     but one TypeRef corresponds to many `ty::t`s; for instance, tup(int, int,
24 //     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26 #[allow(non_camel_case_types)];
27
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
30 use driver::session;
31 use driver::session::Session;
32 use driver::driver::OutputFilenames;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
35 use lib::llvm::{llvm, True, Vector};
36 use lib;
37 use metadata::common::LinkMeta;
38 use metadata::{csearch, encoder};
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
42 use middle::trans::_match;
43 use middle::trans::adt;
44 use middle::trans::build::*;
45 use middle::trans::builder::{Builder, noname};
46 use middle::trans::callee;
47 use middle::trans::cleanup;
48 use middle::trans::cleanup::CleanupMethods;
49 use middle::trans::common::*;
50 use middle::trans::consts;
51 use middle::trans::controlflow;
52 use middle::trans::datum;
53 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
54 use middle::trans::debuginfo;
55 use middle::trans::expr;
56 use middle::trans::foreign;
57 use middle::trans::glue;
58 use middle::trans::inline;
59 use middle::trans::machine;
60 use middle::trans::machine::{llalign_of_min, llsize_of};
61 use middle::trans::meth;
62 use middle::trans::monomorphize;
63 use middle::trans::tvec;
64 use middle::trans::type_::Type;
65 use middle::trans::type_of;
66 use middle::trans::type_of::*;
67 use middle::trans::value::Value;
68 use middle::ty;
69 use middle::typeck;
70 use util::common::indenter;
71 use util::ppaux::{Repr, ty_to_str};
72 use util::sha2::Sha256;
73
74 use arena::TypedArena;
75 use std::c_str::ToCStr;
76 use std::cell::{Cell, RefCell};
77 use collections::HashMap;
78 use std::libc::c_uint;
79 use std::local_data;
80 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic, OsWin32};
81 use syntax::ast_map::PathName;
82 use syntax::ast_util::{local_def, is_local};
83 use syntax::attr::AttrMetaMethods;
84 use syntax::attr;
85 use syntax::codemap::Span;
86 use syntax::parse::token::InternedString;
87 use syntax::parse::token;
88 use syntax::visit::Visitor;
89 use syntax::visit;
90 use syntax::{ast, ast_util, ast_map};
91
92 use time;
93
94 pub use middle::trans::context::task_llcx;
95
96 local_data_key!(task_local_insn_key: ~[&'static str])
97
98 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
99     local_data::get(task_local_insn_key, |c| {
100         match c {
101             Some(ctx) => blk(*ctx),
102             None => ()
103         }
104     })
105 }
106
107 pub fn init_insn_ctxt() {
108     local_data::set(task_local_insn_key, ~[]);
109 }
110
111 pub struct _InsnCtxt { _x: () }
112
113 #[unsafe_destructor]
114 impl Drop for _InsnCtxt {
115     fn drop(&mut self) {
116         local_data::modify(task_local_insn_key, |c| {
117             c.map(|mut ctx| {
118                 ctx.pop();
119                 ctx
120             })
121         })
122     }
123 }
124
125 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
126     debug!("new InsnCtxt: {}", s);
127     local_data::modify(task_local_insn_key, |c| {
128         c.map(|mut ctx| {
129             ctx.push(s);
130             ctx
131         })
132     });
133     _InsnCtxt { _x: () }
134 }
135
136 pub struct StatRecorder {
137     ccx: @CrateContext,
138     name: Option<~str>,
139     start: u64,
140     istart: uint,
141 }
142
143 impl StatRecorder {
144     pub fn new(ccx: @CrateContext, name: ~str) -> StatRecorder {
145         let start = if ccx.sess.trans_stats() {
146             time::precise_time_ns()
147         } else {
148             0
149         };
150         let istart = ccx.stats.n_llvm_insns.get();
151         StatRecorder {
152             ccx: ccx,
153             name: Some(name),
154             start: start,
155             istart: istart,
156         }
157     }
158 }
159
160 #[unsafe_destructor]
161 impl Drop for StatRecorder {
162     fn drop(&mut self) {
163         if self.ccx.sess.trans_stats() {
164             let end = time::precise_time_ns();
165             let elapsed = ((end - self.start) / 1_000_000) as uint;
166             let iend = self.ccx.stats.n_llvm_insns.get();
167             {
168                 let mut fn_stats = self.ccx.stats.fn_stats.borrow_mut();
169                 fn_stats.get().push((self.name.take_unwrap(),
170                                      elapsed,
171                                      iend - self.istart));
172             }
173             self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
174             // Reset LLVM insn count to avoid compound costs.
175             self.ccx.stats.n_llvm_insns.set(self.istart);
176         }
177     }
178 }
179
180 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
181 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
182            ty: Type, output: ty::t) -> ValueRef {
183     let llfn: ValueRef = name.with_c_str(|buf| {
184         unsafe {
185             llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
186         }
187     });
188
189     match ty::get(output).sty {
190         // functions returning bottom may unwind, but can never return normally
191         ty::ty_bot => {
192             unsafe {
193                 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
194             }
195         }
196         // `~` pointer return values never alias because ownership is transferred
197         // FIXME #6750 ~Trait cannot be directly marked as
198         // noalias because the actual object pointer is nested.
199         ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
200         ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) => {
201             unsafe {
202                 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
203             }
204         }
205         _ => {}
206     }
207
208     lib::llvm::SetFunctionCallConv(llfn, cc);
209     // Function addresses in Rust are never significant, allowing functions to be merged.
210     lib::llvm::SetUnnamedAddr(llfn, true);
211
212     llfn
213 }
214
215 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
216 pub fn decl_cdecl_fn(llmod: ModuleRef,
217                      name: &str,
218                      ty: Type,
219                      output: ty::t) -> ValueRef {
220     decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
221 }
222
223 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
224 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
225                      name: &str, cc: lib::llvm::CallConv,
226                      ty: Type, output: ty::t) -> ValueRef {
227     match externs.find_equiv(&name) {
228         Some(n) => return *n,
229         None => {}
230     }
231     let f = decl_fn(llmod, name, cc, ty, output);
232     externs.insert(name.to_owned(), f);
233     f
234 }
235
236 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
237                       name: &str, did: ast::DefId) -> ValueRef {
238     {
239         let externs = ccx.externs.borrow();
240         match externs.get().find_equiv(&name) {
241             Some(n) => return *n,
242             None => ()
243         }
244     }
245
246     let f = decl_rust_fn(ccx, false, inputs, output, name);
247     csearch::get_item_attrs(ccx.tcx.cstore, did, |meta_items| {
248         set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).to_owned_vec(), f)
249     });
250
251     let mut externs = ccx.externs.borrow_mut();
252     externs.get().insert(name.to_owned(), f);
253     f
254 }
255
256 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
257                     inputs: &[ty::t], output: ty::t,
258                     name: &str) -> ValueRef {
259     let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
260     let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
261
262     let uses_outptr = type_of::return_uses_outptr(ccx, output);
263     let offset = if uses_outptr { 1 } else { 0 };
264     let offset = if has_env { offset + 1 } else { offset };
265
266     for (i, &arg_ty) in inputs.iter().enumerate() {
267         let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
268         match ty::get(arg_ty).sty {
269             // `~` pointer parameters never alias because ownership is transferred
270             // FIXME #6750 ~Trait cannot be directly marked as
271             // noalias because the actual object pointer is nested.
272             ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
273             ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) |
274             ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, ..}) => {
275                 unsafe {
276                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
277                 }
278             }
279             _ => {
280                 // For non-immediate arguments the callee gets its own copy of
281                 // the value on the stack, so there are no aliases
282                 if !type_is_immediate(ccx, arg_ty) {
283                     unsafe {
284                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
285                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
286                     }
287                 }
288             }
289         }
290     }
291
292     // The out pointer will never alias with any other pointers, as the object only exists at a
293     // language level after the call. It can also be tagged with SRet to indicate that it is
294     // guaranteed to point to a usable block of memory for the type.
295     if uses_outptr {
296         unsafe {
297             let outptr = llvm::LLVMGetParam(llfn, 0);
298             llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
299             llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
300         }
301     }
302
303     llfn
304 }
305
306 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
307                              inputs: &[ty::t], output: ty::t,
308                              name: &str) -> ValueRef {
309     let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
310     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
311     llfn
312 }
313
314 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
315                         name: &str, ty: Type) -> ValueRef {
316     match externs.find_equiv(&name) {
317         Some(n) => return *n,
318         None => ()
319     }
320     unsafe {
321         let c = name.with_c_str(|buf| {
322             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
323         });
324         externs.insert(name.to_owned(), c);
325         return c;
326     }
327 }
328
329 // Returns a pointer to the body for the box. The box may be an opaque
330 // box. The result will be casted to the type of body_t, if it is statically
331 // known.
332 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
333     let _icx = push_ctxt("at_box_body");
334     let ccx = bcx.ccx();
335     let ty = Type::at_box(ccx, type_of(ccx, body_t));
336     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
337     GEPi(bcx, boxptr, [0u, abi::box_field_body])
338 }
339
340 // malloc_raw_dyn: allocates a box to contain a given type, but with a
341 // potentially dynamic size.
342 pub fn malloc_raw_dyn<'a>(
343                       bcx: &'a Block<'a>,
344                       t: ty::t,
345                       heap: heap,
346                       size: ValueRef)
347                       -> Result<'a> {
348     let _icx = push_ctxt("malloc_raw");
349     let ccx = bcx.ccx();
350
351     fn require_alloc_fn(bcx: &Block, t: ty::t, it: LangItem) -> ast::DefId {
352         let li = &bcx.tcx().lang_items;
353         match li.require(it) {
354             Ok(id) => id,
355             Err(s) => {
356                 bcx.tcx().sess.fatal(format!("allocation of `{}` {}",
357                                           bcx.ty_to_str(t), s));
358             }
359         }
360     }
361
362     if heap == heap_exchange {
363         let llty_value = type_of::type_of(ccx, t);
364
365         // Allocate space:
366         let r = callee::trans_lang_call(
367             bcx,
368             require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
369             [size],
370             None);
371         rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
372     } else {
373         // we treat ~fn as @ here, which isn't ideal
374         let langcall = match heap {
375             heap_managed => {
376                 require_alloc_fn(bcx, t, MallocFnLangItem)
377             }
378             heap_exchange_closure => {
379                 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem)
380             }
381             _ => fail!("heap_exchange already handled")
382         };
383
384         // Grab the TypeRef type of box_ptr_ty.
385         let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
386         let llty = type_of(ccx, box_ptr_ty);
387         let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
388
389         // Allocate space:
390         let drop_glue = glue::get_drop_glue(ccx, t);
391         let r = callee::trans_lang_call(
392             bcx,
393             langcall,
394             [PointerCast(bcx, drop_glue, Type::glue_fn(Type::i8p()).ptr_to()), size, llalign],
395             None);
396         rslt(r.bcx, PointerCast(r.bcx, r.val, llty))
397     }
398 }
399
400 // malloc_raw: expects an unboxed type and returns a pointer to
401 // enough space for a box of that type.  This includes a rust_opaque_box
402 // header.
403 pub fn malloc_raw<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
404                   -> Result<'a> {
405     let ty = type_of(bcx.ccx(), t);
406     let size = llsize_of(bcx.ccx(), ty);
407     malloc_raw_dyn(bcx, t, heap, size)
408 }
409
410 pub struct MallocResult<'a> {
411     bcx: &'a Block<'a>,
412     smart_ptr: ValueRef,
413     body: ValueRef
414 }
415
416 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a smart
417 // pointer, and pulls out the body
418 pub fn malloc_general_dyn<'a>(
419                           bcx: &'a Block<'a>,
420                           t: ty::t,
421                           heap: heap,
422                           size: ValueRef)
423                           -> MallocResult<'a> {
424     assert!(heap != heap_exchange);
425     let _icx = push_ctxt("malloc_general");
426     let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
427     let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
428
429     MallocResult {
430         bcx: bcx,
431         smart_ptr: llbox,
432         body: body,
433     }
434 }
435
436 pub fn malloc_general<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
437                       -> MallocResult<'a> {
438     let ty = type_of(bcx.ccx(), t);
439     assert!(heap != heap_exchange);
440     malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
441 }
442
443 // Type descriptor and type glue stuff
444
445 pub fn get_tydesc_simple(ccx: &CrateContext, t: ty::t) -> ValueRef {
446     get_tydesc(ccx, t).tydesc
447 }
448
449 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
450     {
451         let tydescs = ccx.tydescs.borrow();
452         match tydescs.get().find(&t) {
453             Some(&inf) => return inf,
454             _ => { }
455         }
456     }
457
458     ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
459     let inf = glue::declare_tydesc(ccx, t);
460
461     let mut tydescs = ccx.tydescs.borrow_mut();
462     tydescs.get().insert(t, inf);
463     return inf;
464 }
465
466 pub fn set_optimize_for_size(f: ValueRef) {
467     lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
468 }
469
470 pub fn set_no_inline(f: ValueRef) {
471     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
472 }
473
474 pub fn set_no_unwind(f: ValueRef) {
475     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
476 }
477
478 // Tell LLVM to emit the information necessary to unwind the stack for the
479 // function f.
480 pub fn set_uwtable(f: ValueRef) {
481     lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
482 }
483
484 pub fn set_inline_hint(f: ValueRef) {
485     lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
486 }
487
488 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
489     use syntax::attr::*;
490     // Set the inline hint if there is one
491     match find_inline_attr(attrs) {
492         InlineHint   => set_inline_hint(llfn),
493         InlineAlways => set_always_inline(llfn),
494         InlineNever  => set_no_inline(llfn),
495         InlineNone   => { /* fallthrough */ }
496     }
497
498     // Add the no-split-stack attribute if requested
499     if contains_name(attrs, "no_split_stack") {
500         set_no_split_stack(llfn);
501     }
502
503     if contains_name(attrs, "cold") {
504         unsafe { llvm::LLVMAddColdAttribute(llfn) }
505     }
506 }
507
508 pub fn set_always_inline(f: ValueRef) {
509     lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
510 }
511
512 pub fn set_no_split_stack(f: ValueRef) {
513     "no-split-stack".with_c_str(|buf| {
514         unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
515     })
516 }
517
518 // Double-check that we never ask LLVM to declare the same symbol twice. It
519 // silently mangles such symbols, breaking our linkage model.
520 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
521     let mut all_llvm_symbols = ccx.all_llvm_symbols.borrow_mut();
522     if all_llvm_symbols.get().contains(&sym) {
523         ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
524     }
525     all_llvm_symbols.get().insert(sym);
526 }
527
528
529 pub fn get_res_dtor(ccx: @CrateContext,
530                     did: ast::DefId,
531                     parent_id: ast::DefId,
532                     substs: &[ty::t])
533                  -> ValueRef {
534     let _icx = push_ctxt("trans_res_dtor");
535     let did = if did.krate != ast::LOCAL_CRATE {
536         inline::maybe_instantiate_inline(ccx, did)
537     } else {
538         did
539     };
540     if !substs.is_empty() {
541         assert_eq!(did.krate, ast::LOCAL_CRATE);
542         let tsubsts = ty::substs {
543             regions: ty::ErasedRegions,
544             self_ty: None,
545             tps: substs.to_owned()
546         };
547
548         let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx, did.node, &tsubsts);
549         let (val, _) = monomorphize::monomorphic_fn(ccx, did, &tsubsts, vtables, None, None);
550
551         val
552     } else if did.krate == ast::LOCAL_CRATE {
553         get_item_val(ccx, did.node)
554     } else {
555         let tcx = ccx.tcx;
556         let name = csearch::get_symbol(ccx.sess.cstore, did);
557         let class_ty = ty::subst_tps(tcx,
558                                      substs,
559                                      None,
560                                      ty::lookup_item_type(tcx, parent_id).ty);
561         let llty = type_of_dtor(ccx, class_ty);
562
563         {
564             let mut externs = ccx.externs.borrow_mut();
565             get_extern_fn(externs.get(), ccx.llmod, name,
566                           lib::llvm::CCallConv, llty, ty::mk_nil())
567         }
568     }
569 }
570
571 // Structural comparison: a rather involved form of glue.
572 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
573     if cx.sess.opts.cg.save_temps {
574         s.with_c_str(|buf| {
575             unsafe {
576                 llvm::LLVMSetValueName(v, buf)
577             }
578         })
579     }
580 }
581
582
583 // Used only for creating scalar comparison glue.
584 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
585
586 // NB: This produces an i1, not a Rust bool (i8).
587 pub fn compare_scalar_types<'a>(
588                             cx: &'a Block<'a>,
589                             lhs: ValueRef,
590                             rhs: ValueRef,
591                             t: ty::t,
592                             op: ast::BinOp)
593                             -> Result<'a> {
594     let f = |a| rslt(cx, compare_scalar_values(cx, lhs, rhs, a, op));
595
596     match ty::get(t).sty {
597         ty::ty_nil => f(nil_type),
598         ty::ty_bool | ty::ty_ptr(_) |
599         ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
600         ty::ty_int(_) => f(signed_int),
601         ty::ty_float(_) => f(floating_point),
602             // Should never get here, because t is scalar.
603         _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
604     }
605 }
606
607
608 // A helper function to do the actual comparison of scalar values.
609 pub fn compare_scalar_values<'a>(
610                              cx: &'a Block<'a>,
611                              lhs: ValueRef,
612                              rhs: ValueRef,
613                              nt: scalar_type,
614                              op: ast::BinOp)
615                              -> ValueRef {
616     let _icx = push_ctxt("compare_scalar_values");
617     fn die(cx: &Block) -> ! {
618         cx.tcx().sess.bug("compare_scalar_values: must be a\
619                            comparison operator");
620     }
621     match nt {
622       nil_type => {
623         // We don't need to do actual comparisons for nil.
624         // () == () holds but () < () does not.
625         match op {
626           ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(true),
627           ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(false),
628           // refinements would be nice
629           _ => die(cx)
630         }
631       }
632       floating_point => {
633         let cmp = match op {
634           ast::BiEq => lib::llvm::RealOEQ,
635           ast::BiNe => lib::llvm::RealUNE,
636           ast::BiLt => lib::llvm::RealOLT,
637           ast::BiLe => lib::llvm::RealOLE,
638           ast::BiGt => lib::llvm::RealOGT,
639           ast::BiGe => lib::llvm::RealOGE,
640           _ => die(cx)
641         };
642         return FCmp(cx, cmp, lhs, rhs);
643       }
644       signed_int => {
645         let cmp = match op {
646           ast::BiEq => lib::llvm::IntEQ,
647           ast::BiNe => lib::llvm::IntNE,
648           ast::BiLt => lib::llvm::IntSLT,
649           ast::BiLe => lib::llvm::IntSLE,
650           ast::BiGt => lib::llvm::IntSGT,
651           ast::BiGe => lib::llvm::IntSGE,
652           _ => die(cx)
653         };
654         return ICmp(cx, cmp, lhs, rhs);
655       }
656       unsigned_int => {
657         let cmp = match op {
658           ast::BiEq => lib::llvm::IntEQ,
659           ast::BiNe => lib::llvm::IntNE,
660           ast::BiLt => lib::llvm::IntULT,
661           ast::BiLe => lib::llvm::IntULE,
662           ast::BiGt => lib::llvm::IntUGT,
663           ast::BiGe => lib::llvm::IntUGE,
664           _ => die(cx)
665         };
666         return ICmp(cx, cmp, lhs, rhs);
667       }
668     }
669 }
670
671 pub type val_and_ty_fn<'r,'b> =
672     'r |&'b Block<'b>, ValueRef, ty::t| -> &'b Block<'b>;
673
674 pub fn load_inbounds<'a>(cx: &'a Block<'a>, p: ValueRef, idxs: &[uint])
675                      -> ValueRef {
676     return Load(cx, GEPi(cx, p, idxs));
677 }
678
679 pub fn store_inbounds<'a>(
680                       cx: &'a Block<'a>,
681                       v: ValueRef,
682                       p: ValueRef,
683                       idxs: &[uint]) {
684     Store(cx, v, GEPi(cx, p, idxs));
685 }
686
687 // Iterates through the elements of a structural type.
688 pub fn iter_structural_ty<'r,
689                           'b>(
690                           cx: &'b Block<'b>,
691                           av: ValueRef,
692                           t: ty::t,
693                           f: val_and_ty_fn<'r,'b>)
694                           -> &'b Block<'b> {
695     let _icx = push_ctxt("iter_structural_ty");
696
697     fn iter_variant<'r,
698                     'b>(
699                     cx: &'b Block<'b>,
700                     repr: &adt::Repr,
701                     av: ValueRef,
702                     variant: @ty::VariantInfo,
703                     tps: &[ty::t],
704                     f: val_and_ty_fn<'r,'b>)
705                     -> &'b Block<'b> {
706         let _icx = push_ctxt("iter_variant");
707         let tcx = cx.tcx();
708         let mut cx = cx;
709
710         for (i, &arg) in variant.args.iter().enumerate() {
711             cx = f(cx,
712                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
713                    ty::subst_tps(tcx, tps, None, arg));
714         }
715         return cx;
716     }
717
718     let mut cx = cx;
719     match ty::get(t).sty {
720       ty::ty_struct(..) => {
721           let repr = adt::represent_type(cx.ccx(), t);
722           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
723               for (i, field_ty) in field_tys.iter().enumerate() {
724                   let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
725                   cx = f(cx, llfld_a, field_ty.mt.ty);
726               }
727           })
728       }
729       ty::ty_str(ty::vstore_fixed(_)) |
730       ty::ty_vec(_, ty::vstore_fixed(_)) => {
731         let (base, len) = tvec::get_base_and_byte_len(cx, av, t);
732         cx = tvec::iter_vec_raw(cx, base, t, len, f);
733       }
734       ty::ty_tup(ref args) => {
735           let repr = adt::represent_type(cx.ccx(), t);
736           for (i, arg) in args.iter().enumerate() {
737               let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
738               cx = f(cx, llfld_a, *arg);
739           }
740       }
741       ty::ty_enum(tid, ref substs) => {
742           let fcx = cx.fcx;
743           let ccx = fcx.ccx;
744
745           let repr = adt::represent_type(ccx, t);
746           let variants = ty::enum_variants(ccx.tcx, tid);
747           let n_variants = (*variants).len();
748
749           // NB: we must hit the discriminant first so that structural
750           // comparison know not to proceed when the discriminants differ.
751
752           match adt::trans_switch(cx, repr, av) {
753               (_match::single, None) => {
754                   cx = iter_variant(cx, repr, av, variants[0],
755                                     substs.tps, f);
756               }
757               (_match::switch, Some(lldiscrim_a)) => {
758                   cx = f(cx, lldiscrim_a, ty::mk_int());
759                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
760                   Unreachable(unr_cx);
761                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
762                                         n_variants);
763                   let next_cx = fcx.new_temp_block("enum-iter-next");
764
765                   for variant in (*variants).iter() {
766                       let variant_cx =
767                           fcx.new_temp_block(~"enum-iter-variant-" +
768                                              variant.disr_val.to_str());
769                       match adt::trans_case(cx, repr, variant.disr_val) {
770                           _match::single_result(r) => {
771                               AddCase(llswitch, r.val, variant_cx.llbb)
772                           }
773                           _ => ccx.sess.unimpl("value from adt::trans_case \
774                                                 in iter_structural_ty")
775                       }
776                       let variant_cx =
777                           iter_variant(variant_cx, repr, av, *variant,
778                                        substs.tps, |x,y,z| f(x,y,z));
779                       Br(variant_cx, next_cx.llbb);
780                   }
781                   cx = next_cx;
782               }
783               _ => ccx.sess.unimpl("value from adt::trans_switch \
784                                     in iter_structural_ty")
785           }
786       }
787       _ => cx.sess().unimpl("type in iter_structural_ty")
788     }
789     return cx;
790 }
791
792 pub fn cast_shift_expr_rhs<'a>(
793                            cx: &'a Block<'a>,
794                            op: ast::BinOp,
795                            lhs: ValueRef,
796                            rhs: ValueRef)
797                            -> ValueRef {
798     cast_shift_rhs(op, lhs, rhs,
799                    |a,b| Trunc(cx, a, b),
800                    |a,b| ZExt(cx, a, b))
801 }
802
803 pub fn cast_shift_const_rhs(op: ast::BinOp,
804                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
805     cast_shift_rhs(op, lhs, rhs,
806                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
807                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
808 }
809
810 pub fn cast_shift_rhs(op: ast::BinOp,
811                       lhs: ValueRef,
812                       rhs: ValueRef,
813                       trunc: |ValueRef, Type| -> ValueRef,
814                       zext: |ValueRef, Type| -> ValueRef)
815                       -> ValueRef {
816     // Shifts may have any size int on the rhs
817     unsafe {
818         if ast_util::is_shift_binop(op) {
819             let mut rhs_llty = val_ty(rhs);
820             let mut lhs_llty = val_ty(lhs);
821             if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
822             if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
823             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
824             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
825             if lhs_sz < rhs_sz {
826                 trunc(rhs, lhs_llty)
827             } else if lhs_sz > rhs_sz {
828                 // FIXME (#1877: If shifting by negative
829                 // values becomes not undefined then this is wrong.
830                 zext(rhs, lhs_llty)
831             } else {
832                 rhs
833             }
834         } else {
835             rhs
836         }
837     }
838 }
839
840 pub fn fail_if_zero<'a>(
841                     cx: &'a Block<'a>,
842                     span: Span,
843                     divrem: ast::BinOp,
844                     rhs: ValueRef,
845                     rhs_t: ty::t)
846                     -> &'a Block<'a> {
847     let text = if divrem == ast::BiDiv {
848         "attempted to divide by zero"
849     } else {
850         "attempted remainder with a divisor of zero"
851     };
852     let is_zero = match ty::get(rhs_t).sty {
853       ty::ty_int(t) => {
854         let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
855         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
856       }
857       ty::ty_uint(t) => {
858         let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
859         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
860       }
861       _ => {
862         cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
863                           ty_to_str(cx.ccx().tcx, rhs_t));
864       }
865     };
866     with_cond(cx, is_zero, |bcx| {
867         controlflow::trans_fail(bcx, span, InternedString::new(text))
868     })
869 }
870
871 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
872     let name = csearch::get_symbol(ccx.sess.cstore, did);
873     match ty::get(t).sty {
874         ty::ty_bare_fn(ref fn_ty) => {
875             match fn_ty.abis.for_target(ccx.sess.targ_cfg.os,
876                                         ccx.sess.targ_cfg.arch) {
877                 Some(Rust) | Some(RustIntrinsic) => {
878                     get_extern_rust_fn(ccx, fn_ty.sig.inputs, fn_ty.sig.output, name, did)
879                 }
880                 Some(..) | None => {
881                     let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
882                     let cconv = c.unwrap_or(lib::llvm::CCallConv);
883                     let llty = type_of_fn_from_ty(ccx, t);
884                     let mut externs = ccx.externs.borrow_mut();
885                     get_extern_fn(externs.get(), ccx.llmod, name,
886                                   cconv, llty, fn_ty.sig.output)
887                 }
888             }
889         }
890         ty::ty_closure(ref f) => {
891             get_extern_rust_fn(ccx, f.sig.inputs, f.sig.output, name, did)
892         }
893         _ => {
894             let llty = type_of(ccx, t);
895             let mut externs = ccx.externs.borrow_mut();
896             get_extern_const(externs.get(), ccx.llmod, name, llty)
897         }
898     }
899 }
900
901 pub fn invoke<'a>(
902               bcx: &'a Block<'a>,
903               llfn: ValueRef,
904               llargs: ~[ValueRef],
905               attributes: &[(uint, lib::llvm::Attribute)],
906               call_info: Option<NodeInfo>)
907               -> (ValueRef, &'a Block<'a>) {
908     let _icx = push_ctxt("invoke_");
909     if bcx.unreachable.get() {
910         return (C_null(Type::i8()), bcx);
911     }
912
913     match bcx.opt_node_id {
914         None => {
915             debug!("invoke at ???");
916         }
917         Some(id) => {
918             debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
919         }
920     }
921
922     if need_invoke(bcx) {
923         debug!("invoking {} at {}", llfn, bcx.llbb);
924         for &llarg in llargs.iter() {
925             debug!("arg: {}", llarg);
926         }
927         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
928         let landing_pad = bcx.fcx.get_landing_pad();
929
930         match call_info {
931             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
932             None => debuginfo::clear_source_location(bcx.fcx)
933         };
934
935         let llresult = Invoke(bcx,
936                               llfn,
937                               llargs,
938                               normal_bcx.llbb,
939                               landing_pad,
940                               attributes);
941         return (llresult, normal_bcx);
942     } else {
943         debug!("calling {} at {}", llfn, bcx.llbb);
944         for &llarg in llargs.iter() {
945             debug!("arg: {}", llarg);
946         }
947
948         match call_info {
949             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
950             None => debuginfo::clear_source_location(bcx.fcx)
951         };
952
953         let llresult = Call(bcx, llfn, llargs, attributes);
954         return (llresult, bcx);
955     }
956 }
957
958 pub fn need_invoke(bcx: &Block) -> bool {
959     if bcx.ccx().sess.no_landing_pads() {
960         return false;
961     }
962
963     // Avoid using invoke if we are already inside a landing pad.
964     if bcx.is_lpad {
965         return false;
966     }
967
968     bcx.fcx.needs_invoke()
969 }
970
971 pub fn do_spill(bcx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
972     if ty::type_is_bot(t) {
973         return C_null(Type::i8p());
974     }
975     let llptr = alloc_ty(bcx, t, "");
976     Store(bcx, v, llptr);
977     return llptr;
978 }
979
980 // Since this function does *not* root, it is the caller's responsibility to
981 // ensure that the referent is pointed to by a root.
982 pub fn do_spill_noroot(cx: &Block, v: ValueRef) -> ValueRef {
983     let llptr = alloca(cx, val_ty(v), "");
984     Store(cx, v, llptr);
985     return llptr;
986 }
987
988 pub fn spill_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
989     let _icx = push_ctxt("spill_if_immediate");
990     if type_is_immediate(cx.ccx(), t) { return do_spill(cx, v, t); }
991     return v;
992 }
993
994 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
995     let _icx = push_ctxt("load_if_immediate");
996     if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
997     return v;
998 }
999
1000 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1001     match local.pat.node {
1002         ast::PatWild => true, _ => false
1003     }
1004 }
1005
1006 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1007                   -> &'a Block<'a> {
1008
1009     debug!("init_local(bcx={}, local.id={:?})",
1010            bcx.to_str(), local.id);
1011     let _indenter = indenter();
1012
1013     let _icx = push_ctxt("init_local");
1014
1015     if ignore_lhs(bcx, local) {
1016         // Handle let _ = e; just like e;
1017         match local.init {
1018             Some(init) => {
1019               return expr::trans_into(bcx, init, expr::Ignore);
1020             }
1021             None => { return bcx; }
1022         }
1023     }
1024
1025     _match::store_local(bcx, local)
1026 }
1027
1028 pub fn raw_block<'a>(
1029                  fcx: &'a FunctionContext<'a>,
1030                  is_lpad: bool,
1031                  llbb: BasicBlockRef)
1032                  -> &'a Block<'a> {
1033     Block::new(llbb, is_lpad, None, fcx)
1034 }
1035
1036 pub fn block_locals(b: &ast::Block, it: |@ast::Local|) {
1037     for s in b.stmts.iter() {
1038         match s.node {
1039           ast::StmtDecl(d, _) => {
1040             match d.node {
1041               ast::DeclLocal(ref local) => it(*local),
1042               _ => {} /* fall through */
1043             }
1044           }
1045           _ => {} /* fall through */
1046         }
1047     }
1048 }
1049
1050 pub fn with_cond<'a>(
1051                  bcx: &'a Block<'a>,
1052                  val: ValueRef,
1053                  f: |&'a Block<'a>| -> &'a Block<'a>)
1054                  -> &'a Block<'a> {
1055     let _icx = push_ctxt("with_cond");
1056     let fcx = bcx.fcx;
1057     let next_cx = fcx.new_temp_block("next");
1058     let cond_cx = fcx.new_temp_block("cond");
1059     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1060     let after_cx = f(cond_cx);
1061     if !after_cx.terminated.get() {
1062         Br(after_cx, next_cx.llbb);
1063     }
1064     next_cx
1065 }
1066
1067 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1068     let _icx = push_ctxt("call_memcpy");
1069     let ccx = cx.ccx();
1070     let key = match ccx.sess.targ_cfg.arch {
1071         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1072         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1073     };
1074     let memcpy = ccx.intrinsics.get_copy(&key);
1075     let src_ptr = PointerCast(cx, src, Type::i8p());
1076     let dst_ptr = PointerCast(cx, dst, Type::i8p());
1077     let size = IntCast(cx, n_bytes, ccx.int_type);
1078     let align = C_i32(align as i32);
1079     let volatile = C_i1(false);
1080     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1081 }
1082
1083 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1084     let _icx = push_ctxt("memcpy_ty");
1085     let ccx = bcx.ccx();
1086     if ty::type_is_structural(t) {
1087         let llty = type_of::type_of(ccx, t);
1088         let llsz = llsize_of(ccx, llty);
1089         let llalign = llalign_of_min(ccx, llty);
1090         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1091     } else {
1092         Store(bcx, Load(bcx, src), dst);
1093     }
1094 }
1095
1096 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1097     if cx.unreachable.get() { return; }
1098     let _icx = push_ctxt("zero_mem");
1099     let bcx = cx;
1100     let ccx = cx.ccx();
1101     let llty = type_of::type_of(ccx, t);
1102     memzero(&B(bcx), llptr, llty);
1103 }
1104
1105 // Always use this function instead of storing a zero constant to the memory
1106 // in question. If you store a zero constant, LLVM will drown in vreg
1107 // allocation for large data structures, and the generated code will be
1108 // awful. (A telltale sign of this is large quantities of
1109 // `mov [byte ptr foo],0` in the generated code.)
1110 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1111     let _icx = push_ctxt("memzero");
1112     let ccx = b.ccx;
1113
1114     let intrinsic_key = match ccx.sess.targ_cfg.arch {
1115         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1116         X86_64 => "llvm.memset.p0i8.i64"
1117     };
1118
1119     let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1120     let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1121     let llzeroval = C_u8(0);
1122     let size = machine::llsize_of(ccx, ty);
1123     let align = C_i32(llalign_of_min(ccx, ty) as i32);
1124     let volatile = C_i1(false);
1125     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1126 }
1127
1128 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1129     let _icx = push_ctxt("alloc_ty");
1130     let ccx = bcx.ccx();
1131     let ty = type_of::type_of(ccx, t);
1132     assert!(!ty::type_has_params(t));
1133     let val = alloca(bcx, ty, name);
1134     return val;
1135 }
1136
1137 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1138     alloca_maybe_zeroed(cx, ty, name, false)
1139 }
1140
1141 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1142     let _icx = push_ctxt("alloca");
1143     if cx.unreachable.get() {
1144         unsafe {
1145             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1146         }
1147     }
1148     debuginfo::clear_source_location(cx.fcx);
1149     let p = Alloca(cx, ty, name);
1150     if zero {
1151         let b = cx.fcx.ccx.builder();
1152         b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1153         memzero(&b, p, ty);
1154     }
1155     p
1156 }
1157
1158 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1159     let _icx = push_ctxt("arrayalloca");
1160     if cx.unreachable.get() {
1161         unsafe {
1162             return llvm::LLVMGetUndef(ty.to_ref());
1163         }
1164     }
1165     debuginfo::clear_source_location(cx.fcx);
1166     return ArrayAlloca(cx, ty, v);
1167 }
1168
1169 pub struct BasicBlocks {
1170     sa: BasicBlockRef,
1171 }
1172
1173 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1174     unsafe {
1175         let cx = task_llcx();
1176         "static_allocas".with_c_str(|buf| {
1177             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1178         })
1179     }
1180 }
1181
1182 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1183     unsafe {
1184         let cx = task_llcx();
1185         "return".with_c_str(|buf| {
1186             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1187         })
1188     }
1189 }
1190
1191 // Creates and returns space for, or returns the argument representing, the
1192 // slot where the return value of the function must go.
1193 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1194                            -> ValueRef {
1195     unsafe {
1196         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1197             llvm::LLVMGetParam(fcx.llfn, 0)
1198         } else {
1199             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1200             let bcx = fcx.entry_bcx.get().unwrap();
1201             Alloca(bcx, lloutputtype, "__make_return_pointer")
1202         }
1203     }
1204 }
1205
1206 // NB: must keep 4 fns in sync:
1207 //
1208 //  - type_of_fn
1209 //  - create_datums_for_fn_args.
1210 //  - new_fn_ctxt
1211 //  - trans_args
1212 //
1213 // Be warned! You must call `init_function` before doing anything with the
1214 // returned function context.
1215 pub fn new_fn_ctxt<'a>(ccx: @CrateContext,
1216                        llfndecl: ValueRef,
1217                        id: ast::NodeId,
1218                        has_env: bool,
1219                        output_type: ty::t,
1220                        param_substs: Option<@param_substs>,
1221                        sp: Option<Span>,
1222                        block_arena: &'a TypedArena<Block<'a>>)
1223                        -> FunctionContext<'a> {
1224     for p in param_substs.iter() { p.validate(); }
1225
1226     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1227            if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
1228            id, param_substs.repr(ccx.tcx));
1229
1230     let substd_output_type = match param_substs {
1231         None => output_type,
1232         Some(substs) => {
1233             ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1234         }
1235     };
1236     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1237     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1238
1239     let mut fcx = FunctionContext {
1240           llfn: llfndecl,
1241           llenv: None,
1242           llretptr: Cell::new(None),
1243           entry_bcx: RefCell::new(None),
1244           alloca_insert_pt: Cell::new(None),
1245           llreturn: Cell::new(None),
1246           personality: Cell::new(None),
1247           caller_expects_out_pointer: uses_outptr,
1248           llargs: RefCell::new(HashMap::new()),
1249           lllocals: RefCell::new(HashMap::new()),
1250           llupvars: RefCell::new(HashMap::new()),
1251           id: id,
1252           param_substs: param_substs,
1253           span: sp,
1254           block_arena: block_arena,
1255           ccx: ccx,
1256           debug_context: debug_context,
1257           scopes: RefCell::new(~[])
1258     };
1259
1260     if has_env {
1261         fcx.llenv = Some(unsafe {
1262             llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1263         });
1264     }
1265
1266     fcx
1267 }
1268
1269 /// Performs setup on a newly created function, creating the entry scope block
1270 /// and allocating space for the return pointer.
1271 pub fn init_function<'a>(
1272                      fcx: &'a FunctionContext<'a>,
1273                      skip_retptr: bool,
1274                      output_type: ty::t,
1275                      param_substs: Option<@param_substs>) {
1276     let entry_bcx = fcx.new_temp_block("entry-block");
1277
1278     fcx.entry_bcx.set(Some(entry_bcx));
1279
1280     // Use a dummy instruction as the insertion point for all allocas.
1281     // This is later removed in FunctionContext::cleanup.
1282     fcx.alloca_insert_pt.set(Some(unsafe {
1283         Load(entry_bcx, C_null(Type::i8p()));
1284         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1285     }));
1286
1287     let substd_output_type = match param_substs {
1288         None => output_type,
1289         Some(substs) => {
1290             ty::subst_tps(fcx.ccx.tcx,
1291                           substs.tys,
1292                           substs.self_ty,
1293                           output_type)
1294         }
1295     };
1296
1297     if !return_type_is_void(fcx.ccx, substd_output_type) {
1298         // If the function returns nil/bot, there is no real return
1299         // value, so do not set `llretptr`.
1300         if !skip_retptr || fcx.caller_expects_out_pointer {
1301             // Otherwise, we normally allocate the llretptr, unless we
1302             // have been instructed to skip it for immediate return
1303             // values.
1304             fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1305         }
1306     }
1307 }
1308
1309 // NB: must keep 4 fns in sync:
1310 //
1311 //  - type_of_fn
1312 //  - create_datums_for_fn_args.
1313 //  - new_fn_ctxt
1314 //  - trans_args
1315
1316 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1317     use middle::trans::datum::{ByRef, ByValue};
1318
1319     datum::Rvalue {
1320         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1321     }
1322 }
1323
1324 // work around bizarre resolve errors
1325 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1326 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1327
1328 // create_datums_for_fn_args: creates rvalue datums for each of the
1329 // incoming function arguments. These will later be stored into
1330 // appropriate lvalue datums.
1331 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1332                                  arg_tys: &[ty::t])
1333                                  -> ~[RvalueDatum] {
1334     let _icx = push_ctxt("create_datums_for_fn_args");
1335
1336     // Return an array wrapping the ValueRefs that we get from
1337     // llvm::LLVMGetParam for each argument into datums.
1338     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1339         let llarg = unsafe {
1340             llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1341         };
1342         datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1343     }).collect()
1344 }
1345
1346 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1347                             arg_scope: cleanup::CustomScopeIndex,
1348                             bcx: &'a Block<'a>,
1349                             args: &[ast::Arg],
1350                             arg_datums: ~[RvalueDatum])
1351                             -> &'a Block<'a> {
1352     debug!("copy_args_to_allocas");
1353
1354     let _icx = push_ctxt("copy_args_to_allocas");
1355     let mut bcx = bcx;
1356
1357     let arg_scope_id = cleanup::CustomScope(arg_scope);
1358
1359     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1360         // For certain mode/type combinations, the raw llarg values are passed
1361         // by value.  However, within the fn body itself, we want to always
1362         // have all locals and arguments be by-ref so that we can cancel the
1363         // cleanup and for better interaction with LLVM's debug info.  So, if
1364         // the argument would be passed by value, we store it into an alloca.
1365         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1366         // the event it's not truly needed.
1367
1368         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1369
1370         if fcx.ccx.sess.opts.debuginfo {
1371             debuginfo::create_argument_metadata(bcx, &args[i]);
1372         }
1373     }
1374
1375     bcx
1376 }
1377
1378 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1379 // and builds the return block.
1380 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1381                      last_bcx: &'a Block<'a>) {
1382     let _icx = push_ctxt("finish_fn");
1383
1384     let ret_cx = match fcx.llreturn.get() {
1385         Some(llreturn) => {
1386             if !last_bcx.terminated.get() {
1387                 Br(last_bcx, llreturn);
1388             }
1389             raw_block(fcx, false, llreturn)
1390         }
1391         None => last_bcx
1392     };
1393     build_return_block(fcx, ret_cx);
1394     debuginfo::clear_source_location(fcx);
1395     fcx.cleanup();
1396 }
1397
1398 // Builds the return block for a function.
1399 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1400     // Return the value if this function immediate; otherwise, return void.
1401     if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1402         return RetVoid(ret_cx);
1403     }
1404
1405     let retptr = Value(fcx.llretptr.get().unwrap());
1406     let retval = match retptr.get_dominating_store(ret_cx) {
1407         // If there's only a single store to the ret slot, we can directly return
1408         // the value that was stored and omit the store and the alloca
1409         Some(s) => {
1410             let retval = s.get_operand(0).unwrap().get();
1411             s.erase_from_parent();
1412
1413             if retptr.has_no_uses() {
1414                 retptr.erase_from_parent();
1415             }
1416
1417             retval
1418         }
1419         // Otherwise, load the return value from the ret slot
1420         None => Load(ret_cx, fcx.llretptr.get().unwrap())
1421     };
1422
1423
1424     Ret(ret_cx, retval);
1425 }
1426
1427 // trans_closure: Builds an LLVM function out of a source function.
1428 // If the function closes over its environment a closure will be
1429 // returned.
1430 pub fn trans_closure<'a>(ccx: @CrateContext,
1431                          decl: &ast::FnDecl,
1432                          body: &ast::Block,
1433                          llfndecl: ValueRef,
1434                          param_substs: Option<@param_substs>,
1435                          id: ast::NodeId,
1436                          _attributes: &[ast::Attribute],
1437                          output_type: ty::t,
1438                          maybe_load_env: <'b> |&'b Block<'b>| -> &'b Block<'b>) {
1439     ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1440
1441     let _icx = push_ctxt("trans_closure");
1442     set_uwtable(llfndecl);
1443
1444     debug!("trans_closure(..., param_substs={})",
1445            param_substs.repr(ccx.tcx));
1446
1447     let has_env = match ty::get(ty::node_id_to_type(ccx.tcx, id)).sty {
1448         ty::ty_closure(_) => true,
1449         _ => false
1450     };
1451
1452     let arena = TypedArena::new();
1453     let fcx = new_fn_ctxt(ccx,
1454                           llfndecl,
1455                           id,
1456                           has_env,
1457                           output_type,
1458                           param_substs,
1459                           Some(body.span),
1460                           &arena);
1461     init_function(&fcx, false, output_type, param_substs);
1462
1463     // cleanup scope for the incoming arguments
1464     let arg_scope = fcx.push_custom_cleanup_scope();
1465
1466     // Create the first basic block in the function and keep a handle on it to
1467     //  pass to finish_fn later.
1468     let bcx_top = fcx.entry_bcx.get().unwrap();
1469     let mut bcx = bcx_top;
1470     let block_ty = node_id_type(bcx, body.id);
1471
1472     // Set up arguments to the function.
1473     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1474     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1475
1476     bcx = copy_args_to_allocas(&fcx,
1477                                arg_scope,
1478                                bcx,
1479                                decl.inputs.as_slice(),
1480                                arg_datums);
1481
1482     bcx = maybe_load_env(bcx);
1483
1484     // Up until here, IR instructions for this function have explicitly not been annotated with
1485     // source code location, so we don't step into call setup code. From here on, source location
1486     // emitting should be enabled.
1487     debuginfo::start_emitting_source_locations(&fcx);
1488
1489     let dest = match fcx.llretptr.get() {
1490         Some(e) => {expr::SaveIn(e)}
1491         None => {
1492             assert!(type_is_zero_size(bcx.ccx(), block_ty))
1493             expr::Ignore
1494         }
1495     };
1496
1497     // This call to trans_block is the place where we bridge between
1498     // translation calls that don't have a return value (trans_crate,
1499     // trans_mod, trans_item, et cetera) and those that do
1500     // (trans_block, trans_expr, et cetera).
1501     bcx = controlflow::trans_block(bcx, body, dest);
1502
1503     match fcx.llreturn.get() {
1504         Some(_) => {
1505             Br(bcx, fcx.return_exit_block());
1506             fcx.pop_custom_cleanup_scope(arg_scope);
1507         }
1508         None => {
1509             // Microoptimization writ large: avoid creating a separate
1510             // llreturn basic block
1511             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1512         }
1513     };
1514
1515     // Put return block after all other blocks.
1516     // This somewhat improves single-stepping experience in debugger.
1517     unsafe {
1518         let llreturn = fcx.llreturn.get();
1519         for &llreturn in llreturn.iter() {
1520             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1521         }
1522     }
1523
1524     // Insert the mandatory first few basic blocks before lltop.
1525     finish_fn(&fcx, bcx);
1526 }
1527
1528 // trans_fn: creates an LLVM function corresponding to a source language
1529 // function.
1530 pub fn trans_fn(ccx: @CrateContext,
1531                 decl: &ast::FnDecl,
1532                 body: &ast::Block,
1533                 llfndecl: ValueRef,
1534                 param_substs: Option<@param_substs>,
1535                 id: ast::NodeId,
1536                 attrs: &[ast::Attribute]) {
1537     let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1538     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx));
1539     let _icx = push_ctxt("trans_fn");
1540     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1541     trans_closure(ccx, decl, body, llfndecl,
1542                   param_substs, id, attrs, output_type, |bcx| bcx);
1543 }
1544
1545 pub fn trans_enum_variant(ccx: @CrateContext,
1546                           _enum_id: ast::NodeId,
1547                           variant: &ast::Variant,
1548                           _args: &[ast::VariantArg],
1549                           disr: ty::Disr,
1550                           param_substs: Option<@param_substs>,
1551                           llfndecl: ValueRef) {
1552     let _icx = push_ctxt("trans_enum_variant");
1553
1554     trans_enum_variant_or_tuple_like_struct(
1555         ccx,
1556         variant.node.id,
1557         disr,
1558         param_substs,
1559         llfndecl);
1560 }
1561
1562 pub fn trans_tuple_struct(ccx: @CrateContext,
1563                           _fields: &[ast::StructField],
1564                           ctor_id: ast::NodeId,
1565                           param_substs: Option<@param_substs>,
1566                           llfndecl: ValueRef) {
1567     let _icx = push_ctxt("trans_tuple_struct");
1568
1569     trans_enum_variant_or_tuple_like_struct(
1570         ccx,
1571         ctor_id,
1572         0,
1573         param_substs,
1574         llfndecl);
1575 }
1576
1577 fn trans_enum_variant_or_tuple_like_struct(ccx: @CrateContext,
1578                                            ctor_id: ast::NodeId,
1579                                            disr: ty::Disr,
1580                                            param_substs: Option<@param_substs>,
1581                                            llfndecl: ValueRef) {
1582     let no_substs: &[ty::t] = [];
1583     let ty_param_substs = match param_substs {
1584         Some(ref substs) => {
1585             let v: &[ty::t] = substs.tys;
1586             v
1587         }
1588         None => {
1589             let v: &[ty::t] = no_substs;
1590             v
1591         }
1592     };
1593
1594     let ctor_ty = ty::subst_tps(ccx.tcx,
1595                                 ty_param_substs,
1596                                 None,
1597                                 ty::node_id_to_type(ccx.tcx, ctor_id));
1598
1599     let result_ty = match ty::get(ctor_ty).sty {
1600         ty::ty_bare_fn(ref bft) => bft.sig.output,
1601         _ => ccx.sess.bug(
1602             format!("trans_enum_variant_or_tuple_like_struct: \
1603                   unexpected ctor return type {}",
1604                  ty_to_str(ccx.tcx, ctor_ty)))
1605     };
1606
1607     let arena = TypedArena::new();
1608     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1609                           param_substs, None, &arena);
1610     init_function(&fcx, false, result_ty, param_substs);
1611
1612     let arg_tys = ty::ty_fn_args(ctor_ty);
1613
1614     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1615
1616     let bcx = fcx.entry_bcx.get().unwrap();
1617
1618     if !type_is_zero_size(fcx.ccx, result_ty) {
1619         let repr = adt::represent_type(ccx, result_ty);
1620         adt::trans_start_init(bcx, repr, fcx.llretptr.get().unwrap(), disr);
1621         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1622             let lldestptr = adt::trans_field_ptr(bcx,
1623                                                  repr,
1624                                                  fcx.llretptr.get().unwrap(),
1625                                                  disr,
1626                                                  i);
1627             arg_datum.store_to(bcx, lldestptr);
1628         }
1629     }
1630
1631     finish_fn(&fcx, bcx);
1632 }
1633
1634 pub fn trans_enum_def(ccx: @CrateContext, enum_definition: &ast::EnumDef,
1635                       id: ast::NodeId, vi: @~[@ty::VariantInfo],
1636                       i: &mut uint) {
1637     for &variant in enum_definition.variants.iter() {
1638         let disr_val = vi[*i].disr_val;
1639         *i += 1;
1640
1641         match variant.node.kind {
1642             ast::TupleVariantKind(ref args) if args.len() > 0 => {
1643                 let llfn = get_item_val(ccx, variant.node.id);
1644                 trans_enum_variant(ccx, id, variant, args.as_slice(),
1645                                    disr_val, None, llfn);
1646             }
1647             ast::TupleVariantKind(_) => {
1648                 // Nothing to do.
1649             }
1650             ast::StructVariantKind(struct_def) => {
1651                 trans_struct_def(ccx, struct_def);
1652             }
1653         }
1654     }
1655 }
1656
1657 pub struct TransItemVisitor {
1658     ccx: @CrateContext,
1659 }
1660
1661 impl Visitor<()> for TransItemVisitor {
1662     fn visit_item(&mut self, i: &ast::Item, _:()) {
1663         trans_item(self.ccx, i);
1664     }
1665 }
1666
1667 pub fn trans_item(ccx: @CrateContext, item: &ast::Item) {
1668     let _icx = push_ctxt("trans_item");
1669     match item.node {
1670       ast::ItemFn(decl, purity, _abis, ref generics, body) => {
1671         if purity == ast::ExternFn  {
1672             let llfndecl = get_item_val(ccx, item.id);
1673             foreign::trans_rust_fn_with_foreign_abi(
1674                 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1675         } else if !generics.is_type_parameterized() {
1676             let llfn = get_item_val(ccx, item.id);
1677             trans_fn(ccx,
1678                      decl,
1679                      body,
1680                      llfn,
1681                      None,
1682                      item.id,
1683                      item.attrs.as_slice());
1684         } else {
1685             // Be sure to travel more than just one layer deep to catch nested
1686             // items in blocks and such.
1687             let mut v = TransItemVisitor{ ccx: ccx };
1688             v.visit_block(body, ());
1689         }
1690       }
1691       ast::ItemImpl(ref generics, _, _, ref ms) => {
1692         meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1693       }
1694       ast::ItemMod(ref m) => {
1695         trans_mod(ccx, m);
1696       }
1697       ast::ItemEnum(ref enum_definition, ref generics) => {
1698         if !generics.is_type_parameterized() {
1699             let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
1700             let mut i = 0;
1701             trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
1702         }
1703       }
1704       ast::ItemStatic(_, m, expr) => {
1705           consts::trans_const(ccx, m, item.id);
1706           // Do static_assert checking. It can't really be done much earlier
1707           // because we need to get the value of the bool out of LLVM
1708           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1709               if m == ast::MutMutable {
1710                   ccx.sess.span_fatal(expr.span,
1711                                       "cannot have static_assert on a mutable \
1712                                        static");
1713               }
1714
1715               let const_values = ccx.const_values.borrow();
1716               let v = const_values.get().get_copy(&item.id);
1717               unsafe {
1718                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1719                       ccx.sess.span_fatal(expr.span, "static assertion failed");
1720                   }
1721               }
1722           }
1723       },
1724       ast::ItemForeignMod(ref foreign_mod) => {
1725         foreign::trans_foreign_mod(ccx, foreign_mod);
1726       }
1727       ast::ItemStruct(struct_def, ref generics) => {
1728         if !generics.is_type_parameterized() {
1729             trans_struct_def(ccx, struct_def);
1730         }
1731       }
1732       ast::ItemTrait(..) => {
1733         // Inside of this trait definition, we won't be actually translating any
1734         // functions, but the trait still needs to be walked. Otherwise default
1735         // methods with items will not get translated and will cause ICE's when
1736         // metadata time comes around.
1737         let mut v = TransItemVisitor{ ccx: ccx };
1738         visit::walk_item(&mut v, item, ());
1739       }
1740       _ => {/* fall through */ }
1741     }
1742 }
1743
1744 pub fn trans_struct_def(ccx: @CrateContext, struct_def: @ast::StructDef) {
1745     // If this is a tuple-like struct, translate the constructor.
1746     match struct_def.ctor_id {
1747         // We only need to translate a constructor if there are fields;
1748         // otherwise this is a unit-like struct.
1749         Some(ctor_id) if struct_def.fields.len() > 0 => {
1750             let llfndecl = get_item_val(ccx, ctor_id);
1751             trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1752                                ctor_id, None, llfndecl);
1753         }
1754         Some(_) | None => {}
1755     }
1756 }
1757
1758 // Translate a module. Doing this amounts to translating the items in the
1759 // module; there ends up being no artifact (aside from linkage names) of
1760 // separate modules in the compiled program.  That's because modules exist
1761 // only as a convenience for humans working with the code, to organize names
1762 // and control visibility.
1763 pub fn trans_mod(ccx: @CrateContext, m: &ast::Mod) {
1764     let _icx = push_ctxt("trans_mod");
1765     for item in m.items.iter() {
1766         trans_item(ccx, *item);
1767     }
1768 }
1769
1770 fn finish_register_fn(ccx: @CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1771                       llfn: ValueRef) {
1772     {
1773         let mut item_symbols = ccx.item_symbols.borrow_mut();
1774         item_symbols.get().insert(node_id, sym);
1775     }
1776
1777     {
1778         let reachable = ccx.reachable.borrow();
1779         if !reachable.get().contains(&node_id) {
1780             lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1781         }
1782     }
1783
1784     if is_entry_fn(&ccx.sess, node_id) && !ccx.sess.building_library.get() {
1785         create_entry_wrapper(ccx, sp, llfn);
1786     }
1787 }
1788
1789 fn register_fn(ccx: @CrateContext,
1790                sp: Span,
1791                sym: ~str,
1792                node_id: ast::NodeId,
1793                node_type: ty::t)
1794                -> ValueRef {
1795     let f = match ty::get(node_type).sty {
1796         ty::ty_bare_fn(ref f) => {
1797             assert!(f.abis.is_rust() || f.abis.is_intrinsic());
1798             f
1799         }
1800         _ => fail!("expected bare rust fn or an intrinsic")
1801     };
1802
1803     let llfn = decl_rust_fn(ccx, false, f.sig.inputs, f.sig.output, sym);
1804     finish_register_fn(ccx, sp, sym, node_id, llfn);
1805     llfn
1806 }
1807
1808 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1809 pub fn register_fn_llvmty(ccx: @CrateContext,
1810                           sp: Span,
1811                           sym: ~str,
1812                           node_id: ast::NodeId,
1813                           cc: lib::llvm::CallConv,
1814                           fn_ty: Type,
1815                           output: ty::t) -> ValueRef {
1816     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1817
1818     let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1819     finish_register_fn(ccx, sp, sym, node_id, llfn);
1820     llfn
1821 }
1822
1823 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1824     match sess.entry_fn.get() {
1825         Some((entry_id, _)) => node_id == entry_id,
1826         None => false
1827     }
1828 }
1829
1830 // Create a _rust_main(args: ~[str]) function which will be called from the
1831 // runtime rust_start function
1832 pub fn create_entry_wrapper(ccx: @CrateContext,
1833                            _sp: Span,
1834                            main_llfn: ValueRef) {
1835     let et = ccx.sess.entry_type.get().unwrap();
1836     match et {
1837         session::EntryMain => {
1838             create_entry_fn(ccx, main_llfn, true);
1839         }
1840         session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1841         session::EntryNone => {}    // Do nothing.
1842     }
1843
1844     fn create_entry_fn(ccx: @CrateContext,
1845                        rust_main: ValueRef,
1846                        use_start_lang_item: bool) {
1847         let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
1848                                &ccx.int_type);
1849
1850         let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1851         let llbb = "top".with_c_str(|buf| {
1852             unsafe {
1853                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1854             }
1855         });
1856         let bld = ccx.builder.b;
1857         unsafe {
1858             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1859
1860             let (start_fn, args) = if use_start_lang_item {
1861                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1862                     Ok(id) => id,
1863                     Err(s) => { ccx.tcx.sess.fatal(s); }
1864                 };
1865                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1866                     get_item_val(ccx, start_def_id.node)
1867                 } else {
1868                     let start_fn_type = csearch::get_type(ccx.tcx,
1869                                                           start_def_id).ty;
1870                     trans_external_path(ccx, start_def_id, start_fn_type)
1871                 };
1872
1873                 let args = {
1874                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
1875                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
1876                     });
1877
1878                     ~[
1879                         opaque_rust_main,
1880                         llvm::LLVMGetParam(llfn, 0),
1881                         llvm::LLVMGetParam(llfn, 1)
1882                      ]
1883                 };
1884                 (start_fn, args)
1885             } else {
1886                 debug!("using user-defined start fn");
1887                 let args = ~[
1888                     llvm::LLVMGetParam(llfn, 0 as c_uint),
1889                     llvm::LLVMGetParam(llfn, 1 as c_uint)
1890                 ];
1891
1892                 (rust_main, args)
1893             };
1894
1895             let result = llvm::LLVMBuildCall(bld, start_fn,
1896                                              args.as_ptr(), args.len() as c_uint,
1897                                              noname());
1898
1899             llvm::LLVMBuildRet(bld, result);
1900         }
1901     }
1902 }
1903
1904 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1905                  ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1906     match attr::first_attr_value_str_by_name(attrs, "export_name") {
1907         // Use provided name
1908         Some(name) => name.get().to_owned(),
1909
1910         _ => ccx.tcx.map.with_path(id, |mut path| {
1911             if attr::contains_name(attrs, "no_mangle") {
1912                 // Don't mangle
1913                 path.last().unwrap().to_str()
1914             } else {
1915                 // Usual name mangling
1916                 mangle_exported_name(ccx, path, ty, id)
1917             }
1918         })
1919     }
1920 }
1921
1922 pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
1923     debug!("get_item_val(id=`{:?}`)", id);
1924
1925     let val = {
1926         let item_vals = ccx.item_vals.borrow();
1927         item_vals.get().find_copy(&id)
1928     };
1929
1930     match val {
1931         Some(v) => v,
1932         None => {
1933             let mut foreign = false;
1934             let item = ccx.tcx.map.get(id);
1935             let val = match item {
1936                 ast_map::NodeItem(i) => {
1937                     let ty = ty::node_id_to_type(ccx.tcx, i.id);
1938                     let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1939
1940                     let v = match i.node {
1941                         ast::ItemStatic(_, _, expr) => {
1942                             // If this static came from an external crate, then
1943                             // we need to get the symbol from csearch instead of
1944                             // using the current crate's name/version
1945                             // information in the hash of the symbol
1946                             debug!("making {}", sym);
1947                             let (sym, is_local) = {
1948                                 let external_srcs = ccx.external_srcs
1949                                                        .borrow();
1950                                 match external_srcs.get().find(&i.id) {
1951                                     Some(&did) => {
1952                                         debug!("but found in other crate...");
1953                                         (csearch::get_symbol(ccx.sess.cstore,
1954                                                              did), false)
1955                                     }
1956                                     None => (sym, true)
1957                                 }
1958                             };
1959
1960                             // We need the translated value here, because for enums the
1961                             // LLVM type is not fully determined by the Rust type.
1962                             let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1963                             {
1964                                 let mut const_values = ccx.const_values
1965                                                           .borrow_mut();
1966                                 const_values.get().insert(id, v);
1967                             }
1968                             let mut inlineable = inlineable;
1969
1970                             unsafe {
1971                                 let llty = llvm::LLVMTypeOf(v);
1972                                 let g = sym.with_c_str(|buf| {
1973                                     llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1974                                 });
1975
1976                                 {
1977                                     let reachable = ccx.reachable.borrow();
1978                                     if !reachable.get().contains(&id) {
1979                                         lib::llvm::SetLinkage(
1980                                             g,
1981                                             lib::llvm::InternalLinkage);
1982                                     }
1983                                 }
1984
1985                                 // Apply the `unnamed_addr` attribute if
1986                                 // requested
1987                                 if attr::contains_name(i.attrs.as_slice(),
1988                                                        "address_insignificant"){
1989                                     {
1990                                         let reachable =
1991                                             ccx.reachable.borrow();
1992                                         if reachable.get().contains(&id) {
1993                                             ccx.sess.span_bug(i.span,
1994                                                 "insignificant static is \
1995                                                  reachable");
1996                                         }
1997                                     }
1998                                     lib::llvm::SetUnnamedAddr(g, true);
1999
2000                                     // This is a curious case where we must make
2001                                     // all of these statics inlineable. If a
2002                                     // global is tagged as
2003                                     // address_insignificant, then LLVM won't
2004                                     // coalesce globals unless they have an
2005                                     // internal linkage type. This means that
2006                                     // external crates cannot use this global.
2007                                     // This is a problem for things like inner
2008                                     // statics in generic functions, because the
2009                                     // function will be inlined into another
2010                                     // crate and then attempt to link to the
2011                                     // static in the original crate, only to
2012                                     // find that it's not there. On the other
2013                                     // side of inlininig, the crates knows to
2014                                     // not declare this static as
2015                                     // available_externally (because it isn't)
2016                                     inlineable = true;
2017                                 }
2018
2019                                 if attr::contains_name(i.attrs.as_slice(),
2020                                                        "thread_local") {
2021                                     lib::llvm::set_thread_local(g, true);
2022                                 }
2023
2024                                 if !inlineable {
2025                                     debug!("{} not inlined", sym);
2026                                     let mut non_inlineable_statics =
2027                                         ccx.non_inlineable_statics
2028                                            .borrow_mut();
2029                                     non_inlineable_statics.get().insert(id);
2030                                 }
2031
2032                                 let mut item_symbols = ccx.item_symbols
2033                                                           .borrow_mut();
2034                                 item_symbols.get().insert(i.id, sym);
2035                                 g
2036                             }
2037                         }
2038
2039                         ast::ItemFn(_, purity, _, _, _) => {
2040                             let llfn = if purity != ast::ExternFn {
2041                                 register_fn(ccx, i.span, sym, i.id, ty)
2042                             } else {
2043                                 foreign::register_rust_fn_with_foreign_abi(ccx,
2044                                                                            i.span,
2045                                                                            sym,
2046                                                                            i.id)
2047                             };
2048                             set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2049                             llfn
2050                         }
2051
2052                         _ => fail!("get_item_val: weird result in table")
2053                     };
2054
2055                     match attr::first_attr_value_str_by_name(i.attrs
2056                                                               .as_slice(),
2057                                                              "link_section") {
2058                         Some(sect) => unsafe {
2059                             sect.get().with_c_str(|buf| {
2060                                 llvm::LLVMSetSection(v, buf);
2061                             })
2062                         },
2063                         None => ()
2064                     }
2065
2066                     v
2067                 }
2068
2069                 ast_map::NodeTraitMethod(trait_method) => {
2070                     debug!("get_item_val(): processing a NodeTraitMethod");
2071                     match *trait_method {
2072                         ast::Required(_) => {
2073                             ccx.sess.bug("unexpected variant: required trait method in \
2074                                          get_item_val()");
2075                         }
2076                         ast::Provided(m) => {
2077                             register_method(ccx, id, m)
2078                         }
2079                     }
2080                 }
2081
2082                 ast_map::NodeMethod(m) => {
2083                     register_method(ccx, id, m)
2084                 }
2085
2086                 ast_map::NodeForeignItem(ni) => {
2087                     let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2088                     foreign = true;
2089
2090                     match ni.node {
2091                         ast::ForeignItemFn(..) => {
2092                             let abis = ccx.tcx.map.get_foreign_abis(id);
2093                             foreign::register_foreign_item_fn(ccx, abis, ni)
2094                         }
2095                         ast::ForeignItemStatic(..) => {
2096                             // Treat the crate map static specially in order to
2097                             // a weak-linkage-like functionality where it's
2098                             // dynamically resolved at runtime. If we're
2099                             // building a library, then we declare the static
2100                             // with weak linkage, but if we're building a
2101                             // library then we've already declared the crate map
2102                             // so use that instead.
2103                             if attr::contains_name(ni.attrs.as_slice(),
2104                                                    "crate_map") {
2105                                 if ccx.sess.building_library.get() {
2106                                     let s = "_rust_crate_map_toplevel";
2107                                     let g = unsafe {
2108                                         s.with_c_str(|buf| {
2109                                             let ty = type_of(ccx, ty);
2110                                             llvm::LLVMAddGlobal(ccx.llmod,
2111                                                                 ty.to_ref(),
2112                                                                 buf)
2113                                         })
2114                                     };
2115                                     lib::llvm::SetLinkage(g,
2116                                         lib::llvm::ExternalWeakLinkage);
2117                                     g
2118                                 } else {
2119                                     ccx.crate_map
2120                                 }
2121                             } else {
2122                                 let ident = foreign::link_name(ni);
2123                                 unsafe {
2124                                     ident.get().with_c_str(|buf| {
2125                                         let ty = type_of(ccx, ty);
2126                                         llvm::LLVMAddGlobal(ccx.llmod,
2127                                                             ty.to_ref(), buf)
2128                                     })
2129                                 }
2130                             }
2131                         }
2132                     }
2133                 }
2134
2135                 ast_map::NodeVariant(ref v) => {
2136                     let llfn;
2137                     match v.node.kind {
2138                         ast::TupleVariantKind(ref args) => {
2139                             assert!(args.len() != 0u);
2140                             let ty = ty::node_id_to_type(ccx.tcx, id);
2141                             let parent = ccx.tcx.map.get_parent(id);
2142                             let enm = ccx.tcx.map.expect_item(parent);
2143                             let sym = exported_name(ccx,
2144                                                     id,
2145                                                     ty,
2146                                                     enm.attrs.as_slice());
2147
2148                             llfn = match enm.node {
2149                                 ast::ItemEnum(_, _) => {
2150                                     register_fn(ccx, (*v).span, sym, id, ty)
2151                                 }
2152                                 _ => fail!("NodeVariant, shouldn't happen")
2153                             };
2154                         }
2155                         ast::StructVariantKind(_) => {
2156                             fail!("struct variant kind unexpected in get_item_val")
2157                         }
2158                     }
2159                     set_inline_hint(llfn);
2160                     llfn
2161                 }
2162
2163                 ast_map::NodeStructCtor(struct_def) => {
2164                     // Only register the constructor if this is a tuple-like struct.
2165                     match struct_def.ctor_id {
2166                         None => {
2167                             ccx.tcx.sess.bug("attempt to register a constructor of \
2168                                               a non-tuple-like struct")
2169                         }
2170                         Some(ctor_id) => {
2171                             let parent = ccx.tcx.map.get_parent(id);
2172                             let struct_item = ccx.tcx.map.expect_item(parent);
2173                             let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2174                             let sym = exported_name(ccx,
2175                                                     id,
2176                                                     ty,
2177                                                     struct_item.attrs
2178                                                                .as_slice());
2179                             let llfn = register_fn(ccx, struct_item.span,
2180                                                    sym, ctor_id, ty);
2181                             set_inline_hint(llfn);
2182                             llfn
2183                         }
2184                     }
2185                 }
2186
2187                 ref variant => {
2188                     ccx.sess.bug(format!("get_item_val(): unexpected variant: {:?}",
2189                                  variant))
2190                 }
2191             };
2192
2193             // foreign items (extern fns and extern statics) don't have internal
2194             // linkage b/c that doesn't quite make sense. Otherwise items can
2195             // have internal linkage if they're not reachable.
2196             {
2197                 let reachable = ccx.reachable.borrow();
2198                 if !foreign && !reachable.get().contains(&id) {
2199                     lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2200                 }
2201             }
2202
2203             let mut item_vals = ccx.item_vals.borrow_mut();
2204             item_vals.get().insert(id, val);
2205             val
2206         }
2207     }
2208 }
2209
2210 fn register_method(ccx: @CrateContext, id: ast::NodeId,
2211                    m: &ast::Method) -> ValueRef {
2212     let mty = ty::node_id_to_type(ccx.tcx, id);
2213
2214     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2215
2216     let llfn = register_fn(ccx, m.span, sym, id, mty);
2217     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2218     llfn
2219 }
2220
2221 pub fn vp2i(cx: &Block, v: ValueRef) -> ValueRef {
2222     let ccx = cx.ccx();
2223     return PtrToInt(cx, v, ccx.int_type);
2224 }
2225
2226 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2227     unsafe {
2228         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2229     }
2230 }
2231
2232 macro_rules! ifn (
2233     ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2234         let name = $name;
2235         // HACK(eddyb) dummy output type, shouln't affect anything.
2236         let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret), ty::mk_nil());
2237         $intrinsics.insert(name, f);
2238     })
2239 )
2240
2241 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2242     let i8p = Type::i8p();
2243     let mut intrinsics = HashMap::new();
2244
2245     ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2246          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2247     ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2248          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2249     ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2250          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2251     ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2252          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2253     ifn!(intrinsics, "llvm.memset.p0i8.i32",
2254          [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2255     ifn!(intrinsics, "llvm.memset.p0i8.i64",
2256          [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2257
2258     ifn!(intrinsics, "llvm.trap", [], Type::void());
2259     ifn!(intrinsics, "llvm.debugtrap", [], Type::void());
2260     ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2261
2262     ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2263     ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2264     ifn!(intrinsics, "llvm.pow.f32",  [Type::f32(), Type::f32()], Type::f32());
2265     ifn!(intrinsics, "llvm.pow.f64",  [Type::f64(), Type::f64()], Type::f64());
2266
2267     ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2268     ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2269     ifn!(intrinsics, "llvm.sin.f32",  [Type::f32()], Type::f32());
2270     ifn!(intrinsics, "llvm.sin.f64",  [Type::f64()], Type::f64());
2271     ifn!(intrinsics, "llvm.cos.f32",  [Type::f32()], Type::f32());
2272     ifn!(intrinsics, "llvm.cos.f64",  [Type::f64()], Type::f64());
2273     ifn!(intrinsics, "llvm.exp.f32",  [Type::f32()], Type::f32());
2274     ifn!(intrinsics, "llvm.exp.f64",  [Type::f64()], Type::f64());
2275     ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2276     ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2277     ifn!(intrinsics, "llvm.log.f32",  [Type::f32()], Type::f32());
2278     ifn!(intrinsics, "llvm.log.f64",  [Type::f64()], Type::f64());
2279     ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2280     ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2281     ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2282     ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2283
2284     ifn!(intrinsics, "llvm.fma.f32",  [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2285     ifn!(intrinsics, "llvm.fma.f64",  [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2286
2287     ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2288     ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2289     ifn!(intrinsics, "llvm.copysign.f32", [Type::f32(), Type::f32()], Type::f32());
2290     ifn!(intrinsics, "llvm.copysign.f64", [Type::f64(), Type::f64()], Type::f64());
2291
2292     ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2293     ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2294     ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2295     ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2296     ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2297     ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2298
2299     ifn!(intrinsics, "llvm.rint.f32", [Type::f32()], Type::f32());
2300     ifn!(intrinsics, "llvm.rint.f64", [Type::f64()], Type::f64());
2301     ifn!(intrinsics, "llvm.nearbyint.f32", [Type::f32()], Type::f32());
2302     ifn!(intrinsics, "llvm.nearbyint.f64", [Type::f64()], Type::f64());
2303     ifn!(intrinsics, "llvm.round.f32", [Type::f32()], Type::f32());
2304     ifn!(intrinsics, "llvm.round.f64", [Type::f64()], Type::f64());
2305
2306     ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2307     ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2308     ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2309     ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2310
2311     ifn!(intrinsics, "llvm.ctlz.i8",  [Type::i8() , Type::i1()], Type::i8());
2312     ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2313     ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2314     ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2315
2316     ifn!(intrinsics, "llvm.cttz.i8",  [Type::i8() , Type::i1()], Type::i8());
2317     ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2318     ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2319     ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2320
2321     ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2322     ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2323     ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2324
2325     ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2326         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2327     ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2328         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2329     ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2330         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2331     ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2332         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2333
2334     ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2335         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2336     ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2337         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2338     ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2339         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2340     ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2341         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2342
2343     ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2344         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2345     ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2346         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2347     ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2348         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2349     ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2350         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2351
2352     ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2353         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2354     ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2355         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2356     ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2357         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2358     ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2359         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2360
2361     ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2362         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2363     ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2364         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2365     ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2366         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2367     ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2368         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2369
2370     ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2371         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2372     ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2373         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2374     ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2375         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2376     ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2377         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2378
2379     ifn!(intrinsics, "llvm.expect.i1", [Type::i1(), Type::i1()], Type::i1());
2380
2381     return intrinsics;
2382 }
2383
2384 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2385     ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2386     ifn!(intrinsics,
2387          "llvm.dbg.value",   [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2388 }
2389
2390 pub fn trap(bcx: &Block) {
2391     match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2392       Some(&x) => { Call(bcx, x, [], []); },
2393       _ => bcx.sess().bug("unbound llvm.trap in trap")
2394     }
2395 }
2396
2397 pub fn decl_gc_metadata(ccx: &CrateContext, llmod_id: &str) {
2398     if !ccx.sess.opts.gc || !ccx.uses_gc {
2399         return;
2400     }
2401
2402     let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2403     let gc_metadata = gc_metadata_name.with_c_str(|buf| {
2404         unsafe {
2405             llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2406         }
2407     });
2408     unsafe {
2409         llvm::LLVMSetGlobalConstant(gc_metadata, True);
2410         lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2411
2412         let mut module_data = ccx.module_data.borrow_mut();
2413         module_data.get().insert(~"_gc_module_metadata", gc_metadata);
2414     }
2415 }
2416
2417 pub fn create_module_map(ccx: &CrateContext) -> (ValueRef, uint) {
2418     let str_slice_type = Type::struct_([Type::i8p(), ccx.int_type], false);
2419     let elttype = Type::struct_([str_slice_type, ccx.int_type], false);
2420     let maptype = {
2421         let module_data = ccx.module_data.borrow();
2422         Type::array(&elttype, module_data.get().len() as u64)
2423     };
2424     let map = "_rust_mod_map".with_c_str(|buf| {
2425         unsafe {
2426             llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2427         }
2428     });
2429     lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2430     let mut elts: ~[ValueRef] = ~[];
2431
2432     // This is not ideal, but the borrow checker doesn't
2433     // like the multiple borrows. At least, it doesn't
2434     // like them on the current snapshot. (2013-06-14)
2435     let keys = {
2436         let mut keys = ~[];
2437         let module_data = ccx.module_data.borrow();
2438         for (k, _) in module_data.get().iter() {
2439             keys.push(k.clone());
2440         }
2441         keys
2442     };
2443
2444     for key in keys.iter() {
2445         let llstrval = C_str_slice(ccx, token::intern_and_get_ident(*key));
2446         let module_data = ccx.module_data.borrow();
2447         let val = *module_data.get().find_equiv(key).unwrap();
2448         let v_ptr = p2i(ccx, val);
2449         let elt = C_struct([
2450             llstrval,
2451             v_ptr
2452         ], false);
2453         elts.push(elt);
2454     }
2455     unsafe {
2456         llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2457     }
2458     return (map, keys.len())
2459 }
2460
2461 pub fn symname(name: &str, hash: &str, vers: &str) -> ~str {
2462     let path = [PathName(token::intern(name))];
2463     link::exported_name(ast_map::Values(path.iter()).chain(None), hash, vers)
2464 }
2465
2466 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2467                       llmod: ModuleRef) -> (~str, ValueRef) {
2468     let targ_cfg = sess.targ_cfg;
2469     let int_type = Type::int(targ_cfg.arch);
2470     let mut n_subcrates = 1;
2471     let cstore = sess.cstore;
2472     while cstore.have_crate_data(n_subcrates) { n_subcrates += 1; }
2473     let is_top = !sess.building_library.get() || sess.opts.cg.gen_crate_map;
2474     let sym_name = if is_top {
2475         ~"_rust_crate_map_toplevel"
2476     } else {
2477         symname("_rust_crate_map_" + mapmeta.crateid.name,
2478                 mapmeta.crate_hash.as_str(),
2479                 mapmeta.crateid.version_or_default())
2480     };
2481
2482     let slicetype = Type::struct_([int_type, int_type], false);
2483     let maptype = Type::struct_([
2484         Type::i32(),        // version
2485         slicetype,          // child modules
2486         slicetype,          // sub crate-maps
2487         int_type.ptr_to(),  // event loop factory
2488     ], false);
2489     let map = sym_name.with_c_str(|buf| {
2490         unsafe {
2491             llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2492         }
2493     });
2494     lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2495
2496     // On windows we'd like to export the toplevel cratemap
2497     // such that we can find it from libstd.
2498     if targ_cfg.os == OsWin32 && is_top {
2499         unsafe { llvm::LLVMRustSetDLLExportStorageClass(map) }
2500     }
2501
2502     return (sym_name, map);
2503 }
2504
2505 pub fn fill_crate_map(ccx: @CrateContext, map: ValueRef) {
2506     let mut subcrates: ~[ValueRef] = ~[];
2507     let mut i = 1;
2508     let cstore = ccx.sess.cstore;
2509     while cstore.have_crate_data(i) {
2510         let cdata = cstore.get_crate_data(i);
2511         let nm = symname(format!("_rust_crate_map_{}", cdata.name),
2512                          cstore.get_crate_hash(i).as_str(),
2513                          cstore.get_crate_id(i).version_or_default());
2514         let cr = nm.with_c_str(|buf| {
2515             unsafe {
2516                 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2517             }
2518         });
2519         subcrates.push(p2i(ccx, cr));
2520         i += 1;
2521     }
2522     let event_loop_factory = match ccx.tcx.lang_items.event_loop_factory() {
2523         Some(did) => unsafe {
2524             if is_local(did) {
2525                 llvm::LLVMConstPointerCast(get_item_val(ccx, did.node),
2526                                            ccx.int_type.ptr_to().to_ref())
2527             } else {
2528                 let name = csearch::get_symbol(ccx.sess.cstore, did);
2529                 let global = name.with_c_str(|buf| {
2530                     llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2531                 });
2532                 global
2533             }
2534         },
2535         None => C_null(ccx.int_type.ptr_to())
2536     };
2537     unsafe {
2538         let maptype = Type::array(&ccx.int_type, subcrates.len() as u64);
2539         let vec_elements = "_crate_map_child_vectors".with_c_str(|buf| {
2540             llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2541         });
2542         lib::llvm::SetLinkage(vec_elements, lib::llvm::InternalLinkage);
2543
2544         llvm::LLVMSetInitializer(vec_elements, C_array(ccx.int_type, subcrates));
2545         let (mod_map, mod_count) = create_module_map(ccx);
2546
2547         llvm::LLVMSetInitializer(map, C_struct(
2548             [C_i32(2),
2549              C_struct([
2550                 p2i(ccx, mod_map),
2551                 C_uint(ccx, mod_count)
2552              ], false),
2553              C_struct([
2554                 p2i(ccx, vec_elements),
2555                 C_uint(ccx, subcrates.len())
2556              ], false),
2557             event_loop_factory,
2558         ], false));
2559     }
2560 }
2561
2562 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2563     -> encoder::EncodeParams<'r> {
2564
2565         let diag = cx.sess.diagnostic();
2566         let item_symbols = &cx.item_symbols;
2567         let link_meta = &cx.link_meta;
2568         encoder::EncodeParams {
2569             diag: diag,
2570             tcx: cx.tcx,
2571             reexports2: cx.exp_map2,
2572             item_symbols: item_symbols,
2573             non_inlineable_statics: &cx.non_inlineable_statics,
2574             link_meta: link_meta,
2575             cstore: cx.sess.cstore,
2576             encode_inlined_item: ie,
2577         }
2578 }
2579
2580 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> ~[u8] {
2581     use flate;
2582
2583     if !cx.sess.building_library.get() {
2584         return ~[]
2585     }
2586
2587     let encode_inlined_item: encoder::EncodeInlinedItem =
2588         |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii, cx.maps);
2589
2590     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2591     let metadata = encoder::encode_metadata(encode_parms, krate);
2592     let compressed = encoder::metadata_encoding_version +
2593                         flate::deflate_bytes(metadata).as_slice();
2594     let llmeta = C_bytes(compressed);
2595     let llconst = C_struct([llmeta], false);
2596     let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2597                        cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2598     let llglobal = name.with_c_str(|buf| {
2599         unsafe {
2600             llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2601         }
2602     });
2603     unsafe {
2604         llvm::LLVMSetInitializer(llglobal, llconst);
2605         cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2606             llvm::LLVMSetSection(llglobal, buf)
2607         });
2608     }
2609     return metadata;
2610 }
2611
2612 pub fn trans_crate(sess: session::Session,
2613                    krate: ast::Crate,
2614                    analysis: &CrateAnalysis,
2615                    output: &OutputFilenames) -> CrateTranslation {
2616     // Before we touch LLVM, make sure that multithreading is enabled.
2617     unsafe {
2618         use sync::one::{Once, ONCE_INIT};
2619         static mut INIT: Once = ONCE_INIT;
2620         static mut POISONED: bool = false;
2621         INIT.doit(|| {
2622             if llvm::LLVMStartMultithreaded() != 1 {
2623                 // use an extra bool to make sure that all future usage of LLVM
2624                 // cannot proceed despite the Once not running more than once.
2625                 POISONED = true;
2626             }
2627         });
2628
2629         if POISONED {
2630             sess.bug("couldn't enable multi-threaded LLVM");
2631         }
2632     }
2633
2634     let link_meta = link::build_link_meta(&krate, output);
2635
2636     // Append ".rs" to crate name as LLVM module identifier.
2637     //
2638     // LLVM code generator emits a ".file filename" directive
2639     // for ELF backends. Value of the "filename" is set as the
2640     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2641     // crashes if the module identifer is same as other symbols
2642     // such as a function name in the module.
2643     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2644     let llmod_id = link_meta.crateid.name + ".rs";
2645
2646     let ccx = @CrateContext::new(sess,
2647                                  llmod_id,
2648                                  analysis.ty_cx,
2649                                  analysis.exp_map2,
2650                                  analysis.maps,
2651                                  Sha256::new(),
2652                                  link_meta,
2653                                  analysis.reachable);
2654     {
2655         let _icx = push_ctxt("text");
2656         trans_mod(ccx, &krate.module);
2657     }
2658
2659     decl_gc_metadata(ccx, llmod_id);
2660     fill_crate_map(ccx, ccx.crate_map);
2661
2662     // win32: wart with exporting crate_map symbol
2663     // We set the crate map (_rust_crate_map_toplevel) to use dll_export
2664     // linkage but that ends up causing the linker to look for a
2665     // __rust_crate_map_toplevel symbol (extra underscore) which it will
2666     // subsequently fail to find. So to mitigate that we just introduce
2667     // an alias from the symbol it expects to the one that actually exists.
2668     if ccx.sess.targ_cfg.os == OsWin32 && !ccx.sess.building_library.get() {
2669
2670         let maptype = val_ty(ccx.crate_map).to_ref();
2671
2672         "__rust_crate_map_toplevel".with_c_str(|buf| {
2673             unsafe {
2674                 llvm::LLVMAddAlias(ccx.llmod, maptype,
2675                                    ccx.crate_map, buf);
2676             }
2677         })
2678     }
2679
2680     glue::emit_tydescs(ccx);
2681     if ccx.sess.opts.debuginfo {
2682         debuginfo::finalize(ccx);
2683     }
2684
2685     // Translate the metadata.
2686     let metadata = write_metadata(ccx, &krate);
2687     if ccx.sess.trans_stats() {
2688         println!("--- trans stats ---");
2689         println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2690         println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2691         println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2692         println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2693
2694         println!("n_fns: {}", ccx.stats.n_fns.get());
2695         println!("n_monos: {}", ccx.stats.n_monos.get());
2696         println!("n_inlines: {}", ccx.stats.n_inlines.get());
2697         println!("n_closures: {}", ccx.stats.n_closures.get());
2698         println!("fn stats:");
2699         {
2700             let mut fn_stats = ccx.stats.fn_stats.borrow_mut();
2701             fn_stats.get().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2702                 insns_b.cmp(&insns_a)
2703             });
2704             for tuple in fn_stats.get().iter() {
2705                 match *tuple {
2706                     (ref name, ms, insns) => {
2707                         println!("{} insns, {} ms, {}", insns, ms, *name);
2708                     }
2709                 }
2710             }
2711         }
2712     }
2713     if ccx.sess.count_llvm_insns() {
2714         let llvm_insns = ccx.stats.llvm_insns.borrow();
2715         for (k, v) in llvm_insns.get().iter() {
2716             println!("{:7u} {}", *v, *k);
2717         }
2718     }
2719
2720     let llcx = ccx.llcx;
2721     let link_meta = ccx.link_meta.clone();
2722     let llmod = ccx.llmod;
2723
2724     let mut reachable = {
2725         let reachable_map = ccx.reachable.borrow();
2726         reachable_map.get().iter().filter_map(|id| {
2727             let item_symbols = ccx.item_symbols.borrow();
2728             item_symbols.get().find(id).map(|s| s.to_owned())
2729         }).to_owned_vec()
2730     };
2731
2732     // Make sure that some other crucial symbols are not eliminated from the
2733     // module. This includes the main function, the crate map (used for debug
2734     // log settings and I/O), and finally the curious rust_stack_exhausted
2735     // symbol. This symbol is required for use by the libmorestack library that
2736     // we link in, so we must ensure that this symbol is not internalized (if
2737     // defined in the crate).
2738     reachable.push(ccx.crate_map_name.to_owned());
2739     reachable.push(~"main");
2740     reachable.push(~"rust_stack_exhausted");
2741     reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
2742     reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
2743
2744     return CrateTranslation {
2745         context: llcx,
2746         module: llmod,
2747         link: link_meta,
2748         metadata_module: ccx.metadata_llmod,
2749         metadata: metadata,
2750         reachable: reachable,
2751     };
2752 }