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};
15 use rustc::hir::def_id::DefId;
21 use monomorphize::Instance;
23 use partitioning::CodegenUnit;
25 use rustc_data_structures::base_n;
26 use rustc::ty::subst::Substs;
27 use rustc::ty::{self, Ty, TyCtxt};
28 use rustc::ty::layout::{LayoutTyper, TyLayout};
29 use session::config::NoDebugInfo;
32 use symbol_cache::SymbolCache;
33 use util::nodemap::{NodeSet, DefIdMap, FxHashMap};
35 use std::ffi::{CStr, CString};
36 use std::cell::{Cell, RefCell};
41 use syntax::symbol::InternedString;
42 use syntax_pos::DUMMY_SP;
45 #[derive(Clone, Default)]
47 pub n_glues_created: Cell<usize>,
48 pub n_null_glues: Cell<usize>,
49 pub n_real_glues: Cell<usize>,
50 pub n_fns: Cell<usize>,
51 pub n_inlines: Cell<usize>,
52 pub n_closures: Cell<usize>,
53 pub n_llvm_insns: Cell<usize>,
54 pub llvm_insns: RefCell<FxHashMap<String, usize>>,
55 // (ident, llvm-instructions)
56 pub fn_stats: RefCell<Vec<(String, usize)> >,
60 pub fn extend(&mut self, stats: Stats) {
61 self.n_glues_created.set(self.n_glues_created.get() + stats.n_glues_created.get());
62 self.n_null_glues.set(self.n_null_glues.get() + stats.n_null_glues.get());
63 self.n_real_glues.set(self.n_real_glues.get() + stats.n_real_glues.get());
64 self.n_fns.set(self.n_fns.get() + stats.n_fns.get());
65 self.n_inlines.set(self.n_inlines.get() + stats.n_inlines.get());
66 self.n_closures.set(self.n_closures.get() + stats.n_closures.get());
67 self.n_llvm_insns.set(self.n_llvm_insns.get() + stats.n_llvm_insns.get());
68 self.llvm_insns.borrow_mut().extend(
69 stats.llvm_insns.borrow().iter()
70 .map(|(key, value)| (key.clone(), value.clone())));
71 self.fn_stats.borrow_mut().append(&mut *stats.fn_stats.borrow_mut());
75 /// The shared portion of a `CrateContext`. There is one `SharedCrateContext`
76 /// per crate. The data here is shared between all compilation units of the
77 /// crate, so it must not contain references to any LLVM data structures
78 /// (aside from metadata-related ones).
79 pub struct SharedCrateContext<'a, 'tcx: 'a> {
80 exported_symbols: NodeSet,
81 tcx: TyCtxt<'a, 'tcx, 'tcx>,
82 empty_param_env: ty::ParameterEnvironment<'tcx>,
85 use_dll_storage_attrs: bool,
88 /// The local portion of a `CrateContext`. There is one `LocalCrateContext`
89 /// per compilation unit. Each one has its own LLVM `ContextRef` so that
90 /// several compilation units may be optimized in parallel. All other LLVM
91 /// data structures in the `LocalCrateContext` are tied to that `ContextRef`.
92 pub struct LocalCrateContext<'a, 'tcx: 'a> {
96 codegen_unit: CodegenUnit<'tcx>,
97 needs_unwind_cleanup_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
98 /// Cache instances of monomorphic and polymorphic items
99 instances: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>,
100 /// Cache generated vtables
101 vtables: RefCell<FxHashMap<(ty::Ty<'tcx>,
102 Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>>,
103 /// Cache of constant strings,
104 const_cstr_cache: RefCell<FxHashMap<InternedString, ValueRef>>,
106 /// Reverse-direction for const ptrs cast from globals.
107 /// Key is a ValueRef holding a *T,
108 /// Val is a ValueRef holding a *[T].
110 /// Needed because LLVM loses pointer->pointee association
111 /// when we ptrcast, and we have to ptrcast during translation
112 /// of a [T] const because we form a slice, a (*T,usize) pair, not
113 /// a pointer to an LLVM array type. Similar for trait objects.
114 const_unsized: RefCell<FxHashMap<ValueRef, ValueRef>>,
116 /// Cache of emitted const globals (value -> global)
117 const_globals: RefCell<FxHashMap<ValueRef, ValueRef>>,
119 /// Cache of emitted const values
120 const_values: RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
122 /// Cache of external const values
123 extern_const_values: RefCell<DefIdMap<ValueRef>>,
125 /// Mapping from static definitions to their DefId's.
126 statics: RefCell<FxHashMap<ValueRef, DefId>>,
128 impl_method_cache: RefCell<FxHashMap<(DefId, ast::Name), DefId>>,
130 /// Cache of closure wrappers for bare fn's.
131 closure_bare_wrapper_cache: RefCell<FxHashMap<ValueRef, ValueRef>>,
133 /// List of globals for static variables which need to be passed to the
134 /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete.
135 /// (We have to make sure we don't invalidate any ValueRefs referring
137 statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
139 /// Statics that will be placed in the llvm.used variable
140 /// See http://llvm.org/docs/LangRef.html#the-llvm-used-global-variable for details
141 used_statics: RefCell<Vec<ValueRef>>,
143 lltypes: RefCell<FxHashMap<Ty<'tcx>, Type>>,
144 llsizingtypes: RefCell<FxHashMap<Ty<'tcx>, Type>>,
145 type_hashcodes: RefCell<FxHashMap<Ty<'tcx>, String>>,
147 opaque_vec_type: Type,
148 str_slice_type: Type,
150 /// Holds the LLVM values for closure IDs.
151 closure_vals: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>,
153 dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
155 eh_personality: Cell<Option<ValueRef>>,
156 eh_unwind_resume: Cell<Option<ValueRef>>,
157 rust_try_fn: Cell<Option<ValueRef>>,
159 intrinsics: RefCell<FxHashMap<&'static str, ValueRef>>,
161 /// Depth of the current type-of computation - used to bail out
162 type_of_depth: Cell<usize>,
164 /// A counter that is used for generating local symbol names
165 local_gen_sym_counter: Cell<usize>,
167 symbol_cache: &'a SymbolCache<'a, 'tcx>,
170 /// A CrateContext value binds together one LocalCrateContext with the
171 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
172 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
173 pub struct CrateContext<'a, 'tcx: 'a> {
174 shared: &'a SharedCrateContext<'a, 'tcx>,
175 local_ccx: &'a LocalCrateContext<'a, 'tcx>,
178 impl<'a, 'tcx> CrateContext<'a, 'tcx> {
179 pub fn new(shared: &'a SharedCrateContext<'a, 'tcx>,
180 local_ccx: &'a LocalCrateContext<'a, 'tcx>)
182 CrateContext { shared, local_ccx }
186 impl<'a, 'tcx> DepGraphSafe for CrateContext<'a, 'tcx> {
189 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
190 let reloc_model_arg = match sess.opts.cg.relocation_model {
191 Some(ref s) => &s[..],
192 None => &sess.target.target.options.relocation_model[..],
195 match ::back::write::RELOC_MODEL_ARGS.iter().find(
196 |&&arg| arg.0 == reloc_model_arg) {
199 sess.err(&format!("{:?} is not a valid relocation mode",
203 sess.abort_if_errors();
209 fn is_any_library(sess: &Session) -> bool {
210 sess.crate_types.borrow().iter().any(|ty| {
211 *ty != config::CrateTypeExecutable
215 pub fn is_pie_binary(sess: &Session) -> bool {
216 !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
219 pub unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
220 let llcx = llvm::LLVMContextCreate();
221 let mod_name = CString::new(mod_name).unwrap();
222 let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
224 // Ensure the data-layout values hardcoded remain the defaults.
225 if sess.target.target.options.is_builtin {
226 let tm = ::back::write::create_target_machine(sess);
227 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
228 llvm::LLVMRustDisposeTargetMachine(tm);
230 let data_layout = llvm::LLVMGetDataLayout(llmod);
231 let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
232 .ok().expect("got a non-UTF8 data-layout from LLVM");
234 // Unfortunately LLVM target specs change over time, and right now we
235 // don't have proper support to work with any more than one
236 // `data_layout` than the one that is in the rust-lang/rust repo. If
237 // this compiler is configured against a custom LLVM, we may have a
238 // differing data layout, even though we should update our own to use
241 // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
242 // disable this check entirely as we may be configured with something
243 // that has a different target layout.
245 // Unsure if this will actually cause breakage when rustc is configured
249 let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
250 let custom_llvm_used = cfg_llvm_root.trim() != "";
252 if !custom_llvm_used && sess.target.target.data_layout != data_layout {
253 bug!("data-layout for builtin `{}` target, `{}`, \
254 differs from LLVM default, `{}`",
255 sess.target.target.llvm_target,
256 sess.target.target.data_layout,
261 let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
262 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
264 let llvm_target = sess.target.target.llvm_target.as_bytes();
265 let llvm_target = CString::new(llvm_target).unwrap();
266 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
268 if is_pie_binary(sess) {
269 llvm::LLVMRustSetModulePIELevel(llmod);
275 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
276 pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
277 exported_symbols: NodeSet,
278 check_overflow: bool)
279 -> SharedCrateContext<'b, 'tcx> {
280 // An interesting part of Windows which MSVC forces our hand on (and
281 // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
282 // attributes in LLVM IR as well as native dependencies (in C these
283 // correspond to `__declspec(dllimport)`).
285 // Whenever a dynamic library is built by MSVC it must have its public
286 // interface specified by functions tagged with `dllexport` or otherwise
287 // they're not available to be linked against. This poses a few problems
288 // for the compiler, some of which are somewhat fundamental, but we use
289 // the `use_dll_storage_attrs` variable below to attach the `dllexport`
290 // attribute to all LLVM functions that are exported e.g. they're
291 // already tagged with external linkage). This is suboptimal for a few
294 // * If an object file will never be included in a dynamic library,
295 // there's no need to attach the dllexport attribute. Most object
296 // files in Rust are not destined to become part of a dll as binaries
297 // are statically linked by default.
298 // * If the compiler is emitting both an rlib and a dylib, the same
299 // source object file is currently used but with MSVC this may be less
300 // feasible. The compiler may be able to get around this, but it may
301 // involve some invasive changes to deal with this.
303 // The flipside of this situation is that whenever you link to a dll and
304 // you import a function from it, the import should be tagged with
305 // `dllimport`. At this time, however, the compiler does not emit
306 // `dllimport` for any declarations other than constants (where it is
307 // required), which is again suboptimal for even more reasons!
309 // * Calling a function imported from another dll without using
310 // `dllimport` causes the linker/compiler to have extra overhead (one
311 // `jmp` instruction on x86) when calling the function.
312 // * The same object file may be used in different circumstances, so a
313 // function may be imported from a dll if the object is linked into a
314 // dll, but it may be just linked against if linked into an rlib.
315 // * The compiler has no knowledge about whether native functions should
316 // be tagged dllimport or not.
318 // For now the compiler takes the perf hit (I do not have any numbers to
319 // this effect) by marking very little as `dllimport` and praying the
320 // linker will take care of everything. Fixing this problem will likely
321 // require adding a few attributes to Rust itself (feature gated at the
322 // start) and then strongly recommending static linkage on MSVC!
323 let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
326 exported_symbols: exported_symbols,
327 empty_param_env: tcx.empty_parameter_environment(),
329 check_overflow: check_overflow,
330 use_dll_storage_attrs: use_dll_storage_attrs,
334 pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
335 ty.needs_drop(self.tcx, &self.empty_param_env)
338 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
339 ty.is_sized(self.tcx, &self.empty_param_env, DUMMY_SP)
342 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
343 ty.is_freeze(self.tcx, &self.empty_param_env, DUMMY_SP)
346 pub fn exported_symbols<'a>(&'a self) -> &'a NodeSet {
347 &self.exported_symbols
350 pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
354 pub fn sess<'a>(&'a self) -> &'a Session {
358 pub fn dep_graph<'a>(&'a self) -> &'a DepGraph {
362 pub fn use_dll_storage_attrs(&self) -> bool {
363 self.use_dll_storage_attrs
367 impl<'a, 'tcx> LocalCrateContext<'a, 'tcx> {
368 pub fn new(shared: &SharedCrateContext<'a, 'tcx>,
369 codegen_unit: CodegenUnit<'tcx>,
370 symbol_cache: &'a SymbolCache<'a, 'tcx>)
371 -> LocalCrateContext<'a, 'tcx> {
373 // Append ".rs" to LLVM module identifier.
375 // LLVM code generator emits a ".file filename" directive
376 // for ELF backends. Value of the "filename" is set as the
377 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
378 // crashes if the module identifier is same as other symbols
379 // such as a function name in the module.
380 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
381 let llmod_id = format!("{}.rs", codegen_unit.name());
383 let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
386 let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
387 let dctx = debuginfo::CrateDebugContext::new(llmod);
388 debuginfo::metadata::compile_unit_metadata(shared, &dctx, shared.tcx.sess);
394 let local_ccx = LocalCrateContext {
397 stats: Stats::default(),
398 codegen_unit: codegen_unit,
399 needs_unwind_cleanup_cache: RefCell::new(FxHashMap()),
400 instances: RefCell::new(FxHashMap()),
401 vtables: RefCell::new(FxHashMap()),
402 const_cstr_cache: RefCell::new(FxHashMap()),
403 const_unsized: RefCell::new(FxHashMap()),
404 const_globals: RefCell::new(FxHashMap()),
405 const_values: RefCell::new(FxHashMap()),
406 extern_const_values: RefCell::new(DefIdMap()),
407 statics: RefCell::new(FxHashMap()),
408 impl_method_cache: RefCell::new(FxHashMap()),
409 closure_bare_wrapper_cache: RefCell::new(FxHashMap()),
410 statics_to_rauw: RefCell::new(Vec::new()),
411 used_statics: RefCell::new(Vec::new()),
412 lltypes: RefCell::new(FxHashMap()),
413 llsizingtypes: RefCell::new(FxHashMap()),
414 type_hashcodes: RefCell::new(FxHashMap()),
415 int_type: Type::from_ref(ptr::null_mut()),
416 opaque_vec_type: Type::from_ref(ptr::null_mut()),
417 str_slice_type: Type::from_ref(ptr::null_mut()),
418 closure_vals: RefCell::new(FxHashMap()),
420 eh_personality: Cell::new(None),
421 eh_unwind_resume: Cell::new(None),
422 rust_try_fn: Cell::new(None),
423 intrinsics: RefCell::new(FxHashMap()),
424 type_of_depth: Cell::new(0),
425 local_gen_sym_counter: Cell::new(0),
426 symbol_cache: symbol_cache,
429 let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = {
430 // Do a little dance to create a dummy CrateContext, so we can
431 // create some things in the LLVM module of this codegen unit
432 let mut local_ccxs = vec![local_ccx];
433 let (int_type, opaque_vec_type, str_slice_ty) = {
434 let dummy_ccx = LocalCrateContext::dummy_ccx(shared,
435 local_ccxs.as_mut_slice());
436 let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice");
437 str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx),
438 Type::int(&dummy_ccx)],
440 (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty)
442 (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap())
445 local_ccx.int_type = int_type;
446 local_ccx.opaque_vec_type = opaque_vec_type;
447 local_ccx.str_slice_type = str_slice_ty;
453 /// Create a dummy `CrateContext` from `self` and the provided
454 /// `SharedCrateContext`. This is somewhat dangerous because `self` may
455 /// not be fully initialized.
457 /// This is used in the `LocalCrateContext` constructor to allow calling
458 /// functions that expect a complete `CrateContext`, even before the local
459 /// portion is fully initialized and attached to the `SharedCrateContext`.
460 fn dummy_ccx(shared: &'a SharedCrateContext<'a, 'tcx>,
461 local_ccxs: &'a [LocalCrateContext<'a, 'tcx>])
462 -> CrateContext<'a, 'tcx> {
463 assert!(local_ccxs.len() == 1);
466 local_ccx: &local_ccxs[0]
470 pub fn into_stats(self) -> Stats {
475 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
476 pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
480 fn local(&self) -> &'b LocalCrateContext<'b, 'tcx> {
484 pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
488 pub fn sess<'a>(&'a self) -> &'a Session {
489 &self.shared.tcx.sess
492 pub fn get_intrinsic(&self, key: &str) -> ValueRef {
493 if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
496 match declare_intrinsic(self, key) {
498 None => bug!("unknown intrinsic '{}'", key)
502 pub fn llmod(&self) -> ModuleRef {
506 pub fn llcx(&self) -> ContextRef {
510 pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> {
511 &self.local().codegen_unit
514 pub fn td(&self) -> llvm::TargetDataRef {
515 unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
518 pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FxHashMap<Ty<'tcx>, bool>> {
519 &self.local().needs_unwind_cleanup_cache
522 pub fn instances<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> {
523 &self.local().instances
526 pub fn vtables<'a>(&'a self)
527 -> &'a RefCell<FxHashMap<(ty::Ty<'tcx>,
528 Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>> {
529 &self.local().vtables
532 pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<InternedString, ValueRef>> {
533 &self.local().const_cstr_cache
536 pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
537 &self.local().const_unsized
540 pub fn const_globals<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
541 &self.local().const_globals
544 pub fn const_values<'a>(&'a self) -> &'a RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
546 &self.local().const_values
549 pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
550 &self.local().extern_const_values
553 pub fn statics<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, DefId>> {
554 &self.local().statics
557 pub fn impl_method_cache<'a>(&'a self)
558 -> &'a RefCell<FxHashMap<(DefId, ast::Name), DefId>> {
559 &self.local().impl_method_cache
562 pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
563 &self.local().closure_bare_wrapper_cache
566 pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
567 &self.local().statics_to_rauw
570 pub fn used_statics<'a>(&'a self) -> &'a RefCell<Vec<ValueRef>> {
571 &self.local().used_statics
574 pub fn lltypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> {
575 &self.local().lltypes
578 pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> {
579 &self.local().llsizingtypes
582 pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, String>> {
583 &self.local().type_hashcodes
586 pub fn stats<'a>(&'a self) -> &'a Stats {
590 pub fn int_type(&self) -> Type {
591 self.local().int_type
594 pub fn opaque_vec_type(&self) -> Type {
595 self.local().opaque_vec_type
598 pub fn str_slice_type(&self) -> Type {
599 self.local().str_slice_type
602 pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> {
603 &self.local().closure_vals
606 pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
610 pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
611 &self.local().rust_try_fn
614 fn intrinsics<'a>(&'a self) -> &'a RefCell<FxHashMap<&'static str, ValueRef>> {
615 &self.local().intrinsics
618 pub fn obj_size_bound(&self) -> u64 {
619 self.tcx().data_layout.obj_size_bound()
622 pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
624 &format!("the type `{:?}` is too big for the current architecture",
628 pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
629 let current_depth = self.local().type_of_depth.get();
630 debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
631 if current_depth > self.sess().recursion_limit.get() {
633 &format!("overflow representing the type `{}`", ty))
635 self.local().type_of_depth.set(current_depth + 1);
636 TypeOfDepthLock(self.local())
639 pub fn check_overflow(&self) -> bool {
640 self.shared.check_overflow
643 pub fn use_dll_storage_attrs(&self) -> bool {
644 self.shared.use_dll_storage_attrs()
647 pub fn symbol_cache(&self) -> &'b SymbolCache<'b, 'tcx> {
648 self.local().symbol_cache
651 /// Given the def-id of some item that has no type parameters, make
652 /// a suitable "empty substs" for it.
653 pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
654 self.tcx().empty_substs_for_def_id(item_def_id)
657 /// Generate a new symbol name with the given prefix. This symbol name must
658 /// only be used for definitions with `internal` or `private` linkage.
659 pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
660 let idx = self.local().local_gen_sym_counter.get();
661 self.local().local_gen_sym_counter.set(idx + 1);
662 // Include a '.' character, so there can be no accidental conflicts with
663 // user defined names
664 let mut name = String::with_capacity(prefix.len() + 6);
665 name.push_str(prefix);
667 base_n::push_str(idx as u64, base_n::ALPHANUMERIC_ONLY, &mut name);
671 pub fn eh_personality(&self) -> ValueRef {
672 // The exception handling personality function.
674 // If our compilation unit has the `eh_personality` lang item somewhere
675 // within it, then we just need to translate that. Otherwise, we're
676 // building an rlib which will depend on some upstream implementation of
677 // this function, so we just codegen a generic reference to it. We don't
678 // specify any of the types for the function, we just make it a symbol
679 // that LLVM can later use.
681 // Note that MSVC is a little special here in that we don't use the
682 // `eh_personality` lang item at all. Currently LLVM has support for
683 // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
684 // *name of the personality function* to decide what kind of unwind side
685 // tables/landing pads to emit. It looks like Dwarf is used by default,
686 // injecting a dependency on the `_Unwind_Resume` symbol for resuming
687 // an "exception", but for MSVC we want to force SEH. This means that we
688 // can't actually have the personality function be our standard
689 // `rust_eh_personality` function, but rather we wired it up to the
690 // CRT's custom personality function, which forces LLVM to consider
691 // landing pads as "landing pads for SEH".
692 if let Some(llpersonality) = self.local().eh_personality.get() {
695 let tcx = self.tcx();
696 let llfn = match tcx.lang_items.eh_personality() {
697 Some(def_id) if !base::wants_msvc_seh(self.sess()) => {
698 callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]))
701 let name = if base::wants_msvc_seh(self.sess()) {
704 "rust_eh_personality"
706 let fty = Type::variadic_func(&[], &Type::i32(self));
707 declare::declare_cfn(self, name, fty)
710 self.local().eh_personality.set(Some(llfn));
714 // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined,
715 // otherwise declares it as an external function.
716 pub fn eh_unwind_resume(&self) -> ValueRef {
718 let unwresume = &self.local().eh_unwind_resume;
719 if let Some(llfn) = unwresume.get() {
723 let tcx = self.tcx();
724 assert!(self.sess().target.target.options.custom_unwind_resume);
725 if let Some(def_id) = tcx.lang_items.eh_unwind_resume() {
726 let llfn = callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]));
727 unwresume.set(Some(llfn));
731 let ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
732 iter::once(tcx.mk_mut_ptr(tcx.types.u8)),
735 hir::Unsafety::Unsafe,
739 let llfn = declare::declare_fn(self, "rust_eh_unwind_resume", ty);
740 attributes::unwind(llfn, true);
741 unwresume.set(Some(llfn));
746 impl<'a, 'tcx> ty::layout::HasDataLayout for &'a SharedCrateContext<'a, 'tcx> {
747 fn data_layout(&self) -> &ty::layout::TargetDataLayout {
748 &self.tcx.data_layout
752 impl<'a, 'tcx> ty::layout::HasTyCtxt<'tcx> for &'a SharedCrateContext<'a, 'tcx> {
753 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
758 impl<'a, 'tcx> ty::layout::HasDataLayout for &'a CrateContext<'a, 'tcx> {
759 fn data_layout(&self) -> &ty::layout::TargetDataLayout {
760 &self.shared.tcx.data_layout
764 impl<'a, 'tcx> ty::layout::HasTyCtxt<'tcx> for &'a CrateContext<'a, 'tcx> {
765 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
770 impl<'a, 'tcx> LayoutTyper<'tcx> for &'a SharedCrateContext<'a, 'tcx> {
771 type TyLayout = TyLayout<'tcx>;
773 fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
774 if let Some(&layout) = self.tcx().layout_cache.borrow().get(&ty) {
775 return TyLayout { ty: ty, layout: layout, variant_index: None };
778 self.tcx().infer_ctxt((), traits::Reveal::All).enter(|infcx| {
779 infcx.layout_of(ty).unwrap_or_else(|e| {
781 ty::layout::LayoutError::SizeOverflow(_) =>
782 self.sess().fatal(&e.to_string()),
783 _ => bug!("failed to get layout for `{}`: {}", ty, e)
789 fn normalize_projections(self, ty: Ty<'tcx>) -> Ty<'tcx> {
790 self.tcx().normalize_associated_type(&ty)
794 impl<'a, 'tcx> LayoutTyper<'tcx> for &'a CrateContext<'a, 'tcx> {
795 type TyLayout = TyLayout<'tcx>;
797 fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
798 self.shared.layout_of(ty)
801 fn normalize_projections(self, ty: Ty<'tcx>) -> Ty<'tcx> {
802 self.shared.normalize_projections(ty)
806 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'a, 'tcx>);
808 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
810 self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
814 /// Declare any llvm intrinsics that you might need
815 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
817 ($name:expr, fn() -> $ret:expr) => (
819 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
820 llvm::SetUnnamedAddr(f, false);
821 ccx.intrinsics().borrow_mut().insert($name, f.clone());
825 ($name:expr, fn(...) -> $ret:expr) => (
827 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
828 llvm::SetUnnamedAddr(f, false);
829 ccx.intrinsics().borrow_mut().insert($name, f.clone());
833 ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
835 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
836 llvm::SetUnnamedAddr(f, false);
837 ccx.intrinsics().borrow_mut().insert($name, f.clone());
842 macro_rules! mk_struct {
843 ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
846 let i8p = Type::i8p(ccx);
847 let void = Type::void(ccx);
848 let i1 = Type::i1(ccx);
849 let t_i8 = Type::i8(ccx);
850 let t_i16 = Type::i16(ccx);
851 let t_i32 = Type::i32(ccx);
852 let t_i64 = Type::i64(ccx);
853 let t_i128 = Type::i128(ccx);
854 let t_f32 = Type::f32(ccx);
855 let t_f64 = Type::f64(ccx);
857 ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
858 ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
859 ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
860 ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
861 ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
862 ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
863 ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
864 ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
865 ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
867 ifn!("llvm.trap", fn() -> void);
868 ifn!("llvm.debugtrap", fn() -> void);
869 ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
871 ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
872 ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
873 ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
874 ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
876 ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
877 ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
878 ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
879 ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
880 ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
881 ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
882 ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
883 ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
884 ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
885 ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
886 ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
887 ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
888 ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
889 ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
890 ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
891 ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
893 ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
894 ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
896 ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
897 ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
899 ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
900 ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
901 ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
902 ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
903 ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
904 ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
906 ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
907 ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
908 ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
909 ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
911 ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
912 ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
913 ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
914 ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
916 ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
917 ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
918 ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
919 ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
920 ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
922 ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
923 ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
924 ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
925 ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
926 ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
928 ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
929 ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
930 ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
931 ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
932 ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
934 ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
935 ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
936 ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
937 ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
939 ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
940 ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
941 ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
942 ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
943 ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
945 ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
946 ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
947 ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
948 ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
949 ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
951 ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
952 ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
953 ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
954 ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
955 ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
957 ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
958 ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
959 ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
960 ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
961 ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
963 ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
964 ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
965 ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
966 ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
967 ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
969 ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
970 ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
971 ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
972 ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
973 ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
975 ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
976 ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
978 ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
979 ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
980 ifn!("llvm.localescape", fn(...) -> void);
981 ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
982 ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
984 ifn!("llvm.assume", fn(i1) -> void);
986 if ccx.sess().opts.debuginfo != NoDebugInfo {
987 ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
988 ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);