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