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.
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.
11 use std::ffi::CString;
15 use rustc::middle::allocator::AllocatorKind;
16 use rustc::ty::TyCtxt;
17 use rustc_allocator::{ALLOCATOR_METHODS, AllocatorTy};
20 use llvm::{self, False, True};
22 pub(crate) unsafe fn trans(tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
24 let llmod = mods.llmod;
25 let usize = match &tcx.sess.target.target.target_pointer_width[..] {
26 "16" => llvm::LLVMInt16TypeInContext(llcx),
27 "32" => llvm::LLVMInt32TypeInContext(llcx),
28 "64" => llvm::LLVMInt64TypeInContext(llcx),
29 tws => bug!("Unsupported target word size for int: {}", tws),
31 let i8 = llvm::LLVMInt8TypeInContext(llcx);
32 let i8p = llvm::LLVMPointerType(i8, 0);
33 let void = llvm::LLVMVoidTypeInContext(llcx);
35 for method in ALLOCATOR_METHODS {
36 let mut args = Vec::new();
37 for ty in method.inputs.iter() {
39 AllocatorTy::Layout => {
40 args.push(usize); // size
41 args.push(usize); // align
43 AllocatorTy::Ptr => args.push(i8p),
44 AllocatorTy::Usize => args.push(usize),
47 AllocatorTy::ResultPtr |
48 AllocatorTy::Unit => panic!("invalid allocator arg"),
51 let output = match method.output {
52 AllocatorTy::Bang => None,
53 AllocatorTy::ResultPtr => Some(i8p),
54 AllocatorTy::Unit => None,
58 AllocatorTy::Ptr => panic!("invalid allocator output"),
60 let ty = llvm::LLVMFunctionType(output.unwrap_or(void),
64 let name = CString::new(format!("__rust_{}", method.name)).unwrap();
65 let llfn = llvm::LLVMRustGetOrInsertFunction(llmod,
69 if tcx.sess.target.target.options.default_hidden_visibility {
70 llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
73 let callee = CString::new(kind.fn_name(method.name)).unwrap();
74 let callee = llvm::LLVMRustGetOrInsertFunction(llmod,
78 let llbb = llvm::LLVMAppendBasicBlockInContext(llcx,
80 "entry\0".as_ptr() as *const _);
82 let llbuilder = llvm::LLVMCreateBuilderInContext(llcx);
83 llvm::LLVMPositionBuilderAtEnd(llbuilder, llbb);
84 let args = args.iter().enumerate().map(|(i, _)| {
85 llvm::LLVMGetParam(llfn, i as c_uint)
86 }).collect::<Vec<_>>();
87 let ret = llvm::LLVMRustBuildCall(llbuilder,
92 "\0".as_ptr() as *const _);
93 llvm::LLVMSetTailCall(ret, True);
95 llvm::LLVMBuildRet(llbuilder, ret);
97 llvm::LLVMBuildRetVoid(llbuilder);
99 llvm::LLVMDisposeBuilder(llbuilder);