rustc_codegen_llvm/
allocator.rs

1use libc::c_uint;
2use rustc_ast::expand::allocator::{
3    ALLOCATOR_METHODS, AllocatorKind, AllocatorTy, NO_ALLOC_SHIM_IS_UNSTABLE,
4    alloc_error_handler_name, default_fn_name, global_fn_name,
5};
6use rustc_codegen_ssa::traits::BaseTypeCodegenMethods as _;
7use rustc_middle::bug;
8use rustc_middle::ty::TyCtxt;
9use rustc_session::config::{DebugInfo, OomStrategy};
10use rustc_symbol_mangling::mangle_internal_symbol;
11
12use crate::builder::SBuilder;
13use crate::declare::declare_simple_fn;
14use crate::llvm::{self, False, True, Type};
15use crate::{SimpleCx, attributes, debuginfo};
16
17pub(crate) unsafe fn codegen(
18    tcx: TyCtxt<'_>,
19    cx: SimpleCx<'_>,
20    module_name: &str,
21    kind: AllocatorKind,
22    alloc_error_handler_kind: AllocatorKind,
23) {
24    let usize = match tcx.sess.target.pointer_width {
25        16 => cx.type_i16(),
26        32 => cx.type_i32(),
27        64 => cx.type_i64(),
28        tws => bug!("Unsupported target word size for int: {}", tws),
29    };
30    let i8 = cx.type_i8();
31    let i8p = cx.type_ptr();
32
33    if kind == AllocatorKind::Default {
34        for method in ALLOCATOR_METHODS {
35            let mut args = Vec::with_capacity(method.inputs.len());
36            for input in method.inputs.iter() {
37                match input.ty {
38                    AllocatorTy::Layout => {
39                        args.push(usize); // size
40                        args.push(usize); // align
41                    }
42                    AllocatorTy::Ptr => args.push(i8p),
43                    AllocatorTy::Usize => args.push(usize),
44
45                    AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"),
46                }
47            }
48            let output = match method.output {
49                AllocatorTy::ResultPtr => Some(i8p),
50                AllocatorTy::Unit => None,
51
52                AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
53                    panic!("invalid allocator output")
54                }
55            };
56
57            let from_name = mangle_internal_symbol(tcx, &global_fn_name(method.name));
58            let to_name = mangle_internal_symbol(tcx, &default_fn_name(method.name));
59
60            create_wrapper_function(tcx, &cx, &from_name, &to_name, &args, output, false);
61        }
62    }
63
64    // rust alloc error handler
65    create_wrapper_function(
66        tcx,
67        &cx,
68        &mangle_internal_symbol(tcx, "__rust_alloc_error_handler"),
69        &mangle_internal_symbol(tcx, alloc_error_handler_name(alloc_error_handler_kind)),
70        &[usize, usize], // size, align
71        None,
72        true,
73    );
74
75    unsafe {
76        // __rust_alloc_error_handler_should_panic
77        let name = mangle_internal_symbol(tcx, OomStrategy::SYMBOL);
78        let ll_g = cx.declare_global(&name, i8);
79        llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility()));
80        let val = tcx.sess.opts.unstable_opts.oom.should_panic();
81        let llval = llvm::LLVMConstInt(i8, val as u64, False);
82        llvm::set_initializer(ll_g, llval);
83
84        let name = mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE);
85        let ll_g = cx.declare_global(&name, i8);
86        llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility()));
87        let llval = llvm::LLVMConstInt(i8, 0, False);
88        llvm::set_initializer(ll_g, llval);
89    }
90
91    if tcx.sess.opts.debuginfo != DebugInfo::None {
92        let dbg_cx = debuginfo::CodegenUnitDebugContext::new(cx.llmod);
93        debuginfo::metadata::build_compile_unit_di_node(tcx, module_name, &dbg_cx);
94        dbg_cx.finalize(tcx.sess);
95    }
96}
97
98fn create_wrapper_function(
99    tcx: TyCtxt<'_>,
100    cx: &SimpleCx<'_>,
101    from_name: &str,
102    to_name: &str,
103    args: &[&Type],
104    output: Option<&Type>,
105    no_return: bool,
106) {
107    let ty = cx.type_func(args, output.unwrap_or_else(|| cx.type_void()));
108    let llfn = declare_simple_fn(
109        &cx,
110        from_name,
111        llvm::CallConv::CCallConv,
112        llvm::UnnamedAddr::Global,
113        llvm::Visibility::from_generic(tcx.sess.default_visibility()),
114        ty,
115    );
116    let no_return = if no_return {
117        // -> ! DIFlagNoReturn
118        let no_return = llvm::AttributeKind::NoReturn.create_attr(cx.llcx);
119        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[no_return]);
120        Some(no_return)
121    } else {
122        None
123    };
124
125    if tcx.sess.must_emit_unwind_tables() {
126        let uwtable =
127            attributes::uwtable_attr(cx.llcx, tcx.sess.opts.unstable_opts.use_sync_unwind);
128        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[uwtable]);
129    }
130
131    let callee = declare_simple_fn(
132        &cx,
133        to_name,
134        llvm::CallConv::CCallConv,
135        llvm::UnnamedAddr::Global,
136        llvm::Visibility::Hidden,
137        ty,
138    );
139    if let Some(no_return) = no_return {
140        // -> ! DIFlagNoReturn
141        attributes::apply_to_llfn(callee, llvm::AttributePlace::Function, &[no_return]);
142    }
143    llvm::set_visibility(callee, llvm::Visibility::Hidden);
144
145    let llbb = unsafe { llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, c"entry".as_ptr()) };
146
147    let mut bx = SBuilder::build(&cx, llbb);
148    let args = args
149        .iter()
150        .enumerate()
151        .map(|(i, _)| llvm::get_param(llfn, i as c_uint))
152        .collect::<Vec<_>>();
153    let ret = bx.call(ty, callee, &args, None);
154    llvm::LLVMSetTailCall(ret, True);
155    if output.is_some() {
156        bx.ret(ret);
157    } else {
158        bx.ret_void()
159    }
160}