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