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