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