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