]> git.proxmox.com Git - rustc.git/blame - src/librustc_trans/base.rs
New upstream version 1.21.0+dfsg1
[rustc.git] / src / librustc_trans / base.rs
CommitLineData
9346a6ac 1// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
1a4d82fc
JJ
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.
54a0048b 10
9346a6ac
AL
11//! Translate the completed AST to the LLVM IR.
12//!
13//! Some functions here, such as trans_block and trans_expr, return a value --
54a0048b
SL
14//! the result of the translation to LLVM -- while others, such as trans_fn
15//! and trans_item, are called only for the side effect of adding a
9346a6ac
AL
16//! particular definition to the LLVM IR output we're producing.
17//!
18//! Hopefully useful general knowledge about trans:
19//!
20//! * There's no way to find out the Ty type of a ValueRef. Doing so
21//! would be "trying to get the eggs out of an omelette" (credit:
22//! pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23//! but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24//! int) and rec(x=int, y=int, z=int) will have the same TypeRef.
1a4d82fc 25
5bcae85e
SL
26use super::ModuleLlvm;
27use super::ModuleSource;
1a4d82fc 28use super::ModuleTranslation;
3b2f2976 29use super::ModuleKind;
1a4d82fc 30
5bcae85e 31use assert_module_sources;
3157f602
XL
32use back::link;
33use back::linker::LinkerInfo;
476ff2be 34use back::symbol_export::{self, ExportedSymbols};
3b2f2976 35use back::write::{self, OngoingCrateTranslation};
cc61c64b 36use llvm::{ContextRef, Linkage, ModuleRef, ValueRef, Vector, get_param};
1a4d82fc 37use llvm;
7cac9316 38use metadata;
cc61c64b 39use rustc::hir::def_id::LOCAL_CRATE;
7cac9316 40use rustc::middle::lang_items::StartFnLangItem;
3b2f2976 41use rustc::middle::cstore::{EncodedMetadata, EncodedMetadataHashes};
32a655c1 42use rustc::ty::{self, Ty, TyCtxt};
cc61c64b
XL
43use rustc::dep_graph::AssertDepGraphSafe;
44use rustc::middle::cstore::LinkMeta;
54a0048b 45use rustc::hir::map as hir_map;
3b2f2976
XL
46use rustc::util::common::{time, print_time_passes_entry};
47use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
7cac9316 48use rustc::session::Session;
3b2f2976 49use rustc_incremental::{self, IncrementalHashesMap};
cc61c64b 50use abi;
041b39d2 51use allocator;
32a655c1 52use mir::lvalue::LvalueRef;
54a0048b 53use attributes;
32a655c1 54use builder::Builder;
cc61c64b 55use callee;
32a655c1 56use common::{C_bool, C_bytes_in_context, C_i32, C_uint};
5bcae85e 57use collector::{self, TransItemCollectionMode};
cc61c64b 58use common::{C_struct_in_context, C_u64, C_undef, C_array};
32a655c1 59use common::CrateContext;
9e0c209e 60use common::{type_is_zero_size, val_ty};
54a0048b
SL
61use common;
62use consts;
cc61c64b 63use context::{self, LocalCrateContext, SharedCrateContext, Stats};
32a655c1 64use debuginfo;
54a0048b 65use declare;
54a0048b 66use machine;
54a0048b
SL
67use meth;
68use mir;
69use monomorphize::{self, Instance};
a7813a04 70use partitioning::{self, PartitioningStrategy, CodegenUnit};
54a0048b 71use symbol_names_test;
3b2f2976 72use time_graph;
476ff2be 73use trans_item::{TransItem, DefPathBasedNames};
54a0048b
SL
74use type_::Type;
75use type_of;
54a0048b 76use value::Value;
7cac9316 77use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet};
1a4d82fc 78
9346a6ac 79use libc::c_uint;
85aaf69f 80use std::ffi::{CStr, CString};
1a4d82fc 81use std::str;
3b2f2976
XL
82use std::sync::Arc;
83use std::time::{Instant, Duration};
9e0c209e 84use std::i32;
cc61c64b 85use syntax_pos::Span;
b039eaaf 86use syntax::attr;
54a0048b 87use rustc::hir;
e9174d1e 88use syntax::ast;
1a4d82fc 89
32a655c1 90use mir::lvalue::Alignment;
1a4d82fc
JJ
91
92pub struct StatRecorder<'a, 'tcx: 'a> {
93 ccx: &'a CrateContext<'a, 'tcx>,
94 name: Option<String>,
c34b1796 95 istart: usize,
1a4d82fc
JJ
96}
97
98impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
92a42be0 99 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
1a4d82fc
JJ
100 let istart = ccx.stats().n_llvm_insns.get();
101 StatRecorder {
3b2f2976 102 ccx,
1a4d82fc 103 name: Some(name),
3b2f2976 104 istart,
1a4d82fc
JJ
105 }
106 }
107}
108
1a4d82fc
JJ
109impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
110 fn drop(&mut self) {
111 if self.ccx.sess().trans_stats() {
112 let iend = self.ccx.stats().n_llvm_insns.get();
32a655c1 113 self.ccx.stats().fn_stats.borrow_mut()
92a42be0 114 .push((self.name.take().unwrap(), iend - self.istart));
1a4d82fc
JJ
115 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
116 // Reset LLVM insn count to avoid compound costs.
117 self.ccx.stats().n_llvm_insns.set(self.istart);
118 }
119 }
120}
121
32a655c1
SL
122pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
123 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
9e0c209e
SL
124}
125
32a655c1
SL
126pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
127 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
1a4d82fc
JJ
128}
129
54a0048b 130pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
92a42be0 131 signed: bool)
85aaf69f
SL
132 -> llvm::IntPredicate {
133 match op {
e9174d1e
SL
134 hir::BiEq => llvm::IntEQ,
135 hir::BiNe => llvm::IntNE,
136 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
137 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
138 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
139 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
85aaf69f 140 op => {
54a0048b
SL
141 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
142 found {:?}",
143 op)
85aaf69f 144 }
1a4d82fc
JJ
145 }
146}
147
54a0048b 148pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
85aaf69f 149 match op {
e9174d1e
SL
150 hir::BiEq => llvm::RealOEQ,
151 hir::BiNe => llvm::RealUNE,
152 hir::BiLt => llvm::RealOLT,
153 hir::BiLe => llvm::RealOLE,
154 hir::BiGt => llvm::RealOGT,
155 hir::BiGe => llvm::RealOGE,
85aaf69f 156 op => {
54a0048b
SL
157 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
158 found {:?}",
159 op);
92a42be0
SL
160 }
161 }
162}
163
32a655c1
SL
164pub fn compare_simd_types<'a, 'tcx>(
165 bcx: &Builder<'a, 'tcx>,
166 lhs: ValueRef,
167 rhs: ValueRef,
168 t: Ty<'tcx>,
169 ret_ty: Type,
170 op: hir::BinOp_
171) -> ValueRef {
85aaf69f 172 let signed = match t.sty {
62682a34 173 ty::TyFloat(_) => {
54a0048b 174 let cmp = bin_op_to_fcmp_predicate(op);
32a655c1 175 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
1a4d82fc 176 },
62682a34
SL
177 ty::TyUint(_) => false,
178 ty::TyInt(_) => true,
54a0048b 179 _ => bug!("compare_simd_types: invalid SIMD type"),
85aaf69f
SL
180 };
181
54a0048b 182 let cmp = bin_op_to_icmp_predicate(op, signed);
85aaf69f
SL
183 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
184 // to get the correctly sized type. This will compile to a single instruction
185 // once the IR is converted to assembly if the SIMD instruction is supported
186 // by the target architecture.
32a655c1 187 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
1a4d82fc
JJ
188}
189
92a42be0
SL
190/// Retrieve the information we are losing (making dynamic) in an unsizing
191/// adjustment.
192///
193/// The `old_info` argument is a bit funny. It is intended for use
3b2f2976 194/// in an upcast, where the new vtable for an object will be derived
92a42be0
SL
195/// from the old one.
196pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
197 source: Ty<'tcx>,
198 target: Ty<'tcx>,
54a0048b 199 old_info: Option<ValueRef>)
92a42be0
SL
200 -> ValueRef {
201 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
202 match (&source.sty, &target.sty) {
203 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
476ff2be 204 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
92a42be0
SL
205 // For now, upcasts are limited to changes in marker
206 // traits, and hence never actually require an actual
207 // change to the vtable.
208 old_info.expect("unsized_info: missing old info for trait upcast")
209 }
476ff2be
SL
210 (_, &ty::TyDynamic(ref data, ..)) => {
211 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
92a42be0
SL
212 Type::vtable_ptr(ccx))
213 }
54a0048b 214 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
92a42be0 215 source,
54a0048b 216 target),
92a42be0
SL
217 }
218}
219
220/// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
32a655c1
SL
221pub fn unsize_thin_ptr<'a, 'tcx>(
222 bcx: &Builder<'a, 'tcx>,
223 src: ValueRef,
224 src_ty: Ty<'tcx>,
225 dst_ty: Ty<'tcx>
226) -> (ValueRef, ValueRef) {
92a42be0
SL
227 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
228 match (&src_ty.sty, &dst_ty.sty) {
92a42be0
SL
229 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
231 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
232 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
233 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
234 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
32a655c1
SL
235 assert!(bcx.ccx.shared().type_is_sized(a));
236 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
237 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
238 }
239 (&ty::TyAdt(def_a, _), &ty::TyAdt(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!(bcx.ccx.shared().type_is_sized(a));
242 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
243 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
92a42be0 244 }
54a0048b 245 _ => bug!("unsize_thin_ptr: called on bad types"),
92a42be0
SL
246 }
247}
248
249/// Coerce `src`, which is a reference to a value of type `src_ty`,
250/// to a value of type `dst_ty` and store the result in `dst`
32a655c1
SL
251pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
252 src: &LvalueRef<'tcx>,
253 dst: &LvalueRef<'tcx>) {
254 let src_ty = src.ty.to_ty(bcx.tcx());
255 let dst_ty = dst.ty.to_ty(bcx.tcx());
256 let coerce_ptr = || {
257 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
258 // fat-ptr to fat-ptr unsize preserves the vtable
259 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
260 // So we need to pointercast the base to ensure
261 // the types match up.
262 let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
263 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
264 let base = bcx.pointercast(base, llcast_ty);
265 (base, info)
266 } else {
267 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
268 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
269 };
270 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
271 };
92a42be0 272 match (&src_ty.sty, &dst_ty.sty) {
92a42be0
SL
273 (&ty::TyRef(..), &ty::TyRef(..)) |
274 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
275 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
32a655c1
SL
276 coerce_ptr()
277 }
278 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
279 coerce_ptr()
92a42be0
SL
280 }
281
9e0c209e 282 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
92a42be0
SL
283 assert_eq!(def_a, def_b);
284
9e0c209e
SL
285 let src_fields = def_a.variants[0].fields.iter().map(|f| {
286 monomorphize::field_ty(bcx.tcx(), substs_a, f)
287 });
288 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
289 monomorphize::field_ty(bcx.tcx(), substs_b, f)
290 });
92a42be0 291
9e0c209e 292 let iter = src_fields.zip(dst_fields).enumerate();
92a42be0 293 for (i, (src_fty, dst_fty)) in iter {
32a655c1 294 if type_is_zero_size(bcx.ccx, dst_fty) {
92a42be0
SL
295 continue;
296 }
297
32a655c1
SL
298 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
299 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
92a42be0 300 if src_fty == dst_fty {
32a655c1 301 memcpy_ty(bcx, dst_f, src_f, src_fty, None);
92a42be0 302 } else {
32a655c1
SL
303 coerce_unsized_into(
304 bcx,
305 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
306 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
307 );
92a42be0
SL
308 }
309 }
310 }
54a0048b
SL
311 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
312 src_ty,
313 dst_ty),
92a42be0 314 }
1a4d82fc
JJ
315}
316
32a655c1
SL
317pub fn cast_shift_expr_rhs(
318 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
319) -> ValueRef {
320 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
92a42be0
SL
321}
322
323pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
324 cast_shift_rhs(op,
325 lhs,
326 rhs,
1a4d82fc
JJ
327 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
328 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
329}
330
e9174d1e 331fn cast_shift_rhs<F, G>(op: hir::BinOp_,
c34b1796
AL
332 lhs: ValueRef,
333 rhs: ValueRef,
334 trunc: F,
335 zext: G)
92a42be0
SL
336 -> ValueRef
337 where F: FnOnce(ValueRef, Type) -> ValueRef,
338 G: FnOnce(ValueRef, Type) -> ValueRef
1a4d82fc
JJ
339{
340 // Shifts may have any size int on the rhs
54a0048b 341 if op.is_shift() {
85aaf69f
SL
342 let mut rhs_llty = val_ty(rhs);
343 let mut lhs_llty = val_ty(lhs);
92a42be0
SL
344 if rhs_llty.kind() == Vector {
345 rhs_llty = rhs_llty.element_type()
346 }
347 if lhs_llty.kind() == Vector {
348 lhs_llty = lhs_llty.element_type()
349 }
85aaf69f
SL
350 let rhs_sz = rhs_llty.int_width();
351 let lhs_sz = lhs_llty.int_width();
352 if lhs_sz < rhs_sz {
353 trunc(rhs, lhs_llty)
354 } else if lhs_sz > rhs_sz {
355 // FIXME (#1877: If shifting by negative
356 // values becomes not undefined then this is wrong.
357 zext(rhs, lhs_llty)
1a4d82fc
JJ
358 } else {
359 rhs
360 }
85aaf69f
SL
361 } else {
362 rhs
1a4d82fc
JJ
363 }
364}
365
e9174d1e
SL
366/// Returns whether this session's target will use SEH-based unwinding.
367///
368/// This is only true for MSVC targets, and even then the 64-bit MSVC target
369/// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
370/// 64-bit MinGW) instead of "full SEH".
371pub fn wants_msvc_seh(sess: &Session) -> bool {
7453a54e 372 sess.target.target.options.is_like_msvc
e9174d1e
SL
373}
374
c30ab7b3
SL
375pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
376 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
377 b.call(assume_intrinsic, &[val], None);
378}
379
1a4d82fc
JJ
380/// Helper for loading values from memory. Does the necessary conversion if the in-memory type
381/// differs from the type used for SSA values. Also handles various special cases where the type
382/// gives us better information about what we are loading.
32a655c1
SL
383pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
384 alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
54a0048b
SL
385 let ccx = b.ccx;
386 if type_is_zero_size(ccx, t) {
387 return C_undef(type_of::type_of(ccx, t));
c34b1796
AL
388 }
389
390 unsafe {
391 let global = llvm::LLVMIsAGlobalVariable(ptr);
392 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
393 let val = llvm::LLVMGetInitializer(global);
394 if !val.is_null() {
54a0048b
SL
395 if t.is_bool() {
396 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
397 }
398 return val;
85aaf69f
SL
399 }
400 }
1a4d82fc 401 }
c34b1796 402
54a0048b 403 if t.is_bool() {
32a655c1
SL
404 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
405 Type::i1(ccx))
c1a9b12d 406 } else if t.is_char() {
c34b1796
AL
407 // a char is a Unicode codepoint, and so takes values from 0
408 // to 0x10FFFF inclusive only.
32a655c1 409 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
cc61c64b
XL
410 } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
411 && !common::type_is_fat_ptr(ccx, t)
412 {
32a655c1 413 b.load_nonnull(ptr, alignment.to_align())
c34b1796 414 } else {
32a655c1 415 b.load(ptr, alignment.to_align())
d9579d0f 416 }
1a4d82fc
JJ
417}
418
419/// Helper for storing values in memory. Does the necessary conversion if the in-memory type
420/// differs from the type used for SSA values.
32a655c1
SL
421pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
422 dst_align: Alignment, t: Ty<'tcx>) {
54a0048b 423 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
92a42be0 424
32a655c1
SL
425 if common::type_is_fat_ptr(cx.ccx, t) {
426 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
427 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
428 store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
c1a9b12d 429 } else {
32a655c1 430 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
d9579d0f 431 }
c34b1796
AL
432}
433
32a655c1
SL
434pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
435 data: ValueRef,
436 extra: ValueRef,
437 dst: ValueRef,
438 dst_align: Alignment,
439 _ty: Ty<'tcx>) {
92a42be0 440 // FIXME: emit metadata
32a655c1
SL
441 cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
442 cx.store(extra, get_meta(cx, dst), dst_align.to_align());
c30ab7b3
SL
443}
444
32a655c1
SL
445pub fn load_fat_ptr<'a, 'tcx>(
446 b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
447) -> (ValueRef, ValueRef) {
448 let ptr = get_dataptr(b, src);
449 let ptr = if t.is_region_ptr() || t.is_box() {
450 b.load_nonnull(ptr, alignment.to_align())
c30ab7b3 451 } else {
32a655c1 452 b.load(ptr, alignment.to_align())
c30ab7b3
SL
453 };
454
8bb4bdeb
XL
455 let meta = get_meta(b, src);
456 let meta_ty = val_ty(meta);
457 // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
458 // instead
459 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
460 b.load_nonnull(meta, None)
461 } else {
462 b.load(meta, None)
463 };
c30ab7b3
SL
464
465 (ptr, meta)
92a42be0
SL
466}
467
32a655c1
SL
468pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
469 if val_ty(val) == Type::i1(bcx.ccx) {
470 bcx.zext(val, Type::i8(bcx.ccx))
c34b1796
AL
471 } else {
472 val
473 }
474}
475
32a655c1 476pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
c1a9b12d 477 if ty.is_bool() {
32a655c1 478 bcx.trunc(val, Type::i1(bcx.ccx))
c34b1796
AL
479 } else {
480 val
481 }
482}
483
a7813a04 484pub enum Lifetime { Start, End }
9cc50fc6 485
a7813a04 486impl Lifetime {
32a655c1
SL
487 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
488 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
489 // and the intrinsic for `lt` and passes them to `emit`, which is in
490 // charge of generating code to call the passed intrinsic on whatever
3b2f2976 491 // block of generated code is targeted for the intrinsic.
32a655c1
SL
492 //
493 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
494 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
a7813a04 495 pub fn call(self, b: &Builder, ptr: ValueRef) {
32a655c1
SL
496 if b.ccx.sess().opts.optimize == config::OptLevel::No {
497 return;
498 }
e9174d1e 499
32a655c1
SL
500 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
501 if size == 0 {
502 return;
503 }
a7813a04 504
32a655c1
SL
505 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
506 Lifetime::Start => "llvm.lifetime.start",
507 Lifetime::End => "llvm.lifetime.end"
508 });
1a4d82fc 509
32a655c1
SL
510 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
511 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
92a42be0
SL
512 }
513}
514
32a655c1 515pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
54a0048b
SL
516 dst: ValueRef,
517 src: ValueRef,
518 n_bytes: ValueRef,
519 align: u32) {
54a0048b 520 let ccx = b.ccx;
cc61c64b 521 let ptr_width = &ccx.sess().target.target.target_pointer_width;
e9174d1e 522 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
1a4d82fc 523 let memcpy = ccx.get_intrinsic(&key);
54a0048b
SL
524 let src_ptr = b.pointercast(src, Type::i8p(ccx));
525 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
8bb4bdeb 526 let size = b.intcast(n_bytes, ccx.int_type(), false);
1a4d82fc
JJ
527 let align = C_i32(ccx, align as i32);
528 let volatile = C_bool(ccx, false);
54a0048b 529 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
1a4d82fc
JJ
530}
531
32a655c1
SL
532pub fn memcpy_ty<'a, 'tcx>(
533 bcx: &Builder<'a, 'tcx>,
534 dst: ValueRef,
535 src: ValueRef,
536 t: Ty<'tcx>,
537 align: Option<u32>,
538) {
539 let ccx = bcx.ccx;
1a4d82fc 540
cc61c64b
XL
541 let size = ccx.size_of(t);
542 if size == 0 {
92a42be0
SL
543 return;
544 }
1a4d82fc 545
cc61c64b
XL
546 let align = align.unwrap_or_else(|| ccx.align_of(t));
547 call_memcpy(bcx, dst, src, C_uint(ccx, size), align);
54a0048b
SL
548}
549
32a655c1 550pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
cc61c64b
XL
551 ptr: ValueRef,
552 fill_byte: ValueRef,
553 size: ValueRef,
554 align: ValueRef,
555 volatile: bool) -> ValueRef {
556 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
54a0048b 557 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
32a655c1
SL
558 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
559 let volatile = C_bool(b.ccx, volatile);
560 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
1a4d82fc
JJ
561}
562
476ff2be
SL
563pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
564 let _s = if ccx.sess().trans_stats() {
565 let mut instance_name = String::new();
566 DefPathBasedNames::new(ccx.tcx(), true, true)
cc61c64b 567 .push_def_path(instance.def_id(), &mut instance_name);
476ff2be
SL
568 Some(StatRecorder::new(ccx, instance_name))
569 } else {
570 None
571 };
1a4d82fc 572
3157f602
XL
573 // this is an info! to allow collecting monomorphization statistics
574 // and to allow finding the last function before LLVM aborts from
575 // release builds.
476ff2be 576 info!("trans_instance({})", instance);
a7813a04 577
cc61c64b 578 let fn_ty = common::instance_ty(ccx.shared(), &instance);
8bb4bdeb
XL
579 let sig = common::ty_fn_sig(ccx, fn_ty);
580 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
476ff2be
SL
581
582 let lldecl = match ccx.instances().borrow().get(&instance) {
583 Some(&val) => val,
584 None => bug!("Instance `{:?}` not already declared", instance)
585 };
586
587 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
588
cc61c64b
XL
589 // The `uwtable` attribute according to LLVM is:
590 //
591 // This attribute indicates that the ABI being targeted requires that an
592 // unwind table entry be produced for this function even if we can show
593 // that no exceptions passes by it. This is normally the case for the
594 // ELF x86-64 abi, but it can be disabled for some compilation units.
595 //
596 // Typically when we're compiling with `-C panic=abort` (which implies this
597 // `no_landing_pads` check) we don't need `uwtable` because we can't
598 // generate any exceptions! On Windows, however, exceptions include other
599 // events such as illegal instructions, segfaults, etc. This means that on
600 // Windows we end up still needing the `uwtable` attribute even if the `-C
601 // panic=abort` flag is passed.
602 //
603 // You can also find more info on why Windows is whitelisted here in:
604 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
605 if !ccx.sess().no_landing_pads() ||
606 ccx.sess().target.target.options.is_like_windows {
476ff2be
SL
607 attributes::emit_uwtable(lldecl, true);
608 }
609
cc61c64b 610 let mir = ccx.tcx().instance_mir(instance.def);
8bb4bdeb 611 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
1a4d82fc
JJ
612}
613
1a4d82fc
JJ
614pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
615 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
616 // applicable to variable declarations and may not really make sense for
617 // Rust code in the first place but whitelist them anyway and trust that
618 // the user knows what s/he's doing. Who knows, unanticipated use cases
619 // may pop up in the future.
620 //
621 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
622 // and don't have to be, LLVM treats them as no-ops.
623 match name {
9e0c209e
SL
624 "appending" => Some(llvm::Linkage::AppendingLinkage),
625 "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
626 "common" => Some(llvm::Linkage::CommonLinkage),
627 "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
628 "external" => Some(llvm::Linkage::ExternalLinkage),
629 "internal" => Some(llvm::Linkage::InternalLinkage),
630 "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
631 "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
632 "private" => Some(llvm::Linkage::PrivateLinkage),
633 "weak" => Some(llvm::Linkage::WeakAnyLinkage),
634 "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
1a4d82fc
JJ
635 _ => None,
636 }
637}
638
5bcae85e
SL
639pub fn set_link_section(ccx: &CrateContext,
640 llval: ValueRef,
641 attrs: &[ast::Attribute]) {
642 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
476ff2be 643 if contains_null(&sect.as_str()) {
3157f602
XL
644 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
645 }
646 unsafe {
476ff2be 647 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
3157f602
XL
648 llvm::LLVMSetSection(llval, buf.as_ptr());
649 }
c1a9b12d
SL
650 }
651}
652
3b2f2976
XL
653// check for the #[rustc_error] annotation, which forces an
654// error in trans. This is used to write compile-fail tests
655// that actually test that compilation succeeds without
656// reporting an error.
657fn check_for_rustc_errors_attr(tcx: TyCtxt) {
658 if let Some((id, span)) = *tcx.sess.entry_fn.borrow() {
659 let main_def_id = tcx.hir.local_def_id(id);
660
661 if tcx.has_attr(main_def_id, "rustc_error") {
662 tcx.sess.span_fatal(span, "compilation successful");
663 }
664 }
665}
666
667/// Create the `main` function which will initialize the rust runtime and call
cc61c64b 668/// users main function.
3b2f2976 669fn maybe_create_entry_wrapper(ccx: &CrateContext) {
5bcae85e
SL
670 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
671 Some((id, span)) => {
32a655c1 672 (ccx.tcx().hir.local_def_id(id), span)
1a4d82fc 673 }
5bcae85e
SL
674 None => return,
675 };
54a0048b 676
cc61c64b 677 let instance = Instance::mono(ccx.tcx(), main_def_id);
5bcae85e
SL
678
679 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
680 // We want to create the wrapper in the same codegen unit as Rust's main
681 // function.
682 return;
1a4d82fc 683 }
1a4d82fc 684
cc61c64b 685 let main_llfn = callee::get_fn(ccx, instance);
5bcae85e 686
1a4d82fc
JJ
687 let et = ccx.sess().entry_type.get().unwrap();
688 match et {
32a655c1 689 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
5bcae85e 690 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
1a4d82fc
JJ
691 config::EntryNone => {} // Do nothing.
692 }
693
694 fn create_entry_fn(ccx: &CrateContext,
9346a6ac 695 sp: Span,
1a4d82fc
JJ
696 rust_main: ValueRef,
697 use_start_lang_item: bool) {
92a42be0 698 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
1a4d82fc 699
54a0048b 700 if declare::get_defined_value(ccx, "main").is_some() {
9346a6ac 701 // FIXME: We should be smart and show a better diagnostic here.
9cc50fc6
SL
702 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
703 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
704 .emit();
9346a6ac 705 ccx.sess().abort_if_errors();
54a0048b
SL
706 bug!();
707 }
708 let llfn = declare::declare_cfn(ccx, "main", llfty);
1a4d82fc 709
c30ab7b3
SL
710 // `main` should respect same config for frame pointer elimination as rest of code
711 attributes::set_frame_pointer_elimination(ccx, llfn);
712
32a655c1 713 let bld = Builder::new_block(ccx, llfn, "top");
1a4d82fc 714
32a655c1 715 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
1a4d82fc 716
32a655c1
SL
717 let (start_fn, args) = if use_start_lang_item {
718 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
cc61c64b
XL
719 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
720 let start_fn = callee::get_fn(ccx, start_instance);
32a655c1
SL
721 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
722 get_param(llfn, 1)])
723 } else {
724 debug!("using user-defined start fn");
725 (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
726 };
1a4d82fc 727
32a655c1
SL
728 let result = bld.call(start_fn, &args, None);
729 bld.ret(result);
1a4d82fc
JJ
730 }
731}
732
54a0048b
SL
733fn contains_null(s: &str) -> bool {
734 s.bytes().any(|b| b == 0)
1a4d82fc
JJ
735}
736
cc61c64b
XL
737fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
738 link_meta: &LinkMeta,
739 exported_symbols: &NodeSet)
3b2f2976
XL
740 -> (ContextRef, ModuleRef,
741 EncodedMetadata, EncodedMetadataHashes) {
041b39d2
XL
742 use std::io::Write;
743 use flate2::Compression;
744 use flate2::write::DeflateEncoder;
1a4d82fc 745
cc61c64b
XL
746 let (metadata_llcx, metadata_llmod) = unsafe {
747 context::create_context_and_module(tcx.sess, "metadata")
748 };
749
c30ab7b3
SL
750 #[derive(PartialEq, Eq, PartialOrd, Ord)]
751 enum MetadataKind {
752 None,
753 Uncompressed,
754 Compressed
755 }
756
cc61c64b 757 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
c30ab7b3
SL
758 match *ty {
759 config::CrateTypeExecutable |
760 config::CrateTypeStaticlib |
761 config::CrateTypeCdylib => MetadataKind::None,
762
32a655c1 763 config::CrateTypeRlib => MetadataKind::Uncompressed,
c30ab7b3
SL
764
765 config::CrateTypeDylib |
766 config::CrateTypeProcMacro => MetadataKind::Compressed,
767 }
768 }).max().unwrap();
769
770 if kind == MetadataKind::None {
3b2f2976
XL
771 return (metadata_llcx,
772 metadata_llmod,
773 EncodedMetadata::new(),
774 EncodedMetadataHashes::new());
1a4d82fc
JJ
775 }
776
cc61c64b 777 let cstore = &tcx.sess.cstore;
3b2f2976
XL
778 let (metadata, hashes) = cstore.encode_metadata(tcx,
779 &link_meta,
780 exported_symbols);
c30ab7b3 781 if kind == MetadataKind::Uncompressed {
3b2f2976 782 return (metadata_llcx, metadata_llmod, metadata, hashes);
c30ab7b3
SL
783 }
784
785 assert!(kind == MetadataKind::Compressed);
92a42be0 786 let mut compressed = cstore.metadata_encoding_version().to_vec();
041b39d2
XL
787 DeflateEncoder::new(&mut compressed, Compression::Fast)
788 .write_all(&metadata.raw_data).unwrap();
1a4d82fc 789
cc61c64b
XL
790 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
791 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
792 let name = symbol_export::metadata_symbol_name(tcx);
85aaf69f 793 let buf = CString::new(name).unwrap();
1a4d82fc 794 let llglobal = unsafe {
cc61c64b 795 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
1a4d82fc
JJ
796 };
797 unsafe {
798 llvm::LLVMSetInitializer(llglobal, llconst);
7cac9316 799 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
5bcae85e
SL
800 let name = CString::new(section_name).unwrap();
801 llvm::LLVMSetSection(llglobal, name.as_ptr());
802
803 // Also generate a .section directive to force no
804 // flags, at least for ELF outputs, so that the
805 // metadata doesn't get loaded into memory.
806 let directive = format!(".section {}", section_name);
807 let directive = CString::new(directive).unwrap();
cc61c64b 808 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
1a4d82fc 809 }
3b2f2976 810 return (metadata_llcx, metadata_llmod, metadata, hashes);
e9174d1e
SL
811}
812
813// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
814// This is required to satisfy `dllimport` references to static data in .rlibs
815// when using MSVC linker. We do this only for data, as linker can fix up
816// code references on its own.
817// See #26591, #27438
cc61c64b 818fn create_imps(sess: &Session,
3b2f2976 819 llvm_module: &ModuleLlvm) {
e9174d1e
SL
820 // The x86 ABI seems to require that leading underscores are added to symbol
821 // names, so we need an extra underscore on 32-bit. There's also a leading
822 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
823 // underscores added in front).
cc61c64b 824 let prefix = if sess.target.target.target_pointer_width == "32" {
e9174d1e
SL
825 "\x01__imp__"
826 } else {
827 "\x01__imp_"
828 };
829 unsafe {
3b2f2976
XL
830 let exported: Vec<_> = iter_globals(llvm_module.llmod)
831 .filter(|&val| {
832 llvm::LLVMRustGetLinkage(val) ==
833 llvm::Linkage::ExternalLinkage &&
834 llvm::LLVMIsDeclaration(val) == 0
835 })
836 .collect();
837
838 let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
839 for val in exported {
840 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
841 let mut imp_name = prefix.as_bytes().to_vec();
842 imp_name.extend(name.to_bytes());
843 let imp_name = CString::new(imp_name).unwrap();
844 let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
845 i8p_ty.to_ref(),
846 imp_name.as_ptr() as *const _);
847 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
848 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
e9174d1e
SL
849 }
850 }
851}
1a4d82fc 852
e9174d1e
SL
853struct ValueIter {
854 cur: ValueRef,
855 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
856}
857
858impl Iterator for ValueIter {
859 type Item = ValueRef;
1a4d82fc 860
e9174d1e
SL
861 fn next(&mut self) -> Option<ValueRef> {
862 let old = self.cur;
863 if !old.is_null() {
b039eaaf 864 self.cur = unsafe { (self.step)(old) };
e9174d1e
SL
865 Some(old)
866 } else {
867 None
868 }
1a4d82fc 869 }
e9174d1e 870}
1a4d82fc 871
e9174d1e
SL
872fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
873 unsafe {
874 ValueIter {
875 cur: llvm::LLVMGetFirstGlobal(llmod),
876 step: llvm::LLVMGetNextGlobal,
877 }
878 }
879}
1a4d82fc 880
e9174d1e
SL
881/// The context provided lists a set of reachable ids as calculated by
882/// middle::reachable, but this contains far more ids and symbols than we're
883/// actually exposing from the object file. This function will filter the set in
884/// the context to the set of ids which correspond to symbols that are exposed
885/// from the object file being generated.
886///
887/// This list is later used by linkers to determine the set of symbols needed to
888/// be exposed from a dynamic library and it's also encoded into the metadata.
cc61c64b
XL
889pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet {
890 reachable.iter().cloned().filter(|&id| {
e9174d1e
SL
891 // Next, we want to ignore some FFI functions that are not exposed from
892 // this crate. Reachable FFI functions can be lumped into two
893 // categories:
894 //
895 // 1. Those that are included statically via a static library
896 // 2. Those included otherwise (e.g. dynamically or via a framework)
897 //
898 // Although our LLVM module is not literally emitting code for the
899 // statically included symbols, it's an export of our library which
900 // needs to be passed on to the linker and encoded in the metadata.
901 //
902 // As a result, if this id is an FFI item (foreign item) then we only
903 // let it through if it's included statically.
32a655c1 904 match tcx.hir.get(id) {
e9174d1e 905 hir_map::NodeForeignItem(..) => {
32a655c1 906 let def_id = tcx.hir.local_def_id(id);
476ff2be 907 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
e9174d1e 908 }
3157f602
XL
909
910 // Only consider nodes that actually have exported symbols.
911 hir_map::NodeItem(&hir::Item {
912 node: hir::ItemStatic(..), .. }) |
913 hir_map::NodeItem(&hir::Item {
914 node: hir::ItemFn(..), .. }) |
915 hir_map::NodeImplItem(&hir::ImplItem {
916 node: hir::ImplItemKind::Method(..), .. }) => {
32a655c1 917 let def_id = tcx.hir.local_def_id(id);
7cac9316 918 let generics = tcx.generics_of(def_id);
9e0c209e
SL
919 let attributes = tcx.get_attrs(def_id);
920 (generics.parent_types == 0 && generics.types.is_empty()) &&
921 // Functions marked with #[inline] are only ever translated
922 // with "internal" linkage and are never exported.
cc61c64b 923 !attr::requests_inline(&attributes)
3157f602
XL
924 }
925
926 _ => false
e9174d1e
SL
927 }
928 }).collect()
929}
930
a7813a04 931pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
9e0c209e 932 analysis: ty::CrateAnalysis,
3b2f2976 933 incremental_hashes_map: IncrementalHashesMap,
041b39d2 934 output_filenames: &OutputFilenames)
3b2f2976
XL
935 -> OngoingCrateTranslation {
936 check_for_rustc_errors_attr(tcx);
937
9cc50fc6
SL
938 // Be careful with this krate: obviously it gives access to the
939 // entire contents of the krate. So if you push any subtasks of
940 // `TransCrate`, you need to be careful to register "reads" of the
941 // particular items that will be processed.
32a655c1 942 let krate = tcx.hir.krate();
cc61c64b 943 let ty::CrateAnalysis { reachable, .. } = analysis;
8bb4bdeb 944 let check_overflow = tcx.sess.overflow_checks();
3b2f2976
XL
945 let link_meta = link::build_link_meta(&incremental_hashes_map);
946 let exported_symbol_node_ids = find_exported_symbols(tcx, &reachable);
c1a9b12d 947
a7813a04 948 let shared_ccx = SharedCrateContext::new(tcx,
041b39d2
XL
949 check_overflow,
950 output_filenames);
3157f602 951 // Translate the metadata.
3b2f2976 952 let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
cc61c64b 953 time(tcx.sess.time_passes(), "write metadata", || {
3b2f2976 954 write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
cc61c64b 955 });
3157f602
XL
956
957 let metadata_module = ModuleTranslation {
8bb4bdeb 958 name: link::METADATA_MODULE_NAME.to_string(),
5bcae85e
SL
959 symbol_name_hash: 0, // we always rebuild metadata, at least for now
960 source: ModuleSource::Translated(ModuleLlvm {
cc61c64b
XL
961 llcx: metadata_llcx,
962 llmod: metadata_llmod,
5bcae85e 963 }),
3b2f2976 964 kind: ModuleKind::Metadata,
3157f602 965 };
041b39d2 966
3157f602 967 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
3b2f2976
XL
968 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
969 Some(time_graph::TimeGraph::new())
970 } else {
971 None
972 };
041b39d2 973
32a655c1
SL
974 // Skip crate items and just output metadata in -Z no-trans mode.
975 if tcx.sess.opts.debugging_opts.no_trans ||
976 !tcx.sess.opts.output_types.should_trans() {
977 let empty_exported_symbols = ExportedSymbols::empty();
978 let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
3b2f2976
XL
979 let ongoing_translation = write::start_async_translation(
980 tcx.sess,
981 output_filenames,
982 time_graph.clone(),
983 tcx.crate_name(LOCAL_CRATE),
984 link_meta,
985 metadata,
986 Arc::new(empty_exported_symbols),
987 no_builtins,
988 None,
989 linker_info,
990 false);
991
992 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, metadata_module, true);
993
994 assert_and_save_dep_graph(tcx,
995 incremental_hashes_map,
996 metadata_incr_hashes,
997 link_meta);
998
999 ongoing_translation.check_for_errors(tcx.sess);
1000
1001 return ongoing_translation;
32a655c1
SL
1002 }
1003
3b2f2976
XL
1004 let exported_symbols = Arc::new(ExportedSymbols::compute(tcx,
1005 &exported_symbol_node_ids));
1006
5bcae85e
SL
1007 // Run the translation item collector and partition the collected items into
1008 // codegen units.
7cac9316 1009 let (translation_items, codegen_units) =
3b2f2976
XL
1010 collect_and_partition_translation_items(&shared_ccx, &exported_symbols);
1011
1012 assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
1013
1014 let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1015 let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1016 "windows_subsystem");
1017 let windows_subsystem = subsystem.map(|subsystem| {
1018 if subsystem != "windows" && subsystem != "console" {
1019 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1020 `windows` and `console` are allowed",
1021 subsystem));
1022 }
1023 subsystem.to_string()
1024 });
1025
1026 let no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1027 (tcx.sess.target.target.options.no_integrated_as &&
1028 (output_filenames.outputs.contains_key(&OutputType::Object) ||
1029 output_filenames.outputs.contains_key(&OutputType::Exe)));
1030
1031 let ongoing_translation = write::start_async_translation(
1032 tcx.sess,
1033 output_filenames,
1034 time_graph.clone(),
1035 tcx.crate_name(LOCAL_CRATE),
1036 link_meta,
1037 metadata,
1038 exported_symbols.clone(),
1039 no_builtins,
1040 windows_subsystem,
1041 linker_info,
1042 no_integrated_as);
1043
1044 // Translate an allocator shim, if any
1045 //
1046 // If LTO is enabled and we've got some previous LLVM module we translated
1047 // above, then we can just translate directly into that LLVM module. If not,
1048 // however, we need to create a separate module and trans into that. Note
1049 // that the separate translation is critical for the standard library where
1050 // the rlib's object file doesn't have allocator functions but the dylib
1051 // links in an object file that has allocator functions. When we're
1052 // compiling a final LTO artifact, though, there's no need to worry about
1053 // this as we're not working with this dual "rlib/dylib" functionality.
1054 let allocator_module = if tcx.sess.lto() {
1055 None
1056 } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1057 unsafe {
1058 let (llcx, llmod) =
1059 context::create_context_and_module(tcx.sess, "allocator");
1060 let modules = ModuleLlvm {
1061 llmod,
1062 llcx,
1063 };
1064 time(tcx.sess.time_passes(), "write allocator module", || {
1065 allocator::trans(tcx, &modules, kind)
1066 });
1067
1068 Some(ModuleTranslation {
1069 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1070 symbol_name_hash: 0, // we always rebuild allocator shims
1071 source: ModuleSource::Translated(modules),
1072 kind: ModuleKind::Allocator,
1073 })
1074 }
1075 } else {
1076 None
1077 };
1078
1079 if let Some(allocator_module) = allocator_module {
1080 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, allocator_module, false);
1081 }
1082
1083 let codegen_unit_count = codegen_units.len();
1084 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess,
1085 metadata_module,
1086 codegen_unit_count == 0);
1087
1088 let translation_items = Arc::new(translation_items);
a7813a04 1089
cc61c64b 1090 let mut all_stats = Stats::default();
3b2f2976
XL
1091 let mut module_dispositions = tcx.sess.opts.incremental.as_ref().map(|_| Vec::new());
1092
1093 // We sort the codegen units by size. This way we can schedule work for LLVM
1094 // a bit more efficiently. Note that "size" is defined rather crudely at the
1095 // moment as it is just the number of TransItems in the CGU, not taking into
1096 // account the size of each TransItem.
1097 let codegen_units = {
1098 let mut codegen_units = codegen_units;
1099 codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1100 codegen_units
1101 };
1102
1103 let mut total_trans_time = Duration::new(0, 0);
1104
1105 for (cgu_index, cgu) in codegen_units.into_iter().enumerate() {
1106 ongoing_translation.wait_for_signal_to_translate_item();
1107 ongoing_translation.check_for_errors(tcx.sess);
1108
1109 let start_time = Instant::now();
1110
1111 let module = {
1112 let _timing_guard = time_graph
1113 .as_ref()
1114 .map(|time_graph| time_graph.start(write::TRANS_WORKER_TIMELINE,
1115 write::TRANS_WORK_PACKAGE_KIND));
cc61c64b 1116 let dep_node = cgu.work_product_dep_node();
041b39d2 1117 let ((stats, module), _) =
cc61c64b
XL
1118 tcx.dep_graph.with_task(dep_node,
1119 AssertDepGraphSafe(&shared_ccx),
3b2f2976
XL
1120 AssertDepGraphSafe((cgu,
1121 translation_items.clone(),
1122 exported_symbols.clone())),
cc61c64b
XL
1123 module_translation);
1124 all_stats.extend(stats);
3b2f2976
XL
1125
1126 if let Some(ref mut module_dispositions) = module_dispositions {
1127 module_dispositions.push(module.disposition());
1128 }
1129
cc61c64b 1130 module
3b2f2976
XL
1131 };
1132
1133 let time_to_translate = Instant::now().duration_since(start_time);
1134
1135 // We assume that the cost to run LLVM on a CGU is proportional to
1136 // the time we needed for translating it.
1137 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1138 time_to_translate.subsec_nanos() as u64;
1139
1140 total_trans_time += time_to_translate;
1141
1142 let is_last_cgu = (cgu_index + 1) == codegen_unit_count;
1143
1144 ongoing_translation.submit_translated_module_to_llvm(tcx.sess,
1145 module,
1146 cost,
1147 is_last_cgu);
1148 ongoing_translation.check_for_errors(tcx.sess);
1149 }
1150
1151 // Since the main thread is sometimes blocked during trans, we keep track
1152 // -Ztime-passes output manually.
1153 print_time_passes_entry(tcx.sess.time_passes(),
1154 "translate to LLVM IR",
1155 total_trans_time);
1156
1157 if let Some(module_dispositions) = module_dispositions {
1158 assert_module_sources::assert_module_sources(tcx, &module_dispositions);
1159 }
3157f602 1160
cc61c64b
XL
1161 fn module_translation<'a, 'tcx>(
1162 scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
3b2f2976
XL
1163 args: AssertDepGraphSafe<(CodegenUnit<'tcx>,
1164 Arc<FxHashSet<TransItem<'tcx>>>,
1165 Arc<ExportedSymbols>)>)
cc61c64b
XL
1166 -> (Stats, ModuleTranslation)
1167 {
1168 // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1169 let AssertDepGraphSafe(scx) = scx;
3b2f2976 1170 let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
cc61c64b
XL
1171
1172 let cgu_name = String::from(cgu.name());
1173 let cgu_id = cgu.work_product_id();
7cac9316 1174 let symbol_name_hash = cgu.compute_symbol_name_hash(scx);
cc61c64b
XL
1175
1176 // Check whether there is a previous work-product we can
1177 // re-use. Not only must the file exist, and the inputs not
1178 // be dirty, but the hash of the symbols we will generate must
1179 // be the same.
1180 let previous_work_product =
1181 scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1182 if work_product.input_hash == symbol_name_hash {
1183 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1184 Some(work_product)
1185 } else {
1186 if scx.sess().opts.debugging_opts.incremental_info {
041b39d2
XL
1187 eprintln!("incremental: CGU `{}` invalidated because of \
1188 changed partitioning hash.",
1189 cgu.name());
cc61c64b
XL
1190 }
1191 debug!("trans_reuse_previous_work_products: \
1192 not reusing {:?} because hash changed to {:?}",
1193 work_product, symbol_name_hash);
1194 None
1195 }
1196 });
5bcae85e 1197
cc61c64b
XL
1198 if let Some(buf) = previous_work_product {
1199 // Don't need to translate this module.
1200 let module = ModuleTranslation {
1201 name: cgu_name,
1202 symbol_name_hash,
3b2f2976
XL
1203 source: ModuleSource::Preexisting(buf.clone()),
1204 kind: ModuleKind::Regular,
cc61c64b
XL
1205 };
1206 return (Stats::default(), module);
1207 }
1208
1209 // Instantiate translation items without filling out definitions yet...
3b2f2976 1210 let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
cc61c64b
XL
1211 let module = {
1212 let ccx = CrateContext::new(scx, &lcx);
1213 let trans_items = ccx.codegen_unit()
7cac9316 1214 .items_in_deterministic_order(ccx.tcx());
3b2f2976
XL
1215 for &(trans_item, (linkage, visibility)) in &trans_items {
1216 trans_item.predefine(&ccx, linkage, visibility);
5bcae85e 1217 }
7453a54e 1218
cc61c64b
XL
1219 // ... and now that we have everything pre-defined, fill out those definitions.
1220 for &(trans_item, _) in &trans_items {
5bcae85e
SL
1221 trans_item.define(&ccx);
1222 }
54a0048b 1223
5bcae85e
SL
1224 // If this codegen unit contains the main function, also create the
1225 // wrapper here
1226 maybe_create_entry_wrapper(&ccx);
1a4d82fc 1227
5bcae85e
SL
1228 // Run replace-all-uses-with for statics that need it
1229 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1230 unsafe {
1231 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1232 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1233 llvm::LLVMDeleteGlobal(old_g);
1234 }
c1a9b12d 1235 }
5bcae85e 1236
cc61c64b
XL
1237 // Create the llvm.used variable
1238 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1239 if !ccx.used_statics().borrow().is_empty() {
1240 let name = CString::new("llvm.used").unwrap();
1241 let section = CString::new("llvm.metadata").unwrap();
1242 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1243
1244 unsafe {
1245 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1246 val_ty(array).to_ref(),
1247 name.as_ptr());
1248 llvm::LLVMSetInitializer(g, array);
1249 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1250 llvm::LLVMSetSection(g, section.as_ptr());
1251 }
1252 }
1253
5bcae85e
SL
1254 // Finalize debuginfo
1255 if ccx.sess().opts.debuginfo != NoDebugInfo {
1256 debuginfo::finalize(&ccx);
1257 }
cc61c64b 1258
3b2f2976
XL
1259 let llvm_module = ModuleLlvm {
1260 llcx: ccx.llcx(),
1261 llmod: ccx.llmod(),
1262 };
1263
1264 // In LTO mode we inject the allocator shim into the existing
1265 // module.
1266 if ccx.sess().lto() {
1267 if let Some(kind) = ccx.sess().allocator_kind.get() {
1268 time(ccx.sess().time_passes(), "write allocator module", || {
1269 unsafe {
1270 allocator::trans(ccx.tcx(), &llvm_module, kind);
1271 }
1272 });
1273 }
1274 }
1275
1276 // Adjust exported symbols for MSVC dllimport
1277 if ccx.sess().target.target.options.is_like_msvc &&
1278 ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1279 create_imps(ccx.sess(), &llvm_module);
1280 }
1281
cc61c64b
XL
1282 ModuleTranslation {
1283 name: cgu_name,
1284 symbol_name_hash,
3b2f2976
XL
1285 source: ModuleSource::Translated(llvm_module),
1286 kind: ModuleKind::Regular,
cc61c64b
XL
1287 }
1288 };
1289
1290 (lcx.into_stats(), module)
1a4d82fc
JJ
1291 }
1292
cc61c64b 1293 symbol_names_test::report_symbol_names(tcx);
5bcae85e 1294
1a4d82fc 1295 if shared_ccx.sess().trans_stats() {
1a4d82fc 1296 println!("--- trans stats ---");
cc61c64b
XL
1297 println!("n_glues_created: {}", all_stats.n_glues_created.get());
1298 println!("n_null_glues: {}", all_stats.n_null_glues.get());
1299 println!("n_real_glues: {}", all_stats.n_real_glues.get());
1a4d82fc 1300
cc61c64b
XL
1301 println!("n_fns: {}", all_stats.n_fns.get());
1302 println!("n_inlines: {}", all_stats.n_inlines.get());
1303 println!("n_closures: {}", all_stats.n_closures.get());
1a4d82fc 1304 println!("fn stats:");
cc61c64b 1305 all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1a4d82fc
JJ
1306 insns_b.cmp(&insns_a)
1307 });
cc61c64b 1308 for tuple in all_stats.fn_stats.borrow().iter() {
1a4d82fc
JJ
1309 match *tuple {
1310 (ref name, insns) => {
1311 println!("{} insns, {}", insns, *name);
1312 }
1313 }
1314 }
1315 }
5bcae85e 1316
1a4d82fc 1317 if shared_ccx.sess().count_llvm_insns() {
cc61c64b 1318 for (k, v) in all_stats.llvm_insns.borrow().iter() {
1a4d82fc
JJ
1319 println!("{:7} {}", *v, *k);
1320 }
1321 }
1322
3b2f2976 1323 ongoing_translation.check_for_errors(tcx.sess);
041b39d2 1324
3b2f2976
XL
1325 assert_and_save_dep_graph(tcx,
1326 incremental_hashes_map,
1327 metadata_incr_hashes,
1328 link_meta);
1329 ongoing_translation
1330}
c30ab7b3 1331
3b2f2976
XL
1332fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1333 incremental_hashes_map: IncrementalHashesMap,
1334 metadata_incr_hashes: EncodedMetadataHashes,
1335 link_meta: LinkMeta) {
1336 time(tcx.sess.time_passes(),
1337 "assert dep graph",
1338 || rustc_incremental::assert_dep_graph(tcx));
1339
1340 time(tcx.sess.time_passes(),
1341 "serialize dep graph",
1342 || rustc_incremental::save_dep_graph(tcx,
1343 incremental_hashes_map,
1344 &metadata_incr_hashes,
1345 link_meta.crate_hash));
1a4d82fc 1346}
92a42be0 1347
7cac9316
XL
1348#[inline(never)] // give this a place in the profiler
1349fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1350 where I: Iterator<Item=&'a TransItem<'tcx>>
1351{
1352 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1353 (trans_item, trans_item.symbol_name(tcx))
1354 }).collect();
476ff2be 1355
7cac9316
XL
1356 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1357 sym1.cmp(sym2)
1358 });
476ff2be 1359
7cac9316
XL
1360 for pair in (&symbols[..]).windows(2) {
1361 let sym1 = &pair[0].1;
1362 let sym2 = &pair[1].1;
476ff2be 1363
7cac9316
XL
1364 if *sym1 == *sym2 {
1365 let trans_item1 = pair[0].0;
1366 let trans_item2 = pair[1].0;
476ff2be 1367
7cac9316
XL
1368 let span1 = trans_item1.local_span(tcx);
1369 let span2 = trans_item2.local_span(tcx);
476ff2be 1370
7cac9316
XL
1371 // Deterministically select one of the spans for error reporting
1372 let span = match (span1, span2) {
1373 (Some(span1), Some(span2)) => {
1374 Some(if span1.lo.0 > span2.lo.0 {
1375 span1
1376 } else {
1377 span2
476ff2be 1378 })
7cac9316
XL
1379 }
1380 (Some(span), None) |
1381 (None, Some(span)) => Some(span),
1382 _ => None
1383 };
476ff2be 1384
7cac9316 1385 let error_message = format!("symbol `{}` is already defined", sym1);
476ff2be 1386
7cac9316
XL
1387 if let Some(span) = span {
1388 tcx.sess.span_fatal(span, &error_message)
1389 } else {
1390 tcx.sess.fatal(&error_message)
476ff2be
SL
1391 }
1392 }
1393 }
1394}
1395
3b2f2976
XL
1396fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
1397 exported_symbols: &ExportedSymbols)
cc61c64b 1398 -> (FxHashSet<TransItem<'tcx>>,
7cac9316 1399 Vec<CodegenUnit<'tcx>>) {
a7813a04 1400 let time_passes = scx.sess().time_passes();
7453a54e 1401
a7813a04 1402 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
7453a54e
SL
1403 Some(ref s) => {
1404 let mode_string = s.to_lowercase();
1405 let mode_string = mode_string.trim();
1406 if mode_string == "eager" {
1407 TransItemCollectionMode::Eager
1408 } else {
1409 if mode_string != "lazy" {
1410 let message = format!("Unknown codegen-item collection mode '{}'. \
1411 Falling back to 'lazy' mode.",
1412 mode_string);
a7813a04 1413 scx.sess().warn(&message);
7453a54e
SL
1414 }
1415
1416 TransItemCollectionMode::Lazy
1417 }
1418 }
1419 None => TransItemCollectionMode::Lazy
1420 };
1421
5bcae85e
SL
1422 let (items, inlining_map) =
1423 time(time_passes, "translation item collection", || {
3b2f2976
XL
1424 collector::collect_crate_translation_items(&scx,
1425 exported_symbols,
1426 collection_mode)
7453a54e
SL
1427 });
1428
7cac9316 1429 assert_symbols_are_distinct(scx.tcx(), items.iter());
5bcae85e 1430
a7813a04
XL
1431 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1432 PartitioningStrategy::PerModule
1433 } else {
1434 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1435 };
1436
1437 let codegen_units = time(time_passes, "codegen unit partitioning", || {
9e0c209e 1438 partitioning::partition(scx,
a7813a04
XL
1439 items.iter().cloned(),
1440 strategy,
3b2f2976
XL
1441 &inlining_map,
1442 exported_symbols)
a7813a04
XL
1443 });
1444
5bcae85e
SL
1445 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1446 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1447
cc61c64b 1448 let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
5bcae85e 1449
a7813a04 1450 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
476ff2be 1451 let mut item_to_cgus = FxHashMap();
a7813a04
XL
1452
1453 for cgu in &codegen_units {
5bcae85e 1454 for (&trans_item, &linkage) in cgu.items() {
a7813a04
XL
1455 item_to_cgus.entry(trans_item)
1456 .or_insert(Vec::new())
5bcae85e 1457 .push((cgu.name().clone(), linkage));
a7813a04
XL
1458 }
1459 }
1460
1461 let mut item_keys: Vec<_> = items
1462 .iter()
1463 .map(|i| {
1464 let mut output = i.to_string(scx.tcx());
1465 output.push_str(" @@");
1466 let mut empty = Vec::new();
3b2f2976 1467 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
a7813a04
XL
1468 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1469 cgus.dedup();
3b2f2976 1470 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
a7813a04 1471 output.push_str(" ");
cc61c64b 1472 output.push_str(&cgu_name);
a7813a04
XL
1473
1474 let linkage_abbrev = match linkage {
9e0c209e
SL
1475 llvm::Linkage::ExternalLinkage => "External",
1476 llvm::Linkage::AvailableExternallyLinkage => "Available",
1477 llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1478 llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1479 llvm::Linkage::WeakAnyLinkage => "WeakAny",
1480 llvm::Linkage::WeakODRLinkage => "WeakODR",
1481 llvm::Linkage::AppendingLinkage => "Appending",
1482 llvm::Linkage::InternalLinkage => "Internal",
1483 llvm::Linkage::PrivateLinkage => "Private",
1484 llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1485 llvm::Linkage::CommonLinkage => "Common",
a7813a04
XL
1486 };
1487
1488 output.push_str("[");
1489 output.push_str(linkage_abbrev);
1490 output.push_str("]");
1491 }
1492 output
1493 })
1494 .collect();
1495
7453a54e
SL
1496 item_keys.sort();
1497
1498 for item in item_keys {
1499 println!("TRANS_ITEM {}", item);
1500 }
5bcae85e 1501 }
7453a54e 1502
7cac9316 1503 (translation_items, codegen_units)
5bcae85e 1504}