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