]> git.lizzy.rs Git - rust.git/blob - src/allocator.rs
Emit unwind info for main and alloc shim
[rust.git] / src / allocator.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use crate::prelude::*;
12
13 use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS};
14
15 /// Returns whether an allocator shim was created
16 pub(crate) fn codegen(
17     tcx: TyCtxt<'_>,
18     module: &mut Module<impl Backend + 'static>,
19     unwind_context: &mut UnwindContext<'_>,
20 ) -> bool {
21     let any_dynamic_crate = tcx.dependency_formats(LOCAL_CRATE).iter().any(|(_, list)| {
22         use rustc_middle::middle::dependency_format::Linkage;
23         list.iter().any(|&linkage| linkage == Linkage::Dynamic)
24     });
25     if any_dynamic_crate {
26         false
27     } else if let Some(kind) = tcx.allocator_kind() {
28         codegen_inner(module, unwind_context, kind);
29         true
30     } else {
31         false
32     }
33 }
34
35 fn codegen_inner(
36     module: &mut Module<impl Backend + 'static>,
37     unwind_context: &mut UnwindContext<'_>,
38     kind: AllocatorKind,
39 ) {
40     let usize_ty = module.target_config().pointer_type();
41
42     for method in ALLOCATOR_METHODS {
43         let mut arg_tys = Vec::with_capacity(method.inputs.len());
44         for ty in method.inputs.iter() {
45             match *ty {
46                 AllocatorTy::Layout => {
47                     arg_tys.push(usize_ty); // size
48                     arg_tys.push(usize_ty); // align
49                 }
50                 AllocatorTy::Ptr => arg_tys.push(usize_ty),
51                 AllocatorTy::Usize => arg_tys.push(usize_ty),
52
53                 AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"),
54             }
55         }
56         let output = match method.output {
57             AllocatorTy::ResultPtr => Some(usize_ty),
58             AllocatorTy::Unit => None,
59
60             AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
61                 panic!("invalid allocator output")
62             }
63         };
64
65         let sig = Signature {
66             call_conv: CallConv::triple_default(module.isa().triple()),
67             params: arg_tys.iter().cloned().map(AbiParam::new).collect(),
68             returns: output.into_iter().map(AbiParam::new).collect(),
69         };
70
71         let caller_name = format!("__rust_{}", method.name);
72         let callee_name = kind.fn_name(method.name);
73         //eprintln!("Codegen allocator shim {} -> {} ({:?} -> {:?})", caller_name, callee_name, sig.params, sig.returns);
74
75         let func_id = module
76             .declare_function(&caller_name, Linkage::Export, &sig)
77             .unwrap();
78
79         let callee_func_id = module
80             .declare_function(&callee_name, Linkage::Import, &sig)
81             .unwrap();
82
83         let mut ctx = Context::new();
84         ctx.func = Function::with_name_signature(ExternalName::user(0, 0), sig.clone());
85         {
86             let mut func_ctx = FunctionBuilderContext::new();
87             let mut bcx = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
88
89             let block = bcx.create_block();
90             bcx.switch_to_block(block);
91             let args = arg_tys
92                 .into_iter()
93                 .map(|ty| bcx.append_block_param(block, ty))
94                 .collect::<Vec<Value>>();
95
96             let callee_func_ref = module.declare_func_in_func(callee_func_id, &mut bcx.func);
97
98             let call_inst = bcx.ins().call(callee_func_ref, &args);
99
100             let results = bcx.inst_results(call_inst).to_vec(); // Clone to prevent borrow error
101             bcx.ins().return_(&results);
102             bcx.seal_all_blocks();
103             bcx.finalize();
104         }
105         module.define_function(
106             func_id,
107             &mut ctx,
108             &mut cranelift_codegen::binemit::NullTrapSink {},
109         ).unwrap();
110         unwind_context.add_function(func_id, &ctx, module.isa());
111     }
112 }