]> git.lizzy.rs Git - rust.git/blob - src/main_shim.rs
Rustup to rustc 1.54.0-nightly (881c1ac40 2021-05-08)
[rust.git] / src / main_shim.rs
1 use cranelift_codegen::binemit::{NullStackMapSink, NullTrapSink};
2 use rustc_hir::LangItem;
3 use rustc_middle::ty::subst::GenericArg;
4 use rustc_middle::ty::AssocKind;
5 use rustc_session::config::EntryFnType;
6 use rustc_span::symbol::Ident;
7
8 use crate::prelude::*;
9
10 /// Create the `main` function which will initialize the rust runtime and call
11 /// users main function.
12 pub(crate) fn maybe_create_entry_wrapper(
13     tcx: TyCtxt<'_>,
14     module: &mut impl Module,
15     unwind_context: &mut UnwindContext,
16     is_jit: bool,
17 ) {
18     let (main_def_id, is_main_fn) = match tcx.entry_fn(LOCAL_CRATE) {
19         Some((def_id, entry_ty)) => (
20             def_id,
21             match entry_ty {
22                 EntryFnType::Main => true,
23                 EntryFnType::Start => false,
24             },
25         ),
26         None => return,
27     };
28
29     let instance = Instance::mono(tcx, main_def_id).polymorphize(tcx);
30     if !is_jit && module.get_name(&*tcx.symbol_name(instance).name).is_none() {
31         return;
32     }
33
34     create_entry_fn(tcx, module, unwind_context, main_def_id, is_jit, is_main_fn);
35
36     fn create_entry_fn(
37         tcx: TyCtxt<'_>,
38         m: &mut impl Module,
39         unwind_context: &mut UnwindContext,
40         rust_main_def_id: DefId,
41         ignore_lang_start_wrapper: bool,
42         is_main_fn: bool,
43     ) {
44         let main_ret_ty = tcx.fn_sig(rust_main_def_id).output();
45         // Given that `main()` has no arguments,
46         // then its return type cannot have
47         // late-bound regions, since late-bound
48         // regions must appear in the argument
49         // listing.
50         let main_ret_ty = tcx.erase_regions(main_ret_ty.no_bound_vars().unwrap());
51
52         let cmain_sig = Signature {
53             params: vec![
54                 AbiParam::new(m.target_config().pointer_type()),
55                 AbiParam::new(m.target_config().pointer_type()),
56             ],
57             returns: vec![AbiParam::new(m.target_config().pointer_type() /*isize*/)],
58             call_conv: CallConv::triple_default(m.isa().triple()),
59         };
60
61         let cmain_func_id = m.declare_function("main", Linkage::Export, &cmain_sig).unwrap();
62
63         let instance = Instance::mono(tcx, rust_main_def_id).polymorphize(tcx);
64
65         let main_name = tcx.symbol_name(instance).name;
66         let main_sig = get_function_sig(tcx, m.isa().triple(), instance);
67         let main_func_id = m.declare_function(main_name, Linkage::Import, &main_sig).unwrap();
68
69         let mut ctx = Context::new();
70         ctx.func = Function::with_name_signature(ExternalName::user(0, 0), cmain_sig);
71         {
72             let mut func_ctx = FunctionBuilderContext::new();
73             let mut bcx = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
74
75             let block = bcx.create_block();
76             bcx.switch_to_block(block);
77             let arg_argc = bcx.append_block_param(block, m.target_config().pointer_type());
78             let arg_argv = bcx.append_block_param(block, m.target_config().pointer_type());
79
80             let main_func_ref = m.declare_func_in_func(main_func_id, &mut bcx.func);
81
82             let result = if is_main_fn && ignore_lang_start_wrapper {
83                 // regular main fn, but ignoring #[lang = "start"] as we are running in the jit
84                 // FIXME set program arguments somehow
85                 let call_inst = bcx.ins().call(main_func_ref, &[]);
86                 let call_results = bcx.func.dfg.inst_results(call_inst).to_owned();
87
88                 let termination_trait = tcx.require_lang_item(LangItem::Termination, None);
89                 let report = tcx
90                     .associated_items(termination_trait)
91                     .find_by_name_and_kind(
92                         tcx,
93                         Ident::from_str("report"),
94                         AssocKind::Fn,
95                         termination_trait,
96                     )
97                     .unwrap();
98                 let report = Instance::resolve(
99                     tcx,
100                     ParamEnv::reveal_all(),
101                     report.def_id,
102                     tcx.mk_substs([GenericArg::from(main_ret_ty)].iter()),
103                 )
104                 .unwrap()
105                 .unwrap();
106
107                 let report_name = tcx.symbol_name(report).name;
108                 let report_sig = get_function_sig(tcx, m.isa().triple(), report);
109                 let report_func_id =
110                     m.declare_function(report_name, Linkage::Import, &report_sig).unwrap();
111                 let report_func_ref = m.declare_func_in_func(report_func_id, &mut bcx.func);
112
113                 // FIXME do proper abi handling instead of expecting the pass mode to be identical
114                 // for returns and arguments.
115                 let report_call_inst = bcx.ins().call(report_func_ref, &call_results);
116                 let res = bcx.func.dfg.inst_results(report_call_inst)[0];
117                 match m.target_config().pointer_type() {
118                     types::I32 => res,
119                     types::I64 => bcx.ins().sextend(types::I64, res),
120                     _ => unimplemented!("16bit systems are not yet supported"),
121                 }
122             } else if is_main_fn {
123                 let start_def_id = tcx.require_lang_item(LangItem::Start, None);
124                 let start_instance = Instance::resolve(
125                     tcx,
126                     ParamEnv::reveal_all(),
127                     start_def_id,
128                     tcx.intern_substs(&[main_ret_ty.into()]),
129                 )
130                 .unwrap()
131                 .unwrap()
132                 .polymorphize(tcx);
133                 let start_func_id = import_function(tcx, m, start_instance);
134
135                 let main_val = bcx.ins().func_addr(m.target_config().pointer_type(), main_func_ref);
136
137                 let func_ref = m.declare_func_in_func(start_func_id, &mut bcx.func);
138                 let call_inst = bcx.ins().call(func_ref, &[main_val, arg_argc, arg_argv]);
139                 bcx.inst_results(call_inst)[0]
140             } else {
141                 // using user-defined start fn
142                 let call_inst = bcx.ins().call(main_func_ref, &[arg_argc, arg_argv]);
143                 bcx.inst_results(call_inst)[0]
144             };
145
146             bcx.ins().return_(&[result]);
147             bcx.seal_all_blocks();
148             bcx.finalize();
149         }
150         m.define_function(cmain_func_id, &mut ctx, &mut NullTrapSink {}, &mut NullStackMapSink {})
151             .unwrap();
152         unwind_context.add_function(cmain_func_id, &ctx, m.isa());
153     }
154 }