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