]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/base.rs
Moved common.rs enums
[rust.git] / src / librustc_codegen_llvm / base.rs
1 // Copyright 2012-2015 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 //! Codegen the completed AST to the LLVM IR.
12 //!
13 //! Some functions here, such as codegen_block and codegen_expr, return a value --
14 //! the result of the codegen to LLVM -- while others, such as codegen_fn
15 //! and mono_item, are called only for the side effect of adding a
16 //! particular definition to the LLVM IR output we're producing.
17 //!
18 //! Hopefully useful general knowledge about codegen:
19 //!
20 //!   * There's no way to find out the Ty type of a Value.  Doing so
21 //!     would be "trying to get the eggs out of an omelette" (credit:
22 //!     pcwalton).  You can, instead, find out its llvm::Type by calling val_ty,
23 //!     but one llvm::Type corresponds to many `Ty`s; for instance, tup(int, int,
24 //!     int) and rec(x=int, y=int, z=int) will have the same llvm::Type.
25
26 use super::ModuleLlvm;
27 use super::ModuleCodegen;
28 use super::ModuleKind;
29 use super::CachedModuleCodegen;
30 use super::LlvmCodegenBackend;
31
32 use abi;
33 use back::write;
34 use llvm;
35 use metadata;
36 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
37 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
38 use rustc::middle::lang_items::StartFnLangItem;
39 use rustc::middle::weak_lang_items;
40 use rustc::mir::mono::{Linkage, Visibility, Stats, CodegenUnitNameBuilder};
41 use rustc::middle::cstore::{EncodedMetadata};
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx, HasTyCtxt};
44 use rustc::ty::query::Providers;
45 use rustc::middle::cstore::{self, LinkagePreference};
46 use rustc::middle::exported_symbols;
47 use rustc::util::common::{time, print_time_passes_entry};
48 use rustc::util::profiling::ProfileCategory;
49 use rustc::session::config::{self, DebugInfo, EntryFnType, Lto};
50 use rustc::session::Session;
51 use rustc_incremental;
52 use mir::place::PlaceRef;
53 use builder::{Builder, MemFlags};
54 use callee;
55 use rustc_mir::monomorphize::item::DefPathBasedNames;
56 use common;
57 use rustc_codegen_utils::common::{RealPredicate, TypeKind, IntPredicate};
58 use meth;
59 use mir;
60 use context::CodegenCx;
61 use monomorphize::Instance;
62 use monomorphize::partitioning::{CodegenUnit, CodegenUnitExt};
63 use rustc_codegen_utils::symbol_names_test;
64 use time_graph;
65 use mono_item::{MonoItem, MonoItemExt};
66
67 use rustc::util::nodemap::FxHashMap;
68 use CrateInfo;
69 use rustc_data_structures::small_c_str::SmallCStr;
70 use rustc_data_structures::sync::Lrc;
71 use rustc_data_structures::indexed_vec::Idx;
72
73 use interfaces::*;
74
75 use std::any::Any;
76 use std::cmp;
77 use std::ffi::CString;
78 use std::marker;
79 use std::ops::{Deref, DerefMut};
80 use std::sync::mpsc;
81 use std::time::{Instant, Duration};
82 use syntax_pos::Span;
83 use syntax_pos::symbol::InternedString;
84 use syntax::attr;
85 use rustc::hir::{self, CodegenFnAttrs};
86
87 use value::Value;
88
89 use mir::operand::OperandValue;
90
91 use rustc_codegen_utils::check_for_rustc_errors_attr;
92
93 pub struct StatRecorder<'a, 'tcx, Cx: 'a + CodegenMethods<'tcx>> {
94     cx: &'a Cx,
95     name: Option<String>,
96     istart: usize,
97     _marker: marker::PhantomData<&'tcx ()>,
98 }
99
100 impl<'a, 'tcx, Cx: CodegenMethods<'tcx>> StatRecorder<'a, 'tcx, Cx> {
101     pub fn new(cx: &'a Cx, name: String) -> Self {
102         let istart = cx.stats().borrow().n_llvm_insns;
103         StatRecorder {
104             cx,
105             name: Some(name),
106             istart,
107             _marker: marker::PhantomData,
108         }
109     }
110 }
111
112 impl<'a, 'tcx, Cx: CodegenMethods<'tcx>> Drop for StatRecorder<'a, 'tcx, Cx> {
113     fn drop(&mut self) {
114         if self.cx.sess().codegen_stats() {
115             let mut stats = self.cx.stats().borrow_mut();
116             let iend = stats.n_llvm_insns;
117             stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
118             stats.n_fns += 1;
119             // Reset LLVM insn count to avoid compound costs.
120             stats.n_llvm_insns = self.istart;
121         }
122     }
123 }
124
125 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
126                                 signed: bool)
127                                 -> IntPredicate {
128     match op {
129         hir::BinOpKind::Eq => IntPredicate::IntEQ,
130         hir::BinOpKind::Ne => IntPredicate::IntNE,
131         hir::BinOpKind::Lt => if signed { IntPredicate::IntSLT } else { IntPredicate::IntULT },
132         hir::BinOpKind::Le => if signed { IntPredicate::IntSLE } else { IntPredicate::IntULE },
133         hir::BinOpKind::Gt => if signed { IntPredicate::IntSGT } else { IntPredicate::IntUGT },
134         hir::BinOpKind::Ge => if signed { IntPredicate::IntSGE } else { IntPredicate::IntUGE },
135         op => {
136             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
137                   found {:?}",
138                  op)
139         }
140     }
141 }
142
143 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
144     match op {
145         hir::BinOpKind::Eq => RealPredicate::RealOEQ,
146         hir::BinOpKind::Ne => RealPredicate::RealUNE,
147         hir::BinOpKind::Lt => RealPredicate::RealOLT,
148         hir::BinOpKind::Le => RealPredicate::RealOLE,
149         hir::BinOpKind::Gt => RealPredicate::RealOGT,
150         hir::BinOpKind::Ge => RealPredicate::RealOGE,
151         op => {
152             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
153                   found {:?}",
154                  op);
155         }
156     }
157 }
158
159 pub fn compare_simd_types<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
160     bx: &Bx,
161     lhs: Bx::Value,
162     rhs: Bx::Value,
163     t: Ty<'tcx>,
164     ret_ty: Bx::Type,
165     op: hir::BinOpKind
166 ) -> Bx::Value {
167     let signed = match t.sty {
168         ty::Float(_) => {
169             let cmp = bin_op_to_fcmp_predicate(op);
170             return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
171         },
172         ty::Uint(_) => false,
173         ty::Int(_) => true,
174         _ => bug!("compare_simd_types: invalid SIMD type"),
175     };
176
177     let cmp = bin_op_to_icmp_predicate(op, signed);
178     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
179     // to get the correctly sized type. This will compile to a single instruction
180     // once the IR is converted to assembly if the SIMD instruction is supported
181     // by the target architecture.
182     bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
183 }
184
185 /// Retrieve the information we are losing (making dynamic) in an unsizing
186 /// adjustment.
187 ///
188 /// The `old_info` argument is a bit funny. It is intended for use
189 /// in an upcast, where the new vtable for an object will be derived
190 /// from the old one.
191 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
192     cx: &Cx,
193     source: Ty<'tcx>,
194     target: Ty<'tcx>,
195     old_info: Option<Cx::Value>,
196 ) -> Cx::Value {
197     let (source, target) = cx.tcx().struct_lockstep_tails(source, target);
198     match (&source.sty, &target.sty) {
199         (&ty::Array(_, len), &ty::Slice(_)) => {
200             cx.const_usize(len.unwrap_usize(cx.tcx()))
201         }
202         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
203             // For now, upcasts are limited to changes in marker
204             // traits, and hence never actually require an actual
205             // change to the vtable.
206             old_info.expect("unsized_info: missing old info for trait upcast")
207         }
208         (_, &ty::Dynamic(ref data, ..)) => {
209             let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target))
210                 .field(cx, abi::FAT_PTR_EXTRA);
211             cx.static_ptrcast(meth::get_vtable(cx, source, data.principal()),
212                             cx.backend_type(vtable_ptr))
213         }
214         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
215                   source,
216                   target),
217     }
218 }
219
220 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
221 pub fn unsize_thin_ptr<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
222     bx: &Bx,
223     src: Bx::Value,
224     src_ty: Ty<'tcx>,
225     dst_ty: Ty<'tcx>
226 ) -> (Bx::Value, Bx::Value) {
227     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
228     match (&src_ty.sty, &dst_ty.sty) {
229         (&ty::Ref(_, a, _),
230          &ty::Ref(_, b, _)) |
231         (&ty::Ref(_, a, _),
232          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
233         (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
234          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
235             assert!(bx.cx().type_is_sized(a));
236             let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
237             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
238         }
239         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
240             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
241             assert!(bx.cx().type_is_sized(a));
242             let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
243             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
244         }
245         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
246             assert_eq!(def_a, def_b);
247
248             let src_layout = bx.cx().layout_of(src_ty);
249             let dst_layout = bx.cx().layout_of(dst_ty);
250             let mut result = None;
251             for i in 0..src_layout.fields.count() {
252                 let src_f = src_layout.field(bx.cx(), i);
253                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
254                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
255                 if src_f.is_zst() {
256                     continue;
257                 }
258                 assert_eq!(src_layout.size, src_f.size);
259
260                 let dst_f = dst_layout.field(bx.cx(), i);
261                 assert_ne!(src_f.ty, dst_f.ty);
262                 assert_eq!(result, None);
263                 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
264             }
265             let (lldata, llextra) = result.unwrap();
266             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
267             (bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)),
268              bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)))
269         }
270         _ => bug!("unsize_thin_ptr: called on bad types"),
271     }
272 }
273
274 /// Coerce `src`, which is a reference to a value of type `src_ty`,
275 /// to a value of type `dst_ty` and store the result in `dst`
276 pub fn coerce_unsized_into<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
277     bx: &Bx,
278     src: PlaceRef<'tcx, Bx::Value>,
279     dst: PlaceRef<'tcx, Bx::Value>
280 )  {
281     let src_ty = src.layout.ty;
282     let dst_ty = dst.layout.ty;
283     let coerce_ptr = || {
284         let (base, info) = match bx.load_operand(src).val {
285             OperandValue::Pair(base, info) => {
286                 // fat-ptr to fat-ptr unsize preserves the vtable
287                 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
288                 // So we need to pointercast the base to ensure
289                 // the types match up.
290                 let thin_ptr = dst.layout.field(bx.cx(), abi::FAT_PTR_ADDR);
291                 (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info)
292             }
293             OperandValue::Immediate(base) => {
294                 unsize_thin_ptr(bx, base, src_ty, dst_ty)
295             }
296             OperandValue::Ref(..) => bug!()
297         };
298         OperandValue::Pair(base, info).store(bx, dst);
299     };
300     match (&src_ty.sty, &dst_ty.sty) {
301         (&ty::Ref(..), &ty::Ref(..)) |
302         (&ty::Ref(..), &ty::RawPtr(..)) |
303         (&ty::RawPtr(..), &ty::RawPtr(..)) => {
304             coerce_ptr()
305         }
306         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
307             coerce_ptr()
308         }
309
310         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
311             assert_eq!(def_a, def_b);
312
313             for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
314                 let src_f = src.project_field(bx, i);
315                 let dst_f = dst.project_field(bx, i);
316
317                 if dst_f.layout.is_zst() {
318                     continue;
319                 }
320
321                 if src_f.layout.ty == dst_f.layout.ty {
322                     memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align,
323                               src_f.layout, MemFlags::empty());
324                 } else {
325                     coerce_unsized_into(bx, src_f, dst_f);
326                 }
327             }
328         }
329         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
330                   src_ty,
331                   dst_ty),
332     }
333 }
334
335 pub fn cast_shift_expr_rhs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
336     bx: &Bx,
337     op: hir::BinOpKind,
338     lhs: Bx::Value,
339     rhs: Bx::Value
340 ) -> Bx::Value {
341     cast_shift_rhs(bx, op, lhs, rhs, |a, b| bx.trunc(a, b), |a, b| bx.zext(a, b))
342 }
343
344 fn cast_shift_rhs<'a, 'tcx: 'a, F, G, Bx: BuilderMethods<'a, 'tcx>>(
345     bx: &Bx,
346     op: hir::BinOpKind,
347     lhs: Bx::Value,
348     rhs: Bx::Value,
349     trunc: F,
350     zext: G
351 ) -> Bx::Value
352     where F: FnOnce(
353         Bx::Value,
354         Bx::Type
355     ) -> Bx::Value,
356     G: FnOnce(
357         Bx::Value,
358         Bx::Type
359     ) -> Bx::Value
360 {
361     // Shifts may have any size int on the rhs
362     if op.is_shift() {
363         let mut rhs_llty = bx.cx().val_ty(rhs);
364         let mut lhs_llty = bx.cx().val_ty(lhs);
365         if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
366             rhs_llty = bx.cx().element_type(rhs_llty)
367         }
368         if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
369             lhs_llty = bx.cx().element_type(lhs_llty)
370         }
371         let rhs_sz = bx.cx().int_width(rhs_llty);
372         let lhs_sz = bx.cx().int_width(lhs_llty);
373         if lhs_sz < rhs_sz {
374             trunc(rhs, lhs_llty)
375         } else if lhs_sz > rhs_sz {
376             // FIXME (#1877: If in the future shifting by negative
377             // values is no longer undefined then this is wrong.
378             zext(rhs, lhs_llty)
379         } else {
380             rhs
381         }
382     } else {
383         rhs
384     }
385 }
386
387 /// Returns whether this session's target will use SEH-based unwinding.
388 ///
389 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
390 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
391 /// 64-bit MinGW) instead of "full SEH".
392 pub fn wants_msvc_seh(sess: &Session) -> bool {
393     sess.target.target.options.is_like_msvc
394 }
395
396 pub fn call_assume<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
397     bx: &Bx,
398     val: Bx::Value
399 ) {
400     let assume_intrinsic = bx.cx().get_intrinsic("llvm.assume");
401     bx.call(assume_intrinsic, &[val], None);
402 }
403
404 pub fn from_immediate<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
405     bx: &Bx,
406     val: Bx::Value
407 ) -> Bx::Value {
408     if bx.cx().val_ty(val) == bx.cx().type_i1() {
409         bx.zext(val, bx.cx().type_i8())
410     } else {
411         val
412     }
413 }
414
415 pub fn to_immediate<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
416     bx: &Bx,
417     val: Bx::Value,
418     layout: layout::TyLayout,
419 ) -> Bx::Value {
420     if let layout::Abi::Scalar(ref scalar) = layout.abi {
421         return to_immediate_scalar(bx, val, scalar);
422     }
423     val
424 }
425
426 pub fn to_immediate_scalar<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
427     bx: &Bx,
428     val: Bx::Value,
429     scalar: &layout::Scalar,
430 ) -> Bx::Value {
431     if scalar.is_bool() {
432         return bx.trunc(val, bx.cx().type_i1());
433     }
434     val
435 }
436
437 pub fn memcpy_ty<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
438     bx: &Bx,
439     dst: Bx::Value,
440     dst_align: Align,
441     src: Bx::Value,
442     src_align: Align,
443     layout: TyLayout<'tcx>,
444     flags: MemFlags,
445 ) {
446     let size = layout.size.bytes();
447     if size == 0 {
448         return;
449     }
450
451     bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
452 }
453
454 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
455     cx: &'a Bx::CodegenCx,
456     instance: Instance<'tcx>,
457 ) {
458     let _s = if cx.sess().codegen_stats() {
459         let mut instance_name = String::new();
460         DefPathBasedNames::new(cx.tcx(), true, true)
461             .push_def_path(instance.def_id(), &mut instance_name);
462         Some(StatRecorder::new(cx, instance_name))
463     } else {
464         None
465     };
466
467     // this is an info! to allow collecting monomorphization statistics
468     // and to allow finding the last function before LLVM aborts from
469     // release builds.
470     info!("codegen_instance({})", instance);
471
472     let sig = instance.fn_sig(cx.tcx());
473     let sig = cx.tcx().normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
474
475     let lldecl = cx.instances().borrow().get(&instance).cloned().unwrap_or_else(||
476         bug!("Instance `{:?}` not already declared", instance));
477
478     cx.stats().borrow_mut().n_closures += 1;
479
480     let mir = cx.tcx().instance_mir(instance.def);
481     mir::codegen_mir::<Bx>(cx, lldecl, &mir, instance, sig);
482 }
483
484 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
485     let sect = match attrs.link_section {
486         Some(name) => name,
487         None => return,
488     };
489     unsafe {
490         let buf = SmallCStr::new(&sect.as_str());
491         llvm::LLVMSetSection(llval, buf.as_ptr());
492     }
493 }
494
495 /// Create the `main` function which will initialize the rust runtime and call
496 /// users main function.
497 fn maybe_create_entry_wrapper<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
498     cx: &'a Bx::CodegenCx
499 ) {
500     let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
501         Some((id, span, _)) => {
502             (cx.tcx().hir.local_def_id(id), span)
503         }
504         None => return,
505     };
506
507     let instance = Instance::mono(cx.tcx(), main_def_id);
508
509     if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
510         // We want to create the wrapper in the same codegen unit as Rust's main
511         // function.
512         return;
513     }
514
515     let main_llfn = cx.get_fn(instance);
516
517     let et = cx.sess().entry_fn.get().map(|e| e.2);
518     match et {
519         Some(EntryFnType::Main) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, true),
520         Some(EntryFnType::Start) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, false),
521         None => {}    // Do nothing.
522     }
523
524     fn create_entry_fn<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
525         cx: &'a Bx::CodegenCx,
526         sp: Span,
527         rust_main: Bx::Value,
528         rust_main_def_id: DefId,
529         use_start_lang_item: bool,
530     ) {
531         let llfty =
532             cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int());
533
534         let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
535         // Given that `main()` has no arguments,
536         // then its return type cannot have
537         // late-bound regions, since late-bound
538         // regions must appear in the argument
539         // listing.
540         let main_ret_ty = cx.tcx().erase_regions(
541             &main_ret_ty.no_bound_vars().unwrap(),
542         );
543
544         if cx.get_defined_value("main").is_some() {
545             // FIXME: We should be smart and show a better diagnostic here.
546             cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
547                      .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
548                      .emit();
549             cx.sess().abort_if_errors();
550             bug!();
551         }
552         let llfn = cx.declare_cfn("main", llfty);
553
554         // `main` should respect same config for frame pointer elimination as rest of code
555         cx.set_frame_pointer_elimination(llfn);
556         cx.apply_target_cpu_attr(llfn);
557
558         let bx = Bx::new_block(&cx, llfn, "top");
559
560         bx.insert_reference_to_gdb_debug_scripts_section_global();
561
562         // Params from native main() used as args for rust start function
563         let param_argc = cx.get_param(llfn, 0);
564         let param_argv = cx.get_param(llfn, 1);
565         let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
566         let arg_argv = param_argv;
567
568         let (start_fn, args) = if use_start_lang_item {
569             let start_def_id = cx.tcx().require_lang_item(StartFnLangItem);
570             let start_fn = callee::resolve_and_get_fn(
571                 cx,
572                 start_def_id,
573                 cx.tcx().intern_substs(&[main_ret_ty.into()]),
574             );
575             (start_fn, vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())),
576                             arg_argc, arg_argv])
577         } else {
578             debug!("using user-defined start fn");
579             (rust_main, vec![arg_argc, arg_argv])
580         };
581
582         let result = bx.call(start_fn, &args, None);
583         bx.ret(bx.intcast(result, cx.type_int(), true));
584     }
585 }
586
587 pub(crate) fn write_metadata<'a, 'gcx>(
588     tcx: TyCtxt<'a, 'gcx, 'gcx>,
589     llvm_module: &ModuleLlvm
590 ) -> EncodedMetadata {
591     use std::io::Write;
592     use flate2::Compression;
593     use flate2::write::DeflateEncoder;
594
595     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
596
597     #[derive(PartialEq, Eq, PartialOrd, Ord)]
598     enum MetadataKind {
599         None,
600         Uncompressed,
601         Compressed
602     }
603
604     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
605         match *ty {
606             config::CrateType::Executable |
607             config::CrateType::Staticlib |
608             config::CrateType::Cdylib => MetadataKind::None,
609
610             config::CrateType::Rlib => MetadataKind::Uncompressed,
611
612             config::CrateType::Dylib |
613             config::CrateType::ProcMacro => MetadataKind::Compressed,
614         }
615     }).max().unwrap_or(MetadataKind::None);
616
617     if kind == MetadataKind::None {
618         return EncodedMetadata::new();
619     }
620
621     let metadata = tcx.encode_metadata();
622     if kind == MetadataKind::Uncompressed {
623         return metadata;
624     }
625
626     assert!(kind == MetadataKind::Compressed);
627     let mut compressed = tcx.metadata_encoding_version();
628     DeflateEncoder::new(&mut compressed, Compression::fast())
629         .write_all(&metadata.raw_data).unwrap();
630
631     let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
632     let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
633     let name = exported_symbols::metadata_symbol_name(tcx);
634     let buf = CString::new(name).unwrap();
635     let llglobal = unsafe {
636         llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr())
637     };
638     unsafe {
639         llvm::LLVMSetInitializer(llglobal, llconst);
640         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
641         let name = SmallCStr::new(section_name);
642         llvm::LLVMSetSection(llglobal, name.as_ptr());
643
644         // Also generate a .section directive to force no
645         // flags, at least for ELF outputs, so that the
646         // metadata doesn't get loaded into memory.
647         let directive = format!(".section {}", section_name);
648         let directive = CString::new(directive).unwrap();
649         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
650     }
651     return metadata;
652 }
653
654 pub struct ValueIter<'ll> {
655     cur: Option<&'ll Value>,
656     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
657 }
658
659 impl Iterator for ValueIter<'ll> {
660     type Item = &'ll Value;
661
662     fn next(&mut self) -> Option<&'ll Value> {
663         let old = self.cur;
664         if let Some(old) = old {
665             self.cur = unsafe { (self.step)(old) };
666         }
667         old
668     }
669 }
670
671 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
672     unsafe {
673         ValueIter {
674             cur: llvm::LLVMGetFirstGlobal(llmod),
675             step: llvm::LLVMGetNextGlobal,
676         }
677     }
678 }
679
680 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
681                                  cgu: &CodegenUnit<'tcx>)
682                                  -> CguReuse {
683     if !tcx.dep_graph.is_fully_enabled() {
684         return CguReuse::No
685     }
686
687     let work_product_id = &cgu.work_product_id();
688     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
689         // We don't have anything cached for this CGU. This can happen
690         // if the CGU did not exist in the previous session.
691         return CguReuse::No
692     }
693
694     // Try to mark the CGU as green. If it we can do so, it means that nothing
695     // affecting the LLVM module has changed and we can re-use a cached version.
696     // If we compile with any kind of LTO, this means we can re-use the bitcode
697     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
698     // know that later). If we are not doing LTO, there is only one optimized
699     // version of each module, so we re-use that.
700     let dep_node = cgu.codegen_dep_node(tcx);
701     assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
702         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
703         cgu.name());
704
705     if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
706         // We can re-use either the pre- or the post-thinlto state
707         if tcx.sess.lto() != Lto::No {
708             CguReuse::PreLto
709         } else {
710             CguReuse::PostLto
711         }
712     } else {
713         CguReuse::No
714     }
715 }
716
717 pub fn codegen_crate<B: BackendMethods>(
718     backend: B,
719     tcx: TyCtxt<'a, 'tcx, 'tcx>,
720     rx: mpsc::Receiver<Box<dyn Any + Send>>
721 ) -> B::OngoingCodegen {
722
723     check_for_rustc_errors_attr(tcx);
724
725     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
726
727     // Codegen the metadata.
728     tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
729
730     let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
731                                                             &["crate"],
732                                                             Some("metadata")).as_str()
733                                                                              .to_string();
734     let metadata_llvm_module = backend.new_metadata(tcx.sess, &metadata_cgu_name);
735     let metadata = time(tcx.sess, "write metadata", || {
736         backend.write_metadata(tcx, &metadata_llvm_module)
737     });
738     tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
739
740     let metadata_module = ModuleCodegen {
741         name: metadata_cgu_name,
742         module_llvm: metadata_llvm_module,
743         kind: ModuleKind::Metadata,
744     };
745
746     let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
747         Some(time_graph::TimeGraph::new())
748     } else {
749         None
750     };
751
752     // Skip crate items and just output metadata in -Z no-codegen mode.
753     if tcx.sess.opts.debugging_opts.no_codegen ||
754        !tcx.sess.opts.output_types.should_codegen() {
755         let ongoing_codegen = backend.start_async_codegen(
756             tcx,
757             time_graph,
758             metadata,
759             rx,
760             1);
761
762         backend.submit_pre_codegened_module_to_llvm(&ongoing_codegen, tcx, metadata_module);
763         backend.codegen_finished(&ongoing_codegen, tcx);
764
765         assert_and_save_dep_graph(tcx);
766
767         backend.check_for_errors(&ongoing_codegen, tcx.sess);
768
769         return ongoing_codegen;
770     }
771
772     // Run the monomorphization collector and partition the collected items into
773     // codegen units.
774     let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
775     let codegen_units = (*codegen_units).clone();
776
777     // Force all codegen_unit queries so they are already either red or green
778     // when compile_codegen_unit accesses them. We are not able to re-execute
779     // the codegen_unit query from just the DepNode, so an unknown color would
780     // lead to having to re-execute compile_codegen_unit, possibly
781     // unnecessarily.
782     if tcx.dep_graph.is_fully_enabled() {
783         for cgu in &codegen_units {
784             tcx.codegen_unit(cgu.name().clone());
785         }
786     }
787
788     let ongoing_codegen = backend.start_async_codegen(
789         tcx,
790         time_graph.clone(),
791         metadata,
792         rx,
793         codegen_units.len());
794     let ongoing_codegen = AbortCodegenOnDrop::<B>(Some(ongoing_codegen));
795
796     // Codegen an allocator shim, if necessary.
797     //
798     // If the crate doesn't have an `allocator_kind` set then there's definitely
799     // no shim to generate. Otherwise we also check our dependency graph for all
800     // our output crate types. If anything there looks like its a `Dynamic`
801     // linkage, then it's already got an allocator shim and we'll be using that
802     // one instead. If nothing exists then it's our job to generate the
803     // allocator!
804     let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
805         .iter()
806         .any(|(_, list)| {
807             use rustc::middle::dependency_format::Linkage;
808             list.iter().any(|&linkage| linkage == Linkage::Dynamic)
809         });
810     let allocator_module = if any_dynamic_crate {
811         None
812     } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
813         let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
814                                                        &["crate"],
815                                                        Some("allocator")).as_str()
816                                                                          .to_string();
817         let modules = backend.new_metadata(tcx.sess, &llmod_id);
818         time(tcx.sess, "write allocator module", || {
819             backend.codegen_allocator(tcx, &modules, kind)
820         });
821
822         Some(ModuleCodegen {
823             name: llmod_id,
824             module_llvm: modules,
825             kind: ModuleKind::Allocator,
826         })
827     } else {
828         None
829     };
830
831     if let Some(allocator_module) = allocator_module {
832         backend.submit_pre_codegened_module_to_llvm(&ongoing_codegen, tcx, allocator_module);
833     }
834
835     backend.submit_pre_codegened_module_to_llvm(&ongoing_codegen, tcx, metadata_module);
836
837     // We sort the codegen units by size. This way we can schedule work for LLVM
838     // a bit more efficiently.
839     let codegen_units = {
840         let mut codegen_units = codegen_units;
841         codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
842         codegen_units
843     };
844
845     let mut total_codegen_time = Duration::new(0, 0);
846     let mut all_stats = Stats::default();
847
848     for cgu in codegen_units.into_iter() {
849         backend.wait_for_signal_to_codegen_item(&ongoing_codegen);
850         backend.check_for_errors(&ongoing_codegen, tcx.sess);
851
852         let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
853         tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
854
855         match cgu_reuse {
856             CguReuse::No => {
857                 let _timing_guard = time_graph.as_ref().map(|time_graph| {
858                     time_graph.start(write::CODEGEN_WORKER_TIMELINE,
859                                      write::CODEGEN_WORK_PACKAGE_KIND,
860                                      &format!("codegen {}", cgu.name()))
861                 });
862                 let start_time = Instant::now();
863                 let stats = backend.compile_codegen_unit(tcx, *cgu.name());
864                 all_stats.extend(stats);
865                 total_codegen_time += start_time.elapsed();
866                 false
867             }
868             CguReuse::PreLto => {
869                 write::submit_pre_lto_module_to_llvm(tcx, CachedModuleCodegen {
870                     name: cgu.name().to_string(),
871                     source: cgu.work_product(tcx),
872                 });
873                 true
874             }
875             CguReuse::PostLto => {
876                 write::submit_post_lto_module_to_llvm(tcx, CachedModuleCodegen {
877                     name: cgu.name().to_string(),
878                     source: cgu.work_product(tcx),
879                 });
880                 true
881             }
882         };
883     }
884
885     backend.codegen_finished(&ongoing_codegen, tcx);
886
887     // Since the main thread is sometimes blocked during codegen, we keep track
888     // -Ztime-passes output manually.
889     print_time_passes_entry(tcx.sess.time_passes(),
890                             "codegen to LLVM IR",
891                             total_codegen_time);
892
893     rustc_incremental::assert_module_sources::assert_module_sources(tcx);
894
895     symbol_names_test::report_symbol_names(tcx);
896
897     if tcx.sess.codegen_stats() {
898         println!("--- codegen stats ---");
899         println!("n_glues_created: {}", all_stats.n_glues_created);
900         println!("n_null_glues: {}", all_stats.n_null_glues);
901         println!("n_real_glues: {}", all_stats.n_real_glues);
902
903         println!("n_fns: {}", all_stats.n_fns);
904         println!("n_inlines: {}", all_stats.n_inlines);
905         println!("n_closures: {}", all_stats.n_closures);
906         println!("fn stats:");
907         all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
908         for &(ref name, insns) in all_stats.fn_stats.iter() {
909             println!("{} insns, {}", insns, *name);
910         }
911     }
912
913     if tcx.sess.count_llvm_insns() {
914         for (k, v) in all_stats.llvm_insns.iter() {
915             println!("{:7} {}", *v, *k);
916         }
917     }
918
919     backend.check_for_errors(&ongoing_codegen, tcx.sess);
920
921     assert_and_save_dep_graph(tcx);
922     ongoing_codegen.into_inner()
923 }
924
925 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
926 /// when it's dropped abnormally.
927 ///
928 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
929 /// stumbled upon. The segfault was never reproduced locally, but it was
930 /// suspected to be related to the fact that codegen worker threads were
931 /// sticking around by the time the main thread was exiting, causing issues.
932 ///
933 /// This structure is an attempt to fix that issue where the `codegen_aborted`
934 /// message will block until all workers have finished. This should ensure that
935 /// even if the main codegen thread panics we'll wait for pending work to
936 /// complete before returning from the main thread, hopefully avoiding
937 /// segfaults.
938 ///
939 /// If you see this comment in the code, then it means that this workaround
940 /// worked! We may yet one day track down the mysterious cause of that
941 /// segfault...
942 struct AbortCodegenOnDrop<B: BackendMethods>(Option<B::OngoingCodegen>);
943
944 impl<B: BackendMethods> AbortCodegenOnDrop<B> {
945     fn into_inner(mut self) -> B::OngoingCodegen {
946         self.0.take().unwrap()
947     }
948 }
949
950 impl<B: BackendMethods> Deref for AbortCodegenOnDrop<B> {
951     type Target = B::OngoingCodegen;
952
953     fn deref(&self) -> &B::OngoingCodegen {
954         self.0.as_ref().unwrap()
955     }
956 }
957
958 impl<B: BackendMethods> DerefMut for AbortCodegenOnDrop<B> {
959     fn deref_mut(&mut self) -> &mut B::OngoingCodegen {
960         self.0.as_mut().unwrap()
961     }
962 }
963
964 impl<B: BackendMethods> Drop for AbortCodegenOnDrop<B> {
965     fn drop(&mut self) {
966         if let Some(codegen) = self.0.take() {
967             B::codegen_aborted(codegen);
968         }
969     }
970 }
971
972 fn assert_and_save_dep_graph<'ll, 'tcx>(tcx: TyCtxt<'ll, 'tcx, 'tcx>) {
973     time(tcx.sess,
974          "assert dep graph",
975          || rustc_incremental::assert_dep_graph(tcx));
976
977     time(tcx.sess,
978          "serialize dep graph",
979          || rustc_incremental::save_dep_graph(tcx));
980 }
981
982 impl CrateInfo {
983     pub fn new(tcx: TyCtxt) -> CrateInfo {
984         let mut info = CrateInfo {
985             panic_runtime: None,
986             compiler_builtins: None,
987             profiler_runtime: None,
988             sanitizer_runtime: None,
989             is_no_builtins: Default::default(),
990             native_libraries: Default::default(),
991             used_libraries: tcx.native_libraries(LOCAL_CRATE),
992             link_args: tcx.link_args(LOCAL_CRATE),
993             crate_name: Default::default(),
994             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
995             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
996             used_crate_source: Default::default(),
997             wasm_imports: Default::default(),
998             lang_item_to_crate: Default::default(),
999             missing_lang_items: Default::default(),
1000         };
1001         let lang_items = tcx.lang_items();
1002
1003         let load_wasm_items = tcx.sess.crate_types.borrow()
1004             .iter()
1005             .any(|c| *c != config::CrateType::Rlib) &&
1006             tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
1007
1008         if load_wasm_items {
1009             info.load_wasm_imports(tcx, LOCAL_CRATE);
1010         }
1011
1012         let crates = tcx.crates();
1013
1014         let n_crates = crates.len();
1015         info.native_libraries.reserve(n_crates);
1016         info.crate_name.reserve(n_crates);
1017         info.used_crate_source.reserve(n_crates);
1018         info.missing_lang_items.reserve(n_crates);
1019
1020         for &cnum in crates.iter() {
1021             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1022             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1023             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1024             if tcx.is_panic_runtime(cnum) {
1025                 info.panic_runtime = Some(cnum);
1026             }
1027             if tcx.is_compiler_builtins(cnum) {
1028                 info.compiler_builtins = Some(cnum);
1029             }
1030             if tcx.is_profiler_runtime(cnum) {
1031                 info.profiler_runtime = Some(cnum);
1032             }
1033             if tcx.is_sanitizer_runtime(cnum) {
1034                 info.sanitizer_runtime = Some(cnum);
1035             }
1036             if tcx.is_no_builtins(cnum) {
1037                 info.is_no_builtins.insert(cnum);
1038             }
1039             if load_wasm_items {
1040                 info.load_wasm_imports(tcx, cnum);
1041             }
1042             let missing = tcx.missing_lang_items(cnum);
1043             for &item in missing.iter() {
1044                 if let Ok(id) = lang_items.require(item) {
1045                     info.lang_item_to_crate.insert(item, id.krate);
1046                 }
1047             }
1048
1049             // No need to look for lang items that are whitelisted and don't
1050             // actually need to exist.
1051             let missing = missing.iter()
1052                 .cloned()
1053                 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1054                 .collect();
1055             info.missing_lang_items.insert(cnum, missing);
1056         }
1057
1058         return info
1059     }
1060
1061     fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1062         self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
1063             let instance = Instance::mono(tcx, id);
1064             let import_name = tcx.symbol_name(instance);
1065
1066             (import_name.to_string(), module.clone())
1067         }));
1068     }
1069 }
1070
1071 pub fn compile_codegen_unit<'ll, 'tcx>(tcx: TyCtxt<'ll, 'tcx, 'tcx>,
1072                                   cgu_name: InternedString)
1073                                   -> Stats {
1074     let start_time = Instant::now();
1075
1076     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
1077     let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
1078                                                        tcx,
1079                                                        cgu_name,
1080                                                        module_codegen);
1081     let time_to_codegen = start_time.elapsed();
1082
1083     // We assume that the cost to run LLVM on a CGU is proportional to
1084     // the time we needed for codegenning it.
1085     let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1086                time_to_codegen.subsec_nanos() as u64;
1087
1088     write::submit_codegened_module_to_llvm(tcx,
1089                                            module,
1090                                            cost);
1091     return stats;
1092
1093     fn module_codegen<'ll, 'tcx>(
1094         tcx: TyCtxt<'ll, 'tcx, 'tcx>,
1095         cgu_name: InternedString)
1096         -> (Stats, ModuleCodegen<ModuleLlvm>)
1097     {
1098         let backend = LlvmCodegenBackend(());
1099         let cgu = tcx.codegen_unit(cgu_name);
1100         // Instantiate monomorphizations without filling out definitions yet...
1101         let llvm_module = backend.new_metadata(tcx.sess, &cgu_name.as_str());
1102         let stats = {
1103             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1104             let mono_items = cx.codegen_unit
1105                                .items_in_deterministic_order(cx.tcx);
1106             for &(mono_item, (linkage, visibility)) in &mono_items {
1107                 mono_item.predefine::<Builder<&Value>>(&cx, linkage, visibility);
1108             }
1109
1110             // ... and now that we have everything pre-defined, fill out those definitions.
1111             for &(mono_item, _) in &mono_items {
1112                 mono_item.define::<Builder<&Value>>(&cx);
1113             }
1114
1115             // If this codegen unit contains the main function, also create the
1116             // wrapper here
1117             maybe_create_entry_wrapper::<Builder<&Value>>(&cx);
1118
1119             // Run replace-all-uses-with for statics that need it
1120             for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
1121                 cx.static_replace_all_uses(old_g, new_g)
1122             }
1123
1124             // Create the llvm.used variable
1125             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1126             if !cx.used_statics().borrow().is_empty() {
1127                 cx.create_used_variable()
1128             }
1129
1130             // Finalize debuginfo
1131             if cx.sess().opts.debuginfo != DebugInfo::None {
1132                 cx.debuginfo_finalize();
1133             }
1134
1135             cx.consume_stats().into_inner()
1136         };
1137
1138         (stats, ModuleCodegen {
1139             name: cgu_name.to_string(),
1140             module_llvm: llvm_module,
1141             kind: ModuleKind::Regular,
1142         })
1143     }
1144 }
1145
1146 pub fn provide_both(providers: &mut Providers) {
1147     providers.dllimport_foreign_items = |tcx, krate| {
1148         let module_map = tcx.foreign_modules(krate);
1149         let module_map = module_map.iter()
1150             .map(|lib| (lib.def_id, lib))
1151             .collect::<FxHashMap<_, _>>();
1152
1153         let dllimports = tcx.native_libraries(krate)
1154             .iter()
1155             .filter(|lib| {
1156                 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1157                     return false
1158                 }
1159                 let cfg = match lib.cfg {
1160                     Some(ref cfg) => cfg,
1161                     None => return true,
1162                 };
1163                 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1164             })
1165             .filter_map(|lib| lib.foreign_module)
1166             .map(|id| &module_map[&id])
1167             .flat_map(|module| module.foreign_items.iter().cloned())
1168             .collect();
1169         Lrc::new(dllimports)
1170     };
1171
1172     providers.is_dllimport_foreign_item = |tcx, def_id| {
1173         tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1174     };
1175 }
1176
1177 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1178     match linkage {
1179         Linkage::External => llvm::Linkage::ExternalLinkage,
1180         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1181         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1182         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1183         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1184         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1185         Linkage::Appending => llvm::Linkage::AppendingLinkage,
1186         Linkage::Internal => llvm::Linkage::InternalLinkage,
1187         Linkage::Private => llvm::Linkage::PrivateLinkage,
1188         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1189         Linkage::Common => llvm::Linkage::CommonLinkage,
1190     }
1191 }
1192
1193 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1194     match linkage {
1195         Visibility::Default => llvm::Visibility::Default,
1196         Visibility::Hidden => llvm::Visibility::Hidden,
1197         Visibility::Protected => llvm::Visibility::Protected,
1198     }
1199 }
1200
1201 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1202 //            the HashStable trait. Normally DepGraph::with_task() calls are
1203 //            hidden behind queries, but CGU creation is a special case in two
1204 //            ways: (1) it's not a query and (2) CGU are output nodes, so their
1205 //            Fingerprints are not actually needed. It remains to be clarified
1206 //            how exactly this case will be handled in the red/green system but
1207 //            for now we content ourselves with providing a no-op HashStable
1208 //            implementation for CGUs.
1209 mod temp_stable_hash_impls {
1210     use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1211                                                HashStable};
1212     use {ModuleCodegen, ModuleLlvm};
1213
1214     impl<HCX> HashStable<HCX> for ModuleCodegen<ModuleLlvm> {
1215         fn hash_stable<W: StableHasherResult>(&self,
1216                                               _: &mut HCX,
1217                                               _: &mut StableHasher<W>) {
1218             // do nothing
1219         }
1220     }
1221 }