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.
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.
12 use llvm::{ContextRef, ModuleRef, ValueRef, BuilderRef};
13 use rustc::dep_graph::{DepNode, DepTrackingMap, DepTrackingMapConfig, WorkProduct};
14 use middle::cstore::LinkMeta;
15 use rustc::hir::def::ExportMap;
16 use rustc::hir::def_id::DefId;
18 use rustc::mir::mir_map::MirMap;
19 use rustc::mir::repr as mir;
23 use common::BuilderRef_res;
26 use glue::DropGlueKind;
28 use monomorphize::Instance;
30 use partitioning::CodegenUnit;
31 use trans_item::TransItem;
32 use type_::{Type, TypeNames};
33 use rustc::ty::subst::{Substs, VecPerParamSpace};
34 use rustc::ty::{self, Ty, TyCtxt};
35 use session::config::NoDebugInfo;
37 use symbol_map::SymbolMap;
38 use util::sha2::Sha256;
39 use util::nodemap::{NodeSet, DefIdMap, FnvHashMap, FnvHashSet};
41 use std::ffi::{CStr, CString};
42 use std::cell::{Cell, RefCell};
43 use std::marker::PhantomData;
48 use syntax::parse::token::InternedString;
52 pub n_glues_created: Cell<usize>,
53 pub n_null_glues: Cell<usize>,
54 pub n_real_glues: Cell<usize>,
55 pub n_fallback_instantiations: Cell<usize>,
56 pub n_fns: Cell<usize>,
57 pub n_monos: Cell<usize>,
58 pub n_inlines: Cell<usize>,
59 pub n_closures: Cell<usize>,
60 pub n_llvm_insns: Cell<usize>,
61 pub llvm_insns: RefCell<FnvHashMap<String, usize>>,
62 // (ident, llvm-instructions)
63 pub fn_stats: RefCell<Vec<(String, usize)> >,
66 /// The shared portion of a `CrateContext`. There is one `SharedCrateContext`
67 /// per crate. The data here is shared between all compilation units of the
68 /// crate, so it must not contain references to any LLVM data structures
69 /// (aside from metadata-related ones).
70 pub struct SharedCrateContext<'a, 'tcx: 'a> {
71 metadata_llmod: ModuleRef,
72 metadata_llcx: ContextRef,
74 export_map: ExportMap,
77 symbol_hasher: RefCell<Sha256>,
78 tcx: TyCtxt<'a, 'tcx, 'tcx>,
81 check_drop_flag_for_sanity: bool,
82 mir_map: &'a MirMap<'tcx>,
83 mir_cache: RefCell<DefIdMap<Rc<mir::Mir<'tcx>>>>,
85 use_dll_storage_attrs: bool,
87 translation_items: RefCell<FnvHashSet<TransItem<'tcx>>>,
88 trait_cache: RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>>,
91 /// The local portion of a `CrateContext`. There is one `LocalCrateContext`
92 /// per compilation unit. Each one has its own LLVM `ContextRef` so that
93 /// several compilation units may be optimized in parallel. All other LLVM
94 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
95 pub struct LocalCrateContext<'tcx> {
98 previous_work_product: Option<WorkProduct>,
99 tn: TypeNames, // FIXME: This seems to be largely unused.
100 codegen_unit: CodegenUnit<'tcx>,
101 needs_unwind_cleanup_cache: RefCell<FnvHashMap<Ty<'tcx>, bool>>,
102 fn_pointer_shims: RefCell<FnvHashMap<Ty<'tcx>, ValueRef>>,
103 drop_glues: RefCell<FnvHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>>,
104 /// Cache instances of monomorphic and polymorphic items
105 instances: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
106 monomorphizing: RefCell<DefIdMap<usize>>,
107 /// Cache generated vtables
108 vtables: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>>,
109 /// Cache of constant strings,
110 const_cstr_cache: RefCell<FnvHashMap<InternedString, ValueRef>>,
112 /// Reverse-direction for const ptrs cast from globals.
113 /// Key is a ValueRef holding a *T,
114 /// Val is a ValueRef holding a *[T].
116 /// Needed because LLVM loses pointer->pointee association
117 /// when we ptrcast, and we have to ptrcast during translation
118 /// of a [T] const because we form a slice, a (*T,usize) pair, not
119 /// a pointer to an LLVM array type. Similar for trait objects.
120 const_unsized: RefCell<FnvHashMap<ValueRef, ValueRef>>,
122 /// Cache of emitted const globals (value -> global)
123 const_globals: RefCell<FnvHashMap<ValueRef, ValueRef>>,
125 /// Cache of emitted const values
126 const_values: RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
128 /// Cache of external const values
129 extern_const_values: RefCell<DefIdMap<ValueRef>>,
131 /// Mapping from static definitions to their DefId's.
132 statics: RefCell<FnvHashMap<ValueRef, DefId>>,
134 impl_method_cache: RefCell<FnvHashMap<(DefId, ast::Name), DefId>>,
136 /// Cache of closure wrappers for bare fn's.
137 closure_bare_wrapper_cache: RefCell<FnvHashMap<ValueRef, ValueRef>>,
139 /// List of globals for static variables which need to be passed to the
140 /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete.
141 /// (We have to make sure we don't invalidate any ValueRefs referring
143 statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
145 lltypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
146 llsizingtypes: RefCell<FnvHashMap<Ty<'tcx>, Type>>,
147 adt_reprs: RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>>,
148 type_hashcodes: RefCell<FnvHashMap<Ty<'tcx>, String>>,
150 opaque_vec_type: Type,
151 builder: BuilderRef_res,
153 /// Holds the LLVM values for closure IDs.
154 closure_vals: RefCell<FnvHashMap<Instance<'tcx>, ValueRef>>,
156 dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
158 eh_personality: Cell<Option<ValueRef>>,
159 eh_unwind_resume: Cell<Option<ValueRef>>,
160 rust_try_fn: Cell<Option<ValueRef>>,
162 intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
164 /// Number of LLVM instructions translated into this `LocalCrateContext`.
165 /// This is used to perform some basic load-balancing to keep all LLVM
166 /// contexts around the same size.
167 n_llvm_insns: Cell<usize>,
169 /// Depth of the current type-of computation - used to bail out
170 type_of_depth: Cell<usize>,
172 symbol_map: Rc<SymbolMap<'tcx>>,
175 // Implement DepTrackingMapConfig for `trait_cache`
176 pub struct TraitSelectionCache<'tcx> {
177 data: PhantomData<&'tcx ()>
180 impl<'tcx> DepTrackingMapConfig for TraitSelectionCache<'tcx> {
181 type Key = ty::PolyTraitRef<'tcx>;
182 type Value = traits::Vtable<'tcx, ()>;
183 fn to_dep_node(key: &ty::PolyTraitRef<'tcx>) -> DepNode<DefId> {
184 key.to_poly_trait_predicate().dep_node()
188 /// This list owns a number of LocalCrateContexts and binds them to their common
189 /// SharedCrateContext. This type just exists as a convenience, something to
190 /// pass around all LocalCrateContexts with and get an iterator over them.
191 pub struct CrateContextList<'a, 'tcx: 'a> {
192 shared: &'a SharedCrateContext<'a, 'tcx>,
193 local_ccxs: Vec<LocalCrateContext<'tcx>>,
196 impl<'a, 'tcx: 'a> CrateContextList<'a, 'tcx> {
197 pub fn new(shared_ccx: &'a SharedCrateContext<'a, 'tcx>,
198 codegen_units: Vec<CodegenUnit<'tcx>>,
199 previous_work_products: Vec<Option<WorkProduct>>,
200 symbol_map: Rc<SymbolMap<'tcx>>)
201 -> CrateContextList<'a, 'tcx> {
204 local_ccxs: codegen_units.into_iter().zip(previous_work_products).map(|(cgu, wp)| {
205 LocalCrateContext::new(shared_ccx, cgu, wp, symbol_map.clone())
210 /// Iterate over all crate contexts, whether or not they need
211 /// translation. That is, whether or not a `.o` file is available
212 /// for re-use from a previous incr. comp.).
213 pub fn iter_all<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
214 CrateContextIterator {
217 local_ccxs: &self.local_ccxs[..],
218 filter_to_previous_work_product_unavail: false,
222 /// Iterator over all CCX that need translation (cannot reuse results from
223 /// previous incr. comp.).
224 pub fn iter_need_trans<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
225 CrateContextIterator {
228 local_ccxs: &self.local_ccxs[..],
229 filter_to_previous_work_product_unavail: true,
233 pub fn shared(&self) -> &'a SharedCrateContext<'a, 'tcx> {
238 /// A CrateContext value binds together one LocalCrateContext with the
239 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
240 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
241 pub struct CrateContext<'a, 'tcx: 'a> {
242 shared: &'a SharedCrateContext<'a, 'tcx>,
243 local_ccxs: &'a [LocalCrateContext<'tcx>],
244 /// The index of `local` in `local_ccxs`. This is used in
245 /// `maybe_iter(true)` to identify the original `LocalCrateContext`.
249 pub struct CrateContextIterator<'a, 'tcx: 'a> {
250 shared: &'a SharedCrateContext<'a, 'tcx>,
251 local_ccxs: &'a [LocalCrateContext<'tcx>],
254 /// if true, only return results where `previous_work_product` is none
255 filter_to_previous_work_product_unavail: bool,
258 impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> {
259 type Item = CrateContext<'a, 'tcx>;
261 fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> {
263 if self.index >= self.local_ccxs.len() {
267 let index = self.index;
270 let ccx = CrateContext {
273 local_ccxs: self.local_ccxs,
277 self.filter_to_previous_work_product_unavail &&
278 ccx.previous_work_product().is_some()
288 /// The iterator produced by `CrateContext::maybe_iter`.
289 pub struct CrateContextMaybeIterator<'a, 'tcx: 'a> {
290 shared: &'a SharedCrateContext<'a, 'tcx>,
291 local_ccxs: &'a [LocalCrateContext<'tcx>],
297 impl<'a, 'tcx> Iterator for CrateContextMaybeIterator<'a, 'tcx> {
298 type Item = (CrateContext<'a, 'tcx>, bool);
300 fn next(&mut self) -> Option<(CrateContext<'a, 'tcx>, bool)> {
301 if self.index >= self.local_ccxs.len() {
305 let index = self.index;
308 self.index = self.local_ccxs.len();
311 let ccx = CrateContext {
314 local_ccxs: self.local_ccxs
316 Some((ccx, index == self.origin))
320 unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
321 let llcx = llvm::LLVMContextCreate();
322 let mod_name = CString::new(mod_name).unwrap();
323 let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
325 // Ensure the data-layout values hardcoded remain the defaults.
326 if sess.target.target.options.is_builtin {
327 let tm = ::back::write::create_target_machine(sess);
328 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
329 llvm::LLVMRustDisposeTargetMachine(tm);
331 let data_layout = llvm::LLVMGetDataLayout(llmod);
332 let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
333 .ok().expect("got a non-UTF8 data-layout from LLVM");
335 if sess.target.target.data_layout != data_layout {
336 bug!("data-layout for builtin `{}` target, `{}`, \
337 differs from LLVM default, `{}`",
338 sess.target.target.llvm_target,
339 sess.target.target.data_layout,
344 let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
345 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
347 let llvm_target = sess.target.target.llvm_target.as_bytes();
348 let llvm_target = CString::new(llvm_target).unwrap();
349 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
353 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
354 pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
355 mir_map: &'b MirMap<'tcx>,
356 export_map: ExportMap,
357 symbol_hasher: Sha256,
360 check_overflow: bool,
361 check_drop_flag_for_sanity: bool)
362 -> SharedCrateContext<'b, 'tcx> {
363 let (metadata_llcx, metadata_llmod) = unsafe {
364 create_context_and_module(&tcx.sess, "metadata")
367 // An interesting part of Windows which MSVC forces our hand on (and
368 // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
369 // attributes in LLVM IR as well as native dependencies (in C these
370 // correspond to `__declspec(dllimport)`).
372 // Whenever a dynamic library is built by MSVC it must have its public
373 // interface specified by functions tagged with `dllexport` or otherwise
374 // they're not available to be linked against. This poses a few problems
375 // for the compiler, some of which are somewhat fundamental, but we use
376 // the `use_dll_storage_attrs` variable below to attach the `dllexport`
377 // attribute to all LLVM functions that are reachable (e.g. they're
378 // already tagged with external linkage). This is suboptimal for a few
381 // * If an object file will never be included in a dynamic library,
382 // there's no need to attach the dllexport attribute. Most object
383 // files in Rust are not destined to become part of a dll as binaries
384 // are statically linked by default.
385 // * If the compiler is emitting both an rlib and a dylib, the same
386 // source object file is currently used but with MSVC this may be less
387 // feasible. The compiler may be able to get around this, but it may
388 // involve some invasive changes to deal with this.
390 // The flipside of this situation is that whenever you link to a dll and
391 // you import a function from it, the import should be tagged with
392 // `dllimport`. At this time, however, the compiler does not emit
393 // `dllimport` for any declarations other than constants (where it is
394 // required), which is again suboptimal for even more reasons!
396 // * Calling a function imported from another dll without using
397 // `dllimport` causes the linker/compiler to have extra overhead (one
398 // `jmp` instruction on x86) when calling the function.
399 // * The same object file may be used in different circumstances, so a
400 // function may be imported from a dll if the object is linked into a
401 // dll, but it may be just linked against if linked into an rlib.
402 // * The compiler has no knowledge about whether native functions should
403 // be tagged dllimport or not.
405 // For now the compiler takes the perf hit (I do not have any numbers to
406 // this effect) by marking very little as `dllimport` and praying the
407 // linker will take care of everything. Fixing this problem will likely
408 // require adding a few attributes to Rust itself (feature gated at the
409 // start) and then strongly recommending static linkage on MSVC!
410 let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
413 metadata_llmod: metadata_llmod,
414 metadata_llcx: metadata_llcx,
415 export_map: export_map,
416 reachable: reachable,
417 link_meta: link_meta,
418 symbol_hasher: RefCell::new(symbol_hasher),
421 mir_cache: RefCell::new(DefIdMap()),
423 n_glues_created: Cell::new(0),
424 n_null_glues: Cell::new(0),
425 n_real_glues: Cell::new(0),
426 n_fallback_instantiations: Cell::new(0),
428 n_monos: Cell::new(0),
429 n_inlines: Cell::new(0),
430 n_closures: Cell::new(0),
431 n_llvm_insns: Cell::new(0),
432 llvm_insns: RefCell::new(FnvHashMap()),
433 fn_stats: RefCell::new(Vec::new()),
435 check_overflow: check_overflow,
436 check_drop_flag_for_sanity: check_drop_flag_for_sanity,
437 use_dll_storage_attrs: use_dll_storage_attrs,
438 translation_items: RefCell::new(FnvHashSet()),
439 trait_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
443 pub fn metadata_llmod(&self) -> ModuleRef {
447 pub fn metadata_llcx(&self) -> ContextRef {
451 pub fn export_map<'a>(&'a self) -> &'a ExportMap {
455 pub fn reachable<'a>(&'a self) -> &'a NodeSet {
459 pub fn trait_cache(&self) -> &RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>> {
463 pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
467 pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
471 pub fn sess<'a>(&'a self) -> &'a Session {
475 pub fn stats<'a>(&'a self) -> &'a Stats {
479 pub fn use_dll_storage_attrs(&self) -> bool {
480 self.use_dll_storage_attrs
483 pub fn get_mir(&self, def_id: DefId) -> Option<CachedMir<'b, 'tcx>> {
484 if def_id.is_local() {
485 let node_id = self.tcx.map.as_local_node_id(def_id).unwrap();
486 self.mir_map.map.get(&node_id).map(CachedMir::Ref)
488 if let Some(mir) = self.mir_cache.borrow().get(&def_id).cloned() {
489 return Some(CachedMir::Owned(mir));
492 let mir = self.sess().cstore.maybe_get_item_mir(self.tcx, def_id);
493 let cached = mir.map(Rc::new);
494 if let Some(ref mir) = cached {
495 self.mir_cache.borrow_mut().insert(def_id, mir.clone());
497 cached.map(CachedMir::Owned)
501 pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
502 &self.translation_items
505 /// Given the def-id of some item that has no type parameters, make
506 /// a suitable "empty substs" for it.
507 pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
508 let scheme = self.tcx().lookup_item_type(item_def_id);
509 self.empty_substs_for_scheme(&scheme)
512 pub fn empty_substs_for_scheme(&self, scheme: &ty::TypeScheme<'tcx>)
513 -> &'tcx Substs<'tcx> {
514 assert!(scheme.generics.types.is_empty());
515 self.tcx().mk_substs(
516 Substs::new(VecPerParamSpace::empty(),
517 scheme.generics.regions.map(|_| ty::ReErased)))
520 pub fn symbol_hasher(&self) -> &RefCell<Sha256> {
524 pub fn mir_map(&self) -> &MirMap<'tcx> {
528 pub fn metadata_symbol_name(&self) -> String {
529 format!("rust_metadata_{}_{}",
530 self.link_meta().crate_name,
531 self.link_meta().crate_hash)
535 impl<'tcx> LocalCrateContext<'tcx> {
536 fn new<'a>(shared: &SharedCrateContext<'a, 'tcx>,
537 codegen_unit: CodegenUnit<'tcx>,
538 previous_work_product: Option<WorkProduct>,
539 symbol_map: Rc<SymbolMap<'tcx>>)
540 -> LocalCrateContext<'tcx> {
542 // Append ".rs" to LLVM module identifier.
544 // LLVM code generator emits a ".file filename" directive
545 // for ELF backends. Value of the "filename" is set as the
546 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
547 // crashes if the module identifier is same as other symbols
548 // such as a function name in the module.
549 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
550 let llmod_id = format!("{}.rs", codegen_unit.name());
552 let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
555 let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
556 Some(debuginfo::CrateDebugContext::new(llmod))
561 let local_ccx = LocalCrateContext {
564 previous_work_product: previous_work_product,
565 codegen_unit: codegen_unit,
566 tn: TypeNames::new(),
567 needs_unwind_cleanup_cache: RefCell::new(FnvHashMap()),
568 fn_pointer_shims: RefCell::new(FnvHashMap()),
569 drop_glues: RefCell::new(FnvHashMap()),
570 instances: RefCell::new(FnvHashMap()),
571 monomorphizing: RefCell::new(DefIdMap()),
572 vtables: RefCell::new(FnvHashMap()),
573 const_cstr_cache: RefCell::new(FnvHashMap()),
574 const_unsized: RefCell::new(FnvHashMap()),
575 const_globals: RefCell::new(FnvHashMap()),
576 const_values: RefCell::new(FnvHashMap()),
577 extern_const_values: RefCell::new(DefIdMap()),
578 statics: RefCell::new(FnvHashMap()),
579 impl_method_cache: RefCell::new(FnvHashMap()),
580 closure_bare_wrapper_cache: RefCell::new(FnvHashMap()),
581 statics_to_rauw: RefCell::new(Vec::new()),
582 lltypes: RefCell::new(FnvHashMap()),
583 llsizingtypes: RefCell::new(FnvHashMap()),
584 adt_reprs: RefCell::new(FnvHashMap()),
585 type_hashcodes: RefCell::new(FnvHashMap()),
586 int_type: Type::from_ref(ptr::null_mut()),
587 opaque_vec_type: Type::from_ref(ptr::null_mut()),
588 builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
589 closure_vals: RefCell::new(FnvHashMap()),
591 eh_personality: Cell::new(None),
592 eh_unwind_resume: Cell::new(None),
593 rust_try_fn: Cell::new(None),
594 intrinsics: RefCell::new(FnvHashMap()),
595 n_llvm_insns: Cell::new(0),
596 type_of_depth: Cell::new(0),
597 symbol_map: symbol_map,
600 let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = {
601 // Do a little dance to create a dummy CrateContext, so we can
602 // create some things in the LLVM module of this codegen unit
603 let mut local_ccxs = vec![local_ccx];
604 let (int_type, opaque_vec_type, str_slice_ty) = {
605 let dummy_ccx = LocalCrateContext::dummy_ccx(shared,
606 local_ccxs.as_mut_slice());
607 let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice");
608 str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx),
609 Type::int(&dummy_ccx)],
611 (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty)
613 (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap())
616 local_ccx.int_type = int_type;
617 local_ccx.opaque_vec_type = opaque_vec_type;
618 local_ccx.tn.associate_type("str_slice", &str_slice_ty);
620 if shared.tcx.sess.count_llvm_insns() {
621 base::init_insn_ctxt()
628 /// Create a dummy `CrateContext` from `self` and the provided
629 /// `SharedCrateContext`. This is somewhat dangerous because `self` may
630 /// not be fully initialized.
632 /// This is used in the `LocalCrateContext` constructor to allow calling
633 /// functions that expect a complete `CrateContext`, even before the local
634 /// portion is fully initialized and attached to the `SharedCrateContext`.
635 fn dummy_ccx<'a>(shared: &'a SharedCrateContext<'a, 'tcx>,
636 local_ccxs: &'a [LocalCrateContext<'tcx>])
637 -> CrateContext<'a, 'tcx> {
638 assert!(local_ccxs.len() == 1);
642 local_ccxs: local_ccxs
647 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
648 pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
652 pub fn local(&self) -> &'b LocalCrateContext<'tcx> {
653 &self.local_ccxs[self.index]
656 /// Get a (possibly) different `CrateContext` from the same
657 /// `SharedCrateContext`.
658 pub fn rotate(&'b self) -> CrateContext<'b, 'tcx> {
662 .zip(0..self.local_ccxs.len())
663 .min_by_key(|&(local_ccx, _idx)| local_ccx.n_llvm_insns.get())
668 local_ccxs: &self.local_ccxs[..],
672 /// Either iterate over only `self`, or iterate over all `CrateContext`s in
673 /// the `SharedCrateContext`. The iterator produces `(ccx, is_origin)`
674 /// pairs, where `is_origin` is `true` if `ccx` is `self` and `false`
675 /// otherwise. This method is useful for avoiding code duplication in
676 /// cases where it may or may not be necessary to translate code into every
678 pub fn maybe_iter(&self, iter_all: bool) -> CrateContextMaybeIterator<'b, 'tcx> {
679 CrateContextMaybeIterator {
681 index: if iter_all { 0 } else { self.index },
684 local_ccxs: self.local_ccxs,
688 pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
692 pub fn sess<'a>(&'a self) -> &'a Session {
693 &self.shared.tcx.sess
696 pub fn builder<'a>(&'a self) -> Builder<'a, 'tcx> {
700 pub fn raw_builder<'a>(&'a self) -> BuilderRef {
701 self.local().builder.b
704 pub fn get_intrinsic(&self, key: &str) -> ValueRef {
705 if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
708 match declare_intrinsic(self, key) {
710 None => bug!("unknown intrinsic '{}'", key)
714 pub fn llmod(&self) -> ModuleRef {
718 pub fn llcx(&self) -> ContextRef {
722 pub fn previous_work_product(&self) -> Option<&WorkProduct> {
723 self.local().previous_work_product.as_ref()
726 pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> {
727 &self.local().codegen_unit
730 pub fn td(&self) -> llvm::TargetDataRef {
731 unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
734 pub fn tn<'a>(&'a self) -> &'a TypeNames {
738 pub fn export_map<'a>(&'a self) -> &'a ExportMap {
739 &self.shared.export_map
742 pub fn reachable<'a>(&'a self) -> &'a NodeSet {
743 &self.shared.reachable
746 pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
747 &self.shared.link_meta
750 pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, bool>> {
751 &self.local().needs_unwind_cleanup_cache
754 pub fn fn_pointer_shims(&self) -> &RefCell<FnvHashMap<Ty<'tcx>, ValueRef>> {
755 &self.local().fn_pointer_shims
758 pub fn drop_glues<'a>(&'a self)
759 -> &'a RefCell<FnvHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>> {
760 &self.local().drop_glues
763 pub fn local_node_for_inlined_defid<'a>(&'a self, def_id: DefId) -> Option<ast::NodeId> {
764 self.sess().cstore.local_node_for_inlined_defid(def_id)
767 pub fn defid_for_inlined_node<'a>(&'a self, node_id: ast::NodeId) -> Option<DefId> {
768 self.sess().cstore.defid_for_inlined_node(node_id)
771 pub fn instances<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
772 &self.local().instances
775 pub fn monomorphizing<'a>(&'a self) -> &'a RefCell<DefIdMap<usize>> {
776 &self.local().monomorphizing
779 pub fn vtables<'a>(&'a self) -> &'a RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, ValueRef>> {
780 &self.local().vtables
783 pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<InternedString, ValueRef>> {
784 &self.local().const_cstr_cache
787 pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
788 &self.local().const_unsized
791 pub fn const_globals<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
792 &self.local().const_globals
795 pub fn const_values<'a>(&'a self) -> &'a RefCell<FnvHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
797 &self.local().const_values
800 pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
801 &self.local().extern_const_values
804 pub fn statics<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, DefId>> {
805 &self.local().statics
808 pub fn impl_method_cache<'a>(&'a self)
809 -> &'a RefCell<FnvHashMap<(DefId, ast::Name), DefId>> {
810 &self.local().impl_method_cache
813 pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FnvHashMap<ValueRef, ValueRef>> {
814 &self.local().closure_bare_wrapper_cache
817 pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
818 &self.local().statics_to_rauw
821 pub fn lltypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
822 &self.local().lltypes
825 pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Type>> {
826 &self.local().llsizingtypes
829 pub fn adt_reprs<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, Rc<adt::Repr<'tcx>>>> {
830 &self.local().adt_reprs
833 pub fn symbol_hasher<'a>(&'a self) -> &'a RefCell<Sha256> {
834 &self.shared.symbol_hasher
837 pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FnvHashMap<Ty<'tcx>, String>> {
838 &self.local().type_hashcodes
841 pub fn stats<'a>(&'a self) -> &'a Stats {
845 pub fn int_type(&self) -> Type {
846 self.local().int_type
849 pub fn opaque_vec_type(&self) -> Type {
850 self.local().opaque_vec_type
853 pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FnvHashMap<Instance<'tcx>, ValueRef>> {
854 &self.local().closure_vals
857 pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
861 pub fn eh_personality<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
862 &self.local().eh_personality
865 pub fn eh_unwind_resume<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
866 &self.local().eh_unwind_resume
869 pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
870 &self.local().rust_try_fn
873 fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
874 &self.local().intrinsics
877 pub fn count_llvm_insn(&self) {
878 self.local().n_llvm_insns.set(self.local().n_llvm_insns.get() + 1);
881 pub fn obj_size_bound(&self) -> u64 {
882 self.tcx().data_layout.obj_size_bound()
885 pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
887 &format!("the type `{:?}` is too big for the current architecture",
891 pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
892 let current_depth = self.local().type_of_depth.get();
893 debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
894 if current_depth > self.sess().recursion_limit.get() {
896 &format!("overflow representing the type `{}`", ty))
898 self.local().type_of_depth.set(current_depth + 1);
899 TypeOfDepthLock(self.local())
902 pub fn check_overflow(&self) -> bool {
903 self.shared.check_overflow
906 pub fn check_drop_flag_for_sanity(&self) -> bool {
907 // This controls whether we emit a conditional llvm.debugtrap
908 // guarded on whether the dropflag is one of its (two) valid
910 self.shared.check_drop_flag_for_sanity
913 pub fn use_dll_storage_attrs(&self) -> bool {
914 self.shared.use_dll_storage_attrs()
917 pub fn get_mir(&self, def_id: DefId) -> Option<CachedMir<'b, 'tcx>> {
918 self.shared.get_mir(def_id)
921 pub fn symbol_map(&self) -> &SymbolMap<'tcx> {
922 &*self.local().symbol_map
925 pub fn translation_items(&self) -> &RefCell<FnvHashSet<TransItem<'tcx>>> {
926 &self.shared.translation_items
929 /// Given the def-id of some item that has no type parameters, make
930 /// a suitable "empty substs" for it.
931 pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
932 self.shared().empty_substs_for_def_id(item_def_id)
935 pub fn empty_substs_for_scheme(&self, scheme: &ty::TypeScheme<'tcx>)
936 -> &'tcx Substs<'tcx> {
937 self.shared().empty_substs_for_scheme(scheme)
941 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>);
943 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
945 self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
949 /// Declare any llvm intrinsics that you might need
950 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
952 ($name:expr, fn() -> $ret:expr) => (
954 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
955 llvm::SetUnnamedAddr(f, false);
956 ccx.intrinsics().borrow_mut().insert($name, f.clone());
960 ($name:expr, fn(...) -> $ret:expr) => (
962 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
963 llvm::SetUnnamedAddr(f, false);
964 ccx.intrinsics().borrow_mut().insert($name, f.clone());
968 ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
970 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
971 llvm::SetUnnamedAddr(f, false);
972 ccx.intrinsics().borrow_mut().insert($name, f.clone());
977 macro_rules! mk_struct {
978 ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
981 let i8p = Type::i8p(ccx);
982 let void = Type::void(ccx);
983 let i1 = Type::i1(ccx);
984 let t_i8 = Type::i8(ccx);
985 let t_i16 = Type::i16(ccx);
986 let t_i32 = Type::i32(ccx);
987 let t_i64 = Type::i64(ccx);
988 let t_f32 = Type::f32(ccx);
989 let t_f64 = Type::f64(ccx);
991 ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
992 ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
993 ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
994 ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
995 ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
996 ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
997 ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
998 ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
999 ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
1001 ifn!("llvm.trap", fn() -> void);
1002 ifn!("llvm.debugtrap", fn() -> void);
1003 ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
1005 ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
1006 ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
1007 ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
1008 ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
1010 ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
1011 ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
1012 ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
1013 ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
1014 ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
1015 ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
1016 ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
1017 ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
1018 ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
1019 ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
1020 ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
1021 ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
1022 ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
1023 ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
1024 ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
1025 ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
1027 ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
1028 ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
1030 ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
1031 ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
1033 ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
1034 ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
1035 ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
1036 ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
1037 ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
1038 ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
1040 ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
1041 ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
1042 ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
1043 ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
1045 ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
1046 ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
1047 ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
1048 ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
1050 ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
1051 ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
1052 ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
1053 ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
1055 ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
1056 ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
1057 ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
1058 ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
1060 ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
1061 ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
1062 ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
1063 ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
1065 ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
1066 ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
1067 ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
1069 ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1070 ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1071 ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1072 ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1074 ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1075 ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1076 ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1077 ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1079 ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1080 ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1081 ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1082 ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1084 ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1085 ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1086 ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1087 ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1089 ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1090 ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1091 ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1092 ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1094 ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1095 ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1096 ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1097 ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1099 ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
1100 ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
1102 ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
1103 ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
1104 ifn!("llvm.localescape", fn(...) -> void);
1105 ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
1106 ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
1108 ifn!("llvm.assume", fn(i1) -> void);
1110 if ccx.sess().opts.debuginfo != NoDebugInfo {
1111 ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
1112 ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);