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};
13 use rustc::dep_graph::{DepGraph, DepGraphSafe, DepNode, DepTrackingMap,
14 DepTrackingMapConfig, WorkProduct};
15 use middle::cstore::LinkMeta;
17 use rustc::hir::def_id::DefId;
23 use monomorphize::Instance;
25 use partitioning::CodegenUnit;
26 use trans_item::TransItem;
28 use rustc_data_structures::base_n;
29 use rustc::ty::subst::Substs;
30 use rustc::ty::{self, Ty, TyCtxt};
31 use session::config::NoDebugInfo;
34 use symbol_map::SymbolMap;
35 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
37 use std::ffi::{CStr, CString};
38 use std::cell::{Cell, RefCell};
39 use std::marker::PhantomData;
45 use syntax::symbol::InternedString;
46 use syntax_pos::DUMMY_SP;
50 pub n_glues_created: Cell<usize>,
51 pub n_null_glues: Cell<usize>,
52 pub n_real_glues: Cell<usize>,
53 pub n_fns: Cell<usize>,
54 pub n_inlines: Cell<usize>,
55 pub n_closures: Cell<usize>,
56 pub n_llvm_insns: Cell<usize>,
57 pub llvm_insns: RefCell<FxHashMap<String, usize>>,
58 // (ident, llvm-instructions)
59 pub fn_stats: RefCell<Vec<(String, usize)> >,
62 /// The shared portion of a `CrateContext`. There is one `SharedCrateContext`
63 /// per crate. The data here is shared between all compilation units of the
64 /// crate, so it must not contain references to any LLVM data structures
65 /// (aside from metadata-related ones).
66 pub struct SharedCrateContext<'a, 'tcx: 'a> {
67 metadata_llmod: ModuleRef,
68 metadata_llcx: ContextRef,
70 exported_symbols: NodeSet,
72 tcx: TyCtxt<'a, 'tcx, 'tcx>,
73 empty_param_env: ty::ParameterEnvironment<'tcx>,
77 use_dll_storage_attrs: bool,
79 translation_items: RefCell<FxHashSet<TransItem<'tcx>>>,
80 trait_cache: RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>>,
81 project_cache: RefCell<DepTrackingMap<ProjectionCache<'tcx>>>,
84 /// The local portion of a `CrateContext`. There is one `LocalCrateContext`
85 /// per compilation unit. Each one has its own LLVM `ContextRef` so that
86 /// several compilation units may be optimized in parallel. All other LLVM
87 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
88 pub struct LocalCrateContext<'tcx> {
91 previous_work_product: Option<WorkProduct>,
92 codegen_unit: CodegenUnit<'tcx>,
93 needs_unwind_cleanup_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
94 /// Cache instances of monomorphic and polymorphic items
95 instances: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>,
96 /// Cache generated vtables
97 vtables: RefCell<FxHashMap<(ty::Ty<'tcx>,
98 Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>>,
99 /// Cache of constant strings,
100 const_cstr_cache: RefCell<FxHashMap<InternedString, ValueRef>>,
102 /// Reverse-direction for const ptrs cast from globals.
103 /// Key is a ValueRef holding a *T,
104 /// Val is a ValueRef holding a *[T].
106 /// Needed because LLVM loses pointer->pointee association
107 /// when we ptrcast, and we have to ptrcast during translation
108 /// of a [T] const because we form a slice, a (*T,usize) pair, not
109 /// a pointer to an LLVM array type. Similar for trait objects.
110 const_unsized: RefCell<FxHashMap<ValueRef, ValueRef>>,
112 /// Cache of emitted const globals (value -> global)
113 const_globals: RefCell<FxHashMap<ValueRef, ValueRef>>,
115 /// Cache of emitted const values
116 const_values: RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
118 /// Cache of external const values
119 extern_const_values: RefCell<DefIdMap<ValueRef>>,
121 /// Mapping from static definitions to their DefId's.
122 statics: RefCell<FxHashMap<ValueRef, DefId>>,
124 impl_method_cache: RefCell<FxHashMap<(DefId, ast::Name), DefId>>,
126 /// Cache of closure wrappers for bare fn's.
127 closure_bare_wrapper_cache: RefCell<FxHashMap<ValueRef, ValueRef>>,
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
133 statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
135 lltypes: RefCell<FxHashMap<Ty<'tcx>, Type>>,
136 llsizingtypes: RefCell<FxHashMap<Ty<'tcx>, Type>>,
137 type_hashcodes: RefCell<FxHashMap<Ty<'tcx>, String>>,
139 opaque_vec_type: Type,
140 str_slice_type: Type,
142 /// Holds the LLVM values for closure IDs.
143 closure_vals: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>,
145 dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
147 eh_personality: Cell<Option<ValueRef>>,
148 eh_unwind_resume: Cell<Option<ValueRef>>,
149 rust_try_fn: Cell<Option<ValueRef>>,
151 intrinsics: RefCell<FxHashMap<&'static str, ValueRef>>,
153 /// Depth of the current type-of computation - used to bail out
154 type_of_depth: Cell<usize>,
156 symbol_map: Rc<SymbolMap<'tcx>>,
158 /// A counter that is used for generating local symbol names
159 local_gen_sym_counter: Cell<usize>,
162 // Implement DepTrackingMapConfig for `trait_cache`
163 pub struct TraitSelectionCache<'tcx> {
164 data: PhantomData<&'tcx ()>
167 impl<'tcx> DepTrackingMapConfig for TraitSelectionCache<'tcx> {
168 type Key = ty::PolyTraitRef<'tcx>;
169 type Value = traits::Vtable<'tcx, ()>;
170 fn to_dep_node(key: &ty::PolyTraitRef<'tcx>) -> DepNode<DefId> {
171 key.to_poly_trait_predicate().dep_node()
177 pub struct ProjectionCache<'gcx> {
178 data: PhantomData<&'gcx ()>
181 impl<'gcx> DepTrackingMapConfig for ProjectionCache<'gcx> {
183 type Value = Ty<'gcx>;
184 fn to_dep_node(key: &Self::Key) -> DepNode<DefId> {
185 // Ideally, we'd just put `key` into the dep-node, but we
186 // can't put full types in there. So just collect up all the
187 // def-ids of structs/enums as well as any traits that we
188 // project out of. It doesn't matter so much what we do here,
189 // except that if we are too coarse, we'll create overly
190 // coarse edges between impls and the trans. For example, if
191 // we just used the def-id of things we are projecting out of,
192 // then the key for `<Foo as SomeTrait>::T` and `<Bar as
193 // SomeTrait>::T` would both share a dep-node
194 // (`TraitSelect(SomeTrait)`), and hence the impls for both
195 // `Foo` and `Bar` would be considered inputs. So a change to
196 // `Bar` would affect things that just normalized `Foo`.
197 // Anyway, this heuristic is not ideal, but better than
199 let def_ids: Vec<DefId> =
201 .filter_map(|t| match t.sty {
202 ty::TyAdt(adt_def, _) => Some(adt_def.did),
203 ty::TyProjection(ref proj) => Some(proj.trait_ref.def_id),
208 DepNode::ProjectionCache { def_ids: def_ids }
212 /// This list owns a number of LocalCrateContexts and binds them to their common
213 /// SharedCrateContext. This type just exists as a convenience, something to
214 /// pass around all LocalCrateContexts with and get an iterator over them.
215 pub struct CrateContextList<'a, 'tcx: 'a> {
216 shared: &'a SharedCrateContext<'a, 'tcx>,
217 local_ccxs: Vec<LocalCrateContext<'tcx>>,
220 impl<'a, 'tcx: 'a> CrateContextList<'a, 'tcx> {
221 pub fn new(shared_ccx: &'a SharedCrateContext<'a, 'tcx>,
222 codegen_units: Vec<CodegenUnit<'tcx>>,
223 previous_work_products: Vec<Option<WorkProduct>>,
224 symbol_map: Rc<SymbolMap<'tcx>>)
225 -> CrateContextList<'a, 'tcx> {
228 local_ccxs: codegen_units.into_iter().zip(previous_work_products).map(|(cgu, wp)| {
229 LocalCrateContext::new(shared_ccx, cgu, wp, symbol_map.clone())
234 /// Iterate over all crate contexts, whether or not they need
235 /// translation. That is, whether or not a `.o` file is available
236 /// for re-use from a previous incr. comp.).
237 pub fn iter_all<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
238 CrateContextIterator {
241 local_ccxs: &self.local_ccxs[..],
242 filter_to_previous_work_product_unavail: false,
246 /// Iterator over all CCX that need translation (cannot reuse results from
247 /// previous incr. comp.).
248 pub fn iter_need_trans<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> {
249 CrateContextIterator {
252 local_ccxs: &self.local_ccxs[..],
253 filter_to_previous_work_product_unavail: true,
257 pub fn shared(&self) -> &'a SharedCrateContext<'a, 'tcx> {
262 /// A CrateContext value binds together one LocalCrateContext with the
263 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
264 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
265 pub struct CrateContext<'a, 'tcx: 'a> {
266 shared: &'a SharedCrateContext<'a, 'tcx>,
267 local_ccxs: &'a [LocalCrateContext<'tcx>],
268 /// The index of `local` in `local_ccxs`. This is used in
269 /// `maybe_iter(true)` to identify the original `LocalCrateContext`.
273 impl<'a, 'tcx> DepGraphSafe for CrateContext<'a, 'tcx> {
276 pub struct CrateContextIterator<'a, 'tcx: 'a> {
277 shared: &'a SharedCrateContext<'a, 'tcx>,
278 local_ccxs: &'a [LocalCrateContext<'tcx>],
281 /// if true, only return results where `previous_work_product` is none
282 filter_to_previous_work_product_unavail: bool,
285 impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> {
286 type Item = CrateContext<'a, 'tcx>;
288 fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> {
290 if self.index >= self.local_ccxs.len() {
294 let index = self.index;
297 let ccx = CrateContext {
300 local_ccxs: self.local_ccxs,
304 self.filter_to_previous_work_product_unavail &&
305 ccx.previous_work_product().is_some()
315 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
316 let reloc_model_arg = match sess.opts.cg.relocation_model {
317 Some(ref s) => &s[..],
318 None => &sess.target.target.options.relocation_model[..],
321 match ::back::write::RELOC_MODEL_ARGS.iter().find(
322 |&&arg| arg.0 == reloc_model_arg) {
325 sess.err(&format!("{:?} is not a valid relocation mode",
329 sess.abort_if_errors();
335 fn is_any_library(sess: &Session) -> bool {
336 sess.crate_types.borrow().iter().any(|ty| {
337 *ty != config::CrateTypeExecutable
341 pub fn is_pie_binary(sess: &Session) -> bool {
342 !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
345 unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
346 let llcx = llvm::LLVMContextCreate();
347 let mod_name = CString::new(mod_name).unwrap();
348 let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
350 // Ensure the data-layout values hardcoded remain the defaults.
351 if sess.target.target.options.is_builtin {
352 let tm = ::back::write::create_target_machine(sess);
353 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
354 llvm::LLVMRustDisposeTargetMachine(tm);
356 let data_layout = llvm::LLVMGetDataLayout(llmod);
357 let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
358 .ok().expect("got a non-UTF8 data-layout from LLVM");
360 // Unfortunately LLVM target specs change over time, and right now we
361 // don't have proper support to work with any more than one
362 // `data_layout` than the one that is in the rust-lang/rust repo. If
363 // this compiler is configured against a custom LLVM, we may have a
364 // differing data layout, even though we should update our own to use
367 // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
368 // disable this check entirely as we may be configured with something
369 // that has a different target layout.
371 // Unsure if this will actually cause breakage when rustc is configured
375 let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
376 let custom_llvm_used = cfg_llvm_root.trim() != "";
378 if !custom_llvm_used && sess.target.target.data_layout != data_layout {
379 bug!("data-layout for builtin `{}` target, `{}`, \
380 differs from LLVM default, `{}`",
381 sess.target.target.llvm_target,
382 sess.target.target.data_layout,
387 let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
388 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
390 let llvm_target = sess.target.target.llvm_target.as_bytes();
391 let llvm_target = CString::new(llvm_target).unwrap();
392 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
394 if is_pie_binary(sess) {
395 llvm::LLVMRustSetModulePIELevel(llmod);
401 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
402 pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
404 exported_symbols: NodeSet,
405 check_overflow: bool)
406 -> SharedCrateContext<'b, 'tcx> {
407 let (metadata_llcx, metadata_llmod) = unsafe {
408 create_context_and_module(&tcx.sess, "metadata")
411 // An interesting part of Windows which MSVC forces our hand on (and
412 // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
413 // attributes in LLVM IR as well as native dependencies (in C these
414 // correspond to `__declspec(dllimport)`).
416 // Whenever a dynamic library is built by MSVC it must have its public
417 // interface specified by functions tagged with `dllexport` or otherwise
418 // they're not available to be linked against. This poses a few problems
419 // for the compiler, some of which are somewhat fundamental, but we use
420 // the `use_dll_storage_attrs` variable below to attach the `dllexport`
421 // attribute to all LLVM functions that are exported e.g. they're
422 // already tagged with external linkage). This is suboptimal for a few
425 // * If an object file will never be included in a dynamic library,
426 // there's no need to attach the dllexport attribute. Most object
427 // files in Rust are not destined to become part of a dll as binaries
428 // are statically linked by default.
429 // * If the compiler is emitting both an rlib and a dylib, the same
430 // source object file is currently used but with MSVC this may be less
431 // feasible. The compiler may be able to get around this, but it may
432 // involve some invasive changes to deal with this.
434 // The flipside of this situation is that whenever you link to a dll and
435 // you import a function from it, the import should be tagged with
436 // `dllimport`. At this time, however, the compiler does not emit
437 // `dllimport` for any declarations other than constants (where it is
438 // required), which is again suboptimal for even more reasons!
440 // * Calling a function imported from another dll without using
441 // `dllimport` causes the linker/compiler to have extra overhead (one
442 // `jmp` instruction on x86) when calling the function.
443 // * The same object file may be used in different circumstances, so a
444 // function may be imported from a dll if the object is linked into a
445 // dll, but it may be just linked against if linked into an rlib.
446 // * The compiler has no knowledge about whether native functions should
447 // be tagged dllimport or not.
449 // For now the compiler takes the perf hit (I do not have any numbers to
450 // this effect) by marking very little as `dllimport` and praying the
451 // linker will take care of everything. Fixing this problem will likely
452 // require adding a few attributes to Rust itself (feature gated at the
453 // start) and then strongly recommending static linkage on MSVC!
454 let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
457 metadata_llmod: metadata_llmod,
458 metadata_llcx: metadata_llcx,
459 exported_symbols: exported_symbols,
460 link_meta: link_meta,
461 empty_param_env: tcx.empty_parameter_environment(),
464 n_glues_created: Cell::new(0),
465 n_null_glues: Cell::new(0),
466 n_real_glues: Cell::new(0),
468 n_inlines: Cell::new(0),
469 n_closures: Cell::new(0),
470 n_llvm_insns: Cell::new(0),
471 llvm_insns: RefCell::new(FxHashMap()),
472 fn_stats: RefCell::new(Vec::new()),
474 check_overflow: check_overflow,
475 use_dll_storage_attrs: use_dll_storage_attrs,
476 translation_items: RefCell::new(FxHashSet()),
477 trait_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
478 project_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())),
482 pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
483 self.tcx.type_needs_drop_given_env(ty, &self.empty_param_env)
486 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
487 ty.is_sized(self.tcx, &self.empty_param_env, DUMMY_SP)
490 pub fn metadata_llmod(&self) -> ModuleRef {
494 pub fn metadata_llcx(&self) -> ContextRef {
498 pub fn exported_symbols<'a>(&'a self) -> &'a NodeSet {
499 &self.exported_symbols
502 pub fn trait_cache(&self) -> &RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>> {
506 pub fn project_cache(&self) -> &RefCell<DepTrackingMap<ProjectionCache<'tcx>>> {
510 pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
514 pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
518 pub fn sess<'a>(&'a self) -> &'a Session {
522 pub fn dep_graph<'a>(&'a self) -> &'a DepGraph {
526 pub fn stats<'a>(&'a self) -> &'a Stats {
530 pub fn use_dll_storage_attrs(&self) -> bool {
531 self.use_dll_storage_attrs
534 pub fn translation_items(&self) -> &RefCell<FxHashSet<TransItem<'tcx>>> {
535 &self.translation_items
538 pub fn metadata_symbol_name(&self) -> String {
539 format!("rust_metadata_{}_{}",
540 self.link_meta().crate_name,
541 self.link_meta().crate_hash)
545 impl<'tcx> LocalCrateContext<'tcx> {
546 fn new<'a>(shared: &SharedCrateContext<'a, 'tcx>,
547 codegen_unit: CodegenUnit<'tcx>,
548 previous_work_product: Option<WorkProduct>,
549 symbol_map: Rc<SymbolMap<'tcx>>)
550 -> LocalCrateContext<'tcx> {
552 // Append ".rs" to LLVM module identifier.
554 // LLVM code generator emits a ".file filename" directive
555 // for ELF backends. Value of the "filename" is set as the
556 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
557 // crashes if the module identifier is same as other symbols
558 // such as a function name in the module.
559 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
560 let llmod_id = format!("{}.rs", codegen_unit.name());
562 let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
565 let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
566 let dctx = debuginfo::CrateDebugContext::new(llmod);
567 debuginfo::metadata::compile_unit_metadata(shared, &dctx, shared.tcx.sess);
573 let local_ccx = LocalCrateContext {
576 previous_work_product: previous_work_product,
577 codegen_unit: codegen_unit,
578 needs_unwind_cleanup_cache: RefCell::new(FxHashMap()),
579 instances: RefCell::new(FxHashMap()),
580 vtables: RefCell::new(FxHashMap()),
581 const_cstr_cache: RefCell::new(FxHashMap()),
582 const_unsized: RefCell::new(FxHashMap()),
583 const_globals: RefCell::new(FxHashMap()),
584 const_values: RefCell::new(FxHashMap()),
585 extern_const_values: RefCell::new(DefIdMap()),
586 statics: RefCell::new(FxHashMap()),
587 impl_method_cache: RefCell::new(FxHashMap()),
588 closure_bare_wrapper_cache: RefCell::new(FxHashMap()),
589 statics_to_rauw: RefCell::new(Vec::new()),
590 lltypes: RefCell::new(FxHashMap()),
591 llsizingtypes: RefCell::new(FxHashMap()),
592 type_hashcodes: RefCell::new(FxHashMap()),
593 int_type: Type::from_ref(ptr::null_mut()),
594 opaque_vec_type: Type::from_ref(ptr::null_mut()),
595 str_slice_type: Type::from_ref(ptr::null_mut()),
596 closure_vals: RefCell::new(FxHashMap()),
598 eh_personality: Cell::new(None),
599 eh_unwind_resume: Cell::new(None),
600 rust_try_fn: Cell::new(None),
601 intrinsics: RefCell::new(FxHashMap()),
602 type_of_depth: Cell::new(0),
603 symbol_map: symbol_map,
604 local_gen_sym_counter: Cell::new(0),
607 let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = {
608 // Do a little dance to create a dummy CrateContext, so we can
609 // create some things in the LLVM module of this codegen unit
610 let mut local_ccxs = vec![local_ccx];
611 let (int_type, opaque_vec_type, str_slice_ty) = {
612 let dummy_ccx = LocalCrateContext::dummy_ccx(shared,
613 local_ccxs.as_mut_slice());
614 let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice");
615 str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx),
616 Type::int(&dummy_ccx)],
618 (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty)
620 (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap())
623 local_ccx.int_type = int_type;
624 local_ccx.opaque_vec_type = opaque_vec_type;
625 local_ccx.str_slice_type = str_slice_ty;
631 /// Create a dummy `CrateContext` from `self` and the provided
632 /// `SharedCrateContext`. This is somewhat dangerous because `self` may
633 /// not be fully initialized.
635 /// This is used in the `LocalCrateContext` constructor to allow calling
636 /// functions that expect a complete `CrateContext`, even before the local
637 /// portion is fully initialized and attached to the `SharedCrateContext`.
638 fn dummy_ccx<'a>(shared: &'a SharedCrateContext<'a, 'tcx>,
639 local_ccxs: &'a [LocalCrateContext<'tcx>])
640 -> CrateContext<'a, 'tcx> {
641 assert!(local_ccxs.len() == 1);
645 local_ccxs: local_ccxs
650 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
651 pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
655 fn local(&self) -> &'b LocalCrateContext<'tcx> {
656 &self.local_ccxs[self.index]
659 pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
663 pub fn sess<'a>(&'a self) -> &'a Session {
664 &self.shared.tcx.sess
667 pub fn get_intrinsic(&self, key: &str) -> ValueRef {
668 if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
671 match declare_intrinsic(self, key) {
673 None => bug!("unknown intrinsic '{}'", key)
677 pub fn llmod(&self) -> ModuleRef {
681 pub fn llcx(&self) -> ContextRef {
685 pub fn previous_work_product(&self) -> Option<&WorkProduct> {
686 self.local().previous_work_product.as_ref()
689 pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> {
690 &self.local().codegen_unit
693 pub fn td(&self) -> llvm::TargetDataRef {
694 unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
697 pub fn exported_symbols<'a>(&'a self) -> &'a NodeSet {
698 &self.shared.exported_symbols
701 pub fn link_meta<'a>(&'a self) -> &'a LinkMeta {
702 &self.shared.link_meta
705 pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FxHashMap<Ty<'tcx>, bool>> {
706 &self.local().needs_unwind_cleanup_cache
709 pub fn instances<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> {
710 &self.local().instances
713 pub fn vtables<'a>(&'a self)
714 -> &'a RefCell<FxHashMap<(ty::Ty<'tcx>,
715 Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>> {
716 &self.local().vtables
719 pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<InternedString, ValueRef>> {
720 &self.local().const_cstr_cache
723 pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
724 &self.local().const_unsized
727 pub fn const_globals<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
728 &self.local().const_globals
731 pub fn const_values<'a>(&'a self) -> &'a RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
733 &self.local().const_values
736 pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
737 &self.local().extern_const_values
740 pub fn statics<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, DefId>> {
741 &self.local().statics
744 pub fn impl_method_cache<'a>(&'a self)
745 -> &'a RefCell<FxHashMap<(DefId, ast::Name), DefId>> {
746 &self.local().impl_method_cache
749 pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
750 &self.local().closure_bare_wrapper_cache
753 pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
754 &self.local().statics_to_rauw
757 pub fn lltypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> {
758 &self.local().lltypes
761 pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> {
762 &self.local().llsizingtypes
765 pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, String>> {
766 &self.local().type_hashcodes
769 pub fn stats<'a>(&'a self) -> &'a Stats {
773 pub fn int_type(&self) -> Type {
774 self.local().int_type
777 pub fn opaque_vec_type(&self) -> Type {
778 self.local().opaque_vec_type
781 pub fn str_slice_type(&self) -> Type {
782 self.local().str_slice_type
785 pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> {
786 &self.local().closure_vals
789 pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
793 pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
794 &self.local().rust_try_fn
797 fn intrinsics<'a>(&'a self) -> &'a RefCell<FxHashMap<&'static str, ValueRef>> {
798 &self.local().intrinsics
801 pub fn obj_size_bound(&self) -> u64 {
802 self.tcx().data_layout.obj_size_bound()
805 pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
807 &format!("the type `{:?}` is too big for the current architecture",
811 pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
812 let current_depth = self.local().type_of_depth.get();
813 debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
814 if current_depth > self.sess().recursion_limit.get() {
816 &format!("overflow representing the type `{}`", ty))
818 self.local().type_of_depth.set(current_depth + 1);
819 TypeOfDepthLock(self.local())
822 pub fn layout_of(&self, ty: Ty<'tcx>) -> &'tcx ty::layout::Layout {
823 self.tcx().infer_ctxt((), traits::Reveal::All).enter(|infcx| {
824 ty.layout(&infcx).unwrap_or_else(|e| {
826 ty::layout::LayoutError::SizeOverflow(_) =>
827 self.sess().fatal(&e.to_string()),
828 _ => bug!("failed to get layout for `{}`: {}", ty, e)
834 pub fn check_overflow(&self) -> bool {
835 self.shared.check_overflow
838 pub fn use_dll_storage_attrs(&self) -> bool {
839 self.shared.use_dll_storage_attrs()
842 pub fn symbol_map(&self) -> &SymbolMap<'tcx> {
843 &*self.local().symbol_map
846 pub fn translation_items(&self) -> &RefCell<FxHashSet<TransItem<'tcx>>> {
847 &self.shared.translation_items
850 /// Given the def-id of some item that has no type parameters, make
851 /// a suitable "empty substs" for it.
852 pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
853 self.tcx().empty_substs_for_def_id(item_def_id)
856 /// Generate a new symbol name with the given prefix. This symbol name must
857 /// only be used for definitions with `internal` or `private` linkage.
858 pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
859 let idx = self.local().local_gen_sym_counter.get();
860 self.local().local_gen_sym_counter.set(idx + 1);
861 // Include a '.' character, so there can be no accidental conflicts with
862 // user defined names
863 let mut name = String::with_capacity(prefix.len() + 6);
864 name.push_str(prefix);
866 base_n::push_str(idx as u64, base_n::ALPHANUMERIC_ONLY, &mut name);
870 pub fn eh_personality(&self) -> ValueRef {
871 // The exception handling personality function.
873 // If our compilation unit has the `eh_personality` lang item somewhere
874 // within it, then we just need to translate that. Otherwise, we're
875 // building an rlib which will depend on some upstream implementation of
876 // this function, so we just codegen a generic reference to it. We don't
877 // specify any of the types for the function, we just make it a symbol
878 // that LLVM can later use.
880 // Note that MSVC is a little special here in that we don't use the
881 // `eh_personality` lang item at all. Currently LLVM has support for
882 // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
883 // *name of the personality function* to decide what kind of unwind side
884 // tables/landing pads to emit. It looks like Dwarf is used by default,
885 // injecting a dependency on the `_Unwind_Resume` symbol for resuming
886 // an "exception", but for MSVC we want to force SEH. This means that we
887 // can't actually have the personality function be our standard
888 // `rust_eh_personality` function, but rather we wired it up to the
889 // CRT's custom personality function, which forces LLVM to consider
890 // landing pads as "landing pads for SEH".
891 if let Some(llpersonality) = self.local().eh_personality.get() {
894 let tcx = self.tcx();
895 let llfn = match tcx.lang_items.eh_personality() {
896 Some(def_id) if !base::wants_msvc_seh(self.sess()) => {
897 callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]))
900 let name = if base::wants_msvc_seh(self.sess()) {
903 "rust_eh_personality"
905 let fty = Type::variadic_func(&[], &Type::i32(self));
906 declare::declare_cfn(self, name, fty)
909 self.local().eh_personality.set(Some(llfn));
913 // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined,
914 // otherwise declares it as an external function.
915 pub fn eh_unwind_resume(&self) -> ValueRef {
917 let unwresume = &self.local().eh_unwind_resume;
918 if let Some(llfn) = unwresume.get() {
922 let tcx = self.tcx();
923 assert!(self.sess().target.target.options.custom_unwind_resume);
924 if let Some(def_id) = tcx.lang_items.eh_unwind_resume() {
925 let llfn = callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]));
926 unwresume.set(Some(llfn));
930 let ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
931 iter::once(tcx.mk_mut_ptr(tcx.types.u8)),
934 hir::Unsafety::Unsafe,
938 let llfn = declare::declare_fn(self, "rust_eh_unwind_resume", ty);
939 attributes::unwind(llfn, true);
940 unwresume.set(Some(llfn));
945 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>);
947 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
949 self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
953 /// Declare any llvm intrinsics that you might need
954 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
956 ($name:expr, fn() -> $ret:expr) => (
958 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
959 llvm::SetUnnamedAddr(f, false);
960 ccx.intrinsics().borrow_mut().insert($name, f.clone());
964 ($name:expr, fn(...) -> $ret:expr) => (
966 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
967 llvm::SetUnnamedAddr(f, false);
968 ccx.intrinsics().borrow_mut().insert($name, f.clone());
972 ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
974 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
975 llvm::SetUnnamedAddr(f, false);
976 ccx.intrinsics().borrow_mut().insert($name, f.clone());
981 macro_rules! mk_struct {
982 ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
985 let i8p = Type::i8p(ccx);
986 let void = Type::void(ccx);
987 let i1 = Type::i1(ccx);
988 let t_i8 = Type::i8(ccx);
989 let t_i16 = Type::i16(ccx);
990 let t_i32 = Type::i32(ccx);
991 let t_i64 = Type::i64(ccx);
992 let t_i128 = Type::i128(ccx);
993 let t_f32 = Type::f32(ccx);
994 let t_f64 = Type::f64(ccx);
996 ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
997 ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
998 ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
999 ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
1000 ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
1001 ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
1002 ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
1003 ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
1004 ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
1006 ifn!("llvm.trap", fn() -> void);
1007 ifn!("llvm.debugtrap", fn() -> void);
1008 ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
1010 ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
1011 ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
1012 ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
1013 ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
1015 ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
1016 ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
1017 ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
1018 ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
1019 ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
1020 ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
1021 ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
1022 ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
1023 ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
1024 ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
1025 ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
1026 ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
1027 ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
1028 ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
1029 ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
1030 ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
1032 ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
1033 ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
1035 ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
1036 ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
1038 ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
1039 ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
1040 ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
1041 ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
1042 ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
1043 ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
1045 ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
1046 ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
1047 ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
1048 ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
1050 ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
1051 ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
1052 ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
1053 ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
1055 ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
1056 ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
1057 ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
1058 ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
1059 ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
1061 ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
1062 ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
1063 ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
1064 ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
1065 ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
1067 ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
1068 ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
1069 ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
1070 ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
1071 ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
1073 ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
1074 ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
1075 ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
1076 ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
1078 ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1079 ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1080 ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1081 ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1082 ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
1084 ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1085 ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1086 ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1087 ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1088 ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
1090 ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1091 ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1092 ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1093 ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1094 ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
1096 ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1097 ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1098 ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1099 ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1100 ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
1102 ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1103 ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1104 ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1105 ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1106 ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
1108 ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
1109 ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
1110 ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
1111 ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
1112 ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
1114 ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
1115 ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
1117 ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
1118 ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
1119 ifn!("llvm.localescape", fn(...) -> void);
1120 ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
1121 ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
1123 ifn!("llvm.assume", fn(i1) -> void);
1125 if ccx.sess().opts.debuginfo != NoDebugInfo {
1126 ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
1127 ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);