]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/context.rs
rollup merge of #20482: kmcallister/macro-reform
[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 llvm::{TargetData};
14 use llvm::mk_target_data;
15 use metadata::common::LinkMeta;
16 use middle::def::ExportMap;
17 use middle::traits;
18 use trans::adt;
19 use trans::base;
20 use trans::builder::Builder;
21 use trans::common::{ExternMap,tydesc_info,BuilderRef_res};
22 use trans::debuginfo;
23 use trans::monomorphize::MonoId;
24 use trans::type_::{Type, TypeNames};
25 use middle::ty::{self, Ty};
26 use session::config::NoDebugInfo;
27 use session::Session;
28 use util::ppaux::Repr;
29 use util::sha2::Sha256;
30 use util::nodemap::{NodeMap, NodeSet, DefIdMap, FnvHashMap, FnvHashSet};
31
32 use std::ffi::CString;
33 use std::cell::{Cell, RefCell};
34 use std::ptr;
35 use std::rc::Rc;
36 use syntax::ast;
37 use syntax::parse::token::InternedString;
38
39 pub struct Stats {
40     pub n_static_tydescs: Cell<uint>,
41     pub n_glues_created: Cell<uint>,
42     pub n_null_glues: Cell<uint>,
43     pub n_real_glues: Cell<uint>,
44     pub n_fns: Cell<uint>,
45     pub n_monos: Cell<uint>,
46     pub n_inlines: Cell<uint>,
47     pub n_closures: Cell<uint>,
48     pub n_llvm_insns: Cell<uint>,
49     pub llvm_insns: RefCell<FnvHashMap<String, uint>>,
50     // (ident, llvm-instructions)
51     pub fn_stats: RefCell<Vec<(String, uint)> >,
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<'tcx> {
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: ty::ctxt<'tcx>,
70     stats: Stats,
71
72     available_monomorphizations: RefCell<FnvHashSet<String>>,
73     available_drop_glues: RefCell<FnvHashMap<Ty<'tcx>, String>>,
74 }
75
76 /// The local portion of a `CrateContext`.  There is one `LocalCrateContext`
77 /// per compilation unit.  Each one has its own LLVM `ContextRef` so that
78 /// several compilation units may be optimized in parallel.  All other LLVM
79 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
80 pub struct LocalCrateContext<'tcx> {
81     llmod: ModuleRef,
82     llcx: ContextRef,
83     td: TargetData,
84     tn: TypeNames,
85     externs: RefCell<ExternMap>,
86     item_vals: RefCell<NodeMap<ValueRef>>,
87     needs_unwind_cleanup_cache: RefCell<FnvHashMap<Ty<'tcx>, bool>>,
88     fn_pointer_shims: RefCell<FnvHashMap<Ty<'tcx>, ValueRef>>,
89     drop_glues: RefCell<FnvHashMap<Ty<'tcx>, ValueRef>>,
90     tydescs: RefCell<FnvHashMap<Ty<'tcx>, Rc<tydesc_info<'tcx>>>>,
91     /// Set when running emit_tydescs to enforce that no more tydescs are
92     /// created.
93     finished_tydescs: Cell<bool>,
94     /// Track mapping of external ids to local items imported for inlining
95     external: RefCell<DefIdMap<Option<ast::NodeId>>>,
96     /// Backwards version of the `external` map (inlined items to where they
97     /// came from)
98     external_srcs: RefCell<NodeMap<ast::DefId>>,
99     /// Cache instances of monomorphized functions
100     monomorphized: RefCell<FnvHashMap<MonoId<'tcx>, ValueRef>>,
101     monomorphizing: RefCell<DefIdMap<uint>>,
102     /// Cache generated vtables
103     vtables: RefCell<FnvHashMap<(Ty<'tcx>, ty::PolyTraitRef<'tcx>), ValueRef>>,
104     /// Cache of constant strings,
105     const_cstr_cache: RefCell<FnvHashMap<InternedString, ValueRef>>,
106
107     /// Reverse-direction for const ptrs cast from globals.
108     /// Key is an int, cast from a ValueRef holding a *T,
109     /// Val is a ValueRef holding a *[T].
110     ///
111     /// Needed because LLVM loses pointer->pointee association
112     /// when we ptrcast, and we have to ptrcast during translation
113     /// of a [T] const because we form a slice, a [*T,int] pair, not
114     /// a pointer to an LLVM array type.
115     const_globals: RefCell<FnvHashMap<int, ValueRef>>,
116
117     /// Cache of emitted const values
118     const_values: RefCell<NodeMap<ValueRef>>,
119
120     /// Cache of emitted static values
121     static_values: RefCell<NodeMap<ValueRef>>,
122
123     /// Cache of external const values
124     extern_const_values: RefCell<DefIdMap<ValueRef>>,
125
126     impl_method_cache: RefCell<FnvHashMap<(ast::DefId, ast::Name), ast::DefId>>,
127
128     /// Cache of closure wrappers for bare fn's.
129     closure_bare_wrapper_cache: RefCell<FnvHashMap<ValueRef, ValueRef>>,
130
131     lltypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
132     llsizingtypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
133     adt_reprs: RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>>,
134     type_hashcodes: RefCell<FnvHashMap<Ty<'tcx>, String>>,
135     all_llvm_symbols: RefCell<FnvHashSet<String>>,
136     int_type: Type,
137     opaque_vec_type: Type,
138     builder: BuilderRef_res,
139
140     /// Holds the LLVM values for closure IDs.
141     unboxed_closure_vals: RefCell<FnvHashMap<MonoId<'tcx>, ValueRef>>,
142
143     dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
144
145     eh_personality: RefCell<Option<ValueRef>>,
146
147     intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
148
149     /// Number of LLVM instructions translated into this `LocalCrateContext`.
150     /// This is used to perform some basic load-balancing to keep all LLVM
151     /// contexts around the same size.
152     n_llvm_insns: Cell<uint>,
153
154     trait_cache: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>,
155                                     traits::Vtable<'tcx, ()>>>,
156 }
157
158 pub struct CrateContext<'a, 'tcx: 'a> {
159     shared: &'a SharedCrateContext<'tcx>,
160     local: &'a LocalCrateContext<'tcx>,
161     /// The index of `local` in `shared.local_ccxs`.  This is used in
162     /// `maybe_iter(true)` to identify the original `LocalCrateContext`.
163     index: uint,
164 }
165
166 pub struct CrateContextIterator<'a, 'tcx: 'a> {
167     shared: &'a SharedCrateContext<'tcx>,
168     index: uint,
169 }
170
171 impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> {
172     type Item = CrateContext<'a, 'tcx>;
173
174     fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> {
175         if self.index >= self.shared.local_ccxs.len() {
176             return None;
177         }
178
179         let index = self.index;
180         self.index += 1;
181
182         Some(CrateContext {
183             shared: self.shared,
184             local: &self.shared.local_ccxs[index],
185             index: index,
186         })
187     }
188 }
189
190 /// The iterator produced by `CrateContext::maybe_iter`.
191 pub struct CrateContextMaybeIterator<'a, 'tcx: 'a> {
192     shared: &'a SharedCrateContext<'tcx>,
193     index: uint,
194     single: bool,
195     origin: uint,
196 }
197
198 impl<'a, 'tcx> Iterator for CrateContextMaybeIterator<'a, 'tcx> {
199     type Item = (CrateContext<'a, 'tcx>, bool);
200
201     fn next(&mut self) -> Option<(CrateContext<'a, 'tcx>, bool)> {
202         if self.index >= self.shared.local_ccxs.len() {
203             return None;
204         }
205
206         let index = self.index;
207         self.index += 1;
208         if self.single {
209             self.index = self.shared.local_ccxs.len();
210         }
211
212         let ccx = CrateContext {
213             shared: self.shared,
214             local: &self.shared.local_ccxs[index],
215             index: index,
216         };
217         Some((ccx, index == self.origin))
218     }
219 }
220
221
222 unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
223     let llcx = llvm::LLVMContextCreate();
224     let mod_name = CString::from_slice(mod_name.as_bytes());
225     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
226
227     let data_layout = sess.target.target.data_layout.as_slice();
228     let data_layout = CString::from_slice(data_layout.as_bytes());
229     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
230
231     let llvm_target = sess.target.target.llvm_target.as_slice();
232     let llvm_target = CString::from_slice(llvm_target.as_bytes());
233     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
234     (llcx, llmod)
235 }
236
237 impl<'tcx> SharedCrateContext<'tcx> {
238     pub fn new(crate_name: &str,
239                local_count: uint,
240                tcx: ty::ctxt<'tcx>,
241                export_map: ExportMap,
242                symbol_hasher: Sha256,
243                link_meta: LinkMeta,
244                reachable: NodeSet)
245                -> SharedCrateContext<'tcx> {
246         let (metadata_llcx, metadata_llmod) = unsafe {
247             create_context_and_module(&tcx.sess, "metadata")
248         };
249
250         let mut shared_ccx = SharedCrateContext {
251             local_ccxs: Vec::with_capacity(local_count),
252             metadata_llmod: metadata_llmod,
253             metadata_llcx: metadata_llcx,
254             export_map: export_map,
255             reachable: reachable,
256             item_symbols: RefCell::new(NodeMap::new()),
257             link_meta: link_meta,
258             symbol_hasher: RefCell::new(symbol_hasher),
259             tcx: tcx,
260             stats: Stats {
261                 n_static_tydescs: Cell::new(0u),
262                 n_glues_created: Cell::new(0u),
263                 n_null_glues: Cell::new(0u),
264                 n_real_glues: Cell::new(0u),
265                 n_fns: Cell::new(0u),
266                 n_monos: Cell::new(0u),
267                 n_inlines: Cell::new(0u),
268                 n_closures: Cell::new(0u),
269                 n_llvm_insns: Cell::new(0u),
270                 llvm_insns: RefCell::new(FnvHashMap::new()),
271                 fn_stats: RefCell::new(Vec::new()),
272             },
273             available_monomorphizations: RefCell::new(FnvHashSet::new()),
274             available_drop_glues: RefCell::new(FnvHashMap::new()),
275         };
276
277         for i in range(0, local_count) {
278             // Append ".rs" to crate name as LLVM module identifier.
279             //
280             // LLVM code generator emits a ".file filename" directive
281             // for ELF backends. Value of the "filename" is set as the
282             // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
283             // crashes if the module identifier is same as other symbols
284             // such as a function name in the module.
285             // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
286             let llmod_id = format!("{}.{}.rs", crate_name, i);
287             let local_ccx = LocalCrateContext::new(&shared_ccx, llmod_id[]);
288             shared_ccx.local_ccxs.push(local_ccx);
289         }
290
291         shared_ccx
292     }
293
294     pub fn iter<'a>(&'a self) -> CrateContextIterator<'a, 'tcx> {
295         CrateContextIterator {
296             shared: self,
297             index: 0,
298         }
299     }
300
301     pub fn get_ccx<'a>(&'a self, index: uint) -> CrateContext<'a, 'tcx> {
302         CrateContext {
303             shared: self,
304             local: &self.local_ccxs[index],
305             index: index,
306         }
307     }
308
309     fn get_smallest_ccx<'a>(&'a self) -> CrateContext<'a, 'tcx> {
310         let (local_ccx, index) =
311             self.local_ccxs
312                 .iter()
313                 .zip(range(0, self.local_ccxs.len()))
314                 .min_by(|&(local_ccx, _idx)| local_ccx.n_llvm_insns.get())
315                 .unwrap();
316         CrateContext {
317             shared: self,
318             local: local_ccx,
319             index: index,
320         }
321     }
322
323
324     pub fn metadata_llmod(&self) -> ModuleRef {
325         self.metadata_llmod
326     }
327
328     pub fn metadata_llcx(&self) -> ContextRef {
329         self.metadata_llcx
330     }
331
332     pub fn export_map<'a>(&'a self) -> &'a ExportMap {
333         &self.export_map
334     }
335
336     pub fn reachable<'a>(&'a self) -> &'a NodeSet {
337         &self.reachable
338     }
339
340     pub fn item_symbols<'a>(&'a self) -> &'a RefCell<NodeMap<String>> {
341         &self.item_symbols
342     }
343
344     pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
345         &self.link_meta
346     }
347
348     pub fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
349         &self.tcx
350     }
351
352     pub fn take_tcx(self) -> ty::ctxt<'tcx> {
353         self.tcx
354     }
355
356     pub fn sess<'a>(&'a self) -> &'a Session {
357         &self.tcx.sess
358     }
359
360     pub fn stats<'a>(&'a self) -> &'a Stats {
361         &self.stats
362     }
363 }
364
365 impl<'tcx> LocalCrateContext<'tcx> {
366     fn new(shared: &SharedCrateContext<'tcx>,
367            name: &str)
368            -> LocalCrateContext<'tcx> {
369         unsafe {
370             let (llcx, llmod) = create_context_and_module(&shared.tcx.sess, name);
371
372             let td = mk_target_data(shared.tcx
373                                           .sess
374                                           .target
375                                           .target
376                                           .data_layout
377                                           []);
378
379             let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
380                 Some(debuginfo::CrateDebugContext::new(llmod))
381             } else {
382                 None
383             };
384
385             let mut local_ccx = LocalCrateContext {
386                 llmod: llmod,
387                 llcx: llcx,
388                 td: td,
389                 tn: TypeNames::new(),
390                 externs: RefCell::new(FnvHashMap::new()),
391                 item_vals: RefCell::new(NodeMap::new()),
392                 needs_unwind_cleanup_cache: RefCell::new(FnvHashMap::new()),
393                 fn_pointer_shims: RefCell::new(FnvHashMap::new()),
394                 drop_glues: RefCell::new(FnvHashMap::new()),
395                 tydescs: RefCell::new(FnvHashMap::new()),
396                 finished_tydescs: Cell::new(false),
397                 external: RefCell::new(DefIdMap::new()),
398                 external_srcs: RefCell::new(NodeMap::new()),
399                 monomorphized: RefCell::new(FnvHashMap::new()),
400                 monomorphizing: RefCell::new(DefIdMap::new()),
401                 vtables: RefCell::new(FnvHashMap::new()),
402                 const_cstr_cache: RefCell::new(FnvHashMap::new()),
403                 const_globals: RefCell::new(FnvHashMap::new()),
404                 const_values: RefCell::new(NodeMap::new()),
405                 static_values: RefCell::new(NodeMap::new()),
406                 extern_const_values: RefCell::new(DefIdMap::new()),
407                 impl_method_cache: RefCell::new(FnvHashMap::new()),
408                 closure_bare_wrapper_cache: RefCell::new(FnvHashMap::new()),
409                 lltypes: RefCell::new(FnvHashMap::new()),
410                 llsizingtypes: RefCell::new(FnvHashMap::new()),
411                 adt_reprs: RefCell::new(FnvHashMap::new()),
412                 type_hashcodes: RefCell::new(FnvHashMap::new()),
413                 all_llvm_symbols: RefCell::new(FnvHashSet::new()),
414                 int_type: Type::from_ref(ptr::null_mut()),
415                 opaque_vec_type: Type::from_ref(ptr::null_mut()),
416                 builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
417                 unboxed_closure_vals: RefCell::new(FnvHashMap::new()),
418                 dbg_cx: dbg_cx,
419                 eh_personality: RefCell::new(None),
420                 intrinsics: RefCell::new(FnvHashMap::new()),
421                 n_llvm_insns: Cell::new(0u),
422                 trait_cache: RefCell::new(FnvHashMap::new()),
423             };
424
425             local_ccx.int_type = Type::int(&local_ccx.dummy_ccx(shared));
426             local_ccx.opaque_vec_type = Type::opaque_vec(&local_ccx.dummy_ccx(shared));
427
428             // Done mutating local_ccx directly.  (The rest of the
429             // initialization goes through RefCell.)
430             {
431                 let ccx = local_ccx.dummy_ccx(shared);
432
433                 let mut str_slice_ty = Type::named_struct(&ccx, "str_slice");
434                 str_slice_ty.set_struct_body(&[Type::i8p(&ccx), ccx.int_type()], false);
435                 ccx.tn().associate_type("str_slice", &str_slice_ty);
436
437                 ccx.tn().associate_type("tydesc", &Type::tydesc(&ccx, str_slice_ty));
438
439                 if ccx.sess().count_llvm_insns() {
440                     base::init_insn_ctxt()
441                 }
442             }
443
444             local_ccx
445         }
446     }
447
448     /// Create a dummy `CrateContext` from `self` and  the provided
449     /// `SharedCrateContext`.  This is somewhat dangerous because `self` may
450     /// not actually be an element of `shared.local_ccxs`, which can cause some
451     /// operations to panic unexpectedly.
452     ///
453     /// This is used in the `LocalCrateContext` constructor to allow calling
454     /// functions that expect a complete `CrateContext`, even before the local
455     /// portion is fully initialized and attached to the `SharedCrateContext`.
456     fn dummy_ccx<'a>(&'a self, shared: &'a SharedCrateContext<'tcx>)
457                      -> CrateContext<'a, 'tcx> {
458         CrateContext {
459             shared: shared,
460             local: self,
461             index: -1 as uint,
462         }
463     }
464 }
465
466 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
467     pub fn shared(&self) -> &'b SharedCrateContext<'tcx> {
468         self.shared
469     }
470
471     pub fn local(&self) -> &'b LocalCrateContext<'tcx> {
472         self.local
473     }
474
475
476     /// Get a (possibly) different `CrateContext` from the same
477     /// `SharedCrateContext`.
478     pub fn rotate(&self) -> CrateContext<'b, 'tcx> {
479         self.shared.get_smallest_ccx()
480     }
481
482     /// Either iterate over only `self`, or iterate over all `CrateContext`s in
483     /// the `SharedCrateContext`.  The iterator produces `(ccx, is_origin)`
484     /// pairs, where `is_origin` is `true` if `ccx` is `self` and `false`
485     /// otherwise.  This method is useful for avoiding code duplication in
486     /// cases where it may or may not be necessary to translate code into every
487     /// context.
488     pub fn maybe_iter(&self, iter_all: bool) -> CrateContextMaybeIterator<'b, 'tcx> {
489         CrateContextMaybeIterator {
490             shared: self.shared,
491             index: if iter_all { 0 } else { self.index },
492             single: !iter_all,
493             origin: self.index,
494         }
495     }
496
497
498     pub fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
499         &self.shared.tcx
500     }
501
502     pub fn sess<'a>(&'a self) -> &'a Session {
503         &self.shared.tcx.sess
504     }
505
506     pub fn builder<'a>(&'a self) -> Builder<'a, 'tcx> {
507         Builder::new(self)
508     }
509
510     pub fn raw_builder<'a>(&'a self) -> BuilderRef {
511         self.local.builder.b
512     }
513
514     pub fn tydesc_type(&self) -> Type {
515         self.local.tn.find_type("tydesc").unwrap()
516     }
517
518     pub fn get_intrinsic(&self, key: & &'static str) -> ValueRef {
519         if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
520             return v;
521         }
522         match declare_intrinsic(self, key) {
523             Some(v) => return v,
524             None => panic!()
525         }
526     }
527
528     pub fn is_split_stack_supported(&self) -> bool {
529         self.sess().target.target.options.morestack
530     }
531
532
533     pub fn llmod(&self) -> ModuleRef {
534         self.local.llmod
535     }
536
537     pub fn llcx(&self) -> ContextRef {
538         self.local.llcx
539     }
540
541     pub fn td<'a>(&'a self) -> &'a TargetData {
542         &self.local.td
543     }
544
545     pub fn tn<'a>(&'a self) -> &'a TypeNames {
546         &self.local.tn
547     }
548
549     pub fn externs<'a>(&'a self) -> &'a RefCell<ExternMap> {
550         &self.local.externs
551     }
552
553     pub fn item_vals<'a>(&'a self) -> &'a RefCell<NodeMap<ValueRef>> {
554         &self.local.item_vals
555     }
556
557     pub fn export_map<'a>(&'a self) -> &'a ExportMap {
558         &self.shared.export_map
559     }
560
561     pub fn reachable<'a>(&'a self) -> &'a NodeSet {
562         &self.shared.reachable
563     }
564
565     pub fn item_symbols<'a>(&'a self) -> &'a RefCell<NodeMap<String>> {
566         &self.shared.item_symbols
567     }
568
569     pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
570         &self.shared.link_meta
571     }
572
573     pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, bool>> {
574         &self.local.needs_unwind_cleanup_cache
575     }
576
577     pub fn fn_pointer_shims(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, ValueRef>> {
578         &self.local.fn_pointer_shims
579     }
580
581     pub fn drop_glues<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, ValueRef>> {
582         &self.local.drop_glues
583     }
584
585     pub fn tydescs<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Rc<tydesc_info<'tcx>>>> {
586         &self.local.tydescs
587     }
588
589     pub fn finished_tydescs<'a>(&'a self) -> &'a Cell<bool> {
590         &self.local.finished_tydescs
591     }
592
593     pub fn external<'a>(&'a self) -> &'a RefCell<DefIdMap<Option<ast::NodeId>>> {
594         &self.local.external
595     }
596
597     pub fn external_srcs<'a>(&'a self) -> &'a RefCell<NodeMap<ast::DefId>> {
598         &self.local.external_srcs
599     }
600
601     pub fn monomorphized<'a>(&'a self) -> &'a RefCell<FnvHashMap<MonoId<'tcx>, ValueRef>> {
602         &self.local.monomorphized
603     }
604
605     pub fn monomorphizing<'a>(&'a self) -> &'a RefCell<DefIdMap<uint>> {
606         &self.local.monomorphizing
607     }
608
609     pub fn vtables<'a>(&'a self) -> &'a RefCell<FnvHashMap<(Ty<'tcx>, ty::PolyTraitRef<'tcx>),
610                                                             ValueRef>> {
611         &self.local.vtables
612     }
613
614     pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<InternedString, ValueRef>> {
615         &self.local.const_cstr_cache
616     }
617
618     pub fn const_globals<'a>(&'a self) -> &'a RefCell<FnvHashMap<int, ValueRef>> {
619         &self.local.const_globals
620     }
621
622     pub fn const_values<'a>(&'a self) -> &'a RefCell<NodeMap<ValueRef>> {
623         &self.local.const_values
624     }
625
626     pub fn static_values<'a>(&'a self) -> &'a RefCell<NodeMap<ValueRef>> {
627         &self.local.static_values
628     }
629
630     pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
631         &self.local.extern_const_values
632     }
633
634     pub fn impl_method_cache<'a>(&'a self)
635             -> &'a RefCell<FnvHashMap<(ast::DefId, ast::Name), ast::DefId>> {
636         &self.local.impl_method_cache
637     }
638
639     pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
640         &self.local.closure_bare_wrapper_cache
641     }
642
643     pub fn lltypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
644         &self.local.lltypes
645     }
646
647     pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
648         &self.local.llsizingtypes
649     }
650
651     pub fn adt_reprs<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>> {
652         &self.local.adt_reprs
653     }
654
655     pub fn symbol_hasher<'a>(&'a self) -> &'a RefCell<Sha256> {
656         &self.shared.symbol_hasher
657     }
658
659     pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, String>> {
660         &self.local.type_hashcodes
661     }
662
663     pub fn all_llvm_symbols<'a>(&'a self) -> &'a RefCell<FnvHashSet<String>> {
664         &self.local.all_llvm_symbols
665     }
666
667     pub fn stats<'a>(&'a self) -> &'a Stats {
668         &self.shared.stats
669     }
670
671     pub fn available_monomorphizations<'a>(&'a self) -> &'a RefCell<FnvHashSet<String>> {
672         &self.shared.available_monomorphizations
673     }
674
675     pub fn available_drop_glues<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, String>> {
676         &self.shared.available_drop_glues
677     }
678
679     pub fn int_type(&self) -> Type {
680         self.local.int_type
681     }
682
683     pub fn opaque_vec_type(&self) -> Type {
684         self.local.opaque_vec_type
685     }
686
687     pub fn unboxed_closure_vals<'a>(&'a self) -> &'a RefCell<FnvHashMap<MonoId<'tcx>,ValueRef>> {
688         &self.local.unboxed_closure_vals
689     }
690
691     pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
692         &self.local.dbg_cx
693     }
694
695     pub fn eh_personality<'a>(&'a self) -> &'a RefCell<Option<ValueRef>> {
696         &self.local.eh_personality
697     }
698
699     fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
700         &self.local.intrinsics
701     }
702
703     pub fn count_llvm_insn(&self) {
704         self.local.n_llvm_insns.set(self.local.n_llvm_insns.get() + 1);
705     }
706
707     pub fn trait_cache(&self) -> &RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>,
708                                                      traits::Vtable<'tcx, ()>>> {
709         &self.local.trait_cache
710     }
711
712     /// Return exclusive upper bound on object size.
713     ///
714     /// The theoretical maximum object size is defined as the maximum positive `int` value. This
715     /// ensures that the `offset` semantics remain well-defined by allowing it to correctly index
716     /// every address within an object along with one byte past the end, along with allowing `int`
717     /// to store the difference between any two pointers into an object.
718     ///
719     /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer to
720     /// represent object size in bits. It would need to be 1 << 61 to account for this, but is
721     /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
722     /// address space on 64-bit ARMv8 and x86_64.
723     pub fn obj_size_bound(&self) -> u64 {
724         match self.sess().target.target.target_word_size[] {
725             "32" => 1 << 31,
726             "64" => 1 << 47,
727             _ => unreachable!() // error handled by config::build_target_config
728         }
729     }
730
731     pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
732         self.sess().fatal(
733             format!("the type `{}` is too big for the current architecture",
734                     obj.repr(self.tcx()))[])
735     }
736 }
737
738 fn declare_intrinsic(ccx: &CrateContext, key: & &'static str) -> Option<ValueRef> {
739     macro_rules! ifn {
740         ($name:expr fn() -> $ret:expr) => (
741             if *key == $name {
742                 let f = base::decl_cdecl_fn(
743                     ccx, $name, Type::func(&[], &$ret),
744                     ty::mk_nil(ccx.tcx()));
745                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
746                 return Some(f);
747             }
748         );
749         ($name:expr fn($($arg:expr),*) -> $ret:expr) => (
750             if *key == $name {
751                 let f = base::decl_cdecl_fn(ccx, $name,
752                                   Type::func(&[$($arg),*], &$ret), ty::mk_nil(ccx.tcx()));
753                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
754                 return Some(f);
755             }
756         )
757     }
758     macro_rules! mk_struct {
759         ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
760     }
761
762     let i8p = Type::i8p(ccx);
763     let void = Type::void(ccx);
764     let i1 = Type::i1(ccx);
765     let t_i8 = Type::i8(ccx);
766     let t_i16 = Type::i16(ccx);
767     let t_i32 = Type::i32(ccx);
768     let t_i64 = Type::i64(ccx);
769     let t_f32 = Type::f32(ccx);
770     let t_f64 = Type::f64(ccx);
771
772     ifn!("llvm.memcpy.p0i8.p0i8.i32" fn(i8p, i8p, t_i32, t_i32, i1) -> void);
773     ifn!("llvm.memcpy.p0i8.p0i8.i64" fn(i8p, i8p, t_i64, t_i32, i1) -> void);
774     ifn!("llvm.memmove.p0i8.p0i8.i32" fn(i8p, i8p, t_i32, t_i32, i1) -> void);
775     ifn!("llvm.memmove.p0i8.p0i8.i64" fn(i8p, i8p, t_i64, t_i32, i1) -> void);
776     ifn!("llvm.memset.p0i8.i32" fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
777     ifn!("llvm.memset.p0i8.i64" fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
778
779     ifn!("llvm.trap" fn() -> void);
780     ifn!("llvm.debugtrap" fn() -> void);
781     ifn!("llvm.frameaddress" fn(t_i32) -> i8p);
782
783     ifn!("llvm.powi.f32" fn(t_f32, t_i32) -> t_f32);
784     ifn!("llvm.powi.f64" fn(t_f64, t_i32) -> t_f64);
785     ifn!("llvm.pow.f32" fn(t_f32, t_f32) -> t_f32);
786     ifn!("llvm.pow.f64" fn(t_f64, t_f64) -> t_f64);
787
788     ifn!("llvm.sqrt.f32" fn(t_f32) -> t_f32);
789     ifn!("llvm.sqrt.f64" fn(t_f64) -> t_f64);
790     ifn!("llvm.sin.f32" fn(t_f32) -> t_f32);
791     ifn!("llvm.sin.f64" fn(t_f64) -> t_f64);
792     ifn!("llvm.cos.f32" fn(t_f32) -> t_f32);
793     ifn!("llvm.cos.f64" fn(t_f64) -> t_f64);
794     ifn!("llvm.exp.f32" fn(t_f32) -> t_f32);
795     ifn!("llvm.exp.f64" fn(t_f64) -> t_f64);
796     ifn!("llvm.exp2.f32" fn(t_f32) -> t_f32);
797     ifn!("llvm.exp2.f64" fn(t_f64) -> t_f64);
798     ifn!("llvm.log.f32" fn(t_f32) -> t_f32);
799     ifn!("llvm.log.f64" fn(t_f64) -> t_f64);
800     ifn!("llvm.log10.f32" fn(t_f32) -> t_f32);
801     ifn!("llvm.log10.f64" fn(t_f64) -> t_f64);
802     ifn!("llvm.log2.f32" fn(t_f32) -> t_f32);
803     ifn!("llvm.log2.f64" fn(t_f64) -> t_f64);
804
805     ifn!("llvm.fma.f32" fn(t_f32, t_f32, t_f32) -> t_f32);
806     ifn!("llvm.fma.f64" fn(t_f64, t_f64, t_f64) -> t_f64);
807
808     ifn!("llvm.fabs.f32" fn(t_f32) -> t_f32);
809     ifn!("llvm.fabs.f64" fn(t_f64) -> t_f64);
810
811     ifn!("llvm.floor.f32" fn(t_f32) -> t_f32);
812     ifn!("llvm.floor.f64" fn(t_f64) -> t_f64);
813     ifn!("llvm.ceil.f32" fn(t_f32) -> t_f32);
814     ifn!("llvm.ceil.f64" fn(t_f64) -> t_f64);
815     ifn!("llvm.trunc.f32" fn(t_f32) -> t_f32);
816     ifn!("llvm.trunc.f64" fn(t_f64) -> t_f64);
817
818     ifn!("llvm.rint.f32" fn(t_f32) -> t_f32);
819     ifn!("llvm.rint.f64" fn(t_f64) -> t_f64);
820     ifn!("llvm.nearbyint.f32" fn(t_f32) -> t_f32);
821     ifn!("llvm.nearbyint.f64" fn(t_f64) -> t_f64);
822
823     ifn!("llvm.ctpop.i8" fn(t_i8) -> t_i8);
824     ifn!("llvm.ctpop.i16" fn(t_i16) -> t_i16);
825     ifn!("llvm.ctpop.i32" fn(t_i32) -> t_i32);
826     ifn!("llvm.ctpop.i64" fn(t_i64) -> t_i64);
827
828     ifn!("llvm.ctlz.i8" fn(t_i8 , i1) -> t_i8);
829     ifn!("llvm.ctlz.i16" fn(t_i16, i1) -> t_i16);
830     ifn!("llvm.ctlz.i32" fn(t_i32, i1) -> t_i32);
831     ifn!("llvm.ctlz.i64" fn(t_i64, i1) -> t_i64);
832
833     ifn!("llvm.cttz.i8" fn(t_i8 , i1) -> t_i8);
834     ifn!("llvm.cttz.i16" fn(t_i16, i1) -> t_i16);
835     ifn!("llvm.cttz.i32" fn(t_i32, i1) -> t_i32);
836     ifn!("llvm.cttz.i64" fn(t_i64, i1) -> t_i64);
837
838     ifn!("llvm.bswap.i16" fn(t_i16) -> t_i16);
839     ifn!("llvm.bswap.i32" fn(t_i32) -> t_i32);
840     ifn!("llvm.bswap.i64" fn(t_i64) -> t_i64);
841
842     ifn!("llvm.sadd.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
843     ifn!("llvm.sadd.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
844     ifn!("llvm.sadd.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
845     ifn!("llvm.sadd.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
846
847     ifn!("llvm.uadd.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
848     ifn!("llvm.uadd.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
849     ifn!("llvm.uadd.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
850     ifn!("llvm.uadd.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
851
852     ifn!("llvm.ssub.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
853     ifn!("llvm.ssub.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
854     ifn!("llvm.ssub.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
855     ifn!("llvm.ssub.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
856
857     ifn!("llvm.usub.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
858     ifn!("llvm.usub.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
859     ifn!("llvm.usub.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
860     ifn!("llvm.usub.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
861
862     ifn!("llvm.smul.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
863     ifn!("llvm.smul.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
864     ifn!("llvm.smul.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
865     ifn!("llvm.smul.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
866
867     ifn!("llvm.umul.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
868     ifn!("llvm.umul.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
869     ifn!("llvm.umul.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
870     ifn!("llvm.umul.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
871
872     ifn!("llvm.lifetime.start" fn(t_i64,i8p) -> void);
873     ifn!("llvm.lifetime.end" fn(t_i64, i8p) -> void);
874
875     ifn!("llvm.expect.i1" fn(i1, i1) -> i1);
876     ifn!("llvm.assume" fn(i1) -> void);
877
878     // Some intrinsics were introduced in later versions of LLVM, but they have
879     // fallbacks in libc or libm and such. Currently, all of these intrinsics
880     // were introduced in LLVM 3.4, so we case on that.
881     macro_rules! compatible_ifn {
882         ($name:expr, $cname:ident ($($arg:expr),*) -> $ret:expr) => (
883             if unsafe { llvm::LLVMVersionMinor() >= 4 } {
884                 // The `if key == $name` is already in ifn!
885                 ifn!($name fn($($arg),*) -> $ret);
886             } else if *key == $name {
887                 let f = base::decl_cdecl_fn(ccx, stringify!($cname),
888                                       Type::func(&[$($arg),*], &$ret),
889                                       ty::mk_nil(ccx.tcx()));
890                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
891                 return Some(f);
892             }
893         )
894     }
895
896     compatible_ifn!("llvm.copysign.f32", copysignf(t_f32, t_f32) -> t_f32);
897     compatible_ifn!("llvm.copysign.f64", copysign(t_f64, t_f64) -> t_f64);
898     compatible_ifn!("llvm.round.f32", roundf(t_f32) -> t_f32);
899     compatible_ifn!("llvm.round.f64", round(t_f64) -> t_f64);
900
901
902     if ccx.sess().opts.debuginfo != NoDebugInfo {
903         ifn!("llvm.dbg.declare" fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
904         ifn!("llvm.dbg.value" fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);
905     }
906     return None;
907 }