base.rs 54.2 KB
Newer Older
1
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
10

11 12 13
//! Translate the completed AST to the LLVM IR.
//!
//! Some functions here, such as trans_block and trans_expr, return a value --
14 15
//! the result of the translation to LLVM -- while others, such as trans_fn
//! and trans_item, are called only for the side effect of adding a
16 17 18 19 20 21 22 23 24
//! particular definition to the LLVM IR output we're producing.
//!
//! Hopefully useful general knowledge about trans:
//!
//!   * There's no way to find out the Ty type of a ValueRef.  Doing so
//!     would be "trying to get the eggs out of an omelette" (credit:
//!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
//!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
//!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25

26 27
use super::ModuleLlvm;
use super::ModuleSource;
28
use super::ModuleTranslation;
29
use super::ModuleKind;
30

31
use assert_module_sources;
32
use back::link;
33
use back::symbol_export;
34
use back::write::{self, OngoingCrateTranslation, create_target_machine};
35
use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
36
use llvm;
37
use metadata;
38
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
39
use rustc::middle::lang_items::StartFnLangItem;
A
Alex Crichton 已提交
40
use rustc::middle::trans::{Linkage, Visibility, Stats};
41
use rustc::middle::cstore::{EncodedMetadata, EncodedMetadataHashes};
42
use rustc::ty::{self, Ty, TyCtxt};
43
use rustc::ty::maps::Providers;
44
use rustc::dep_graph::{DepNode, DepKind, DepConstructor};
45
use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
46
use rustc::util::common::{time, print_time_passes_entry};
A
Alex Crichton 已提交
47
use rustc::session::config::{self, NoDebugInfo};
48
use rustc::session::Session;
49
use rustc_incremental;
50
use abi;
51
use allocator;
52
use mir::lvalue::LvalueRef;
53
use attributes;
M
Mark-Simulacrum 已提交
54
use builder::Builder;
55
use callee;
56
use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
57
use collector::{self, TransItemCollectionMode};
J
Jorge Aparicio 已提交
58
use common::{C_struct_in_context, C_u64, C_undef, C_array};
M
Mark Simulacrum 已提交
59
use common::CrateContext;
60
use common::{type_is_zero_size, val_ty};
61 62
use common;
use consts;
A
Alex Crichton 已提交
63
use context::{self, LocalCrateContext, SharedCrateContext};
M
Mark-Simulacrum 已提交
64
use debuginfo;
65 66 67 68 69
use declare;
use machine;
use meth;
use mir;
use monomorphize::{self, Instance};
70
use partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
71
use symbol_names_test;
72
use time_graph;
73
use trans_item::{TransItem, TransItemExt, DefPathBasedNames};
74 75 76
use type_::Type;
use type_of;
use value::Value;
77
use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet, DefIdSet};
78
use CrateInfo;
J
James Miller 已提交
79

80
use std::any::Any;
81
use std::ffi::CString;
A
Alex Crichton 已提交
82
use std::str;
83
use std::sync::Arc;
84
use std::time::{Instant, Duration};
85
use std::i32;
86
use std::sync::mpsc;
87
use syntax_pos::Span;
A
Alex Crichton 已提交
88
use syntax_pos::symbol::InternedString;
89
use syntax::attr;
90
use rustc::hir;
91
use syntax::ast;
T
Tim Chevalier 已提交
92

93 94
use mir::lvalue::Alignment;

B
bjorn3 已提交
95
pub use rustc_trans_utils::{find_exported_symbols, check_for_rustc_errors_attr};
B
bjorn3 已提交
96

97 98
pub struct StatRecorder<'a, 'tcx: 'a> {
    ccx: &'a CrateContext<'a, 'tcx>,
99
    name: Option<String>,
100
    istart: usize,
101 102
}

103
impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
M
Ms2ger 已提交
104
    pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
A
Alex Crichton 已提交
105
        let istart = ccx.stats().borrow().n_llvm_insns;
106
        StatRecorder {
107
            ccx,
108
            name: Some(name),
109
            istart,
110 111 112 113
        }
    }
}

114
impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
D
Daniel Micay 已提交
115
    fn drop(&mut self) {
E
Eduard Burtescu 已提交
116
        if self.ccx.sess().trans_stats() {
A
Alex Crichton 已提交
117 118 119 120
            let mut stats = self.ccx.stats().borrow_mut();
            let iend = stats.n_llvm_insns;
            stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
            stats.n_fns += 1;
121
            // Reset LLVM insn count to avoid compound costs.
A
Alex Crichton 已提交
122
            stats.n_llvm_insns = self.istart;
123 124 125 126
        }
    }
}

M
Mark-Simulacrum 已提交
127
pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
128
    bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
129 130
}

M
Mark-Simulacrum 已提交
131
pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
132
    bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
133 134
}

135
pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
M
Ms2ger 已提交
136
                                signed: bool)
137 138
                                -> llvm::IntPredicate {
    match op {
139 140 141 142 143 144
        hir::BiEq => llvm::IntEQ,
        hir::BiNe => llvm::IntNE,
        hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
        hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
        hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
        hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
145
        op => {
146 147 148
            bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
                  found {:?}",
                 op)
149 150 151
        }
    }
}
152

153
pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
154
    match op {
155 156 157 158 159 160
        hir::BiEq => llvm::RealOEQ,
        hir::BiNe => llvm::RealUNE,
        hir::BiLt => llvm::RealOLT,
        hir::BiLe => llvm::RealOLE,
        hir::BiGt => llvm::RealOGT,
        hir::BiGe => llvm::RealOGE,
161
        op => {
162 163 164
            bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
                  found {:?}",
                 op);
165 166 167 168
        }
    }
}

M
Mark Simulacrum 已提交
169
pub fn compare_simd_types<'a, 'tcx>(
170
    bcx: &Builder<'a, 'tcx>,
M
Mark Simulacrum 已提交
171 172 173 174 175 176
    lhs: ValueRef,
    rhs: ValueRef,
    t: Ty<'tcx>,
    ret_ty: Type,
    op: hir::BinOp_
) -> ValueRef {
177
    let signed = match t.sty {
178
        ty::TyFloat(_) => {
179
            let cmp = bin_op_to_fcmp_predicate(op);
180
            return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
181
        },
182 183
        ty::TyUint(_) => false,
        ty::TyInt(_) => true,
184
        _ => bug!("compare_simd_types: invalid SIMD type"),
185
    };
186

187
    let cmp = bin_op_to_icmp_predicate(op, signed);
188 189 190 191
    // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
    // to get the correctly sized type. This will compile to a single instruction
    // once the IR is converted to assembly if the SIMD instruction is supported
    // by the target architecture.
192
    bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
193 194
}

A
Ariel Ben-Yehuda 已提交
195 196 197 198
/// Retrieve the information we are losing (making dynamic) in an unsizing
/// adjustment.
///
/// The `old_info` argument is a bit funny. It is intended for use
B
Bastien Orivel 已提交
199
/// in an upcast, where the new vtable for an object will be derived
A
Ariel Ben-Yehuda 已提交
200 201 202 203
/// from the old one.
pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
                                source: Ty<'tcx>,
                                target: Ty<'tcx>,
204
                                old_info: Option<ValueRef>)
A
Ariel Ben-Yehuda 已提交
205 206 207
                                -> ValueRef {
    let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
    match (&source.sty, &target.sty) {
208 209 210
        (&ty::TyArray(_, len), &ty::TySlice(_)) => {
            C_usize(ccx, len.val.to_const_int().unwrap().to_u64().unwrap())
        }
211
        (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
A
Ariel Ben-Yehuda 已提交
212 213 214 215 216
            // For now, upcasts are limited to changes in marker
            // traits, and hence never actually require an actual
            // change to the vtable.
            old_info.expect("unsized_info: missing old info for trait upcast")
        }
217 218
        (_, &ty::TyDynamic(ref data, ..)) => {
            consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
A
Ariel Ben-Yehuda 已提交
219 220
                            Type::vtable_ptr(ccx))
        }
221
        _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
A
Ariel Ben-Yehuda 已提交
222
                                     source,
223
                                     target),
A
Ariel Ben-Yehuda 已提交
224 225 226 227
    }
}

/// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
M
Mark Simulacrum 已提交
228
pub fn unsize_thin_ptr<'a, 'tcx>(
229
    bcx: &Builder<'a, 'tcx>,
M
Mark Simulacrum 已提交
230 231 232 233
    src: ValueRef,
    src_ty: Ty<'tcx>,
    dst_ty: Ty<'tcx>
) -> (ValueRef, ValueRef) {
A
Ariel Ben-Yehuda 已提交
234 235 236 237 238 239 240 241
    debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
    match (&src_ty.sty, &dst_ty.sty) {
        (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
         &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
        (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
         &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
        (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
         &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
M
Mark Simulacrum 已提交
242 243 244
            assert!(bcx.ccx.shared().type_is_sized(a));
            let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
            (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
A
Ariel Ben-Yehuda 已提交
245
        }
246 247 248 249 250 251
        (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
            let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
            assert!(bcx.ccx.shared().type_is_sized(a));
            let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
            (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
        }
252
        _ => bug!("unsize_thin_ptr: called on bad types"),
A
Ariel Ben-Yehuda 已提交
253 254 255 256 257
    }
}

/// Coerce `src`, which is a reference to a value of type `src_ty`,
/// to a value of type `dst_ty` and store the result in `dst`
258
pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
259 260 261 262
                                     src: &LvalueRef<'tcx>,
                                     dst: &LvalueRef<'tcx>) {
    let src_ty = src.ty.to_ty(bcx.tcx());
    let dst_ty = dst.ty.to_ty(bcx.tcx());
263 264 265 266 267 268
    let coerce_ptr = || {
        let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
            // fat-ptr to fat-ptr unsize preserves the vtable
            // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
            // So we need to pointercast the base to ensure
            // the types match up.
269
            let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
270 271 272 273
            let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
            let base = bcx.pointercast(base, llcast_ty);
            (base, info)
        } else {
274
            let base = load_ty(bcx, src.llval, src.alignment, src_ty);
275 276
            unsize_thin_ptr(bcx, base, src_ty, dst_ty)
        };
277
        store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
278
    };
A
Ariel Ben-Yehuda 已提交
279 280 281 282
    match (&src_ty.sty, &dst_ty.sty) {
        (&ty::TyRef(..), &ty::TyRef(..)) |
        (&ty::TyRef(..), &ty::TyRawPtr(..)) |
        (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
283 284 285 286
            coerce_ptr()
        }
        (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
            coerce_ptr()
A
Ariel Ben-Yehuda 已提交
287 288
        }

289
        (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
A
Ariel Ben-Yehuda 已提交
290 291
            assert_eq!(def_a, def_b);

292
            let src_fields = def_a.variants[0].fields.iter().map(|f| {
293
                monomorphize::field_ty(bcx.tcx(), substs_a, f)
294 295
            });
            let dst_fields = def_b.variants[0].fields.iter().map(|f| {
296
                monomorphize::field_ty(bcx.tcx(), substs_b, f)
297
            });
A
Ariel Ben-Yehuda 已提交
298

299
            let iter = src_fields.zip(dst_fields).enumerate();
A
Ariel Ben-Yehuda 已提交
300
            for (i, (src_fty, dst_fty)) in iter {
M
Mark Simulacrum 已提交
301
                if type_is_zero_size(bcx.ccx, dst_fty) {
M
Ms2ger 已提交
302 303
                    continue;
                }
A
Ariel Ben-Yehuda 已提交
304

305 306
                let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
                let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
A
Ariel Ben-Yehuda 已提交
307
                if src_fty == dst_fty {
308
                    memcpy_ty(bcx, dst_f, src_f, src_fty, None);
A
Ariel Ben-Yehuda 已提交
309
                } else {
310 311 312 313 314
                    coerce_unsized_into(
                        bcx,
                        &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
                        &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
                    );
A
Ariel Ben-Yehuda 已提交
315 316 317
                }
            }
        }
318 319 320
        _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
                  src_ty,
                  dst_ty),
A
Ariel Ben-Yehuda 已提交
321 322 323
    }
}

324
pub fn cast_shift_expr_rhs(
325
    cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
326 327
) -> ValueRef {
    cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
328 329
}

M
Ms2ger 已提交
330 331 332 333
pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
    cast_shift_rhs(op,
                   lhs,
                   rhs,
J
James Miller 已提交
334 335
                   |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
                   |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
336 337
}

338
fn cast_shift_rhs<F, G>(op: hir::BinOp_,
339 340 341 342
                        lhs: ValueRef,
                        rhs: ValueRef,
                        trunc: F,
                        zext: G)
M
Ms2ger 已提交
343 344 345
                        -> ValueRef
    where F: FnOnce(ValueRef, Type) -> ValueRef,
          G: FnOnce(ValueRef, Type) -> ValueRef
346
{
347
    // Shifts may have any size int on the rhs
348
    if op.is_shift() {
349 350
        let mut rhs_llty = val_ty(rhs);
        let mut lhs_llty = val_ty(lhs);
M
Ms2ger 已提交
351 352 353 354 355 356
        if rhs_llty.kind() == Vector {
            rhs_llty = rhs_llty.element_type()
        }
        if lhs_llty.kind() == Vector {
            lhs_llty = lhs_llty.element_type()
        }
357 358 359 360 361 362 363 364
        let rhs_sz = rhs_llty.int_width();
        let lhs_sz = lhs_llty.int_width();
        if lhs_sz < rhs_sz {
            trunc(rhs, lhs_llty)
        } else if lhs_sz > rhs_sz {
            // FIXME (#1877: If shifting by negative
            // values becomes not undefined then this is wrong.
            zext(rhs, lhs_llty)
365 366 367
        } else {
            rhs
        }
368 369
    } else {
        rhs
370 371 372
    }
}

373 374 375 376 377 378
/// Returns whether this session's target will use SEH-based unwinding.
///
/// This is only true for MSVC targets, and even then the 64-bit MSVC target
/// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
/// 64-bit MinGW) instead of "full SEH".
pub fn wants_msvc_seh(sess: &Session) -> bool {
379
    sess.target.target.options.is_like_msvc
380 381
}

382 383 384 385 386
pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
    let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
    b.call(assume_intrinsic, &[val], None);
}

S
Steve Klabnik 已提交
387 388 389
/// Helper for loading values from memory. Does the necessary conversion if the in-memory type
/// differs from the type used for SSA values. Also handles various special cases where the type
/// gives us better information about what we are loading.
390 391
pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
                         alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
392 393 394 395
    let ccx = b.ccx;
    if type_is_zero_size(ccx, t) {
        return C_undef(type_of::type_of(ccx, t));
    }
396 397 398 399 400 401

    unsafe {
        let global = llvm::LLVMIsAGlobalVariable(ptr);
        if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
            let val = llvm::LLVMGetInitializer(global);
            if !val.is_null() {
402 403 404 405
                if t.is_bool() {
                    return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
                }
                return val;
406 407
            }
        }
408
    }
409

410
    if t.is_bool() {
411 412
        b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
                Type::i1(ccx))
413
    } else if t.is_char() {
414 415
        // a char is a Unicode codepoint, and so takes values from 0
        // to 0x10FFFF inclusive only.
416
        b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
A
Ariel Ben-Yehuda 已提交
417 418 419
    } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
        && !common::type_is_fat_ptr(ccx, t)
    {
420
        b.load_nonnull(ptr, alignment.to_align())
421
    } else {
422
        b.load(ptr, alignment.to_align())
423
    }
424 425
}

S
Steve Klabnik 已提交
426 427
/// Helper for storing values in memory. Does the necessary conversion if the in-memory type
/// differs from the type used for SSA values.
428 429
pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
                          dst_align: Alignment, t: Ty<'tcx>) {
430
    debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
431

M
Mark Simulacrum 已提交
432
    if common::type_is_fat_ptr(cx.ccx, t) {
433 434
        let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
        let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
435
        store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
436
    } else {
437
        cx.store(from_immediate(cx, v), dst, dst_align.to_align());
438
    }
439 440
}

441
pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
M
Mark Simulacrum 已提交
442 443 444
                               data: ValueRef,
                               extra: ValueRef,
                               dst: ValueRef,
445
                               dst_align: Alignment,
M
Mark Simulacrum 已提交
446
                               _ty: Ty<'tcx>) {
447
    // FIXME: emit metadata
448 449
    cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
    cx.store(extra, get_meta(cx, dst), dst_align.to_align());
450 451
}

M
Mark-Simulacrum 已提交
452
pub fn load_fat_ptr<'a, 'tcx>(
453
    b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
M
Mark Simulacrum 已提交
454
) -> (ValueRef, ValueRef) {
M
Mark-Simulacrum 已提交
455
    let ptr = get_dataptr(b, src);
456
    let ptr = if t.is_region_ptr() || t.is_box() {
457
        b.load_nonnull(ptr, alignment.to_align())
458
    } else {
459
        b.load(ptr, alignment.to_align())
460 461
    };

462 463 464 465 466 467 468 469 470
    let meta = get_meta(b, src);
    let meta_ty = val_ty(meta);
    // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
    // instead
    let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
        b.load_nonnull(meta, None)
    } else {
        b.load(meta, None)
    };
471 472

    (ptr, meta)
473 474
}

475
pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
M
Mark Simulacrum 已提交
476 477
    if val_ty(val) == Type::i1(bcx.ccx) {
        bcx.zext(val, Type::i8(bcx.ccx))
478 479 480 481 482
    } else {
        val
    }
}

483
pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
484
    if ty.is_bool() {
M
Mark Simulacrum 已提交
485
        bcx.trunc(val, Type::i1(bcx.ccx))
486 487 488 489 490
    } else {
        val
    }
}

491
pub enum Lifetime { Start, End }
492

493
impl Lifetime {
M
Mark-Simulacrum 已提交
494 495 496 497
    // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
    // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
    // and the intrinsic for `lt` and passes them to `emit`, which is in
    // charge of generating code to call the passed intrinsic on whatever
B
Bastien Orivel 已提交
498
    // block of generated code is targeted for the intrinsic.
M
Mark-Simulacrum 已提交
499 500 501
    //
    // If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
    // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
502
    pub fn call(self, b: &Builder, ptr: ValueRef) {
M
Mark-Simulacrum 已提交
503 504 505 506 507 508 509 510
        if b.ccx.sess().opts.optimize == config::OptLevel::No {
            return;
        }

        let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
        if size == 0 {
            return;
        }
511

M
Mark-Simulacrum 已提交
512 513 514 515 516 517 518 519
        let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
            Lifetime::Start => "llvm.lifetime.start",
            Lifetime::End => "llvm.lifetime.end"
        });

        let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
        b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
    }
520 521
}

M
Mark Simulacrum 已提交
522
pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
523 524 525 526 527
                               dst: ValueRef,
                               src: ValueRef,
                               n_bytes: ValueRef,
                               align: u32) {
    let ccx = b.ccx;
528
    let ptr_width = &ccx.sess().target.target.target_pointer_width;
529
    let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
M
Michael Darakananda 已提交
530
    let memcpy = ccx.get_intrinsic(&key);
531 532
    let src_ptr = b.pointercast(src, Type::i8p(ccx));
    let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
533
    let size = b.intcast(n_bytes, ccx.isize_ty(), false);
534
    let align = C_i32(ccx, align as i32);
535
    let volatile = C_bool(ccx, false);
536
    b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
537 538
}

539 540 541 542 543 544 545
pub fn memcpy_ty<'a, 'tcx>(
    bcx: &Builder<'a, 'tcx>,
    dst: ValueRef,
    src: ValueRef,
    t: Ty<'tcx>,
    align: Option<u32>,
) {
M
Mark Simulacrum 已提交
546
    let ccx = bcx.ccx;
547

548 549
    let size = ccx.size_of(t);
    if size == 0 {
550 551 552
        return;
    }

553
    let align = align.unwrap_or_else(|| ccx.align_of(t));
554
    call_memcpy(bcx, dst, src, C_usize(ccx, size), align);
555 556
}

M
Mark Simulacrum 已提交
557
pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
558 559 560 561 562
                             ptr: ValueRef,
                             fill_byte: ValueRef,
                             size: ValueRef,
                             align: ValueRef,
                             volatile: bool) -> ValueRef {
563
    let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
564
    let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
565 566 567
    let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
    let volatile = C_bool(b.ccx, volatile);
    b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
568 569
}

570
pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
571 572 573
    let _s = if ccx.sess().trans_stats() {
        let mut instance_name = String::new();
        DefPathBasedNames::new(ccx.tcx(), true, true)
574
            .push_def_path(instance.def_id(), &mut instance_name);
575 576 577 578 579
        Some(StatRecorder::new(ccx, instance_name))
    } else {
        None
    };

580 581 582 583 584
    // this is an info! to allow collecting monomorphization statistics
    // and to allow finding the last function before LLVM aborts from
    // release builds.
    info!("trans_instance({})", instance);

585
    let fn_ty = common::instance_ty(ccx.tcx(), &instance);
586 587
    let sig = common::ty_fn_sig(ccx, fn_ty);
    let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
588 589 590 591 592 593

    let lldecl = match ccx.instances().borrow().get(&instance) {
        Some(&val) => val,
        None => bug!("Instance `{:?}` not already declared", instance)
    };

A
Alex Crichton 已提交
594
    ccx.stats().borrow_mut().n_closures += 1;
595

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    // The `uwtable` attribute according to LLVM is:
    //
    //     This attribute indicates that the ABI being targeted requires that an
    //     unwind table entry be produced for this function even if we can show
    //     that no exceptions passes by it. This is normally the case for the
    //     ELF x86-64 abi, but it can be disabled for some compilation units.
    //
    // Typically when we're compiling with `-C panic=abort` (which implies this
    // `no_landing_pads` check) we don't need `uwtable` because we can't
    // generate any exceptions! On Windows, however, exceptions include other
    // events such as illegal instructions, segfaults, etc. This means that on
    // Windows we end up still needing the `uwtable` attribute even if the `-C
    // panic=abort` flag is passed.
    //
    // You can also find more info on why Windows is whitelisted here in:
    //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
    if !ccx.sess().no_landing_pads() ||
       ccx.sess().target.target.options.is_like_windows {
614
        attributes::emit_uwtable(lldecl, true);
615
    }
616

617
    let mir = ccx.tcx().instance_mir(instance.def);
618
    mir::trans_mir(ccx, lldecl, &mir, instance, sig);
619 620
}

621 622 623
pub fn linkage_by_name(name: &str) -> Option<Linkage> {
    use rustc::middle::trans::Linkage::*;

624 625 626 627 628 629 630 631 632
    // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
    // applicable to variable declarations and may not really make sense for
    // Rust code in the first place but whitelist them anyway and trust that
    // the user knows what s/he's doing. Who knows, unanticipated use cases
    // may pop up in the future.
    //
    // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
    // and don't have to be, LLVM treats them as no-ops.
    match name {
633 634 635 636 637 638 639 640 641 642 643
        "appending" => Some(Appending),
        "available_externally" => Some(AvailableExternally),
        "common" => Some(Common),
        "extern_weak" => Some(ExternalWeak),
        "external" => Some(External),
        "internal" => Some(Internal),
        "linkonce" => Some(LinkOnceAny),
        "linkonce_odr" => Some(LinkOnceODR),
        "private" => Some(Private),
        "weak" => Some(WeakAny),
        "weak_odr" => Some(WeakODR),
644 645 646 647
        _ => None,
    }
}

648 649 650 651
pub fn set_link_section(ccx: &CrateContext,
                        llval: ValueRef,
                        attrs: &[ast::Attribute]) {
    if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
652
        if contains_null(&sect.as_str()) {
653 654 655
            ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
        }
        unsafe {
656
            let buf = CString::new(sect.as_str().as_bytes()).unwrap();
657 658
            llvm::LLVMSetSection(llval, buf.as_ptr());
        }
E
Eli Friedman 已提交
659 660 661
    }
}

F
Fourchaux 已提交
662
/// Create the `main` function which will initialize the rust runtime and call
663
/// users main function.
664
fn maybe_create_entry_wrapper(ccx: &CrateContext) {
665 666
    let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
        Some((id, span)) => {
667
            (ccx.tcx().hir.local_def_id(id), span)
668 669 670 671
        }
        None => return,
    };

672
    let instance = Instance::mono(ccx.tcx(), main_def_id);
673

674
    if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
675 676 677
        // We want to create the wrapper in the same codegen unit as Rust's main
        // function.
        return;
678 679
    }

680
    let main_llfn = callee::get_fn(ccx, instance);
681

E
Eduard Burtescu 已提交
682
    let et = ccx.sess().entry_type.get().unwrap();
683
    match et {
M
Mark-Simulacrum 已提交
684
        config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
685
        config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
N
Nick Cameron 已提交
686
        config::EntryNone => {}    // Do nothing.
687
    }
688

E
Eduard Burtescu 已提交
689
    fn create_entry_fn(ccx: &CrateContext,
S
Simonas Kazlauskas 已提交
690
                       sp: Span,
691 692
                       rust_main: ValueRef,
                       use_start_lang_item: bool) {
693 694
        // Signature of native main(), corresponding to C's `int main(int, char **)`
        let llfty = Type::func(&[Type::c_int(ccx), Type::i8p(ccx).ptr_to()], &Type::c_int(ccx));
K
kyeongwoon 已提交
695

696
        if declare::get_defined_value(ccx, "main").is_some() {
S
Simonas Kazlauskas 已提交
697
            // FIXME: We should be smart and show a better diagnostic here.
N
Nick Cameron 已提交
698 699 700
            ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
                      .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
                      .emit();
S
Simonas Kazlauskas 已提交
701
            ccx.sess().abort_if_errors();
702
            bug!();
703 704
        }
        let llfn = declare::declare_cfn(ccx, "main", llfty);
705

706 707 708
        // `main` should respect same config for frame pointer elimination as rest of code
        attributes::set_frame_pointer_elimination(ccx, llfn);

709
        let bld = Builder::new_block(ccx, llfn, "top");
710

M
Mark-Simulacrum 已提交
711
        debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
712

713 714 715 716 717 718
        // Params from native main() used as args for rust start function
        let param_argc = get_param(llfn, 0);
        let param_argv = get_param(llfn, 1);
        let arg_argc = bld.intcast(param_argc, ccx.isize_ty(), true);
        let arg_argv = param_argv;

M
Mark-Simulacrum 已提交
719 720
        let (start_fn, args) = if use_start_lang_item {
            let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
721 722
            let start_instance = Instance::mono(ccx.tcx(), start_def_id);
            let start_fn = callee::get_fn(ccx, start_instance);
723 724
            (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()),
                            arg_argc, arg_argv])
M
Mark-Simulacrum 已提交
725 726
        } else {
            debug!("using user-defined start fn");
727
            (rust_main, vec![arg_argc, arg_argv])
M
Mark-Simulacrum 已提交
728
        };
729

M
Mark-Simulacrum 已提交
730
        let result = bld.call(start_fn, &args, None);
731 732 733

        // Return rust start function's result from native main()
        bld.ret(bld.intcast(result, Type::c_int(ccx), true));
M
Marijn Haverbeke 已提交
734
    }
735 736
}

737
fn contains_null(s: &str) -> bool {
738
    s.bytes().any(|b| b == 0)
739 740
}

741
fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
742
                            llmod_id: &str,
743 744
                            link_meta: &LinkMeta,
                            exported_symbols: &NodeSet)
745 746
                            -> (ContextRef, ModuleRef,
                                EncodedMetadata, EncodedMetadataHashes) {
A
Alex Crichton 已提交
747 748
    use std::io::Write;
    use flate2::Compression;
749
    use flate2::write::DeflateEncoder;
750

751
    let (metadata_llcx, metadata_llmod) = unsafe {
752
        context::create_context_and_module(tcx.sess, llmod_id)
753 754
    };

N
Nicholas Nethercote 已提交
755 756 757 758 759 760 761
    #[derive(PartialEq, Eq, PartialOrd, Ord)]
    enum MetadataKind {
        None,
        Uncompressed,
        Compressed
    }

762
    let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
N
Nicholas Nethercote 已提交
763 764 765 766 767
        match *ty {
            config::CrateTypeExecutable |
            config::CrateTypeStaticlib |
            config::CrateTypeCdylib => MetadataKind::None,

768
            config::CrateTypeRlib => MetadataKind::Uncompressed,
N
Nicholas Nethercote 已提交
769 770 771 772 773 774 775

            config::CrateTypeDylib |
            config::CrateTypeProcMacro => MetadataKind::Compressed,
        }
    }).max().unwrap();

    if kind == MetadataKind::None {
776 777 778 779
        return (metadata_llcx,
                metadata_llmod,
                EncodedMetadata::new(),
                EncodedMetadataHashes::new());
780
    }
J
James Miller 已提交
781

782
    let (metadata, hashes) = tcx.encode_metadata(link_meta, exported_symbols);
N
Nicholas Nethercote 已提交
783
    if kind == MetadataKind::Uncompressed {
784
        return (metadata_llcx, metadata_llmod, metadata, hashes);
N
Nicholas Nethercote 已提交
785 786 787
    }

    assert!(kind == MetadataKind::Compressed);
788
    let mut compressed = tcx.metadata_encoding_version();
789
    DeflateEncoder::new(&mut compressed, Compression::Fast)
A
Alex Crichton 已提交
790
        .write_all(&metadata.raw_data).unwrap();
791

792 793
    let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
    let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
794
    let name = symbol_export::metadata_symbol_name(tcx);
795
    let buf = CString::new(name).unwrap();
A
Alex Crichton 已提交
796
    let llglobal = unsafe {
797
        llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
A
Alex Crichton 已提交
798
    };
799 800
    unsafe {
        llvm::LLVMSetInitializer(llglobal, llconst);
801
        let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
802 803 804 805 806 807 808 809
        let name = CString::new(section_name).unwrap();
        llvm::LLVMSetSection(llglobal, name.as_ptr());

        // Also generate a .section directive to force no
        // flags, at least for ELF outputs, so that the
        // metadata doesn't get loaded into memory.
        let directive = format!(".section {}", section_name);
        let directive = CString::new(directive).unwrap();
810
        llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
811
    }
812
    return (metadata_llcx, metadata_llmod, metadata, hashes);
813 814
}

815
pub struct ValueIter {
816 817 818
    cur: ValueRef,
    step: unsafe extern "C" fn(ValueRef) -> ValueRef,
}
819

820 821
impl Iterator for ValueIter {
    type Item = ValueRef;
822

823 824 825
    fn next(&mut self) -> Option<ValueRef> {
        let old = self.cur;
        if !old.is_null() {
826
            self.cur = unsafe { (self.step)(old) };
827 828 829 830
            Some(old)
        } else {
            None
        }
831
    }
832
}
833

834
pub fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
835 836 837 838 839 840 841
    unsafe {
        ValueIter {
            cur: llvm::LLVMGetFirstGlobal(llmod),
            step: llvm::LLVMGetNextGlobal,
        }
    }
}
J
Jorge Aparicio 已提交
842

843
pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
A
Alex Crichton 已提交
844
                             rx: mpsc::Receiver<Box<Any + Send>>)
845
                             -> OngoingCrateTranslation {
B
bjorn3 已提交
846

847 848
    check_for_rustc_errors_attr(tcx);

A
Alex Crichton 已提交
849 850 851 852 853
    if tcx.sess.opts.debugging_opts.thinlto {
        if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
            tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
        }
    }
854 855

    let crate_hash = tcx.dep_graph
856
                        .fingerprint_of(&DepNode::new_no_params(DepKind::Krate));
857
    let link_meta = link::build_link_meta(crate_hash);
858
    let exported_symbol_node_ids = find_exported_symbols(tcx);
859

A
Alex Crichton 已提交
860
    let shared_ccx = SharedCrateContext::new(tcx);
861
    // Translate the metadata.
862
    let llmod_id = "metadata";
863
    let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
864
        time(tcx.sess.time_passes(), "write metadata", || {
865
            write_metadata(tcx, llmod_id, &link_meta, &exported_symbol_node_ids)
866
        });
867 868

    let metadata_module = ModuleTranslation {
869
        name: link::METADATA_MODULE_NAME.to_string(),
870
        llmod_id: llmod_id.to_string(),
871
        source: ModuleSource::Translated(ModuleLlvm {
872 873
            llcx: metadata_llcx,
            llmod: metadata_llmod,
874
            tm: create_target_machine(tcx.sess),
875
        }),
876
        kind: ModuleKind::Metadata,
877
    };
878

879 880 881 882 883
    let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
        Some(time_graph::TimeGraph::new())
    } else {
        None
    };
884

885 886 887
    // Skip crate items and just output metadata in -Z no-trans mode.
    if tcx.sess.opts.debugging_opts.no_trans ||
       !tcx.sess.opts.output_types.should_trans() {
888
        let ongoing_translation = write::start_async_translation(
889
            tcx,
890
            time_graph.clone(),
891
            link_meta,
892
            metadata,
A
Alex Crichton 已提交
893 894
            rx,
            1);
895

A
Alex Crichton 已提交
896 897
        ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
        ongoing_translation.translation_finished(tcx);
898

899 900 901 902
        assert_and_save_dep_graph(tcx,
                                  metadata_incr_hashes,
                                  link_meta);

903 904
        ongoing_translation.check_for_errors(tcx.sess);

905
        return ongoing_translation;
906 907
    }

908 909
    // Run the translation item collector and partition the collected items into
    // codegen units.
910 911 912
    let codegen_units =
        shared_ccx.tcx().collect_and_partition_translation_items(LOCAL_CRATE).1;
    let codegen_units = (*codegen_units).clone();
913

914 915 916 917 918 919 920 921 922 923 924
    // Force all codegen_unit queries so they are already either red or green
    // when compile_codegen_unit accesses them. We are not able to re-execute
    // the codegen_unit query from just the DepNode, so an unknown color would
    // lead to having to re-execute compile_codegen_unit, possibly
    // unnecessarily.
    if tcx.dep_graph.is_fully_enabled() {
        for cgu in &codegen_units {
            tcx.codegen_unit(cgu.name().clone());
        }
    }

925
    let ongoing_translation = write::start_async_translation(
926
        tcx,
927
        time_graph.clone(),
928
        link_meta,
929
        metadata,
A
Alex Crichton 已提交
930 931
        rx,
        codegen_units.len());
932

933
    // Translate an allocator shim, if any
934
    let allocator_module = if let Some(kind) = tcx.sess.allocator_kind.get() {
935
        unsafe {
936
            let llmod_id = "allocator";
937
            let (llcx, llmod) =
938
                context::create_context_and_module(tcx.sess, llmod_id);
939
            let modules = ModuleLlvm {
940 941
                llmod,
                llcx,
942
                tm: create_target_machine(tcx.sess),
943 944 945 946 947 948 949
            };
            time(tcx.sess.time_passes(), "write allocator module", || {
                allocator::trans(tcx, &modules, kind)
            });

            Some(ModuleTranslation {
                name: link::ALLOCATOR_MODULE_NAME.to_string(),
950
                llmod_id: llmod_id.to_string(),
951 952 953 954 955 956 957 958 959
                source: ModuleSource::Translated(modules),
                kind: ModuleKind::Allocator,
            })
        }
    } else {
        None
    };

    if let Some(allocator_module) = allocator_module {
A
Alex Crichton 已提交
960
        ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
961 962
    }

A
Alex Crichton 已提交
963
    ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
964

965 966 967 968 969 970 971 972 973 974
    // We sort the codegen units by size. This way we can schedule work for LLVM
    // a bit more efficiently. Note that "size" is defined rather crudely at the
    // moment as it is just the number of TransItems in the CGU, not taking into
    // account the size of each TransItem.
    let codegen_units = {
        let mut codegen_units = codegen_units;
        codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
        codegen_units
    };

975
    let mut total_trans_time = Duration::new(0, 0);
A
Alex Crichton 已提交
976
    let mut all_stats = Stats::default();
977

A
Alex Crichton 已提交
978
    for cgu in codegen_units.into_iter() {
979
        ongoing_translation.wait_for_signal_to_translate_item();
980
        ongoing_translation.check_for_errors(tcx.sess);
981

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
        // First, if incremental compilation is enabled, we try to re-use the
        // codegen unit from the cache.
        if tcx.dep_graph.is_fully_enabled() {
            let cgu_id = cgu.work_product_id();

            // Check whether there is a previous work-product we can
            // re-use.  Not only must the file exist, and the inputs not
            // be dirty, but the hash of the symbols we will generate must
            // be the same.
            if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
                let dep_node = &DepNode::new(tcx,
                    DepConstructor::CompileCodegenUnit(cgu.name().clone()));

                // We try to mark the DepNode::CompileCodegenUnit green. If we
                // succeed it means that none of the dependencies has changed
                // and we can safely re-use.
                if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
                    // Append ".rs" to LLVM module identifier.
                    //
                    // LLVM code generator emits a ".file filename" directive
                    // for ELF backends. Value of the "filename" is set as the
                    // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
                    // crashes if the module identifier is same as other symbols
                    // such as a function name in the module.
                    // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
                    let llmod_id = format!("{}.rs", cgu.name());

                    let module = ModuleTranslation {
                        name: cgu.name().to_string(),
                        source: ModuleSource::Preexisting(buf),
                        kind: ModuleKind::Regular,
                        llmod_id,
                    };
                    tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
                    write::submit_translated_module_to_llvm(tcx, module, 0);
                    // Continue to next cgu, this one is done.
                    continue
                }
            } else {
                // This can happen if files were  deleted from the cache
                // directory for some reason. We just re-compile then.
            }
        }

1026 1027 1028 1029 1030
        let _timing_guard = time_graph.as_ref().map(|time_graph| {
            time_graph.start(write::TRANS_WORKER_TIMELINE,
                             write::TRANS_WORK_PACKAGE_KIND,
                             &format!("codegen {}", cgu.name()))
        });
1031
        let start_time = Instant::now();
A
Alex Crichton 已提交
1032 1033
        all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
        total_trans_time += start_time.elapsed();
1034
        ongoing_translation.check_for_errors(tcx.sess);
1035 1036
    }

A
Alex Crichton 已提交
1037 1038
    ongoing_translation.translation_finished(tcx);

1039 1040 1041 1042 1043 1044
    // Since the main thread is sometimes blocked during trans, we keep track
    // -Ztime-passes output manually.
    print_time_passes_entry(tcx.sess.time_passes(),
                            "translate to LLVM IR",
                            total_trans_time);

A
Alex Crichton 已提交
1045
    if tcx.sess.opts.incremental.is_some() {
1046
        assert_module_sources::assert_module_sources(tcx);
1047 1048
    }

N
Niko Matsakis 已提交
1049
    symbol_names_test::report_symbol_names(tcx);
1050

1051
    if shared_ccx.sess().trans_stats() {
1052
        println!("--- trans stats ---");
A
Alex Crichton 已提交
1053 1054 1055
        println!("n_glues_created: {}", all_stats.n_glues_created);
        println!("n_null_glues: {}", all_stats.n_null_glues);
        println!("n_real_glues: {}", all_stats.n_real_glues);
1056

A
Alex Crichton 已提交
1057 1058 1059
        println!("n_fns: {}", all_stats.n_fns);
        println!("n_inlines: {}", all_stats.n_inlines);
        println!("n_closures: {}", all_stats.n_closures);
1060
        println!("fn stats:");
A
Alex Crichton 已提交
1061 1062 1063
        all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
        for &(ref name, insns) in all_stats.fn_stats.iter() {
            println!("{} insns, {}", insns, *name);
1064
        }
J
James Miller 已提交
1065
    }
1066

1067
    if shared_ccx.sess().count_llvm_insns() {
A
Alex Crichton 已提交
1068
        for (k, v) in all_stats.llvm_insns.iter() {
A
Alex Crichton 已提交
1069
            println!("{:7} {}", *v, *k);
1070 1071 1072
        }
    }

1073
    ongoing_translation.check_for_errors(tcx.sess);
1074

1075 1076 1077
    assert_and_save_dep_graph(tcx,
                              metadata_incr_hashes,
                              link_meta);
1078
    ongoing_translation
1079
}
1080

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                       metadata_incr_hashes: EncodedMetadataHashes,
                                       link_meta: LinkMeta) {
    time(tcx.sess.time_passes(),
         "assert dep graph",
         || rustc_incremental::assert_dep_graph(tcx));

    time(tcx.sess.time_passes(),
         "serialize dep graph",
         || rustc_incremental::save_dep_graph(tcx,
                                              &metadata_incr_hashes,
                                              link_meta.crate_hash));
}

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
#[inline(never)] // give this a place in the profiler
fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
    where I: Iterator<Item=&'a TransItem<'tcx>>
{
    let mut symbols: Vec<_> = trans_items.map(|trans_item| {
        (trans_item, trans_item.symbol_name(tcx))
    }).collect();

    (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
        sym1.cmp(sym2)
    });

    for pair in (&symbols[..]).windows(2) {
        let sym1 = &pair[0].1;
        let sym2 = &pair[1].1;

        if *sym1 == *sym2 {
            let trans_item1 = pair[0].0;
            let trans_item2 = pair[1].0;

            let span1 = trans_item1.local_span(tcx);
            let span2 = trans_item2.local_span(tcx);

            // Deterministically select one of the spans for error reporting
            let span = match (span1, span2) {
                (Some(span1), Some(span2)) => {
1121
                    Some(if span1.lo().0 > span2.lo().0 {
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
                        span1
                    } else {
                        span2
                    })
                }
                (Some(span), None) |
                (None, Some(span)) => Some(span),
                _ => None
            };

            let error_message = format!("symbol `{}` is already defined", sym1);

            if let Some(span) = span {
                tcx.sess.span_fatal(span, &error_message)
            } else {
                tcx.sess.fatal(&error_message)
            }
        }
    }
}

1143 1144 1145
fn collect_and_partition_translation_items<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    cnum: CrateNum,
1146
) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
1147 1148
{
    assert_eq!(cnum, LOCAL_CRATE);
1149
    let time_passes = tcx.sess.time_passes();
1150

1151
    let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
        Some(ref s) => {
            let mode_string = s.to_lowercase();
            let mode_string = mode_string.trim();
            if mode_string == "eager" {
                TransItemCollectionMode::Eager
            } else {
                if mode_string != "lazy" {
                    let message = format!("Unknown codegen-item collection mode '{}'. \
                                           Falling back to 'lazy' mode.",
                                           mode_string);
1162
                    tcx.sess.warn(&message);
1163 1164 1165 1166 1167 1168 1169 1170
                }

                TransItemCollectionMode::Lazy
            }
        }
        None => TransItemCollectionMode::Lazy
    };

1171 1172
    let (items, inlining_map) =
        time(time_passes, "translation item collection", || {
1173
            collector::collect_crate_translation_items(tcx, collection_mode)
1174 1175
    });

1176
    assert_symbols_are_distinct(tcx, items.iter());
1177

1178
    let strategy = if tcx.sess.opts.debugging_opts.incremental.is_some() {
1179 1180
        PartitioningStrategy::PerModule
    } else {
1181
        PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
1182 1183
    };

1184
    let codegen_units = time(time_passes, "codegen unit partitioning", || {
1185
        partitioning::partition(tcx,
1186 1187
                                items.iter().cloned(),
                                strategy,
1188
                                &inlining_map)
1189 1190 1191
            .into_iter()
            .map(Arc::new)
            .collect::<Vec<_>>()
1192 1193
    });

1194 1195 1196 1197 1198 1199
    let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
        match *trans_item {
            TransItem::Fn(ref instance) => Some(instance.def_id()),
            _ => None,
        }
    }).collect();
1200

1201
    if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1202
        let mut item_to_cgus = FxHashMap();
1203

1204
        for cgu in &codegen_units {
1205
            for (&trans_item, &linkage) in cgu.items() {
1206 1207
                item_to_cgus.entry(trans_item)
                            .or_insert(Vec::new())
1208
                            .push((cgu.name().clone(), linkage));
1209 1210 1211 1212 1213 1214
            }
        }

        let mut item_keys: Vec<_> = items
            .iter()
            .map(|i| {
1215
                let mut output = i.to_string(tcx);
1216 1217
                output.push_str(" @@");
                let mut empty = Vec::new();
1218
                let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1219 1220
                cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
                cgus.dedup();
1221
                for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1222
                    output.push_str(" ");
1223
                    output.push_str(&cgu_name);
1224 1225

                    let linkage_abbrev = match linkage {
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
                        Linkage::External => "External",
                        Linkage::AvailableExternally => "Available",
                        Linkage::LinkOnceAny => "OnceAny",
                        Linkage::LinkOnceODR => "OnceODR",
                        Linkage::WeakAny => "WeakAny",
                        Linkage::WeakODR => "WeakODR",
                        Linkage::Appending => "Appending",
                        Linkage::Internal => "Internal",
                        Linkage::Private => "Private",
                        Linkage::ExternalWeak => "ExternalWeak",
                        Linkage::Common => "Common",
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
                    };

                    output.push_str("[");
                    output.push_str(linkage_abbrev);
                    output.push_str("]");
                }
                output
            })
            .collect();

1247 1248 1249 1250 1251 1252
        item_keys.sort();

        for item in item_keys {
            println!("TRANS_ITEM {}", item);
        }
    }
1253

1254
    (Arc::new(translation_items), Arc::new(codegen_units))
1255
}
1256 1257

impl CrateInfo {
1258
    pub fn new(tcx: TyCtxt) -> CrateInfo {
1259 1260 1261 1262 1263 1264
        let mut info = CrateInfo {
            panic_runtime: None,
            compiler_builtins: None,
            profiler_runtime: None,
            sanitizer_runtime: None,
            is_no_builtins: FxHashSet(),
1265
            native_libraries: FxHashMap(),
1266 1267
            used_libraries: tcx.native_libraries(LOCAL_CRATE),
            link_args: tcx.link_args(LOCAL_CRATE),
1268
            crate_name: FxHashMap(),
1269 1270 1271
            used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
            used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
            used_crate_source: FxHashMap(),
1272 1273
        };

1274
        for &cnum in tcx.crates().iter() {
1275
            info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1276
            info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1277
            info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
            if tcx.is_panic_runtime(cnum) {
                info.panic_runtime = Some(cnum);
            }
            if tcx.is_compiler_builtins(cnum) {
                info.compiler_builtins = Some(cnum);
            }
            if tcx.is_profiler_runtime(cnum) {
                info.profiler_runtime = Some(cnum);
            }
            if tcx.is_sanitizer_runtime(cnum) {
                info.sanitizer_runtime = Some(cnum);
            }
            if tcx.is_no_builtins(cnum) {
                info.is_no_builtins.insert(cnum);
            }
        }

1295

1296 1297 1298
        return info
    }
}
1299

1300
fn is_translated_function(tcx: TyCtxt, id: DefId) -> bool {
1301 1302 1303
    let (all_trans_items, _) =
        tcx.collect_and_partition_translation_items(LOCAL_CRATE);
    all_trans_items.contains(&id)
1304 1305
}

A
Alex Crichton 已提交
1306 1307
fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                  cgu: InternedString) -> Stats {
1308
    let cgu = tcx.codegen_unit(cgu);
A
Alex Crichton 已提交
1309 1310

    let start_time = Instant::now();
1311
    let (stats, module) = module_translation(tcx, cgu);
A
Alex Crichton 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    let time_to_translate = start_time.elapsed();

    // We assume that the cost to run LLVM on a CGU is proportional to
    // the time we needed for translating it.
    let cost = time_to_translate.as_secs() * 1_000_000_000 +
               time_to_translate.subsec_nanos() as u64;

    write::submit_translated_module_to_llvm(tcx,
                                            module,
                                            cost);
    return stats;

    fn module_translation<'a, 'tcx>(
1325 1326
        tcx: TyCtxt<'a, 'tcx, 'tcx>,
        cgu: Arc<CodegenUnit<'tcx>>)
A
Alex Crichton 已提交
1327 1328 1329 1330
        -> (Stats, ModuleTranslation)
    {
        let cgu_name = cgu.name().to_string();

1331 1332 1333 1334 1335 1336 1337 1338
        // Append ".rs" to LLVM module identifier.
        //
        // LLVM code generator emits a ".file filename" directive
        // for ELF backends. Value of the "filename" is set as the
        // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
        // crashes if the module identifier is same as other symbols
        // such as a function name in the module.
        // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
A
Alex Crichton 已提交
1339 1340 1341
        let llmod_id = format!("{}-{}.rs",
                               cgu.name(),
                               tcx.crate_disambiguator(LOCAL_CRATE));
1342

A
Alex Crichton 已提交
1343 1344
        // Instantiate translation items without filling out definitions yet...
        let scx = SharedCrateContext::new(tcx);
1345
        let lcx = LocalCrateContext::new(&scx, cgu, &llmod_id);
A
Alex Crichton 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
        let module = {
            let ccx = CrateContext::new(&scx, &lcx);
            let trans_items = ccx.codegen_unit()
                                 .items_in_deterministic_order(ccx.tcx());
            for &(trans_item, (linkage, visibility)) in &trans_items {
                trans_item.predefine(&ccx, linkage, visibility);
            }

            // ... and now that we have everything pre-defined, fill out those definitions.
            for &(trans_item, _) in &trans_items {
                trans_item.define(&ccx);
            }

            // If this codegen unit contains the main function, also create the
            // wrapper here
            maybe_create_entry_wrapper(&ccx);

            // Run replace-all-uses-with for statics that need it
            for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
                unsafe {
                    let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
                    llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
                    llvm::LLVMDeleteGlobal(old_g);
                }
            }

            // Create the llvm.used variable
            // This variable has type [N x i8*] and is stored in the llvm.metadata section
            if !ccx.used_statics().borrow().is_empty() {
                let name = CString::new("llvm.used").unwrap();
                let section = CString::new("llvm.metadata").unwrap();
                let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());

                unsafe {
                    let g = llvm::LLVMAddGlobal(ccx.llmod(),
                                                val_ty(array).to_ref(),
                                                name.as_ptr());
                    llvm::LLVMSetInitializer(g, array);
                    llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
                    llvm::LLVMSetSection(g, section.as_ptr());
                }
            }

            // Finalize debuginfo
            if ccx.sess().opts.debuginfo != NoDebugInfo {
                debuginfo::finalize(&ccx);
            }

            let llvm_module = ModuleLlvm {
                llcx: ccx.llcx(),
                llmod: ccx.llmod(),
1397
                tm: create_target_machine(ccx.sess()),
A
Alex Crichton 已提交
1398 1399 1400 1401 1402 1403
            };

            ModuleTranslation {
                name: cgu_name,
                source: ModuleSource::Translated(llvm_module),
                kind: ModuleKind::Regular,
1404
                llmod_id,
A
Alex Crichton 已提交
1405 1406 1407 1408 1409 1410 1411
            }
        };

        (lcx.into_stats(), module)
    }
}

1412
pub fn provide_local(providers: &mut Providers) {
1413 1414
    providers.collect_and_partition_translation_items =
        collect_and_partition_translation_items;
1415 1416

    providers.is_translated_function = is_translated_function;
A
Alex Crichton 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425

    providers.codegen_unit = |tcx, name| {
        let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
        all.iter()
            .find(|cgu| *cgu.name() == name)
            .cloned()
            .expect(&format!("failed to find cgu with name {:?}", name))
    };
    providers.compile_codegen_unit = compile_codegen_unit;
1426 1427 1428 1429
}

pub fn provide_extern(providers: &mut Providers) {
    providers.is_translated_function = is_translated_function;
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
}

pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
    match linkage {
        Linkage::External => llvm::Linkage::ExternalLinkage,
        Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
        Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
        Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
        Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
        Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
        Linkage::Appending => llvm::Linkage::AppendingLinkage,
        Linkage::Internal => llvm::Linkage::InternalLinkage,
        Linkage::Private => llvm::Linkage::PrivateLinkage,
        Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
        Linkage::Common => llvm::Linkage::CommonLinkage,
    }
}

pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
    match linkage {
        Visibility::Default => llvm::Visibility::Default,
        Visibility::Hidden => llvm::Visibility::Hidden,
        Visibility::Protected => llvm::Visibility::Protected,
1453
    }
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
}

// FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
//            the HashStable trait. Normally DepGraph::with_task() calls are
//            hidden behind queries, but CGU creation is a special case in two
//            ways: (1) it's not a query and (2) CGU are output nodes, so their
//            Fingerprints are not actually needed. It remains to be clarified
//            how exactly this case will be handled in the red/green system but
//            for now we content ourselves with providing a no-op HashStable
//            implementation for CGUs.
mod temp_stable_hash_impls {
    use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
                                               HashStable};
    use ModuleTranslation;

    impl<HCX> HashStable<HCX> for ModuleTranslation {
        fn hash_stable<W: StableHasherResult>(&self,
                                              _: &mut HCX,
                                              _: &mut StableHasher<W>) {
            // do nothing
        }
1475 1476
    }
}