7 use syntax::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS};
9 use crate::llvm::{self, False, True};
10 use crate::ModuleLlvm;
12 pub(crate) unsafe fn codegen(tcx: TyCtxt<'_>, mods: &mut ModuleLlvm, kind: AllocatorKind) {
13 let llcx = &*mods.llcx;
14 let llmod = mods.llmod();
15 let usize = match &tcx.sess.target.target.target_pointer_width[..] {
16 "16" => llvm::LLVMInt16TypeInContext(llcx),
17 "32" => llvm::LLVMInt32TypeInContext(llcx),
18 "64" => llvm::LLVMInt64TypeInContext(llcx),
19 tws => bug!("Unsupported target word size for int: {}", tws),
21 let i8 = llvm::LLVMInt8TypeInContext(llcx);
22 let i8p = llvm::LLVMPointerType(i8, 0);
23 let void = llvm::LLVMVoidTypeInContext(llcx);
25 for method in ALLOCATOR_METHODS {
26 let mut args = Vec::with_capacity(method.inputs.len());
27 for ty in method.inputs.iter() {
29 AllocatorTy::Layout => {
30 args.push(usize); // size
31 args.push(usize); // align
33 AllocatorTy::Ptr => args.push(i8p),
34 AllocatorTy::Usize => args.push(usize),
36 AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"),
39 let output = match method.output {
40 AllocatorTy::ResultPtr => Some(i8p),
41 AllocatorTy::Unit => None,
43 AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
44 panic!("invalid allocator output")
47 let ty = llvm::LLVMFunctionType(
48 output.unwrap_or(void),
53 let name = CString::new(format!("__rust_{}", method.name)).unwrap();
54 let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr(), ty);
56 if tcx.sess.target.target.options.default_hidden_visibility {
57 llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
59 if tcx.sess.target.target.options.requires_uwtable {
60 attributes::emit_uwtable(llfn, true);
63 let callee = CString::new(kind.fn_name(method.name)).unwrap();
64 let callee = llvm::LLVMRustGetOrInsertFunction(llmod, callee.as_ptr(), ty);
65 llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden);
67 let llbb = llvm::LLVMAppendBasicBlockInContext(llcx, llfn, "entry\0".as_ptr().cast());
69 let llbuilder = llvm::LLVMCreateBuilderInContext(llcx);
70 llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb);
74 .map(|(i, _)| llvm::LLVMGetParam(llfn, i as c_uint))
76 let ret = llvm::LLVMRustBuildCall(
84 llvm::LLVMSetTailCall(ret, True);
86 llvm::LLVMBuildRet(llbuilder, ret);
88 llvm::LLVMBuildRetVoid(llbuilder);
90 llvm::LLVMDisposeBuilder(llbuilder);