4 use std::os::raw::{c_char, c_int};
6 use rustc::middle::cstore::EncodedMetadata;
7 use rustc::mir::mono::{Linkage as RLinkage, Visibility};
8 use rustc::session::config::{DebugInfo, OutputType};
9 use rustc_codegen_ssa::back::linker::LinkerInfo;
10 use rustc_codegen_ssa::CrateInfo;
12 use cranelift_faerie::*;
14 use crate::prelude::*;
16 pub fn codegen_crate<'a, 'tcx>(
17 tcx: TyCtxt<'tcx, 'tcx>,
18 metadata: EncodedMetadata,
19 need_metadata_module: bool,
21 if !tcx.sess.crate_types.get().contains(&CrateType::Executable)
22 && std::env::var("SHOULD_RUN").is_ok()
25 .err("Can't JIT run non executable (SHOULD_RUN env var is set)");
28 tcx.sess.abort_if_errors();
30 let mut log = if cfg!(debug_assertions) {
31 Some(File::create(concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/log.txt")).unwrap())
36 if std::env::var("SHOULD_RUN").is_ok() {
37 #[cfg(not(target_arch = "wasm32"))]
38 let _: ! = run_jit(tcx, &mut log);
40 #[cfg(target_arch = "wasm32")]
41 panic!("jit not supported on wasm");
44 run_aot(tcx, metadata, need_metadata_module, &mut log)
47 #[cfg(not(target_arch = "wasm32"))]
48 fn run_jit<'a, 'tcx: 'a>(tcx: TyCtxt<'tcx, 'tcx>, log: &mut Option<File>) -> ! {
49 use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
51 let mut jit_module: Module<SimpleJITBackend> = Module::new(SimpleJITBuilder::new(
52 cranelift_module::default_libcall_names(),
54 assert_eq!(pointer_ty(tcx), jit_module.target_config().pointer_type());
58 AbiParam::new(jit_module.target_config().pointer_type()),
59 AbiParam::new(jit_module.target_config().pointer_type()),
61 returns: vec![AbiParam::new(
62 jit_module.target_config().pointer_type(), /*isize*/
64 call_conv: CallConv::SystemV,
66 let main_func_id = jit_module
67 .declare_function("main", Linkage::Import, &sig)
70 codegen_cgus(tcx, &mut jit_module, &mut None, log);
71 crate::allocator::codegen(tcx.sess, &mut jit_module);
72 jit_module.finalize_definitions();
74 tcx.sess.abort_if_errors();
76 let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
78 println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
80 let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
81 unsafe { ::std::mem::transmute(finalized_main) };
83 let args = ::std::env::var("JIT_ARGS").unwrap_or_else(|_| String::new());
86 .chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
87 .map(|arg| CString::new(arg).unwrap())
89 let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
90 // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
92 let ret = f(args.len() as c_int, argv.as_ptr());
95 std::process::exit(ret);
98 fn run_aot<'a, 'tcx: 'a>(
99 tcx: TyCtxt<'tcx, 'tcx>,
100 metadata: EncodedMetadata,
101 need_metadata_module: bool,
102 log: &mut Option<File>,
103 ) -> Box<CodegenResults> {
104 let new_module = |name: String| {
105 let module: Module<FaerieBackend> = Module::new(
107 crate::build_isa(tcx.sess),
109 FaerieTrapCollection::Disabled,
110 cranelift_module::default_libcall_names(),
114 assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
118 let emit_module = |name: &str,
120 mut module: Module<FaerieBackend>,
121 debug: Option<DebugContext>| {
122 module.finalize_definitions();
123 let mut artifact = module.finish().artifact;
125 if let Some(mut debug) = debug {
126 debug.emit(&mut artifact);
130 .output_filenames(LOCAL_CRATE)
131 .temp_path(OutputType::Object, Some(name));
132 let obj = artifact.emit().unwrap();
133 std::fs::write(&tmp_file, obj).unwrap();
135 name: name.to_string(),
137 object: Some(tmp_file),
139 bytecode_compressed: None,
143 let mut faerie_module = new_module("some_file".to_string());
145 let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None
146 // macOS debuginfo doesn't work yet (see #303)
147 && !tcx.sess.target.target.options.is_like_osx
149 let debug = DebugContext::new(
151 faerie_module.target_config().pointer_type().bytes() as u8,
158 codegen_cgus(tcx, &mut faerie_module, &mut debug, log);
160 tcx.sess.abort_if_errors();
162 let mut allocator_module = new_module("allocator_shim.o".to_string());
163 let created_alloc_shim = crate::allocator::codegen(tcx.sess, &mut allocator_module);
165 rustc_incremental::assert_dep_graph(tcx);
166 rustc_incremental::save_dep_graph(tcx);
167 rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE));
169 let metadata_module = if need_metadata_module {
170 use rustc::mir::mono::CodegenUnitNameBuilder;
172 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
173 let metadata_cgu_name = cgu_name_builder
174 .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
178 let mut metadata_artifact =
179 faerie::Artifact::new(crate::build_isa(tcx.sess).triple().clone(), metadata_cgu_name.clone());
180 crate::metadata::write_metadata(tcx, &mut metadata_artifact);
183 .output_filenames(LOCAL_CRATE)
184 .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
186 let obj = metadata_artifact.emit().unwrap();
187 std::fs::write(&tmp_file, obj).unwrap();
189 Some(CompiledModule {
190 name: metadata_cgu_name,
191 kind: ModuleKind::Metadata,
192 object: Some(tmp_file),
194 bytecode_compressed: None,
200 Box::new(CodegenResults {
201 crate_name: tcx.crate_name(LOCAL_CRATE),
202 modules: vec![emit_module(
208 allocator_module: if created_alloc_shim {
211 ModuleKind::Allocator,
219 crate_hash: tcx.crate_hash(LOCAL_CRATE),
221 windows_subsystem: None, // Windows is not yet supported
222 linker_info: LinkerInfo::new(tcx),
223 crate_info: CrateInfo::new(tcx),
227 fn codegen_cgus<'a, 'tcx: 'a>(
228 tcx: TyCtxt<'tcx, 'tcx>,
229 module: &mut Module<impl Backend + 'static>,
230 debug: &mut Option<DebugContext<'tcx>>,
231 log: &mut Option<File>,
233 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
234 let mono_items = cgus
236 .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
238 .collect::<FxHashMap<_, (_, _)>>();
240 codegen_mono_items(tcx, module, debug.as_mut(), log, mono_items);
242 crate::main_shim::maybe_create_entry_wrapper(tcx, module);
245 fn codegen_mono_items<'a, 'tcx: 'a>(
246 tcx: TyCtxt<'tcx, 'tcx>,
247 module: &mut Module<impl Backend + 'static>,
248 debug_context: Option<&mut DebugContext<'tcx>>,
249 log: &mut Option<File>,
250 mono_items: FxHashMap<MonoItem<'tcx>, (RLinkage, Visibility)>,
252 let mut cx = CodegenCx::new(tcx, module, debug_context);
253 time("codegen mono items", move || {
254 for (mono_item, (linkage, visibility)) in mono_items {
255 crate::unimpl::try_unimpl(tcx, log, || {
256 let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
257 trans_mono_item(&mut cx, mono_item, linkage);
265 fn trans_mono_item<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
266 cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
267 mono_item: MonoItem<'tcx>,
272 MonoItem::Fn(inst) => {
274 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
275 debug_assert!(!inst.substs.needs_infer());
276 let _mir_guard = PrintOnPanic(|| {
279 | InstanceDef::DropGlue(_, _)
280 | InstanceDef::Virtual(_, _) => {
281 let mut mir = ::std::io::Cursor::new(Vec::new());
282 crate::rustc_mir::util::write_mir_pretty(
288 String::from_utf8(mir.into_inner()).unwrap()
291 // FIXME fix write_mir_pretty for these instances
292 format!("{:#?}", tcx.instance_mir(inst.def))
297 crate::base::trans_fn(cx, inst, linkage);
299 MonoItem::Static(def_id) => {
300 crate::constant::codegen_static(&mut cx.ccx, def_id);
302 MonoItem::GlobalAsm(node_id) => tcx
304 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
308 fn time<R>(name: &str, f: impl FnOnce() -> R) -> R {
309 println!("[{}] start", name);
310 let before = std::time::Instant::now();
312 let after = std::time::Instant::now();
313 println!("[{}] end time: {:?}", name, after - before);