]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
3cfabf7f96b7f2ff75e5d2bdf23463cba26458f1
[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                     let c = foreign::llvm_calling_convention(ccx, fn_ty.abi);
864                     let cconv = c.unwrap_or(lib::llvm::CCallConv);
865                     let llty = type_of_fn_from_ty(ccx, t);
866                     get_extern_fn(&mut *ccx.externs.borrow_mut(),
867                                   ccx.llmod,
868                                   name.as_slice(),
869                                   cconv,
870                                   llty,
871                                   fn_ty.sig.output)
872                 }
873             }
874         }
875         ty::ty_closure(ref f) => {
876             get_extern_rust_fn(ccx,
877                                f.sig.inputs.as_slice(),
878                                f.sig.output,
879                                name.as_slice(),
880                                did)
881         }
882         _ => {
883             let llty = type_of(ccx, t);
884             get_extern_const(&mut *ccx.externs.borrow_mut(),
885                              ccx.llmod,
886                              name.as_slice(),
887                              llty)
888         }
889     }
890 }
891
892 pub fn invoke<'a>(
893               bcx: &'a Block<'a>,
894               llfn: ValueRef,
895               llargs: Vec<ValueRef> ,
896               attributes: &[(uint, lib::llvm::Attribute)],
897               call_info: Option<NodeInfo>)
898               -> (ValueRef, &'a Block<'a>) {
899     let _icx = push_ctxt("invoke_");
900     if bcx.unreachable.get() {
901         return (C_null(Type::i8(bcx.ccx())), bcx);
902     }
903
904     match bcx.opt_node_id {
905         None => {
906             debug!("invoke at ???");
907         }
908         Some(id) => {
909             debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
910         }
911     }
912
913     if need_invoke(bcx) {
914         debug!("invoking {} at {}", llfn, bcx.llbb);
915         for &llarg in llargs.iter() {
916             debug!("arg: {}", llarg);
917         }
918         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
919         let landing_pad = bcx.fcx.get_landing_pad();
920
921         match call_info {
922             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
923             None => debuginfo::clear_source_location(bcx.fcx)
924         };
925
926         let llresult = Invoke(bcx,
927                               llfn,
928                               llargs.as_slice(),
929                               normal_bcx.llbb,
930                               landing_pad,
931                               attributes);
932         return (llresult, normal_bcx);
933     } else {
934         debug!("calling {} at {}", llfn, bcx.llbb);
935         for &llarg in llargs.iter() {
936             debug!("arg: {}", llarg);
937         }
938
939         match call_info {
940             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
941             None => debuginfo::clear_source_location(bcx.fcx)
942         };
943
944         let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
945         return (llresult, bcx);
946     }
947 }
948
949 pub fn need_invoke(bcx: &Block) -> bool {
950     if bcx.sess().no_landing_pads() {
951         return false;
952     }
953
954     // Avoid using invoke if we are already inside a landing pad.
955     if bcx.is_lpad {
956         return false;
957     }
958
959     bcx.fcx.needs_invoke()
960 }
961
962 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
963     let _icx = push_ctxt("load_if_immediate");
964     if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
965     return v;
966 }
967
968 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
969     match local.pat.node {
970         ast::PatWild => true, _ => false
971     }
972 }
973
974 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
975                   -> &'a Block<'a> {
976
977     debug!("init_local(bcx={}, local.id={:?})",
978            bcx.to_str(), local.id);
979     let _indenter = indenter();
980
981     let _icx = push_ctxt("init_local");
982
983     if ignore_lhs(bcx, local) {
984         // Handle let _ = e; just like e;
985         match local.init {
986             Some(init) => {
987                 return controlflow::trans_stmt_semi(bcx, init)
988             }
989             None => { return bcx; }
990         }
991     }
992
993     _match::store_local(bcx, local)
994 }
995
996 pub fn raw_block<'a>(
997                  fcx: &'a FunctionContext<'a>,
998                  is_lpad: bool,
999                  llbb: BasicBlockRef)
1000                  -> &'a Block<'a> {
1001     Block::new(llbb, is_lpad, None, fcx)
1002 }
1003
1004 pub fn with_cond<'a>(
1005                  bcx: &'a Block<'a>,
1006                  val: ValueRef,
1007                  f: |&'a Block<'a>| -> &'a Block<'a>)
1008                  -> &'a Block<'a> {
1009     let _icx = push_ctxt("with_cond");
1010     let fcx = bcx.fcx;
1011     let next_cx = fcx.new_temp_block("next");
1012     let cond_cx = fcx.new_temp_block("cond");
1013     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1014     let after_cx = f(cond_cx);
1015     if !after_cx.terminated.get() {
1016         Br(after_cx, next_cx.llbb);
1017     }
1018     next_cx
1019 }
1020
1021 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1022     let _icx = push_ctxt("call_memcpy");
1023     let ccx = cx.ccx();
1024     let key = match ccx.sess().targ_cfg.arch {
1025         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1026         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1027     };
1028     let memcpy = ccx.get_intrinsic(&key);
1029     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1030     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1031     let size = IntCast(cx, n_bytes, ccx.int_type);
1032     let align = C_i32(ccx, align as i32);
1033     let volatile = C_i1(ccx, false);
1034     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1035 }
1036
1037 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1038     let _icx = push_ctxt("memcpy_ty");
1039     let ccx = bcx.ccx();
1040     if ty::type_is_structural(t) {
1041         let llty = type_of::type_of(ccx, t);
1042         let llsz = llsize_of(ccx, llty);
1043         let llalign = llalign_of_min(ccx, llty);
1044         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1045     } else {
1046         Store(bcx, Load(bcx, src), dst);
1047     }
1048 }
1049
1050 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1051     if cx.unreachable.get() { return; }
1052     let _icx = push_ctxt("zero_mem");
1053     let bcx = cx;
1054     let ccx = cx.ccx();
1055     let llty = type_of::type_of(ccx, t);
1056     memzero(&B(bcx), llptr, llty);
1057 }
1058
1059 // Always use this function instead of storing a zero constant to the memory
1060 // in question. If you store a zero constant, LLVM will drown in vreg
1061 // allocation for large data structures, and the generated code will be
1062 // awful. (A telltale sign of this is large quantities of
1063 // `mov [byte ptr foo],0` in the generated code.)
1064 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1065     let _icx = push_ctxt("memzero");
1066     let ccx = b.ccx;
1067
1068     let intrinsic_key = match ccx.sess().targ_cfg.arch {
1069         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1070         X86_64 => "llvm.memset.p0i8.i64"
1071     };
1072
1073     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1074     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1075     let llzeroval = C_u8(ccx, 0);
1076     let size = machine::llsize_of(ccx, ty);
1077     let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1078     let volatile = C_i1(ccx, false);
1079     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1080 }
1081
1082 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1083     let _icx = push_ctxt("alloc_ty");
1084     let ccx = bcx.ccx();
1085     let ty = type_of::type_of(ccx, t);
1086     assert!(!ty::type_has_params(t));
1087     let val = alloca(bcx, ty, name);
1088     return val;
1089 }
1090
1091 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1092     alloca_maybe_zeroed(cx, ty, name, false)
1093 }
1094
1095 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1096     let _icx = push_ctxt("alloca");
1097     if cx.unreachable.get() {
1098         unsafe {
1099             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1100         }
1101     }
1102     debuginfo::clear_source_location(cx.fcx);
1103     let p = Alloca(cx, ty, name);
1104     if zero {
1105         let b = cx.fcx.ccx.builder();
1106         b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1107         memzero(&b, p, ty);
1108     }
1109     p
1110 }
1111
1112 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1113     let _icx = push_ctxt("arrayalloca");
1114     if cx.unreachable.get() {
1115         unsafe {
1116             return llvm::LLVMGetUndef(ty.to_ref());
1117         }
1118     }
1119     debuginfo::clear_source_location(cx.fcx);
1120     return ArrayAlloca(cx, ty, v);
1121 }
1122
1123 // Creates and returns space for, or returns the argument representing, the
1124 // slot where the return value of the function must go.
1125 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1126                            -> ValueRef {
1127     unsafe {
1128         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1129             llvm::LLVMGetParam(fcx.llfn, 0)
1130         } else {
1131             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1132             let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1133             Alloca(bcx, lloutputtype, "__make_return_pointer")
1134         }
1135     }
1136 }
1137
1138 // NB: must keep 4 fns in sync:
1139 //
1140 //  - type_of_fn
1141 //  - create_datums_for_fn_args.
1142 //  - new_fn_ctxt
1143 //  - trans_args
1144 //
1145 // Be warned! You must call `init_function` before doing anything with the
1146 // returned function context.
1147 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1148                        llfndecl: ValueRef,
1149                        id: ast::NodeId,
1150                        has_env: bool,
1151                        output_type: ty::t,
1152                        param_substs: Option<&'a param_substs>,
1153                        sp: Option<Span>,
1154                        block_arena: &'a TypedArena<Block<'a>>)
1155                        -> FunctionContext<'a> {
1156     for p in param_substs.iter() { p.validate(); }
1157
1158     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1159            if id == -1 {
1160                "".to_owned()
1161            } else {
1162                ccx.tcx.map.path_to_str(id).to_owned()
1163            },
1164            id, param_substs.map(|s| s.repr(ccx.tcx())));
1165
1166     let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1167     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1168     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1169
1170     let mut fcx = FunctionContext {
1171           llfn: llfndecl,
1172           llenv: None,
1173           llretptr: Cell::new(None),
1174           entry_bcx: RefCell::new(None),
1175           alloca_insert_pt: Cell::new(None),
1176           llreturn: Cell::new(None),
1177           personality: Cell::new(None),
1178           caller_expects_out_pointer: uses_outptr,
1179           llargs: RefCell::new(NodeMap::new()),
1180           lllocals: RefCell::new(NodeMap::new()),
1181           llupvars: RefCell::new(NodeMap::new()),
1182           id: id,
1183           param_substs: param_substs,
1184           span: sp,
1185           block_arena: block_arena,
1186           ccx: ccx,
1187           debug_context: debug_context,
1188           scopes: RefCell::new(Vec::new())
1189     };
1190
1191     if has_env {
1192         fcx.llenv = Some(unsafe {
1193             llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1194         });
1195     }
1196
1197     fcx
1198 }
1199
1200 /// Performs setup on a newly created function, creating the entry scope block
1201 /// and allocating space for the return pointer.
1202 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1203                          skip_retptr: bool,
1204                          output_type: ty::t) {
1205     let entry_bcx = fcx.new_temp_block("entry-block");
1206
1207     *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1208
1209     // Use a dummy instruction as the insertion point for all allocas.
1210     // This is later removed in FunctionContext::cleanup.
1211     fcx.alloca_insert_pt.set(Some(unsafe {
1212         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1213         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1214     }));
1215
1216     // This shouldn't need to recompute the return type,
1217     // as new_fn_ctxt did it already.
1218     let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1219
1220     if !return_type_is_void(fcx.ccx, substd_output_type) {
1221         // If the function returns nil/bot, there is no real return
1222         // value, so do not set `llretptr`.
1223         if !skip_retptr || fcx.caller_expects_out_pointer {
1224             // Otherwise, we normally allocate the llretptr, unless we
1225             // have been instructed to skip it for immediate return
1226             // values.
1227             fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1228         }
1229     }
1230 }
1231
1232 // NB: must keep 4 fns in sync:
1233 //
1234 //  - type_of_fn
1235 //  - create_datums_for_fn_args.
1236 //  - new_fn_ctxt
1237 //  - trans_args
1238
1239 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1240     use middle::trans::datum::{ByRef, ByValue};
1241
1242     datum::Rvalue {
1243         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1244     }
1245 }
1246
1247 // work around bizarre resolve errors
1248 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1249 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1250
1251 // create_datums_for_fn_args: creates rvalue datums for each of the
1252 // incoming function arguments. These will later be stored into
1253 // appropriate lvalue datums.
1254 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1255                                  arg_tys: &[ty::t])
1256                                  -> Vec<RvalueDatum> {
1257     let _icx = push_ctxt("create_datums_for_fn_args");
1258
1259     // Return an array wrapping the ValueRefs that we get from
1260     // llvm::LLVMGetParam for each argument into datums.
1261     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1262         let llarg = unsafe {
1263             llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1264         };
1265         datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1266     }).collect()
1267 }
1268
1269 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1270                             arg_scope: cleanup::CustomScopeIndex,
1271                             bcx: &'a Block<'a>,
1272                             args: &[ast::Arg],
1273                             arg_datums: Vec<RvalueDatum> )
1274                             -> &'a Block<'a> {
1275     debug!("copy_args_to_allocas");
1276
1277     let _icx = push_ctxt("copy_args_to_allocas");
1278     let mut bcx = bcx;
1279
1280     let arg_scope_id = cleanup::CustomScope(arg_scope);
1281
1282     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1283         // For certain mode/type combinations, the raw llarg values are passed
1284         // by value.  However, within the fn body itself, we want to always
1285         // have all locals and arguments be by-ref so that we can cancel the
1286         // cleanup and for better interaction with LLVM's debug info.  So, if
1287         // the argument would be passed by value, we store it into an alloca.
1288         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1289         // the event it's not truly needed.
1290
1291         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1292
1293         if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1294             debuginfo::create_argument_metadata(bcx, &args[i]);
1295         }
1296     }
1297
1298     bcx
1299 }
1300
1301 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1302 // and builds the return block.
1303 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1304                      last_bcx: &'a Block<'a>) {
1305     let _icx = push_ctxt("finish_fn");
1306
1307     let ret_cx = match fcx.llreturn.get() {
1308         Some(llreturn) => {
1309             if !last_bcx.terminated.get() {
1310                 Br(last_bcx, llreturn);
1311             }
1312             raw_block(fcx, false, llreturn)
1313         }
1314         None => last_bcx
1315     };
1316     build_return_block(fcx, ret_cx);
1317     debuginfo::clear_source_location(fcx);
1318     fcx.cleanup();
1319 }
1320
1321 // Builds the return block for a function.
1322 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1323     // Return the value if this function immediate; otherwise, return void.
1324     if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1325         return RetVoid(ret_cx);
1326     }
1327
1328     let retptr = Value(fcx.llretptr.get().unwrap());
1329     let retval = match retptr.get_dominating_store(ret_cx) {
1330         // If there's only a single store to the ret slot, we can directly return
1331         // the value that was stored and omit the store and the alloca
1332         Some(s) => {
1333             let retval = s.get_operand(0).unwrap().get();
1334             s.erase_from_parent();
1335
1336             if retptr.has_no_uses() {
1337                 retptr.erase_from_parent();
1338             }
1339
1340             retval
1341         }
1342         // Otherwise, load the return value from the ret slot
1343         None => Load(ret_cx, fcx.llretptr.get().unwrap())
1344     };
1345
1346
1347     Ret(ret_cx, retval);
1348 }
1349
1350 // trans_closure: Builds an LLVM function out of a source function.
1351 // If the function closes over its environment a closure will be
1352 // returned.
1353 pub fn trans_closure(ccx: &CrateContext,
1354                      decl: &ast::FnDecl,
1355                      body: &ast::Block,
1356                      llfndecl: ValueRef,
1357                      param_substs: Option<&param_substs>,
1358                      id: ast::NodeId,
1359                      _attributes: &[ast::Attribute],
1360                      output_type: ty::t,
1361                      maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1362     ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1363
1364     let _icx = push_ctxt("trans_closure");
1365     set_uwtable(llfndecl);
1366
1367     debug!("trans_closure(..., param_substs={})",
1368            param_substs.map(|s| s.repr(ccx.tcx())));
1369
1370     let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1371         ty::ty_closure(_) => true,
1372         _ => false
1373     };
1374
1375     let arena = TypedArena::new();
1376     let fcx = new_fn_ctxt(ccx,
1377                           llfndecl,
1378                           id,
1379                           has_env,
1380                           output_type,
1381                           param_substs.map(|s| &*s),
1382                           Some(body.span),
1383                           &arena);
1384     init_function(&fcx, false, output_type);
1385
1386     // cleanup scope for the incoming arguments
1387     let arg_scope = fcx.push_custom_cleanup_scope();
1388
1389     // Create the first basic block in the function and keep a handle on it to
1390     //  pass to finish_fn later.
1391     let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1392     let mut bcx = bcx_top;
1393     let block_ty = node_id_type(bcx, body.id);
1394
1395     // Set up arguments to the function.
1396     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1397     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1398
1399     bcx = copy_args_to_allocas(&fcx,
1400                                arg_scope,
1401                                bcx,
1402                                decl.inputs.as_slice(),
1403                                arg_datums);
1404
1405     bcx = maybe_load_env(bcx);
1406
1407     // Up until here, IR instructions for this function have explicitly not been annotated with
1408     // source code location, so we don't step into call setup code. From here on, source location
1409     // emitting should be enabled.
1410     debuginfo::start_emitting_source_locations(&fcx);
1411
1412     let dest = match fcx.llretptr.get() {
1413         Some(e) => {expr::SaveIn(e)}
1414         None => {
1415             assert!(type_is_zero_size(bcx.ccx(), block_ty))
1416             expr::Ignore
1417         }
1418     };
1419
1420     // This call to trans_block is the place where we bridge between
1421     // translation calls that don't have a return value (trans_crate,
1422     // trans_mod, trans_item, et cetera) and those that do
1423     // (trans_block, trans_expr, et cetera).
1424     bcx = controlflow::trans_block(bcx, body, dest);
1425
1426     match fcx.llreturn.get() {
1427         Some(_) => {
1428             Br(bcx, fcx.return_exit_block());
1429             fcx.pop_custom_cleanup_scope(arg_scope);
1430         }
1431         None => {
1432             // Microoptimization writ large: avoid creating a separate
1433             // llreturn basic block
1434             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1435         }
1436     };
1437
1438     // Put return block after all other blocks.
1439     // This somewhat improves single-stepping experience in debugger.
1440     unsafe {
1441         let llreturn = fcx.llreturn.get();
1442         for &llreturn in llreturn.iter() {
1443             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1444         }
1445     }
1446
1447     // Insert the mandatory first few basic blocks before lltop.
1448     finish_fn(&fcx, bcx);
1449 }
1450
1451 // trans_fn: creates an LLVM function corresponding to a source language
1452 // function.
1453 pub fn trans_fn(ccx: &CrateContext,
1454                 decl: &ast::FnDecl,
1455                 body: &ast::Block,
1456                 llfndecl: ValueRef,
1457                 param_substs: Option<&param_substs>,
1458                 id: ast::NodeId,
1459                 attrs: &[ast::Attribute]) {
1460     let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_strbuf());
1461     debug!("trans_fn(param_substs={})", param_substs.map(|s| s.repr(ccx.tcx())));
1462     let _icx = push_ctxt("trans_fn");
1463     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1464     trans_closure(ccx, decl, body, llfndecl,
1465                   param_substs, id, attrs, output_type, |bcx| bcx);
1466 }
1467
1468 pub fn trans_enum_variant(ccx: &CrateContext,
1469                           _enum_id: ast::NodeId,
1470                           variant: &ast::Variant,
1471                           _args: &[ast::VariantArg],
1472                           disr: ty::Disr,
1473                           param_substs: Option<&param_substs>,
1474                           llfndecl: ValueRef) {
1475     let _icx = push_ctxt("trans_enum_variant");
1476
1477     trans_enum_variant_or_tuple_like_struct(
1478         ccx,
1479         variant.node.id,
1480         disr,
1481         param_substs,
1482         llfndecl);
1483 }
1484
1485 pub fn trans_tuple_struct(ccx: &CrateContext,
1486                           _fields: &[ast::StructField],
1487                           ctor_id: ast::NodeId,
1488                           param_substs: Option<&param_substs>,
1489                           llfndecl: ValueRef) {
1490     let _icx = push_ctxt("trans_tuple_struct");
1491
1492     trans_enum_variant_or_tuple_like_struct(
1493         ccx,
1494         ctor_id,
1495         0,
1496         param_substs,
1497         llfndecl);
1498 }
1499
1500 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1501                                            ctor_id: ast::NodeId,
1502                                            disr: ty::Disr,
1503                                            param_substs: Option<&param_substs>,
1504                                            llfndecl: ValueRef) {
1505     let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1506     let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1507
1508     let result_ty = match ty::get(ctor_ty).sty {
1509         ty::ty_bare_fn(ref bft) => bft.sig.output,
1510         _ => ccx.sess().bug(
1511             format!("trans_enum_variant_or_tuple_like_struct: \
1512                   unexpected ctor return type {}",
1513                  ty_to_str(ccx.tcx(), ctor_ty)))
1514     };
1515
1516     let arena = TypedArena::new();
1517     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1518                           param_substs.map(|s| &*s), None, &arena);
1519     init_function(&fcx, false, result_ty);
1520
1521     let arg_tys = ty::ty_fn_args(ctor_ty);
1522
1523     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1524
1525     let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1526
1527     if !type_is_zero_size(fcx.ccx, result_ty) {
1528         let repr = adt::represent_type(ccx, result_ty);
1529         adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1530         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1531             let lldestptr = adt::trans_field_ptr(bcx,
1532                                                  &*repr,
1533                                                  fcx.llretptr.get().unwrap(),
1534                                                  disr,
1535                                                  i);
1536             arg_datum.store_to(bcx, lldestptr);
1537         }
1538     }
1539
1540     finish_fn(&fcx, bcx);
1541 }
1542
1543 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1544                   id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1545                   i: &mut uint) {
1546     for &variant in enum_definition.variants.iter() {
1547         let disr_val = vi[*i].disr_val;
1548         *i += 1;
1549
1550         match variant.node.kind {
1551             ast::TupleVariantKind(ref args) if args.len() > 0 => {
1552                 let llfn = get_item_val(ccx, variant.node.id);
1553                 trans_enum_variant(ccx, id, variant, args.as_slice(),
1554                                    disr_val, None, llfn);
1555             }
1556             ast::TupleVariantKind(_) => {
1557                 // Nothing to do.
1558             }
1559             ast::StructVariantKind(struct_def) => {
1560                 trans_struct_def(ccx, struct_def);
1561             }
1562         }
1563     }
1564 }
1565
1566 pub struct TransItemVisitor<'a> {
1567     pub ccx: &'a CrateContext,
1568 }
1569
1570 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1571     fn visit_item(&mut self, i: &ast::Item, _:()) {
1572         trans_item(self.ccx, i);
1573     }
1574 }
1575
1576 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1577     let _icx = push_ctxt("trans_item");
1578     match item.node {
1579       ast::ItemFn(decl, _fn_style, abi, ref generics, body) => {
1580         if abi != Rust  {
1581             let llfndecl = get_item_val(ccx, item.id);
1582             foreign::trans_rust_fn_with_foreign_abi(
1583                 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1584         } else if !generics.is_type_parameterized() {
1585             let llfn = get_item_val(ccx, item.id);
1586             trans_fn(ccx,
1587                      decl,
1588                      body,
1589                      llfn,
1590                      None,
1591                      item.id,
1592                      item.attrs.as_slice());
1593         } else {
1594             // Be sure to travel more than just one layer deep to catch nested
1595             // items in blocks and such.
1596             let mut v = TransItemVisitor{ ccx: ccx };
1597             v.visit_block(body, ());
1598         }
1599       }
1600       ast::ItemImpl(ref generics, _, _, ref ms) => {
1601         meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1602       }
1603       ast::ItemMod(ref m) => {
1604         trans_mod(ccx, m);
1605       }
1606       ast::ItemEnum(ref enum_definition, ref generics) => {
1607         if !generics.is_type_parameterized() {
1608             let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1609             let mut i = 0;
1610             trans_enum_def(ccx, enum_definition, item.id, vi.as_slice(), &mut i);
1611         }
1612       }
1613       ast::ItemStatic(_, m, expr) => {
1614           // Recurse on the expression to catch items in blocks
1615           let mut v = TransItemVisitor{ ccx: ccx };
1616           v.visit_expr(expr, ());
1617           consts::trans_const(ccx, m, item.id);
1618           // Do static_assert checking. It can't really be done much earlier
1619           // because we need to get the value of the bool out of LLVM
1620           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1621               if m == ast::MutMutable {
1622                   ccx.sess().span_fatal(expr.span,
1623                                         "cannot have static_assert on a mutable \
1624                                          static");
1625               }
1626
1627               let v = ccx.const_values.borrow().get_copy(&item.id);
1628               unsafe {
1629                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1630                       ccx.sess().span_fatal(expr.span, "static assertion failed");
1631                   }
1632               }
1633           }
1634       },
1635       ast::ItemForeignMod(ref foreign_mod) => {
1636         foreign::trans_foreign_mod(ccx, foreign_mod);
1637       }
1638       ast::ItemStruct(struct_def, ref generics) => {
1639         if !generics.is_type_parameterized() {
1640             trans_struct_def(ccx, struct_def);
1641         }
1642       }
1643       ast::ItemTrait(..) => {
1644         // Inside of this trait definition, we won't be actually translating any
1645         // functions, but the trait still needs to be walked. Otherwise default
1646         // methods with items will not get translated and will cause ICE's when
1647         // metadata time comes around.
1648         let mut v = TransItemVisitor{ ccx: ccx };
1649         visit::walk_item(&mut v, item, ());
1650       }
1651       _ => {/* fall through */ }
1652     }
1653 }
1654
1655 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1656     // If this is a tuple-like struct, translate the constructor.
1657     match struct_def.ctor_id {
1658         // We only need to translate a constructor if there are fields;
1659         // otherwise this is a unit-like struct.
1660         Some(ctor_id) if struct_def.fields.len() > 0 => {
1661             let llfndecl = get_item_val(ccx, ctor_id);
1662             trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1663                                ctor_id, None, llfndecl);
1664         }
1665         Some(_) | None => {}
1666     }
1667 }
1668
1669 // Translate a module. Doing this amounts to translating the items in the
1670 // module; there ends up being no artifact (aside from linkage names) of
1671 // separate modules in the compiled program.  That's because modules exist
1672 // only as a convenience for humans working with the code, to organize names
1673 // and control visibility.
1674 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1675     let _icx = push_ctxt("trans_mod");
1676     for item in m.items.iter() {
1677         trans_item(ccx, *item);
1678     }
1679 }
1680
1681 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: StrBuf, node_id: ast::NodeId,
1682                       llfn: ValueRef) {
1683     ccx.item_symbols.borrow_mut().insert(node_id, sym);
1684
1685     if !ccx.reachable.contains(&node_id) {
1686         lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1687     }
1688
1689     if is_entry_fn(ccx.sess(), node_id) {
1690         create_entry_wrapper(ccx, sp, llfn);
1691     }
1692 }
1693
1694 fn register_fn(ccx: &CrateContext,
1695                sp: Span,
1696                sym: StrBuf,
1697                node_id: ast::NodeId,
1698                node_type: ty::t)
1699                -> ValueRef {
1700     let f = match ty::get(node_type).sty {
1701         ty::ty_bare_fn(ref f) => {
1702             assert!(f.abi == Rust || f.abi == RustIntrinsic);
1703             f
1704         }
1705         _ => fail!("expected bare rust fn or an intrinsic")
1706     };
1707
1708     let llfn = decl_rust_fn(ccx,
1709                             false,
1710                             f.sig.inputs.as_slice(),
1711                             f.sig.output,
1712                             sym.as_slice());
1713     finish_register_fn(ccx, sp, sym, node_id, llfn);
1714     llfn
1715 }
1716
1717 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1718 pub fn register_fn_llvmty(ccx: &CrateContext,
1719                           sp: Span,
1720                           sym: StrBuf,
1721                           node_id: ast::NodeId,
1722                           cc: lib::llvm::CallConv,
1723                           fn_ty: Type,
1724                           output: ty::t) -> ValueRef {
1725     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1726
1727     let llfn = decl_fn(ccx.llmod, sym.as_slice(), cc, fn_ty, output);
1728     finish_register_fn(ccx, sp, sym, node_id, llfn);
1729     llfn
1730 }
1731
1732 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1733     match *sess.entry_fn.borrow() {
1734         Some((entry_id, _)) => node_id == entry_id,
1735         None => false
1736     }
1737 }
1738
1739 // Create a _rust_main(args: ~[str]) function which will be called from the
1740 // runtime rust_start function
1741 pub fn create_entry_wrapper(ccx: &CrateContext,
1742                            _sp: Span,
1743                            main_llfn: ValueRef) {
1744     let et = ccx.sess().entry_type.get().unwrap();
1745     match et {
1746         config::EntryMain => {
1747             create_entry_fn(ccx, main_llfn, true);
1748         }
1749         config::EntryStart => create_entry_fn(ccx, main_llfn, false),
1750         config::EntryNone => {}    // Do nothing.
1751     }
1752
1753     fn create_entry_fn(ccx: &CrateContext,
1754                        rust_main: ValueRef,
1755                        use_start_lang_item: bool) {
1756         let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1757                                &ccx.int_type);
1758
1759         let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1760         let llbb = "top".with_c_str(|buf| {
1761             unsafe {
1762                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1763             }
1764         });
1765         let bld = ccx.builder.b;
1766         unsafe {
1767             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1768
1769             let (start_fn, args) = if use_start_lang_item {
1770                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1771                     Ok(id) => id,
1772                     Err(s) => { ccx.sess().fatal(s.as_slice()); }
1773                 };
1774                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1775                     get_item_val(ccx, start_def_id.node)
1776                 } else {
1777                     let start_fn_type = csearch::get_type(ccx.tcx(),
1778                                                           start_def_id).ty;
1779                     trans_external_path(ccx, start_def_id, start_fn_type)
1780                 };
1781
1782                 let args = {
1783                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
1784                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1785                     });
1786
1787                     vec!(
1788                         opaque_rust_main,
1789                         llvm::LLVMGetParam(llfn, 0),
1790                         llvm::LLVMGetParam(llfn, 1)
1791                      )
1792                 };
1793                 (start_fn, args)
1794             } else {
1795                 debug!("using user-defined start fn");
1796                 let args = vec!(
1797                     llvm::LLVMGetParam(llfn, 0 as c_uint),
1798                     llvm::LLVMGetParam(llfn, 1 as c_uint)
1799                 );
1800
1801                 (rust_main, args)
1802             };
1803
1804             let result = llvm::LLVMBuildCall(bld,
1805                                              start_fn,
1806                                              args.as_ptr(),
1807                                              args.len() as c_uint,
1808                                              noname());
1809
1810             llvm::LLVMBuildRet(bld, result);
1811         }
1812     }
1813 }
1814
1815 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1816                  ty: ty::t, attrs: &[ast::Attribute]) -> StrBuf {
1817     match attr::first_attr_value_str_by_name(attrs, "export_name") {
1818         // Use provided name
1819         Some(name) => name.get().to_strbuf(),
1820
1821         _ => ccx.tcx.map.with_path(id, |mut path| {
1822             if attr::contains_name(attrs, "no_mangle") {
1823                 // Don't mangle
1824                 path.last().unwrap().to_str().to_strbuf()
1825             } else {
1826                 // Usual name mangling
1827                 mangle_exported_name(ccx, path, ty, id)
1828             }
1829         })
1830     }
1831 }
1832
1833 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1834     debug!("get_item_val(id=`{:?}`)", id);
1835
1836     match ccx.item_vals.borrow().find_copy(&id) {
1837         Some(v) => return v,
1838         None => {}
1839     }
1840
1841     let mut foreign = false;
1842     let item = ccx.tcx.map.get(id);
1843     let val = match item {
1844         ast_map::NodeItem(i) => {
1845             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1846             let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1847
1848             let v = match i.node {
1849                 ast::ItemStatic(_, _, expr) => {
1850                     // If this static came from an external crate, then
1851                     // we need to get the symbol from csearch instead of
1852                     // using the current crate's name/version
1853                     // information in the hash of the symbol
1854                     debug!("making {}", sym);
1855                     let (sym, is_local) = {
1856                         match ccx.external_srcs.borrow().find(&i.id) {
1857                             Some(&did) => {
1858                                 debug!("but found in other crate...");
1859                                 (csearch::get_symbol(&ccx.sess().cstore,
1860                                                      did), false)
1861                             }
1862                             None => (sym, true)
1863                         }
1864                     };
1865
1866                     // We need the translated value here, because for enums the
1867                     // LLVM type is not fully determined by the Rust type.
1868                     let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1869                     ccx.const_values.borrow_mut().insert(id, v);
1870                     let mut inlineable = inlineable;
1871
1872                     unsafe {
1873                         let llty = llvm::LLVMTypeOf(v);
1874                         let g = sym.as_slice().with_c_str(|buf| {
1875                             llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1876                         });
1877
1878                         if !ccx.reachable.contains(&id) {
1879                             lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1880                         }
1881
1882                         // Apply the `unnamed_addr` attribute if
1883                         // requested
1884                         if attr::contains_name(i.attrs.as_slice(),
1885                                                "address_insignificant") {
1886                             if ccx.reachable.contains(&id) {
1887                                 ccx.sess().span_bug(i.span,
1888                                     "insignificant static is reachable");
1889                             }
1890                             lib::llvm::SetUnnamedAddr(g, true);
1891
1892                             // This is a curious case where we must make
1893                             // all of these statics inlineable. If a
1894                             // global is tagged as
1895                             // address_insignificant, then LLVM won't
1896                             // coalesce globals unless they have an
1897                             // internal linkage type. This means that
1898                             // external crates cannot use this global.
1899                             // This is a problem for things like inner
1900                             // statics in generic functions, because the
1901                             // function will be inlined into another
1902                             // crate and then attempt to link to the
1903                             // static in the original crate, only to
1904                             // find that it's not there. On the other
1905                             // side of inlininig, the crates knows to
1906                             // not declare this static as
1907                             // available_externally (because it isn't)
1908                             inlineable = true;
1909                         }
1910
1911                         if attr::contains_name(i.attrs.as_slice(),
1912                                                "thread_local") {
1913                             lib::llvm::set_thread_local(g, true);
1914                         }
1915
1916                         if !inlineable {
1917                             debug!("{} not inlined", sym);
1918                             ccx.non_inlineable_statics.borrow_mut()
1919                                                       .insert(id);
1920                         }
1921
1922                         ccx.item_symbols.borrow_mut().insert(i.id, sym);
1923                         g
1924                     }
1925                 }
1926
1927                 ast::ItemFn(_, _, abi, _, _) => {
1928                     let llfn = if abi == Rust {
1929                         register_fn(ccx, i.span, sym, i.id, ty)
1930                     } else {
1931                         foreign::register_rust_fn_with_foreign_abi(ccx,
1932                                                                    i.span,
1933                                                                    sym,
1934                                                                    i.id)
1935                     };
1936                     set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
1937                     llfn
1938                 }
1939
1940                 _ => fail!("get_item_val: weird result in table")
1941             };
1942
1943             match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
1944                                                      "link_section") {
1945                 Some(sect) => unsafe {
1946                     sect.get().with_c_str(|buf| {
1947                         llvm::LLVMSetSection(v, buf);
1948                     })
1949                 },
1950                 None => ()
1951             }
1952
1953             v
1954         }
1955
1956         ast_map::NodeTraitMethod(trait_method) => {
1957             debug!("get_item_val(): processing a NodeTraitMethod");
1958             match *trait_method {
1959                 ast::Required(_) => {
1960                     ccx.sess().bug("unexpected variant: required trait method in \
1961                                    get_item_val()");
1962                 }
1963                 ast::Provided(m) => {
1964                     register_method(ccx, id, m)
1965                 }
1966             }
1967         }
1968
1969         ast_map::NodeMethod(m) => {
1970             register_method(ccx, id, m)
1971         }
1972
1973         ast_map::NodeForeignItem(ni) => {
1974             foreign = true;
1975
1976             match ni.node {
1977                 ast::ForeignItemFn(..) => {
1978                     let abi = ccx.tcx.map.get_foreign_abi(id);
1979                     foreign::register_foreign_item_fn(ccx, abi, ni)
1980                 }
1981                 ast::ForeignItemStatic(..) => {
1982                     foreign::register_static(ccx, ni)
1983                 }
1984             }
1985         }
1986
1987         ast_map::NodeVariant(ref v) => {
1988             let llfn;
1989             let args = match v.node.kind {
1990                 ast::TupleVariantKind(ref args) => args,
1991                 ast::StructVariantKind(_) => {
1992                     fail!("struct variant kind unexpected in get_item_val")
1993                 }
1994             };
1995             assert!(args.len() != 0u);
1996             let ty = ty::node_id_to_type(ccx.tcx(), id);
1997             let parent = ccx.tcx.map.get_parent(id);
1998             let enm = ccx.tcx.map.expect_item(parent);
1999             let sym = exported_name(ccx,
2000                                     id,
2001                                     ty,
2002                                     enm.attrs.as_slice());
2003
2004             llfn = match enm.node {
2005                 ast::ItemEnum(_, _) => {
2006                     register_fn(ccx, (*v).span, sym, id, ty)
2007                 }
2008                 _ => fail!("NodeVariant, shouldn't happen")
2009             };
2010             set_inline_hint(llfn);
2011             llfn
2012         }
2013
2014         ast_map::NodeStructCtor(struct_def) => {
2015             // Only register the constructor if this is a tuple-like struct.
2016             let ctor_id = match struct_def.ctor_id {
2017                 None => {
2018                     ccx.sess().bug("attempt to register a constructor of \
2019                                     a non-tuple-like struct")
2020                 }
2021                 Some(ctor_id) => ctor_id,
2022             };
2023             let parent = ccx.tcx.map.get_parent(id);
2024             let struct_item = ccx.tcx.map.expect_item(parent);
2025             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2026             let sym = exported_name(ccx,
2027                                     id,
2028                                     ty,
2029                                     struct_item.attrs
2030                                                .as_slice());
2031             let llfn = register_fn(ccx, struct_item.span,
2032                                    sym, ctor_id, ty);
2033             set_inline_hint(llfn);
2034             llfn
2035         }
2036
2037         ref variant => {
2038             ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2039                            variant))
2040         }
2041     };
2042
2043     // foreign items (extern fns and extern statics) don't have internal
2044     // linkage b/c that doesn't quite make sense. Otherwise items can
2045     // have internal linkage if they're not reachable.
2046     if !foreign && !ccx.reachable.contains(&id) {
2047         lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2048     }
2049
2050     ccx.item_vals.borrow_mut().insert(id, val);
2051     val
2052 }
2053
2054 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2055                    m: &ast::Method) -> ValueRef {
2056     let mty = ty::node_id_to_type(ccx.tcx(), id);
2057
2058     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2059
2060     let llfn = register_fn(ccx, m.span, sym, id, mty);
2061     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2062     llfn
2063 }
2064
2065 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2066     unsafe {
2067         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2068     }
2069 }
2070
2071 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2072     -> encoder::EncodeParams<'r> {
2073         encoder::EncodeParams {
2074             diag: cx.sess().diagnostic(),
2075             tcx: cx.tcx(),
2076             reexports2: &cx.exp_map2,
2077             item_symbols: &cx.item_symbols,
2078             non_inlineable_statics: &cx.non_inlineable_statics,
2079             link_meta: &cx.link_meta,
2080             cstore: &cx.sess().cstore,
2081             encode_inlined_item: ie,
2082         }
2083 }
2084
2085 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2086     use flate;
2087
2088     let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2089         *ty != config::CrateTypeExecutable
2090     });
2091     if !any_library {
2092         return Vec::new()
2093     }
2094
2095     let encode_inlined_item: encoder::EncodeInlinedItem =
2096         |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2097
2098     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2099     let metadata = encoder::encode_metadata(encode_parms, krate);
2100     let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2101                      .append(match flate::deflate_bytes(metadata.as_slice()) {
2102                          Some(compressed) => compressed,
2103                          None => cx.sess().fatal(format!("failed to compress metadata"))
2104                      }.as_slice());
2105     let llmeta = C_bytes(cx, compressed.as_slice());
2106     let llconst = C_struct(cx, [llmeta], false);
2107     let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2108                        cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2109     let llglobal = name.with_c_str(|buf| {
2110         unsafe {
2111             llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2112         }
2113     });
2114     unsafe {
2115         llvm::LLVMSetInitializer(llglobal, llconst);
2116         cx.sess()
2117           .targ_cfg
2118           .target_strs
2119           .meta_sect_name
2120           .as_slice()
2121           .with_c_str(|buf| {
2122             llvm::LLVMSetSection(llglobal, buf)
2123         });
2124     }
2125     return metadata;
2126 }
2127
2128 pub fn trans_crate(krate: ast::Crate,
2129                    analysis: CrateAnalysis,
2130                    output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2131     let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, .. } = analysis;
2132
2133     // Before we touch LLVM, make sure that multithreading is enabled.
2134     unsafe {
2135         use sync::one::{Once, ONCE_INIT};
2136         static mut INIT: Once = ONCE_INIT;
2137         static mut POISONED: bool = false;
2138         INIT.doit(|| {
2139             if llvm::LLVMStartMultithreaded() != 1 {
2140                 // use an extra bool to make sure that all future usage of LLVM
2141                 // cannot proceed despite the Once not running more than once.
2142                 POISONED = true;
2143             }
2144         });
2145
2146         if POISONED {
2147             tcx.sess.bug("couldn't enable multi-threaded LLVM");
2148         }
2149     }
2150
2151     let link_meta = link::build_link_meta(&krate,
2152                                           output.out_filestem.as_slice());
2153
2154     // Append ".rs" to crate name as LLVM module identifier.
2155     //
2156     // LLVM code generator emits a ".file filename" directive
2157     // for ELF backends. Value of the "filename" is set as the
2158     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2159     // crashes if the module identifer is same as other symbols
2160     // such as a function name in the module.
2161     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2162     let mut llmod_id = link_meta.crateid.name.clone();
2163     llmod_id.push_str(".rs");
2164
2165     let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2166                                 Sha256::new(), link_meta, reachable);
2167     {
2168         let _icx = push_ctxt("text");
2169         trans_mod(&ccx, &krate.module);
2170     }
2171
2172     glue::emit_tydescs(&ccx);
2173     if ccx.sess().opts.debuginfo != NoDebugInfo {
2174         debuginfo::finalize(&ccx);
2175     }
2176
2177     // Translate the metadata.
2178     let metadata = write_metadata(&ccx, &krate);
2179     if ccx.sess().trans_stats() {
2180         println!("--- trans stats ---");
2181         println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2182         println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2183         println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2184         println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2185
2186         println!("n_fns: {}", ccx.stats.n_fns.get());
2187         println!("n_monos: {}", ccx.stats.n_monos.get());
2188         println!("n_inlines: {}", ccx.stats.n_inlines.get());
2189         println!("n_closures: {}", ccx.stats.n_closures.get());
2190         println!("fn stats:");
2191         ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2192             insns_b.cmp(&insns_a)
2193         });
2194         for tuple in ccx.stats.fn_stats.borrow().iter() {
2195             match *tuple {
2196                 (ref name, ms, insns) => {
2197                     println!("{} insns, {} ms, {}", insns, ms, *name);
2198                 }
2199             }
2200         }
2201     }
2202     if ccx.sess().count_llvm_insns() {
2203         for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2204             println!("{:7u} {}", *v, *k);
2205         }
2206     }
2207
2208     let llcx = ccx.llcx;
2209     let link_meta = ccx.link_meta.clone();
2210     let llmod = ccx.llmod;
2211
2212     let mut reachable: Vec<StrBuf> = ccx.reachable.iter().filter_map(|id| {
2213         ccx.item_symbols.borrow().find(id).map(|s| s.to_strbuf())
2214     }).collect();
2215
2216     // Make sure that some other crucial symbols are not eliminated from the
2217     // module. This includes the main function, the crate map (used for debug
2218     // log settings and I/O), and finally the curious rust_stack_exhausted
2219     // symbol. This symbol is required for use by the libmorestack library that
2220     // we link in, so we must ensure that this symbol is not internalized (if
2221     // defined in the crate).
2222     reachable.push("main".to_strbuf());
2223     reachable.push("rust_stack_exhausted".to_strbuf());
2224
2225     // referenced from .eh_frame section on some platforms
2226     reachable.push("rust_eh_personality".to_strbuf());
2227     // referenced from rt/rust_try.ll
2228     reachable.push("rust_eh_personality_catch".to_strbuf());
2229
2230     let metadata_module = ccx.metadata_llmod;
2231     let formats = ccx.tcx.dependency_formats.borrow().clone();
2232
2233     (ccx.tcx, CrateTranslation {
2234         context: llcx,
2235         module: llmod,
2236         link: link_meta,
2237         metadata_module: metadata_module,
2238         metadata: metadata,
2239         reachable: reachable,
2240         crate_formats: formats,
2241     })
2242 }