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