Skip to main content

rustc_builtin_macros/
global_allocator.rs

1use rustc_ast::expand::allocator::{
2    ALLOCATOR_METHODS, AllocatorMethod, AllocatorMethodInput, AllocatorTy, global_fn_name,
3};
4use rustc_ast::{
5    self as ast, Expr, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety, Stmt,
6    StmtKind, Ty,
7};
8use rustc_expand::base::{Annotatable, ExtCtxt};
9use rustc_span::{Ident, Span, Symbol, sym};
10use thin_vec::{ThinVec, thin_vec};
11
12use crate::diagnostics;
13use crate::util::check_builtin_macro_attribute;
14
15pub(crate) fn expand(
16    ecx: &mut ExtCtxt<'_>,
17    _span: Span,
18    meta_item: &ast::MetaItem,
19    item: Annotatable,
20) -> Vec<Annotatable> {
21    check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);
22
23    let orig_item = item.clone();
24
25    // Allow using `#[global_allocator]` on an item statement
26    // FIXME - if we get deref patterns, use them to reduce duplication here
27    let (item, ident, is_stmt, ty_span) = if let Annotatable::Item(item) = &item
28        && let ItemKind::Static(ast::StaticItem { ident, ty, .. }) = &item.kind
29    {
30        (item, *ident, false, ecx.with_def_site_ctxt(ty.span))
31    } else if let Annotatable::Stmt(stmt) = &item
32        && let StmtKind::Item(item) = &stmt.kind
33        && let ItemKind::Static(ast::StaticItem { ident, ty, .. }) = &item.kind
34    {
35        (item, *ident, true, ecx.with_def_site_ctxt(ty.span))
36    } else {
37        ecx.dcx().emit_err(diagnostics::AllocMustStatics { span: item.span() });
38        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [orig_item]))vec![orig_item];
39    };
40
41    // Forbid `#[thread_local]` attributes on the item
42    if let Some(attr) = item.attrs.iter().find(|x| x.has_name(sym::thread_local)) {
43        ecx.dcx()
44            .emit_err(diagnostics::AllocCannotThreadLocal { span: item.span, attr: attr.span });
45        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [orig_item]))vec![orig_item];
46    }
47
48    let span = ecx.with_def_site_ctxt(item.span);
49
50    // Generate item statements for the allocator methods.
51    let stmts = ALLOCATOR_METHODS
52        .iter()
53        .map(|method| allocator_fn(ecx, span, ty_span, ident, method))
54        .collect();
55
56    // Generate anonymous constant serving as container for the allocator methods.
57    let const_item = ecx.item_const_underscore(span, ecx.block(span, stmts));
58    let const_item = if is_stmt {
59        Annotatable::Stmt(ecx.stmt_item(span, const_item))
60    } else {
61        Annotatable::Item(const_item)
62    };
63
64    // Return the original item and the new methods.
65    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [orig_item, const_item]))vec![orig_item, const_item]
66}
67
68fn allocator_fn(
69    cx: &ExtCtxt<'_>,
70    span: Span,
71    ty_span: Span,
72    global: Ident,
73    method: &AllocatorMethod,
74) -> Stmt {
75    let mut abi_args = ThinVec::new();
76    let args = method.inputs.iter().map(|input| arg_ty(cx, span, input, &mut abi_args)).collect();
77    let result = call_allocator(cx, ty_span, global, method.name, args);
78    let output_ty = match method.output {
79        AllocatorTy::ResultPtr => ptr_u8(cx, span),
80        AllocatorTy::Unit => cx.ty_unit(span),
81        AllocatorTy::Layout | AllocatorTy::Never | AllocatorTy::Usize | AllocatorTy::Ptr => {
82            {
    ::core::panicking::panic_fmt(format_args!("can\'t convert `AllocatorTy` to an output"));
}panic!("can't convert `AllocatorTy` to an output")
83        }
84    };
85    let decl = cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty));
86    let header = FnHeader { safety: Safety::Unsafe(span), ..FnHeader::default() };
87    let sig = FnSig { decl, header, span };
88    let body = Some(cx.block_expr(result));
89    let kind = ItemKind::Fn(cx.item_fn(
90        sig,
91        Ident::from_str_and_span(&global_fn_name(method.name), span),
92        Generics::default(),
93        body,
94    ));
95    let alloc_attr = match method.name {
96        sym::alloc => sym::rustc_allocator,
97        sym::dealloc => sym::rustc_deallocator,
98        sym::realloc => sym::rustc_reallocator,
99        sym::alloc_zeroed => sym::rustc_allocator_zeroed,
100        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unknown allocator method!")));
}unreachable!("Unknown allocator method!"),
101    };
102    let attrs = {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.attr_word(sym::rustc_std_internal_symbol, span));
    vec.push(cx.attr_word(alloc_attr, span));
    vec
}thin_vec![
103        cx.attr_word(sym::rustc_std_internal_symbol, span),
104        cx.attr_word(alloc_attr, span)
105    ];
106    let item = cx.item(span, attrs, kind);
107    cx.stmt_item(ty_span, item)
108}
109
110fn call_allocator(
111    cx: &ExtCtxt<'_>,
112    ty_span: Span,
113    global: Ident,
114    method: Symbol,
115    mut args: ThinVec<Box<Expr>>,
116) -> Box<Expr> {
117    let method = cx.std_path(ty_span, &[sym::alloc, sym::GlobalAlloc, method]);
118    let method = cx.expr_path(method);
119    let allocator = cx.path_ident(ty_span, global);
120    let allocator = cx.expr_path(allocator);
121    let allocator = cx.expr_ref(ty_span, allocator);
122    args.insert(0, allocator);
123
124    cx.expr_call(ty_span, method, args)
125}
126
127fn arg_ty(
128    cx: &ExtCtxt<'_>,
129    span: Span,
130    input: &AllocatorMethodInput,
131    args: &mut ThinVec<Param>,
132) -> Box<Expr> {
133    match input.ty {
134        AllocatorTy::Layout => {
135            // If an allocator method is ever introduced having multiple
136            // Layout arguments, these argument names need to be
137            // disambiguated somehow. Currently the generated code would
138            // fail to compile with "identifier is bound more than once in
139            // this parameter list".
140
141            let ty_usize = cx.ty_name(span, sym::usize);
142            args.push(cx.param(span, sym::size, ty_usize));
143            let ty_align = cx.ty_path(cx.std_path(span, &[sym::mem, sym::Alignment]));
144            args.push(cx.param(span, sym::align, ty_align));
145
146            let layout_new =
147                cx.std_path(span, &[sym::alloc, sym::Layout, sym::from_size_alignment_unchecked]);
148            let layout_new = cx.expr_path(layout_new);
149            let size = cx.expr_name(span, sym::size);
150            let align = cx.expr_name(span, sym::align);
151            cx.expr_call(span, layout_new, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(size);
    vec.push(align);
    vec
}thin_vec![size, align])
152        }
153        AllocatorTy::Ptr => {
154            let name = Symbol::intern(input.name);
155            args.push(cx.param(span, name, ptr_u8(cx, span)));
156            cx.expr_name(span, name)
157        }
158        AllocatorTy::Usize => {
159            let name = Symbol::intern(input.name);
160            args.push(cx.param(span, name, cx.ty_name(span, sym::usize)));
161            cx.expr_name(span, name)
162        }
163        AllocatorTy::Never | AllocatorTy::ResultPtr | AllocatorTy::Unit => {
164            {
    ::core::panicking::panic_fmt(format_args!("can\'t convert AllocatorTy to an argument"));
}panic!("can't convert AllocatorTy to an argument")
165        }
166    }
167}
168
169fn ptr_u8(cx: &ExtCtxt<'_>, span: Span) -> Box<Ty> {
170    let ty_u8 = cx.ty_name(span, sym::u8);
171    cx.ty_ptr(span, ty_u8, Mutability::Mut)
172}