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