]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/context.rs
Auto merge of #35915 - llogiq:rfc-1623, r=nikomatsakis
[rust.git] / src / librustc_trans / context.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use llvm;
12 use llvm::{ContextRef, ModuleRef, ValueRef, BuilderRef};
13 use rustc::dep_graph::{DepNode, DepTrackingMap, DepTrackingMapConfig, WorkProduct};
14 use middle::cstore::LinkMeta;
15 use rustc::hir::def::ExportMap;
16 use rustc::hir::def_id::DefId;
17 use rustc::traits;
18 use rustc::mir::mir_map::MirMap;
19 use rustc::mir::repr as mir;
20 use adt;
21 use base;
22 use builder::Builder;
23 use common::BuilderRef_res;
24 use debuginfo;
25 use declare;
26 use glue::DropGlueKind;
27 use mir::CachedMir;
28 use monomorphize::Instance;
29
30 use partitioning::CodegenUnit;
31 use trans_item::TransItem;
32 use type_::{Type, TypeNames};
33 use rustc::ty::subst::Substs;
34 use rustc::ty::{self, Ty, TyCtxt};
35 use session::config::NoDebugInfo;
36 use session::Session;
37 use session::config;
38 use symbol_map::SymbolMap;
39 use util::sha2::Sha256;
40 use util::nodemap::{NodeSet, DefIdMap, FnvHashMap, FnvHashSet};
41
42 use std::ffi::{CStr, CString};
43 use std::cell::{Cell, RefCell};
44 use std::marker::PhantomData;
45 use std::ptr;
46 use std::rc::Rc;
47 use std::str;
48 use syntax::ast;
49 use syntax::parse::token::InternedString;
50 use abi::FnType;
51
52 pub struct Stats {
53     pub n_glues_created: Cell<usize>,
54     pub n_null_glues: Cell<usize>,
55     pub n_real_glues: Cell<usize>,
56     pub n_fns: Cell<usize>,
57     pub n_inlines: Cell<usize>,
58     pub n_closures: Cell<usize>,
59     pub n_llvm_insns: Cell<usize>,
60     pub llvm_insns: RefCell<FnvHashMap<String, usize>>,
61     // (ident, llvm-instructions)
62     pub fn_stats: RefCell<Vec<(String, usize)> >,
63 }
64
65 /// The shared portion of a `CrateContext`.  There is one `SharedCrateContext`
66 /// per crate.  The data here is shared between all compilation units of the
67 /// crate, so it must not contain references to any LLVM data structures
68 /// (aside from metadata-related ones).
69 pub struct SharedCrateContext<'a, 'tcx: 'a> {
70     metadata_llmod: ModuleRef,
71     metadata_llcx: ContextRef,
72
73     export_map: ExportMap,
74     reachable: NodeSet,
75     link_meta: LinkMeta,
76     symbol_hasher: RefCell<Sha256>,
77     tcx: TyCtxt<'a, 'tcx, 'tcx>,
78     stats: Stats,
79     check_overflow: bool,
80     mir_map: &'a MirMap<'tcx>,
81     mir_cache: RefCell<DepTrackingMap<MirCache<'tcx>>>,
82
83     use_dll_storage_attrs: bool,
84
85     translation_items: RefCell<FnvHashSet<TransItem<'tcx>>>,
86     trait_cache: RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>>,
87     project_cache: RefCell<DepTrackingMap<ProjectionCache<'tcx>>>,
88 }
89
90 /// The local portion of a `CrateContext`.  There is one `LocalCrateContext`
91 /// per compilation unit.  Each one has its own LLVM `ContextRef` so that
92 /// several compilation units may be optimized in parallel.  All other LLVM
93 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
94 pub struct LocalCrateContext<'tcx> {
95     llmod: ModuleRef,
96     llcx: ContextRef,
97     previous_work_product: Option<WorkProduct>,
98     tn: TypeNames, // FIXME: This seems to be largely unused.
99     codegen_unit: CodegenUnit<'tcx>,
100     needs_unwind_cleanup_cache: RefCell<FnvHashMap<Ty<'tcx>, bool>>,
101     fn_pointer_shims: RefCell<FnvHashMap<Ty<'tcx>, ValueRef>>,
102     drop_glues: RefCell<FnvHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>>,
103     /// Cache instances of monomorphic and polymorphic items
104     instances: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
105     /// Cache generated vtables
106     vtables: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>>,
107     /// Cache of constant strings,
108     const_cstr_cache: RefCell<FnvHashMap<InternedString, ValueRef>>,
109
110     /// Reverse-direction for const ptrs cast from globals.
111     /// Key is a ValueRef holding a *T,
112     /// Val is a ValueRef holding a *[T].
113     ///
114     /// Needed because LLVM loses pointer->pointee association
115     /// when we ptrcast, and we have to ptrcast during translation
116     /// of a [T] const because we form a slice, a (*T,usize) pair, not
117     /// a pointer to an LLVM array type. Similar for trait objects.
118     const_unsized: RefCell<FnvHashMap<ValueRef, ValueRef>>,
119
120     /// Cache of emitted const globals (value -> global)
121     const_globals: RefCell<FnvHashMap<ValueRef, ValueRef>>,
122
123     /// Cache of emitted const values
124     const_values: RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
125
126     /// Cache of external const values
127     extern_const_values: RefCell<DefIdMap<ValueRef>>,
128
129     /// Mapping from static definitions to their DefId's.
130     statics: RefCell<FnvHashMap<ValueRef, DefId>>,
131
132     impl_method_cache: RefCell<FnvHashMap<(DefId, ast::Name), DefId>>,
133
134     /// Cache of closure wrappers for bare fn's.
135     closure_bare_wrapper_cache: RefCell<FnvHashMap<ValueRef, ValueRef>>,
136
137     /// List of globals for static variables which need to be passed to the
138     /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete.
139     /// (We have to make sure we don't invalidate any ValueRefs referring
140     /// to constants.)
141     statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
142
143     lltypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
144     llsizingtypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
145     adt_reprs: RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>>,
146     type_hashcodes: RefCell<FnvHashMap<Ty<'tcx>, String>>,
147     int_type: Type,
148     opaque_vec_type: Type,
149     builder: BuilderRef_res,
150
151     /// Holds the LLVM values for closure IDs.
152     closure_vals: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
153
154     dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
155
156     eh_personality: Cell<Option<ValueRef>>,
157     eh_unwind_resume: Cell<Option<ValueRef>>,
158     rust_try_fn: Cell<Option<ValueRef>>,
159
160     intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
161
162     /// Number of LLVM instructions translated into this `LocalCrateContext`.
163     /// This is used to perform some basic load-balancing to keep all LLVM
164     /// contexts around the same size.
165     n_llvm_insns: Cell<usize>,
166
167     /// Depth of the current type-of computation - used to bail out
168     type_of_depth: Cell<usize>,
169
170     symbol_map: Rc<SymbolMap<'tcx>>,
171 }
172
173 // Implement DepTrackingMapConfig for `trait_cache`
174 pub struct TraitSelectionCache<'tcx> {
175     data: PhantomData<&'tcx ()>
176 }
177
178 impl<'tcx> DepTrackingMapConfig for TraitSelectionCache<'tcx> {
179     type Key = ty::PolyTraitRef<'tcx>;
180     type Value = traits::Vtable<'tcx, ()>;
181     fn to_dep_node(key: &ty::PolyTraitRef<'tcx>) -> DepNode<DefId> {
182         key.to_poly_trait_predicate().dep_node()
183     }
184 }
185
186 // Cache for mir loaded from metadata
187 struct MirCache<'tcx> {
188     data: PhantomData<&'tcx ()>
189 }
190
191 impl<'tcx> DepTrackingMapConfig for MirCache<'tcx> {
192     type Key = DefId;
193     type Value = Rc<mir::Mir<'tcx>>;
194     fn to_dep_node(key: &DefId) -> DepNode<DefId> {
195         DepNode::Mir(*key)
196     }
197 }
198
199 // # Global Cache
200
201 pub struct ProjectionCache<'gcx> {
202     data: PhantomData<&'gcx ()>
203 }
204
205 impl<'gcx> DepTrackingMapConfig for ProjectionCache<'gcx> {
206     type Key = Ty<'gcx>;
207     type Value = Ty<'gcx>;
208     fn to_dep_node(key: &Self::Key) -> DepNode<DefId> {
209         // Ideally, we'd just put `key` into the dep-node, but we
210         // can't put full types in there. So just collect up all the
211         // def-ids of structs/enums as well as any traits that we
212         // project out of. It doesn't matter so much what we do here,
213         // except that if we are too coarse, we'll create overly
214         // coarse edges between impls and the trans. For example, if
215         // we just used the def-id of things we are projecting out of,
216         // then the key for `<Foo as SomeTrait>::T` and `<Bar as
217         // SomeTrait>::T` would both share a dep-node
218         // (`TraitSelect(SomeTrait)`), and hence the impls for both
219         // `Foo` and `Bar` would be considered inputs. So a change to
220         // `Bar` would affect things that just normalized `Foo`.
221         // Anyway, this heuristic is not ideal, but better than
222         // nothing.
223         let def_ids: Vec<DefId> =
224             key.walk()
225                .filter_map(|t| match t.sty {
226                    ty::TyStruct(adt_def, _) |
227                    ty::TyEnum(adt_def, _) =>
228                        Some(adt_def.did),
229                    ty::TyProjection(ref proj) =>
230                        Some(proj.trait_ref.def_id),
231                    _ =>
232                        None
233                })
234                .collect();
235         DepNode::TraitSelect(def_ids)
236     }
237 }
238
239 /// This list owns a number of LocalCrateContexts and binds them to their common
240 /// SharedCrateContext. This type just exists as a convenience, something to
241 /// pass around all LocalCrateContexts with and get an iterator over them.
242 pub struct CrateContextList<'a, 'tcx: 'a> {
243     shared: &'a SharedCrateContext<'a, 'tcx>,
244     local_ccxs: Vec<LocalCrateContext<'tcx>>,
245 }
246
247 impl<'a, 'tcx: 'a> CrateContextList<'a, 'tcx> {
248     pub fn new(shared_ccx: &'a SharedCrateContext<'a, 'tcx>,
249                codegen_units: Vec<CodegenUnit<'tcx>>,
250                previous_work_products: Vec<Option<WorkProduct>>,
251                symbol_map: Rc<SymbolMap<'tcx>>)
252                -> CrateContextList<'a, 'tcx> {
253         CrateContextList {
254             shared: shared_ccx,
255             local_ccxs: codegen_units.into_iter().zip(previous_work_products).map(|(cgu, wp)| {
256                 LocalCrateContext::new(shared_ccx, cgu, wp, symbol_map.clone())
257             }).collect()
258         }
259     }
260
261     /// Iterate over all crate contexts, whether or not they need
262     /// translation.  That is, whether or not a `.o` file is available
263     /// for re-use from a previous incr. comp.).
264     pub fn iter_all<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
265         CrateContextIterator {
266             shared: self.shared,
267             index: 0,
268             local_ccxs: &self.local_ccxs[..],
269             filter_to_previous_work_product_unavail: false,
270         }
271     }
272
273     /// Iterator over all CCX that need translation (cannot reuse results from
274     /// previous incr. comp.).
275     pub fn iter_need_trans<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
276         CrateContextIterator {
277             shared: self.shared,
278             index: 0,
279             local_ccxs: &self.local_ccxs[..],
280             filter_to_previous_work_product_unavail: true,
281         }
282     }
283
284     pub fn shared(&self) -> &'a SharedCrateContext<'a, 'tcx> {
285         self.shared
286     }
287 }
288
289 /// A CrateContext value binds together one LocalCrateContext with the
290 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
291 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
292 pub struct CrateContext<'a, 'tcx: 'a> {
293     shared: &'a SharedCrateContext<'a, 'tcx>,
294     local_ccxs: &'a [LocalCrateContext<'tcx>],
295     /// The index of `local` in `local_ccxs`.  This is used in
296     /// `maybe_iter(true)` to identify the original `LocalCrateContext`.
297     index: usize,
298 }
299
300 pub struct CrateContextIterator<'a, 'tcx: 'a> {
301     shared: &'a SharedCrateContext<'a, 'tcx>,
302     local_ccxs: &'a [LocalCrateContext<'tcx>],
303     index: usize,
304
305     /// if true, only return results where `previous_work_product` is none
306     filter_to_previous_work_product_unavail: bool,
307 }
308
309 impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> {
310     type Item = CrateContext<'a, 'tcx>;
311
312     fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> {
313         loop {
314             if self.index >= self.local_ccxs.len() {
315                 return None;
316             }
317
318             let index = self.index;
319             self.index += 1;
320
321             let ccx = CrateContext {
322                 shared: self.shared,
323                 index: index,
324                 local_ccxs: self.local_ccxs,
325             };
326
327             if
328                 self.filter_to_previous_work_product_unavail &&
329                 ccx.previous_work_product().is_some()
330             {
331                 continue;
332             }
333
334             return Some(ccx);
335         }
336     }
337 }
338
339 /// The iterator produced by `CrateContext::maybe_iter`.
340 pub struct CrateContextMaybeIterator<'a, 'tcx: 'a> {
341     shared: &'a SharedCrateContext<'a, 'tcx>,
342     local_ccxs: &'a [LocalCrateContext<'tcx>],
343     index: usize,
344     single: bool,
345     origin: usize,
346 }
347
348 impl<'a, 'tcx> Iterator for CrateContextMaybeIterator<'a, 'tcx> {
349     type Item = (CrateContext<'a, 'tcx>, bool);
350
351     fn next(&mut self) -> Option<(CrateContext<'a, 'tcx>, bool)> {
352         if self.index >= self.local_ccxs.len() {
353             return None;
354         }
355
356         let index = self.index;
357         self.index += 1;
358         if self.single {
359             self.index = self.local_ccxs.len();
360         }
361
362         let ccx = CrateContext {
363             shared: self.shared,
364             index: index,
365             local_ccxs: self.local_ccxs
366         };
367         Some((ccx, index == self.origin))
368     }
369 }
370
371 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
372     let reloc_model_arg = match sess.opts.cg.relocation_model {
373         Some(ref s) => &s[..],
374         None => &sess.target.target.options.relocation_model[..],
375     };
376
377     match ::back::write::RELOC_MODEL_ARGS.iter().find(
378         |&&arg| arg.0 == reloc_model_arg) {
379         Some(x) => x.1,
380         _ => {
381             sess.err(&format!("{:?} is not a valid relocation mode",
382                              sess.opts
383                                  .cg
384                                  .code_model));
385             sess.abort_if_errors();
386             bug!();
387         }
388     }
389 }
390
391 fn is_any_library(sess: &Session) -> bool {
392     sess.crate_types.borrow().iter().any(|ty| {
393         *ty != config::CrateTypeExecutable
394     })
395 }
396
397 pub fn is_pie_binary(sess: &Session) -> bool {
398     !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
399 }
400
401 unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
402     let llcx = llvm::LLVMContextCreate();
403     let mod_name = CString::new(mod_name).unwrap();
404     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
405
406     // Ensure the data-layout values hardcoded remain the defaults.
407     if sess.target.target.options.is_builtin {
408         let tm = ::back::write::create_target_machine(sess);
409         llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
410         llvm::LLVMRustDisposeTargetMachine(tm);
411
412         let data_layout = llvm::LLVMGetDataLayout(llmod);
413         let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
414             .ok().expect("got a non-UTF8 data-layout from LLVM");
415
416         // Unfortunately LLVM target specs change over time, and right now we
417         // don't have proper support to work with any more than one
418         // `data_layout` than the one that is in the rust-lang/rust repo. If
419         // this compiler is configured against a custom LLVM, we may have a
420         // differing data layout, even though we should update our own to use
421         // that one.
422         //
423         // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
424         // disable this check entirely as we may be configured with something
425         // that has a different target layout.
426         //
427         // Unsure if this will actually cause breakage when rustc is configured
428         // as such.
429         //
430         // FIXME(#34960)
431         let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
432         let custom_llvm_used = cfg_llvm_root.trim() != "";
433
434         if !custom_llvm_used && sess.target.target.data_layout != data_layout {
435             bug!("data-layout for builtin `{}` target, `{}`, \
436                   differs from LLVM default, `{}`",
437                  sess.target.target.llvm_target,
438                  sess.target.target.data_layout,
439                  data_layout);
440         }
441     }
442
443     let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
444     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
445
446     let llvm_target = sess.target.target.llvm_target.as_bytes();
447     let llvm_target = CString::new(llvm_target).unwrap();
448     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
449
450     if is_pie_binary(sess) {
451         llvm::LLVMRustSetModulePIELevel(llmod);
452     }
453
454     (llcx, llmod)
455 }
456
457 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
458     pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
459                mir_map: &'b MirMap<'tcx>,
460                export_map: ExportMap,
461                symbol_hasher: Sha256,
462                link_meta: LinkMeta,
463                reachable: NodeSet,
464                check_overflow: bool)
465                -> SharedCrateContext<'b, 'tcx> {
466         let (metadata_llcx, metadata_llmod) = unsafe {
467             create_context_and_module(&tcx.sess, "metadata")
468         };
469
470         // An interesting part of Windows which MSVC forces our hand on (and
471         // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
472         // attributes in LLVM IR as well as native dependencies (in C these
473         // correspond to `__declspec(dllimport)`).
474         //
475         // Whenever a dynamic library is built by MSVC it must have its public
476         // interface specified by functions tagged with `dllexport` or otherwise
477         // they're not available to be linked against. This poses a few problems
478         // for the compiler, some of which are somewhat fundamental, but we use
479         // the `use_dll_storage_attrs` variable below to attach the `dllexport`
480         // attribute to all LLVM functions that are reachable (e.g. they're
481         // already tagged with external linkage). This is suboptimal for a few
482         // reasons:
483         //
484         // * If an object file will never be included in a dynamic library,
485         //   there's no need to attach the dllexport attribute. Most object
486         //   files in Rust are not destined to become part of a dll as binaries
487         //   are statically linked by default.
488         // * If the compiler is emitting both an rlib and a dylib, the same
489         //   source object file is currently used but with MSVC this may be less
490         //   feasible. The compiler may be able to get around this, but it may
491         //   involve some invasive changes to deal with this.
492         //
493         // The flipside of this situation is that whenever you link to a dll and
494         // you import a function from it, the import should be tagged with
495         // `dllimport`. At this time, however, the compiler does not emit
496         // `dllimport` for any declarations other than constants (where it is
497         // required), which is again suboptimal for even more reasons!
498         //
499         // * Calling a function imported from another dll without using
500         //   `dllimport` causes the linker/compiler to have extra overhead (one
501         //   `jmp` instruction on x86) when calling the function.
502         // * The same object file may be used in different circumstances, so a
503         //   function may be imported from a dll if the object is linked into a
504         //   dll, but it may be just linked against if linked into an rlib.
505         // * The compiler has no knowledge about whether native functions should
506         //   be tagged dllimport or not.
507         //
508         // For now the compiler takes the perf hit (I do not have any numbers to
509         // this effect) by marking very little as `dllimport` and praying the
510         // linker will take care of everything. Fixing this problem will likely
511         // require adding a few attributes to Rust itself (feature gated at the
512         // start) and then strongly recommending static linkage on MSVC!
513         let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
514
515         SharedCrateContext {
516             metadata_llmod: metadata_llmod,
517             metadata_llcx: metadata_llcx,
518             export_map: export_map,
519             reachable: reachable,
520             link_meta: link_meta,
521             symbol_hasher: RefCell::new(symbol_hasher),
522             tcx: tcx,
523             mir_map: mir_map,
524             mir_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
525             stats: Stats {
526                 n_glues_created: Cell::new(0),
527                 n_null_glues: Cell::new(0),
528                 n_real_glues: Cell::new(0),
529                 n_fns: Cell::new(0),
530                 n_inlines: Cell::new(0),
531                 n_closures: Cell::new(0),
532                 n_llvm_insns: Cell::new(0),
533                 llvm_insns: RefCell::new(FnvHashMap()),
534                 fn_stats: RefCell::new(Vec::new()),
535             },
536             check_overflow: check_overflow,
537             use_dll_storage_attrs: use_dll_storage_attrs,
538             translation_items: RefCell::new(FnvHashSet()),
539             trait_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
540             project_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
541         }
542     }
543
544     pub fn metadata_llmod(&self) -> ModuleRef {
545         self.metadata_llmod
546     }
547
548     pub fn metadata_llcx(&self) -> ContextRef {
549         self.metadata_llcx
550     }
551
552     pub fn export_map<'a>(&'a self) -> &'a ExportMap {
553         &self.export_map
554     }
555
556     pub fn reachable<'a>(&'a self) -> &'a NodeSet {
557         &self.reachable
558     }
559
560     pub fn trait_cache(&self) -> &RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>> {
561         &self.trait_cache
562     }
563
564     pub fn project_cache(&self) -> &RefCell<DepTrackingMap<ProjectionCache<'tcx>>> {
565         &self.project_cache
566     }
567
568     pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
569         &self.link_meta
570     }
571
572     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
573         self.tcx
574     }
575
576     pub fn sess<'a>(&'a self) -> &'a Session {
577         &self.tcx.sess
578     }
579
580     pub fn stats<'a>(&'a self) -> &'a Stats {
581         &self.stats
582     }
583
584     pub fn use_dll_storage_attrs(&self) -> bool {
585         self.use_dll_storage_attrs
586     }
587
588     pub fn get_mir(&self, def_id: DefId) -> Option<CachedMir<'b, 'tcx>> {
589         if def_id.is_local() {
590             self.mir_map.map.get(&def_id).map(CachedMir::Ref)
591         } else {
592             if let Some(mir) = self.mir_cache.borrow().get(&def_id).cloned() {
593                 return Some(CachedMir::Owned(mir));
594             }
595
596             let mir = self.sess().cstore.maybe_get_item_mir(self.tcx, def_id);
597             let cached = mir.map(Rc::new);
598             if let Some(ref mir) = cached {
599                 self.mir_cache.borrow_mut().insert(def_id, mir.clone());
600             }
601             cached.map(CachedMir::Owned)
602         }
603     }
604
605     pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
606         &self.translation_items
607     }
608
609     /// Given the def-id of some item that has no type parameters, make
610     /// a suitable "empty substs" for it.
611     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
612         Substs::for_item(self.tcx(), item_def_id,
613                          |_, _| self.tcx().mk_region(ty::ReErased),
614                          |_, _| {
615             bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
616         })
617     }
618
619     pub fn symbol_hasher(&self) -> &RefCell<Sha256> {
620         &self.symbol_hasher
621     }
622
623     pub fn mir_map(&self) -> &MirMap<'tcx> {
624         &self.mir_map
625     }
626
627     pub fn metadata_symbol_name(&self) -> String {
628         format!("rust_metadata_{}_{}",
629                 self.link_meta().crate_name,
630                 self.link_meta().crate_hash)
631     }
632 }
633
634 impl<'tcx> LocalCrateContext<'tcx> {
635     fn new<'a>(shared: &SharedCrateContext<'a, 'tcx>,
636                codegen_unit: CodegenUnit<'tcx>,
637                previous_work_product: Option<WorkProduct>,
638                symbol_map: Rc<SymbolMap<'tcx>>)
639            -> LocalCrateContext<'tcx> {
640         unsafe {
641             // Append ".rs" to LLVM module identifier.
642             //
643             // LLVM code generator emits a ".file filename" directive
644             // for ELF backends. Value of the "filename" is set as the
645             // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
646             // crashes if the module identifier is same as other symbols
647             // such as a function name in the module.
648             // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
649             let llmod_id = format!("{}.rs", codegen_unit.name());
650
651             let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
652                                                           &llmod_id[..]);
653
654             let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
655                 let dctx = debuginfo::CrateDebugContext::new(llmod);
656                 debuginfo::metadata::compile_unit_metadata(shared, &dctx, shared.tcx.sess);
657                 Some(dctx)
658             } else {
659                 None
660             };
661
662             let local_ccx = LocalCrateContext {
663                 llmod: llmod,
664                 llcx: llcx,
665                 previous_work_product: previous_work_product,
666                 codegen_unit: codegen_unit,
667                 tn: TypeNames::new(),
668                 needs_unwind_cleanup_cache: RefCell::new(FnvHashMap()),
669                 fn_pointer_shims: RefCell::new(FnvHashMap()),
670                 drop_glues: RefCell::new(FnvHashMap()),
671                 instances: RefCell::new(FnvHashMap()),
672                 vtables: RefCell::new(FnvHashMap()),
673                 const_cstr_cache: RefCell::new(FnvHashMap()),
674                 const_unsized: RefCell::new(FnvHashMap()),
675                 const_globals: RefCell::new(FnvHashMap()),
676                 const_values: RefCell::new(FnvHashMap()),
677                 extern_const_values: RefCell::new(DefIdMap()),
678                 statics: RefCell::new(FnvHashMap()),
679                 impl_method_cache: RefCell::new(FnvHashMap()),
680                 closure_bare_wrapper_cache: RefCell::new(FnvHashMap()),
681                 statics_to_rauw: RefCell::new(Vec::new()),
682                 lltypes: RefCell::new(FnvHashMap()),
683                 llsizingtypes: RefCell::new(FnvHashMap()),
684                 adt_reprs: RefCell::new(FnvHashMap()),
685                 type_hashcodes: RefCell::new(FnvHashMap()),
686                 int_type: Type::from_ref(ptr::null_mut()),
687                 opaque_vec_type: Type::from_ref(ptr::null_mut()),
688                 builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
689                 closure_vals: RefCell::new(FnvHashMap()),
690                 dbg_cx: dbg_cx,
691                 eh_personality: Cell::new(None),
692                 eh_unwind_resume: Cell::new(None),
693                 rust_try_fn: Cell::new(None),
694                 intrinsics: RefCell::new(FnvHashMap()),
695                 n_llvm_insns: Cell::new(0),
696                 type_of_depth: Cell::new(0),
697                 symbol_map: symbol_map,
698             };
699
700             let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = {
701                 // Do a little dance to create a dummy CrateContext, so we can
702                 // create some things in the LLVM module of this codegen unit
703                 let mut local_ccxs = vec![local_ccx];
704                 let (int_type, opaque_vec_type, str_slice_ty) = {
705                     let dummy_ccx = LocalCrateContext::dummy_ccx(shared,
706                                                                  local_ccxs.as_mut_slice());
707                     let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice");
708                     str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx),
709                                                    Type::int(&dummy_ccx)],
710                                                  false);
711                     (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty)
712                 };
713                 (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap())
714             };
715
716             local_ccx.int_type = int_type;
717             local_ccx.opaque_vec_type = opaque_vec_type;
718             local_ccx.tn.associate_type("str_slice", &str_slice_ty);
719
720             if shared.tcx.sess.count_llvm_insns() {
721                 base::init_insn_ctxt()
722             }
723
724             local_ccx
725         }
726     }
727
728     /// Create a dummy `CrateContext` from `self` and  the provided
729     /// `SharedCrateContext`.  This is somewhat dangerous because `self` may
730     /// not be fully initialized.
731     ///
732     /// This is used in the `LocalCrateContext` constructor to allow calling
733     /// functions that expect a complete `CrateContext`, even before the local
734     /// portion is fully initialized and attached to the `SharedCrateContext`.
735     fn dummy_ccx<'a>(shared: &'a SharedCrateContext<'a, 'tcx>,
736                      local_ccxs: &'a [LocalCrateContext<'tcx>])
737                      -> CrateContext<'a, 'tcx> {
738         assert!(local_ccxs.len() == 1);
739         CrateContext {
740             shared: shared,
741             index: 0,
742             local_ccxs: local_ccxs
743         }
744     }
745 }
746
747 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
748     pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
749         self.shared
750     }
751
752     pub fn local(&self) -> &'b LocalCrateContext<'tcx> {
753         &self.local_ccxs[self.index]
754     }
755
756     /// Get a (possibly) different `CrateContext` from the same
757     /// `SharedCrateContext`.
758     pub fn rotate(&'b self) -> CrateContext<'b, 'tcx> {
759         let (_, index) =
760             self.local_ccxs
761                 .iter()
762                 .zip(0..self.local_ccxs.len())
763                 .min_by_key(|&(local_ccx, _idx)| local_ccx.n_llvm_insns.get())
764                 .unwrap();
765         CrateContext {
766             shared: self.shared,
767             index: index,
768             local_ccxs: &self.local_ccxs[..],
769         }
770     }
771
772     /// Either iterate over only `self`, or iterate over all `CrateContext`s in
773     /// the `SharedCrateContext`.  The iterator produces `(ccx, is_origin)`
774     /// pairs, where `is_origin` is `true` if `ccx` is `self` and `false`
775     /// otherwise.  This method is useful for avoiding code duplication in
776     /// cases where it may or may not be necessary to translate code into every
777     /// context.
778     pub fn maybe_iter(&self, iter_all: bool) -> CrateContextMaybeIterator<'b, 'tcx> {
779         CrateContextMaybeIterator {
780             shared: self.shared,
781             index: if iter_all { 0 } else { self.index },
782             single: !iter_all,
783             origin: self.index,
784             local_ccxs: self.local_ccxs,
785         }
786     }
787
788     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
789         self.shared.tcx
790     }
791
792     pub fn sess<'a>(&'a self) -> &'a Session {
793         &self.shared.tcx.sess
794     }
795
796     pub fn builder<'a>(&'a self) -> Builder<'a, 'tcx> {
797         Builder::new(self)
798     }
799
800     pub fn raw_builder<'a>(&'a self) -> BuilderRef {
801         self.local().builder.b
802     }
803
804     pub fn get_intrinsic(&self, key: &str) -> ValueRef {
805         if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
806             return v;
807         }
808         match declare_intrinsic(self, key) {
809             Some(v) => return v,
810             None => bug!("unknown intrinsic '{}'", key)
811         }
812     }
813
814     pub fn llmod(&self) -> ModuleRef {
815         self.local().llmod
816     }
817
818     pub fn llcx(&self) -> ContextRef {
819         self.local().llcx
820     }
821
822     pub fn previous_work_product(&self) -> Option<&WorkProduct> {
823         self.local().previous_work_product.as_ref()
824     }
825
826     pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> {
827         &self.local().codegen_unit
828     }
829
830     pub fn td(&self) -> llvm::TargetDataRef {
831         unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
832     }
833
834     pub fn tn<'a>(&'a self) -> &'a TypeNames {
835         &self.local().tn
836     }
837
838     pub fn export_map<'a>(&'a self) -> &'a ExportMap {
839         &self.shared.export_map
840     }
841
842     pub fn reachable<'a>(&'a self) -> &'a NodeSet {
843         &self.shared.reachable
844     }
845
846     pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
847         &self.shared.link_meta
848     }
849
850     pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, bool>> {
851         &self.local().needs_unwind_cleanup_cache
852     }
853
854     pub fn fn_pointer_shims(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, ValueRef>> {
855         &self.local().fn_pointer_shims
856     }
857
858     pub fn drop_glues<'a>(&'a self)
859                           -> &'a RefCell<FnvHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>> {
860         &self.local().drop_glues
861     }
862
863     pub fn local_node_for_inlined_defid<'a>(&'a self, def_id: DefId) -> Option<ast::NodeId> {
864         self.sess().cstore.local_node_for_inlined_defid(def_id)
865     }
866
867     pub fn defid_for_inlined_node<'a>(&'a self, node_id: ast::NodeId) -> Option<DefId> {
868         self.sess().cstore.defid_for_inlined_node(node_id)
869     }
870
871     pub fn instances<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
872         &self.local().instances
873     }
874
875     pub fn vtables<'a>(&'a self) -> &'a RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>> {
876         &self.local().vtables
877     }
878
879     pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<InternedString, ValueRef>> {
880         &self.local().const_cstr_cache
881     }
882
883     pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
884         &self.local().const_unsized
885     }
886
887     pub fn const_globals<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
888         &self.local().const_globals
889     }
890
891     pub fn const_values<'a>(&'a self) -> &'a RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
892                                                                 ValueRef>> {
893         &self.local().const_values
894     }
895
896     pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
897         &self.local().extern_const_values
898     }
899
900     pub fn statics<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, DefId>> {
901         &self.local().statics
902     }
903
904     pub fn impl_method_cache<'a>(&'a self)
905             -> &'a RefCell<FnvHashMap<(DefId, ast::Name), DefId>> {
906         &self.local().impl_method_cache
907     }
908
909     pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
910         &self.local().closure_bare_wrapper_cache
911     }
912
913     pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
914         &self.local().statics_to_rauw
915     }
916
917     pub fn lltypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
918         &self.local().lltypes
919     }
920
921     pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
922         &self.local().llsizingtypes
923     }
924
925     pub fn adt_reprs<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>> {
926         &self.local().adt_reprs
927     }
928
929     pub fn symbol_hasher<'a>(&'a self) -> &'a RefCell<Sha256> {
930         &self.shared.symbol_hasher
931     }
932
933     pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, String>> {
934         &self.local().type_hashcodes
935     }
936
937     pub fn stats<'a>(&'a self) -> &'a Stats {
938         &self.shared.stats
939     }
940
941     pub fn int_type(&self) -> Type {
942         self.local().int_type
943     }
944
945     pub fn opaque_vec_type(&self) -> Type {
946         self.local().opaque_vec_type
947     }
948
949     pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
950         &self.local().closure_vals
951     }
952
953     pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
954         &self.local().dbg_cx
955     }
956
957     pub fn eh_personality<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
958         &self.local().eh_personality
959     }
960
961     pub fn eh_unwind_resume<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
962         &self.local().eh_unwind_resume
963     }
964
965     pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
966         &self.local().rust_try_fn
967     }
968
969     fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
970         &self.local().intrinsics
971     }
972
973     pub fn count_llvm_insn(&self) {
974         self.local().n_llvm_insns.set(self.local().n_llvm_insns.get() + 1);
975     }
976
977     pub fn obj_size_bound(&self) -> u64 {
978         self.tcx().data_layout.obj_size_bound()
979     }
980
981     pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
982         self.sess().fatal(
983             &format!("the type `{:?}` is too big for the current architecture",
984                     obj))
985     }
986
987     pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
988         let current_depth = self.local().type_of_depth.get();
989         debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
990         if current_depth > self.sess().recursion_limit.get() {
991             self.sess().fatal(
992                 &format!("overflow representing the type `{}`", ty))
993         }
994         self.local().type_of_depth.set(current_depth + 1);
995         TypeOfDepthLock(self.local())
996     }
997
998     pub fn layout_of(&self, ty: Ty<'tcx>) -> &'tcx ty::layout::Layout {
999         self.tcx().infer_ctxt(None, None, traits::Reveal::All).enter(|infcx| {
1000             ty.layout(&infcx).unwrap_or_else(|e| {
1001                 bug!("failed to get layout for `{}`: {}", ty, e);
1002             })
1003         })
1004     }
1005
1006     pub fn check_overflow(&self) -> bool {
1007         self.shared.check_overflow
1008     }
1009
1010     pub fn use_dll_storage_attrs(&self) -> bool {
1011         self.shared.use_dll_storage_attrs()
1012     }
1013
1014     pub fn get_mir(&self, def_id: DefId) -> Option<CachedMir<'b, 'tcx>> {
1015         self.shared.get_mir(def_id)
1016     }
1017
1018     pub fn symbol_map(&self) -> &SymbolMap<'tcx> {
1019         &*self.local().symbol_map
1020     }
1021
1022     pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
1023         &self.shared.translation_items
1024     }
1025
1026     /// Given the def-id of some item that has no type parameters, make
1027     /// a suitable "empty substs" for it.
1028     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
1029         self.shared().empty_substs_for_def_id(item_def_id)
1030     }
1031 }
1032
1033 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>);
1034
1035 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
1036     fn drop(&mut self) {
1037         self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
1038     }
1039 }
1040
1041 /// Declare any llvm intrinsics that you might need
1042 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
1043     macro_rules! ifn {
1044         ($name:expr, fn() -> $ret:expr) => (
1045             if key == $name {
1046                 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
1047                 llvm::SetUnnamedAddr(f, false);
1048                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1049                 return Some(f);
1050             }
1051         );
1052         ($name:expr, fn(...) -> $ret:expr) => (
1053             if key == $name {
1054                 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
1055                 llvm::SetUnnamedAddr(f, false);
1056                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1057                 return Some(f);
1058             }
1059         );
1060         ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
1061             if key == $name {
1062                 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
1063                 llvm::SetUnnamedAddr(f, false);
1064                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
1065                 return Some(f);
1066             }
1067         );
1068     }
1069     macro_rules! mk_struct {
1070         ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
1071     }
1072
1073     let i8p = Type::i8p(ccx);
1074     let void = Type::void(ccx);
1075     let i1 = Type::i1(ccx);
1076     let t_i8 = Type::i8(ccx);
1077     let t_i16 = Type::i16(ccx);
1078     let t_i32 = Type::i32(ccx);
1079     let t_i64 = Type::i64(ccx);
1080     let t_f32 = Type::f32(ccx);
1081     let t_f64 = Type::f64(ccx);
1082
1083     ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
1084     ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
1085     ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
1086     ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
1087     ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
1088     ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
1089     ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
1090     ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
1091     ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
1092
1093     ifn!("llvm.trap", fn() -> void);
1094     ifn!("llvm.debugtrap", fn() -> void);
1095     ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
1096
1097     ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
1098     ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
1099     ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
1100     ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
1101
1102     ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
1103     ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
1104     ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
1105     ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
1106     ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
1107     ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
1108     ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
1109     ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
1110     ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
1111     ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
1112     ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
1113     ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
1114     ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
1115     ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
1116     ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
1117     ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
1118
1119     ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
1120     ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
1121
1122     ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
1123     ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
1124
1125     ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
1126     ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
1127     ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
1128     ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
1129     ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
1130     ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
1131
1132     ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
1133     ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
1134     ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
1135     ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
1136
1137     ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
1138     ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
1139     ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
1140     ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
1141
1142     ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
1143     ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
1144     ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
1145     ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
1146
1147     ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
1148     ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
1149     ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
1150     ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
1151
1152     ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
1153     ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
1154     ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
1155     ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
1156
1157     ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
1158     ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
1159     ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
1160
1161     ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1162     ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1163     ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1164     ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1165
1166     ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1167     ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1168     ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1169     ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1170
1171     ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1172     ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1173     ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1174     ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1175
1176     ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1177     ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1178     ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1179     ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1180
1181     ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1182     ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1183     ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1184     ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1185
1186     ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1187     ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1188     ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1189     ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1190
1191     ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
1192     ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
1193
1194     ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
1195     ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
1196     ifn!("llvm.localescape", fn(...) -> void);
1197     ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
1198     ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
1199
1200     ifn!("llvm.assume", fn(i1) -> void);
1201
1202     if ccx.sess().opts.debuginfo != NoDebugInfo {
1203         ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
1204         ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);
1205     }
1206     return None;
1207 }