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