]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/context.rs
Rollup merge of #42016 - pietroalbini:stabilize/loop_break_value, r=nikomatsakis
[rust.git] / src / librustc_trans / context.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use llvm;
12 use llvm::{ContextRef, ModuleRef, ValueRef};
13 use rustc::dep_graph::{DepGraph, DepGraphSafe};
14 use rustc::hir;
15 use rustc::hir::def_id::DefId;
16 use rustc::traits;
17 use debuginfo;
18 use callee;
19 use base;
20 use declare;
21 use monomorphize::Instance;
22
23 use partitioning::CodegenUnit;
24 use type_::Type;
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;
30 use session::Session;
31 use session::config;
32 use util::nodemap::{NodeSet, DefIdMap, FxHashMap};
33
34 use std::ffi::{CStr, CString};
35 use std::cell::{Cell, RefCell};
36 use std::ptr;
37 use std::iter;
38 use std::str;
39 use std::marker::PhantomData;
40 use syntax::ast;
41 use syntax::symbol::InternedString;
42 use syntax_pos::DUMMY_SP;
43 use abi::Abi;
44
45 #[derive(Clone, Default)]
46 pub struct Stats {
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)> >,
57 }
58
59 impl Stats {
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());
72     }
73 }
74
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>,
83     check_overflow: bool,
84
85     use_dll_storage_attrs: bool,
86 }
87
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> {
93     llmod: ModuleRef,
94     llcx: ContextRef,
95     stats: Stats,
96     codegen_unit: CodegenUnit<'tcx>,
97     /// Cache instances of monomorphic and polymorphic items
98     instances: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>,
99     /// Cache generated vtables
100     vtables: RefCell<FxHashMap<(ty::Ty<'tcx>,
101                                 Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>>,
102     /// Cache of constant strings,
103     const_cstr_cache: RefCell<FxHashMap<InternedString, ValueRef>>,
104
105     /// Reverse-direction for const ptrs cast from globals.
106     /// Key is a ValueRef holding a *T,
107     /// Val is a ValueRef holding a *[T].
108     ///
109     /// Needed because LLVM loses pointer->pointee association
110     /// when we ptrcast, and we have to ptrcast during translation
111     /// of a [T] const because we form a slice, a (*T,usize) pair, not
112     /// a pointer to an LLVM array type. Similar for trait objects.
113     const_unsized: RefCell<FxHashMap<ValueRef, ValueRef>>,
114
115     /// Cache of emitted const globals (value -> global)
116     const_globals: RefCell<FxHashMap<ValueRef, ValueRef>>,
117
118     /// Cache of emitted const values
119     const_values: RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>,
120
121     /// Cache of external const values
122     extern_const_values: RefCell<DefIdMap<ValueRef>>,
123
124     /// Mapping from static definitions to their DefId's.
125     statics: RefCell<FxHashMap<ValueRef, DefId>>,
126
127     /// List of globals for static variables which need to be passed to the
128     /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete.
129     /// (We have to make sure we don't invalidate any ValueRefs referring
130     /// to constants.)
131     statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>,
132
133     /// Statics that will be placed in the llvm.used variable
134     /// See http://llvm.org/docs/LangRef.html#the-llvm-used-global-variable for details
135     used_statics: RefCell<Vec<ValueRef>>,
136
137     lltypes: RefCell<FxHashMap<Ty<'tcx>, Type>>,
138     type_hashcodes: RefCell<FxHashMap<Ty<'tcx>, String>>,
139     int_type: Type,
140     opaque_vec_type: Type,
141     str_slice_type: Type,
142
143     dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>,
144
145     eh_personality: Cell<Option<ValueRef>>,
146     eh_unwind_resume: Cell<Option<ValueRef>>,
147     rust_try_fn: Cell<Option<ValueRef>>,
148
149     intrinsics: RefCell<FxHashMap<&'static str, ValueRef>>,
150
151     /// Depth of the current type-of computation - used to bail out
152     type_of_depth: Cell<usize>,
153
154     /// A counter that is used for generating local symbol names
155     local_gen_sym_counter: Cell<usize>,
156
157     /// A placeholder so we can add lifetimes
158     placeholder: PhantomData<&'a ()>,
159 }
160
161 /// A CrateContext value binds together one LocalCrateContext with the
162 /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to
163 /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans.
164 pub struct CrateContext<'a, 'tcx: 'a> {
165     shared: &'a SharedCrateContext<'a, 'tcx>,
166     local_ccx: &'a LocalCrateContext<'a, 'tcx>,
167 }
168
169 impl<'a, 'tcx> CrateContext<'a, 'tcx> {
170     pub fn new(shared: &'a SharedCrateContext<'a, 'tcx>,
171                local_ccx: &'a LocalCrateContext<'a, 'tcx>)
172                -> Self {
173         CrateContext { shared, local_ccx }
174     }
175 }
176
177 impl<'a, 'tcx> DepGraphSafe for CrateContext<'a, 'tcx> {
178 }
179
180 pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
181     let reloc_model_arg = match sess.opts.cg.relocation_model {
182         Some(ref s) => &s[..],
183         None => &sess.target.target.options.relocation_model[..],
184     };
185
186     match ::back::write::RELOC_MODEL_ARGS.iter().find(
187         |&&arg| arg.0 == reloc_model_arg) {
188         Some(x) => x.1,
189         _ => {
190             sess.err(&format!("{:?} is not a valid relocation mode",
191                              sess.opts
192                                  .cg
193                                  .code_model));
194             sess.abort_if_errors();
195             bug!();
196         }
197     }
198 }
199
200 fn is_any_library(sess: &Session) -> bool {
201     sess.crate_types.borrow().iter().any(|ty| {
202         *ty != config::CrateTypeExecutable
203     })
204 }
205
206 pub fn is_pie_binary(sess: &Session) -> bool {
207     !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
208 }
209
210 pub unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) {
211     let llcx = llvm::LLVMContextCreate();
212     let mod_name = CString::new(mod_name).unwrap();
213     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
214
215     // Ensure the data-layout values hardcoded remain the defaults.
216     if sess.target.target.options.is_builtin {
217         let tm = ::back::write::create_target_machine(sess);
218         llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
219         llvm::LLVMRustDisposeTargetMachine(tm);
220
221         let data_layout = llvm::LLVMGetDataLayout(llmod);
222         let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes())
223             .ok().expect("got a non-UTF8 data-layout from LLVM");
224
225         // Unfortunately LLVM target specs change over time, and right now we
226         // don't have proper support to work with any more than one
227         // `data_layout` than the one that is in the rust-lang/rust repo. If
228         // this compiler is configured against a custom LLVM, we may have a
229         // differing data layout, even though we should update our own to use
230         // that one.
231         //
232         // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
233         // disable this check entirely as we may be configured with something
234         // that has a different target layout.
235         //
236         // Unsure if this will actually cause breakage when rustc is configured
237         // as such.
238         //
239         // FIXME(#34960)
240         let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
241         let custom_llvm_used = cfg_llvm_root.trim() != "";
242
243         if !custom_llvm_used && sess.target.target.data_layout != data_layout {
244             bug!("data-layout for builtin `{}` target, `{}`, \
245                   differs from LLVM default, `{}`",
246                  sess.target.target.llvm_target,
247                  sess.target.target.data_layout,
248                  data_layout);
249         }
250     }
251
252     let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap();
253     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
254
255     let llvm_target = sess.target.target.llvm_target.as_bytes();
256     let llvm_target = CString::new(llvm_target).unwrap();
257     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
258
259     if is_pie_binary(sess) {
260         llvm::LLVMRustSetModulePIELevel(llmod);
261     }
262
263     (llcx, llmod)
264 }
265
266 impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> {
267     pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>,
268                exported_symbols: NodeSet,
269                check_overflow: bool)
270                -> SharedCrateContext<'b, 'tcx> {
271         // An interesting part of Windows which MSVC forces our hand on (and
272         // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
273         // attributes in LLVM IR as well as native dependencies (in C these
274         // correspond to `__declspec(dllimport)`).
275         //
276         // Whenever a dynamic library is built by MSVC it must have its public
277         // interface specified by functions tagged with `dllexport` or otherwise
278         // they're not available to be linked against. This poses a few problems
279         // for the compiler, some of which are somewhat fundamental, but we use
280         // the `use_dll_storage_attrs` variable below to attach the `dllexport`
281         // attribute to all LLVM functions that are exported e.g. they're
282         // already tagged with external linkage). This is suboptimal for a few
283         // reasons:
284         //
285         // * If an object file will never be included in a dynamic library,
286         //   there's no need to attach the dllexport attribute. Most object
287         //   files in Rust are not destined to become part of a dll as binaries
288         //   are statically linked by default.
289         // * If the compiler is emitting both an rlib and a dylib, the same
290         //   source object file is currently used but with MSVC this may be less
291         //   feasible. The compiler may be able to get around this, but it may
292         //   involve some invasive changes to deal with this.
293         //
294         // The flipside of this situation is that whenever you link to a dll and
295         // you import a function from it, the import should be tagged with
296         // `dllimport`. At this time, however, the compiler does not emit
297         // `dllimport` for any declarations other than constants (where it is
298         // required), which is again suboptimal for even more reasons!
299         //
300         // * Calling a function imported from another dll without using
301         //   `dllimport` causes the linker/compiler to have extra overhead (one
302         //   `jmp` instruction on x86) when calling the function.
303         // * The same object file may be used in different circumstances, so a
304         //   function may be imported from a dll if the object is linked into a
305         //   dll, but it may be just linked against if linked into an rlib.
306         // * The compiler has no knowledge about whether native functions should
307         //   be tagged dllimport or not.
308         //
309         // For now the compiler takes the perf hit (I do not have any numbers to
310         // this effect) by marking very little as `dllimport` and praying the
311         // linker will take care of everything. Fixing this problem will likely
312         // require adding a few attributes to Rust itself (feature gated at the
313         // start) and then strongly recommending static linkage on MSVC!
314         let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc;
315
316         SharedCrateContext {
317             exported_symbols: exported_symbols,
318             empty_param_env: tcx.empty_parameter_environment(),
319             tcx: tcx,
320             check_overflow: check_overflow,
321             use_dll_storage_attrs: use_dll_storage_attrs,
322         }
323     }
324
325     pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
326         ty.needs_drop(self.tcx, &self.empty_param_env)
327     }
328
329     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
330         ty.is_sized(self.tcx, &self.empty_param_env, DUMMY_SP)
331     }
332
333     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
334         ty.is_freeze(self.tcx, &self.empty_param_env, DUMMY_SP)
335     }
336
337     pub fn exported_symbols<'a>(&'a self) -> &'a NodeSet {
338         &self.exported_symbols
339     }
340
341     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
342         self.tcx
343     }
344
345     pub fn sess<'a>(&'a self) -> &'a Session {
346         &self.tcx.sess
347     }
348
349     pub fn dep_graph<'a>(&'a self) -> &'a DepGraph {
350         &self.tcx.dep_graph
351     }
352
353     pub fn use_dll_storage_attrs(&self) -> bool {
354         self.use_dll_storage_attrs
355     }
356 }
357
358 impl<'a, 'tcx> LocalCrateContext<'a, 'tcx> {
359     pub fn new(shared: &SharedCrateContext<'a, 'tcx>,
360                codegen_unit: CodegenUnit<'tcx>)
361                -> LocalCrateContext<'a, 'tcx> {
362         unsafe {
363             // Append ".rs" to LLVM module identifier.
364             //
365             // LLVM code generator emits a ".file filename" directive
366             // for ELF backends. Value of the "filename" is set as the
367             // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
368             // crashes if the module identifier is same as other symbols
369             // such as a function name in the module.
370             // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
371             let llmod_id = format!("{}.rs", codegen_unit.name());
372
373             let (llcx, llmod) = create_context_and_module(&shared.tcx.sess,
374                                                           &llmod_id[..]);
375
376             let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo {
377                 let dctx = debuginfo::CrateDebugContext::new(llmod);
378                 debuginfo::metadata::compile_unit_metadata(shared,
379                                                            codegen_unit.name(),
380                                                            &dctx,
381                                                            shared.tcx.sess);
382                 Some(dctx)
383             } else {
384                 None
385             };
386
387             let local_ccx = LocalCrateContext {
388                 llmod: llmod,
389                 llcx: llcx,
390                 stats: Stats::default(),
391                 codegen_unit: codegen_unit,
392                 instances: RefCell::new(FxHashMap()),
393                 vtables: RefCell::new(FxHashMap()),
394                 const_cstr_cache: RefCell::new(FxHashMap()),
395                 const_unsized: RefCell::new(FxHashMap()),
396                 const_globals: RefCell::new(FxHashMap()),
397                 const_values: RefCell::new(FxHashMap()),
398                 extern_const_values: RefCell::new(DefIdMap()),
399                 statics: RefCell::new(FxHashMap()),
400                 statics_to_rauw: RefCell::new(Vec::new()),
401                 used_statics: RefCell::new(Vec::new()),
402                 lltypes: RefCell::new(FxHashMap()),
403                 type_hashcodes: RefCell::new(FxHashMap()),
404                 int_type: Type::from_ref(ptr::null_mut()),
405                 opaque_vec_type: Type::from_ref(ptr::null_mut()),
406                 str_slice_type: Type::from_ref(ptr::null_mut()),
407                 dbg_cx: dbg_cx,
408                 eh_personality: Cell::new(None),
409                 eh_unwind_resume: Cell::new(None),
410                 rust_try_fn: Cell::new(None),
411                 intrinsics: RefCell::new(FxHashMap()),
412                 type_of_depth: Cell::new(0),
413                 local_gen_sym_counter: Cell::new(0),
414                 placeholder: PhantomData,
415             };
416
417             let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = {
418                 // Do a little dance to create a dummy CrateContext, so we can
419                 // create some things in the LLVM module of this codegen unit
420                 let mut local_ccxs = vec![local_ccx];
421                 let (int_type, opaque_vec_type, str_slice_ty) = {
422                     let dummy_ccx = LocalCrateContext::dummy_ccx(shared,
423                                                                  local_ccxs.as_mut_slice());
424                     let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice");
425                     str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx),
426                                                    Type::int(&dummy_ccx)],
427                                                  false);
428                     (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty)
429                 };
430                 (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap())
431             };
432
433             local_ccx.int_type = int_type;
434             local_ccx.opaque_vec_type = opaque_vec_type;
435             local_ccx.str_slice_type = str_slice_ty;
436
437             local_ccx
438         }
439     }
440
441     /// Create a dummy `CrateContext` from `self` and  the provided
442     /// `SharedCrateContext`.  This is somewhat dangerous because `self` may
443     /// not be fully initialized.
444     ///
445     /// This is used in the `LocalCrateContext` constructor to allow calling
446     /// functions that expect a complete `CrateContext`, even before the local
447     /// portion is fully initialized and attached to the `SharedCrateContext`.
448     fn dummy_ccx(shared: &'a SharedCrateContext<'a, 'tcx>,
449                  local_ccxs: &'a [LocalCrateContext<'a, 'tcx>])
450                  -> CrateContext<'a, 'tcx> {
451         assert!(local_ccxs.len() == 1);
452         CrateContext {
453             shared: shared,
454             local_ccx: &local_ccxs[0]
455         }
456     }
457
458     pub fn into_stats(self) -> Stats {
459         self.stats
460     }
461 }
462
463 impl<'b, 'tcx> CrateContext<'b, 'tcx> {
464     pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> {
465         self.shared
466     }
467
468     fn local(&self) -> &'b LocalCrateContext<'b, 'tcx> {
469         self.local_ccx
470     }
471
472     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
473         self.shared.tcx
474     }
475
476     pub fn sess<'a>(&'a self) -> &'a Session {
477         &self.shared.tcx.sess
478     }
479
480     pub fn get_intrinsic(&self, key: &str) -> ValueRef {
481         if let Some(v) = self.intrinsics().borrow().get(key).cloned() {
482             return v;
483         }
484         match declare_intrinsic(self, key) {
485             Some(v) => return v,
486             None => bug!("unknown intrinsic '{}'", key)
487         }
488     }
489
490     pub fn llmod(&self) -> ModuleRef {
491         self.local().llmod
492     }
493
494     pub fn llcx(&self) -> ContextRef {
495         self.local().llcx
496     }
497
498     pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> {
499         &self.local().codegen_unit
500     }
501
502     pub fn td(&self) -> llvm::TargetDataRef {
503         unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) }
504     }
505
506     pub fn instances<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> {
507         &self.local().instances
508     }
509
510     pub fn vtables<'a>(&'a self)
511         -> &'a RefCell<FxHashMap<(ty::Ty<'tcx>,
512                                   Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>> {
513         &self.local().vtables
514     }
515
516     pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<InternedString, ValueRef>> {
517         &self.local().const_cstr_cache
518     }
519
520     pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
521         &self.local().const_unsized
522     }
523
524     pub fn const_globals<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> {
525         &self.local().const_globals
526     }
527
528     pub fn const_values<'a>(&'a self) -> &'a RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>),
529                                                                ValueRef>> {
530         &self.local().const_values
531     }
532
533     pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> {
534         &self.local().extern_const_values
535     }
536
537     pub fn statics<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, DefId>> {
538         &self.local().statics
539     }
540
541     pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> {
542         &self.local().statics_to_rauw
543     }
544
545     pub fn used_statics<'a>(&'a self) -> &'a RefCell<Vec<ValueRef>> {
546         &self.local().used_statics
547     }
548
549     pub fn lltypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> {
550         &self.local().lltypes
551     }
552
553     pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, String>> {
554         &self.local().type_hashcodes
555     }
556
557     pub fn stats<'a>(&'a self) -> &'a Stats {
558         &self.local().stats
559     }
560
561     pub fn int_type(&self) -> Type {
562         self.local().int_type
563     }
564
565     pub fn opaque_vec_type(&self) -> Type {
566         self.local().opaque_vec_type
567     }
568
569     pub fn str_slice_type(&self) -> Type {
570         self.local().str_slice_type
571     }
572
573     pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> {
574         &self.local().dbg_cx
575     }
576
577     pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> {
578         &self.local().rust_try_fn
579     }
580
581     fn intrinsics<'a>(&'a self) -> &'a RefCell<FxHashMap<&'static str, ValueRef>> {
582         &self.local().intrinsics
583     }
584
585     pub fn obj_size_bound(&self) -> u64 {
586         self.tcx().data_layout.obj_size_bound()
587     }
588
589     pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! {
590         self.sess().fatal(
591             &format!("the type `{:?}` is too big for the current architecture",
592                     obj))
593     }
594
595     pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> {
596         let current_depth = self.local().type_of_depth.get();
597         debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth);
598         if current_depth > self.sess().recursion_limit.get() {
599             self.sess().fatal(
600                 &format!("overflow representing the type `{}`", ty))
601         }
602         self.local().type_of_depth.set(current_depth + 1);
603         TypeOfDepthLock(self.local())
604     }
605
606     pub fn check_overflow(&self) -> bool {
607         self.shared.check_overflow
608     }
609
610     pub fn use_dll_storage_attrs(&self) -> bool {
611         self.shared.use_dll_storage_attrs()
612     }
613
614     /// Given the def-id of some item that has no type parameters, make
615     /// a suitable "empty substs" for it.
616     pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
617         self.tcx().empty_substs_for_def_id(item_def_id)
618     }
619
620     /// Generate a new symbol name with the given prefix. This symbol name must
621     /// only be used for definitions with `internal` or `private` linkage.
622     pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
623         let idx = self.local().local_gen_sym_counter.get();
624         self.local().local_gen_sym_counter.set(idx + 1);
625         // Include a '.' character, so there can be no accidental conflicts with
626         // user defined names
627         let mut name = String::with_capacity(prefix.len() + 6);
628         name.push_str(prefix);
629         name.push_str(".");
630         base_n::push_str(idx as u64, base_n::ALPHANUMERIC_ONLY, &mut name);
631         name
632     }
633
634     pub fn eh_personality(&self) -> ValueRef {
635         // The exception handling personality function.
636         //
637         // If our compilation unit has the `eh_personality` lang item somewhere
638         // within it, then we just need to translate that. Otherwise, we're
639         // building an rlib which will depend on some upstream implementation of
640         // this function, so we just codegen a generic reference to it. We don't
641         // specify any of the types for the function, we just make it a symbol
642         // that LLVM can later use.
643         //
644         // Note that MSVC is a little special here in that we don't use the
645         // `eh_personality` lang item at all. Currently LLVM has support for
646         // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
647         // *name of the personality function* to decide what kind of unwind side
648         // tables/landing pads to emit. It looks like Dwarf is used by default,
649         // injecting a dependency on the `_Unwind_Resume` symbol for resuming
650         // an "exception", but for MSVC we want to force SEH. This means that we
651         // can't actually have the personality function be our standard
652         // `rust_eh_personality` function, but rather we wired it up to the
653         // CRT's custom personality function, which forces LLVM to consider
654         // landing pads as "landing pads for SEH".
655         if let Some(llpersonality) = self.local().eh_personality.get() {
656             return llpersonality
657         }
658         let tcx = self.tcx();
659         let llfn = match tcx.lang_items.eh_personality() {
660             Some(def_id) if !base::wants_msvc_seh(self.sess()) => {
661                 callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]))
662             }
663             _ => {
664                 let name = if base::wants_msvc_seh(self.sess()) {
665                     "__CxxFrameHandler3"
666                 } else {
667                     "rust_eh_personality"
668                 };
669                 let fty = Type::variadic_func(&[], &Type::i32(self));
670                 declare::declare_cfn(self, name, fty)
671             }
672         };
673         self.local().eh_personality.set(Some(llfn));
674         llfn
675     }
676
677     // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined,
678     // otherwise declares it as an external function.
679     pub fn eh_unwind_resume(&self) -> ValueRef {
680         use attributes;
681         let unwresume = &self.local().eh_unwind_resume;
682         if let Some(llfn) = unwresume.get() {
683             return llfn;
684         }
685
686         let tcx = self.tcx();
687         assert!(self.sess().target.target.options.custom_unwind_resume);
688         if let Some(def_id) = tcx.lang_items.eh_unwind_resume() {
689             let llfn = callee::resolve_and_get_fn(self, def_id, tcx.intern_substs(&[]));
690             unwresume.set(Some(llfn));
691             return llfn;
692         }
693
694         let ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
695             iter::once(tcx.mk_mut_ptr(tcx.types.u8)),
696             tcx.types.never,
697             false,
698             hir::Unsafety::Unsafe,
699             Abi::C
700         )));
701
702         let llfn = declare::declare_fn(self, "rust_eh_unwind_resume", ty);
703         attributes::unwind(llfn, true);
704         unwresume.set(Some(llfn));
705         llfn
706     }
707 }
708
709 impl<'a, 'tcx> ty::layout::HasDataLayout for &'a SharedCrateContext<'a, 'tcx> {
710     fn data_layout(&self) -> &ty::layout::TargetDataLayout {
711         &self.tcx.data_layout
712     }
713 }
714
715 impl<'a, 'tcx> ty::layout::HasTyCtxt<'tcx> for &'a SharedCrateContext<'a, 'tcx> {
716     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
717         self.tcx
718     }
719 }
720
721 impl<'a, 'tcx> ty::layout::HasDataLayout for &'a CrateContext<'a, 'tcx> {
722     fn data_layout(&self) -> &ty::layout::TargetDataLayout {
723         &self.shared.tcx.data_layout
724     }
725 }
726
727 impl<'a, 'tcx> ty::layout::HasTyCtxt<'tcx> for &'a CrateContext<'a, 'tcx> {
728     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
729         self.shared.tcx
730     }
731 }
732
733 impl<'a, 'tcx> LayoutTyper<'tcx> for &'a SharedCrateContext<'a, 'tcx> {
734     type TyLayout = TyLayout<'tcx>;
735
736     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
737         if let Some(&layout) = self.tcx().layout_cache.borrow().get(&ty) {
738             return TyLayout { ty: ty, layout: layout, variant_index: None };
739         }
740
741         self.tcx().infer_ctxt((), traits::Reveal::All).enter(|infcx| {
742             infcx.layout_of(ty).unwrap_or_else(|e| {
743                 match e {
744                     ty::layout::LayoutError::SizeOverflow(_) =>
745                         self.sess().fatal(&e.to_string()),
746                     _ => bug!("failed to get layout for `{}`: {}", ty, e)
747                 }
748             })
749         })
750     }
751
752     fn normalize_projections(self, ty: Ty<'tcx>) -> Ty<'tcx> {
753         self.tcx().normalize_associated_type(&ty)
754     }
755 }
756
757 impl<'a, 'tcx> LayoutTyper<'tcx> for &'a CrateContext<'a, 'tcx> {
758     type TyLayout = TyLayout<'tcx>;
759
760     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
761         self.shared.layout_of(ty)
762     }
763
764     fn normalize_projections(self, ty: Ty<'tcx>) -> Ty<'tcx> {
765         self.shared.normalize_projections(ty)
766     }
767 }
768
769 pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'a, 'tcx>);
770
771 impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> {
772     fn drop(&mut self) {
773         self.0.type_of_depth.set(self.0.type_of_depth.get() - 1);
774     }
775 }
776
777 /// Declare any llvm intrinsics that you might need
778 fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> {
779     macro_rules! ifn {
780         ($name:expr, fn() -> $ret:expr) => (
781             if key == $name {
782                 let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret));
783                 llvm::SetUnnamedAddr(f, false);
784                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
785                 return Some(f);
786             }
787         );
788         ($name:expr, fn(...) -> $ret:expr) => (
789             if key == $name {
790                 let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret));
791                 llvm::SetUnnamedAddr(f, false);
792                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
793                 return Some(f);
794             }
795         );
796         ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
797             if key == $name {
798                 let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret));
799                 llvm::SetUnnamedAddr(f, false);
800                 ccx.intrinsics().borrow_mut().insert($name, f.clone());
801                 return Some(f);
802             }
803         );
804     }
805     macro_rules! mk_struct {
806         ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false))
807     }
808
809     let i8p = Type::i8p(ccx);
810     let void = Type::void(ccx);
811     let i1 = Type::i1(ccx);
812     let t_i8 = Type::i8(ccx);
813     let t_i16 = Type::i16(ccx);
814     let t_i32 = Type::i32(ccx);
815     let t_i64 = Type::i64(ccx);
816     let t_i128 = Type::i128(ccx);
817     let t_f32 = Type::f32(ccx);
818     let t_f64 = Type::f64(ccx);
819
820     ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
821     ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
822     ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
823     ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void);
824     ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void);
825     ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void);
826     ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void);
827     ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
828     ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
829
830     ifn!("llvm.trap", fn() -> void);
831     ifn!("llvm.debugtrap", fn() -> void);
832     ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
833
834     ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
835     ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
836     ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
837     ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
838
839     ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
840     ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
841     ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
842     ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
843     ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
844     ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
845     ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
846     ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
847     ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
848     ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
849     ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
850     ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
851     ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
852     ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
853     ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
854     ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
855
856     ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
857     ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
858
859     ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
860     ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
861
862     ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
863     ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
864     ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
865     ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
866     ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
867     ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
868
869     ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
870     ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
871     ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
872     ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
873
874     ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
875     ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
876     ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
877     ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
878
879     ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
880     ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
881     ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
882     ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
883     ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
884
885     ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8);
886     ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
887     ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
888     ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
889     ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
890
891     ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8);
892     ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
893     ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
894     ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
895     ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
896
897     ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
898     ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
899     ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
900     ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
901
902     ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
903     ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
904     ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
905     ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
906     ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
907
908     ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
909     ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
910     ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
911     ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
912     ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
913
914     ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
915     ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
916     ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
917     ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
918     ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
919
920     ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
921     ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
922     ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
923     ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
924     ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
925
926     ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
927     ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
928     ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
929     ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
930     ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
931
932     ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
933     ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
934     ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
935     ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
936     ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1});
937
938     ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void);
939     ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void);
940
941     ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
942     ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
943     ifn!("llvm.localescape", fn(...) -> void);
944     ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
945     ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
946
947     ifn!("llvm.assume", fn(i1) -> void);
948
949     if ccx.sess().opts.debuginfo != NoDebugInfo {
950         ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
951         ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);
952     }
953     return None;
954 }