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