rust/src/lib.rs

406 lines
14 KiB
Rust
Raw Normal View History

#![feature(rustc_private, macro_at_most_once_rep, iterator_find_map)]
#![allow(intra_doc_link_resolution_failure)]
2018-06-17 11:05:11 -05:00
extern crate syntax;
2018-06-18 11:39:07 -05:00
#[macro_use]
2018-06-17 11:05:11 -05:00
extern crate rustc;
extern crate rustc_codegen_utils;
extern crate rustc_incremental;
extern crate rustc_mir;
extern crate rustc_target;
2018-07-24 07:10:53 -05:00
#[macro_use]
2018-06-17 11:05:11 -05:00
extern crate rustc_data_structures;
2018-07-24 07:10:53 -05:00
extern crate ar;
2018-08-09 03:46:56 -05:00
#[macro_use]
extern crate bitflags;
2018-07-24 07:10:53 -05:00
extern crate faerie;
//extern crate goblin;
2018-07-14 04:59:42 -05:00
extern crate cranelift;
extern crate cranelift_faerie;
2018-07-14 04:59:42 -05:00
extern crate cranelift_module;
extern crate cranelift_simplejit;
extern crate target_lexicon;
2018-07-23 04:17:39 -05:00
use std::any::Any;
use std::fs::File;
use std::sync::{mpsc, Arc};
2018-06-17 11:05:11 -05:00
use rustc::dep_graph::DepGraph;
use rustc::middle::cstore::MetadataLoader;
2018-08-11 08:05:57 -05:00
use rustc::session::{config::OutputFilenames, CompileIncomplete};
2018-06-23 11:26:54 -05:00
use rustc::ty::query::Providers;
2018-07-23 04:17:39 -05:00
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc_codegen_utils::link::{build_link_meta, out_filename};
use rustc_data_structures::svh::Svh;
use syntax::symbol::Symbol;
2018-06-17 11:05:11 -05:00
2018-07-23 04:17:39 -05:00
use cranelift::codegen::settings;
use cranelift_faerie::*;
2018-06-17 11:05:11 -05:00
2018-08-08 08:38:03 -05:00
struct NonFatal(pub String);
macro_rules! unimpl {
($($tt:tt)*) => {
panic!(crate::NonFatal(format!($($tt)*)));
2018-08-08 08:38:03 -05:00
};
}
macro_rules! each_module {
($cx:expr, |$p:pat| $res:expr) => {
ModuleTup {
jit: $cx.jit.as_mut().map(|$p| $res),
faerie: $cx.faerie.as_mut().map(|$p| $res),
}
};
}
2018-07-19 12:33:42 -05:00
mod abi;
2018-08-09 03:46:56 -05:00
mod analyze;
2018-06-17 11:05:11 -05:00
mod base;
2018-06-22 12:18:53 -05:00
mod common;
mod constant;
2018-07-14 04:59:42 -05:00
mod pretty_clif;
2018-08-15 05:07:08 -05:00
mod metadata;
2018-06-17 11:05:11 -05:00
mod prelude {
2018-06-30 09:37:02 -05:00
pub use std::any::Any;
2018-07-16 08:13:37 -05:00
pub use std::collections::{HashMap, HashSet};
2018-06-22 12:18:53 -05:00
2018-06-17 11:05:11 -05:00
pub use rustc::hir::def_id::{DefId, LOCAL_CRATE};
2018-06-23 11:26:54 -05:00
pub use rustc::mir;
2018-07-16 08:13:37 -05:00
pub use rustc::mir::interpret::AllocId;
pub use rustc::mir::*;
2018-08-11 08:05:57 -05:00
pub use rustc::session::{config::CrateType, Session};
pub use rustc::ty::layout::{self, LayoutOf, Size, TyLayout};
2018-06-23 11:54:15 -05:00
pub use rustc::ty::{
self, subst::Substs, FnSig, Instance, InstanceDef, ParamEnv, PolyFnSig, Ty, TyCtxt,
TypeAndMut, TypeFoldable, TypeVariants,
2018-06-17 11:05:11 -05:00
};
2018-08-13 11:04:39 -05:00
pub use rustc_data_structures::{fx::FxHashMap, indexed_vec::Idx, sync::Lrc};
pub use rustc_mir::monomorphize::{collector, MonoItem};
pub use syntax::ast::{FloatTy, IntTy, UintTy};
pub use syntax::codemap::DUMMY_SP;
2018-06-22 12:18:53 -05:00
2018-07-14 04:59:42 -05:00
pub use cranelift::codegen::ir::{
condcodes::IntCC, function::Function, ExternalName, FuncRef, Inst, StackSlot,
2018-06-22 12:18:53 -05:00
};
2018-07-14 04:59:42 -05:00
pub use cranelift::codegen::Context;
pub use cranelift::prelude::*;
pub use cranelift_module::{
Backend, DataContext, DataId, FuncId, Linkage, Module, Writability,
};
pub use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
2018-06-22 12:18:53 -05:00
pub use crate::abi::*;
pub use crate::base::{trans_operand, trans_place};
pub use crate::common::*;
2018-06-30 09:37:02 -05:00
pub use crate::{CodegenCx, ModuleTup};
2018-08-14 05:13:07 -05:00
pub fn should_codegen(sess: &Session) -> bool {
2018-08-14 05:13:07 -05:00
::std::env::var("SHOULD_CODEGEN").is_ok()
|| sess.crate_types.get().contains(&CrateType::Executable)
2018-08-14 05:13:07 -05:00
}
2018-06-17 11:05:11 -05:00
}
use crate::constant::ConstantCx;
use crate::prelude::*;
2018-06-17 11:05:11 -05:00
pub struct CodegenCx<'a, 'tcx: 'a> {
2018-06-30 09:37:02 -05:00
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub jit: Option<(ConstantCx, &'a mut Module<SimpleJITBackend>)>,
pub faerie: Option<(ConstantCx, &'a mut Module<FaerieBackend>)>,
pub defined_functions: Vec<FuncId>,
2018-08-14 11:52:43 -05:00
// Cache
pub context: Context,
2018-06-30 09:37:02 -05:00
}
pub struct ModuleTup<T> {
jit: Option<T>,
#[allow(dead_code)]
faerie: Option<T>,
}
2018-07-23 04:17:39 -05:00
struct CraneliftCodegenBackend;
struct OngoingCodegen {
2018-07-24 07:10:53 -05:00
product: cranelift_faerie::FaerieProduct,
metadata: Vec<u8>,
2018-07-23 04:17:39 -05:00
crate_name: Symbol,
crate_hash: Svh,
2018-07-23 04:17:39 -05:00
}
2018-07-14 04:59:42 -05:00
impl CodegenBackend for CraneliftCodegenBackend {
2018-06-17 11:05:11 -05:00
fn init(&self, sess: &Session) {
for cty in sess.opts.crate_types.iter() {
match *cty {
2018-08-07 09:43:09 -05:00
CrateType::Rlib | CrateType::Dylib | CrateType::Executable => {}
2018-06-17 11:05:11 -05:00
_ => {
sess.err(&format!(
"Rustc codegen cranelift doesn't support output type {}",
cty
));
}
2018-06-17 11:05:11 -05:00
}
}
}
fn metadata_loader(&self) -> Box<MetadataLoader + Sync> {
2018-08-15 05:07:08 -05:00
Box::new(crate::metadata::CraneliftMetadataLoader)
2018-06-17 11:05:11 -05:00
}
fn provide(&self, providers: &mut Providers) {
rustc_codegen_utils::symbol_names::provide(providers);
providers.target_features_whitelist = |_tcx, _cnum| Lrc::new(Default::default());
2018-06-17 11:05:11 -05:00
providers.is_reachable_non_generic = |_tcx, _defid| true;
providers.exported_symbols = |_tcx, _crate| Arc::new(Vec::new());
providers.upstream_monomorphizations = |_tcx, _cnum| Lrc::new(FxHashMap());
providers.upstream_monomorphizations_for = |tcx, def_id| {
debug_assert!(!def_id.is_local());
tcx.upstream_monomorphizations(LOCAL_CRATE)
.get(&def_id)
.cloned()
};
2018-06-17 11:05:11 -05:00
}
fn provide_extern(&self, providers: &mut Providers) {
providers.is_reachable_non_generic = |_tcx, _defid| true;
}
fn codegen_crate<'a, 'tcx>(
&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
_rx: mpsc::Receiver<Box<Any + Send>>,
2018-06-17 11:05:11 -05:00
) -> Box<Any> {
use rustc_mir::monomorphize::item::MonoItem;
rustc_codegen_utils::check_for_rustc_errors_attr(tcx);
rustc_codegen_utils::symbol_names_test::report_symbol_names(tcx);
rustc_incremental::assert_dep_graph(tcx);
rustc_incremental::assert_module_sources::assert_module_sources(tcx);
rustc_mir::monomorphize::assert_symbols_are_distinct(
tcx,
collector::collect_crate_mono_items(tcx, collector::MonoItemCollectionMode::Eager)
.0
.iter(),
2018-06-17 11:05:11 -05:00
);
//::rustc::middle::dependency_format::calculate(tcx);
let _ = tcx.link_args(LOCAL_CRATE);
let _ = tcx.native_libraries(LOCAL_CRATE);
for mono_item in
collector::collect_crate_mono_items(tcx, collector::MonoItemCollectionMode::Eager).0
{
2018-06-17 11:05:11 -05:00
match mono_item {
MonoItem::Fn(inst) => {
let def_id = inst.def_id();
if def_id.is_local() {
2018-06-17 11:05:11 -05:00
let _ = inst.def.is_inline(tcx);
let _ = tcx.codegen_fn_attrs(def_id);
}
}
_ => {}
}
}
if !tcx.sess.crate_types.get().contains(&CrateType::Executable)
&& std::env::var("SHOULD_RUN").is_ok()
{
tcx.sess
.err("Can't JIT run non executable (SHOULD_RUN env var is set)");
}
2018-06-17 11:05:11 -05:00
tcx.sess.abort_if_errors();
let link_meta = build_link_meta(tcx.crate_hash(LOCAL_CRATE));
2018-06-30 09:37:02 -05:00
let metadata = tcx.encode_metadata(&link_meta);
2018-07-23 04:17:39 -05:00
let mut flags_builder = settings::builder();
flags_builder.enable("is_pic").unwrap();
let flags = settings::Flags::new(flags_builder);
let isa = cranelift::codegen::isa::lookup(target_lexicon::Triple::host())
.unwrap()
.finish(flags);
2018-08-14 11:52:43 -05:00
let mut jit_module: Module<SimpleJITBackend> = Module::new(SimpleJITBuilder::new());
let mut faerie_module: Module<FaerieBackend> = Module::new(
FaerieBuilder::new(
isa,
"some_file.o".to_string(),
FaerieTrapCollection::Disabled,
FaerieBuilder::default_libcall_names(),
).unwrap(),
);
2018-06-30 09:37:02 -05:00
let defined_functions = {
2018-08-09 08:30:26 -05:00
use std::io::Write;
2018-06-30 09:37:02 -05:00
let mut cx = CodegenCx {
tcx,
jit: Some((ConstantCx::default(), &mut jit_module)),
faerie: Some((ConstantCx::default(), &mut faerie_module)),
defined_functions: Vec::new(),
2018-08-14 11:52:43 -05:00
context: Context::new(),
2018-06-30 09:37:02 -05:00
};
let mut log = ::std::fs::File::create("log.txt").unwrap();
2018-08-09 08:30:26 -05:00
2018-08-11 08:21:26 -05:00
let before = ::std::time::Instant::now();
2018-08-13 11:04:39 -05:00
let mono_items =
collector::collect_crate_mono_items(tcx, collector::MonoItemCollectionMode::Eager)
.0;
// TODO: move to the end of this function when compiling libcore doesn't have unimplemented stuff anymore
save_incremental(tcx);
tcx.sess.warn("Saved incremental data");
for mono_item in mono_items {
2018-08-08 08:38:03 -05:00
let cx = &mut cx;
let res = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(move || {
2018-08-14 11:52:43 -05:00
base::trans_mono_item(cx, mono_item);
2018-08-08 08:38:03 -05:00
}));
if let Err(err) = res {
match err.downcast::<NonFatal>() {
2018-08-09 08:30:26 -05:00
Ok(non_fatal) => {
writeln!(log, "{}", &non_fatal.0);
tcx.sess.err(&non_fatal.0)
}
2018-08-08 08:38:03 -05:00
Err(err) => ::std::panic::resume_unwind(err),
}
}
2018-06-30 09:37:02 -05:00
}
match cx {
CodegenCx {
tcx,
jit,
faerie,
defined_functions: _,
context: _,
} => {
jit.map(|jit| jit.0.finalize(tcx, jit.1));
faerie.map(|faerie| faerie.0.finalize(tcx, faerie.1));
}
}
2018-08-11 08:21:26 -05:00
let after = ::std::time::Instant::now();
println!("time: {:?}", after - before);
2018-08-11 06:59:34 -05:00
cx.defined_functions
};
2018-06-30 09:37:02 -05:00
tcx.sess.abort_if_errors();
2018-06-30 09:37:02 -05:00
tcx.sess.warn("Compiled everything");
// TODO: this doesn't work most of the time
if std::env::var("SHOULD_RUN").is_ok() {
tcx.sess.warn("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
2018-08-11 08:05:57 -05:00
let start_wrapper = tcx.lang_items().start_fn().expect("no start lang item");
2018-08-11 08:05:57 -05:00
let (name, sig) =
crate::abi::get_function_name_and_sig(tcx, Instance::mono(tcx, start_wrapper));
2018-08-14 11:52:43 -05:00
let called_func_id = jit_module
.declare_function(&name, Linkage::Import, &sig)
.unwrap();
for func_id in defined_functions {
if func_id != called_func_id {
2018-08-14 11:52:43 -05:00
jit_module.finalize_function(func_id);
}
2018-06-30 09:37:02 -05:00
}
tcx.sess.warn("Finalized everything");
2018-08-14 11:52:43 -05:00
let finalized_function: *const u8 = jit_module.finalize_function(called_func_id);
2018-08-11 08:05:57 -05:00
let f: extern "C" fn(*const u8, isize, *const *const u8) -> isize =
unsafe { ::std::mem::transmute(finalized_function) };
2018-08-11 08:05:57 -05:00
let res = f(0 as *const u8, 0, 0 as *const _);
tcx.sess.warn(&format!("main returned {}", res));
2018-06-30 09:37:02 -05:00
2018-08-14 11:52:43 -05:00
jit_module.finish();
::std::process::exit(0);
} else if should_codegen(tcx.sess) {
jit_module.finalize_all();
faerie_module.finalize_all();
2018-08-14 05:13:07 -05:00
tcx.sess.warn("Finalized everything");
}
2018-06-30 09:37:02 -05:00
Box::new(OngoingCodegen {
2018-08-14 11:52:43 -05:00
product: faerie_module.finish(),
2018-07-24 07:10:53 -05:00
metadata: metadata.raw_data,
2018-06-30 09:37:02 -05:00
crate_name: tcx.crate_name(LOCAL_CRATE),
crate_hash: tcx.crate_hash(LOCAL_CRATE),
2018-06-30 09:37:02 -05:00
})
2018-06-17 11:05:11 -05:00
}
fn join_codegen_and_link(
&self,
ongoing_codegen: Box<Any>,
sess: &Session,
_dep_graph: &DepGraph,
outputs: &OutputFilenames,
) -> Result<(), CompileIncomplete> {
let ongoing_codegen = *ongoing_codegen
.downcast::<OngoingCodegen>()
2018-07-23 04:17:39 -05:00
.expect("Expected CraneliftCodegenBackend's OngoingCodegen, found Box<Any>");
2018-07-24 07:10:53 -05:00
let mut artifact = ongoing_codegen.product.artifact;
let metadata = ongoing_codegen.metadata;
let metadata_name = ".rustc.clif_metadata".to_string() + &ongoing_codegen.crate_hash.to_string();
artifact
.declare_with(
&metadata_name,
faerie::artifact::Decl::Data {
global: true,
writeable: false,
},
metadata.clone(),
).unwrap();
2018-07-24 07:10:53 -05:00
2018-06-17 11:05:11 -05:00
for &crate_type in sess.opts.crate_types.iter() {
2018-08-11 08:05:57 -05:00
match crate_type {
// TODO: link executable
CrateType::Executable | CrateType::Rlib => {
2018-08-11 08:05:57 -05:00
let output_name = out_filename(
sess,
crate_type,
&outputs,
&ongoing_codegen.crate_name.as_str(),
);
let file = File::create(&output_name).unwrap();
let mut builder = ar::Builder::new(file);
builder
.append(
&ar::Header::new(metadata_name.as_bytes().to_vec(), metadata.len() as u64),
2018-08-11 08:05:57 -05:00
::std::io::Cursor::new(metadata.clone()),
).unwrap();
if should_codegen(sess) {
let obj = artifact.emit().unwrap();
builder
.append(
&ar::Header::new(b"data.o".to_vec(), obj.len() as u64),
::std::io::Cursor::new(obj),
).unwrap();
}
2018-08-11 08:05:57 -05:00
}
_ => sess.fatal(&format!("Unsupported crate type: {:?}", crate_type)),
2018-06-17 11:05:11 -05:00
}
}
Ok(())
}
}
fn save_incremental<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
rustc_incremental::assert_dep_graph(tcx);
rustc_incremental::save_dep_graph(tcx);
rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE));
}
2018-07-14 04:59:42 -05:00
/// This is the entrypoint for a hot plugged rustc_codegen_cranelift
2018-06-17 11:05:11 -05:00
#[no_mangle]
pub fn __rustc_codegen_backend() -> Box<CodegenBackend> {
2018-07-23 04:17:39 -05:00
Box::new(CraneliftCodegenBackend)
2018-06-18 11:39:07 -05:00
}