1 // Copyright 2012-2015 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 #![allow(non_upper_case_globals)]
12 #![allow(non_camel_case_types)]
13 #![allow(non_snake_case)]
14 #![deny(bare_trait_objects)]
16 pub use self::IntPredicate::*;
17 pub use self::RealPredicate::*;
18 pub use self::AtomicRmwBinOp::*;
19 pub use self::MetadataType::*;
20 pub use self::CodeGenOptSize::*;
21 pub use self::CallConv::*;
22 pub use self::Linkage::*;
24 use std::str::FromStr;
25 use std::string::FromUtf8Error;
28 use std::cell::RefCell;
29 use libc::{self, c_uint, c_char, size_t};
30 use rustc_data_structures::small_c_str::SmallCStr;
39 pub fn into_result(self) -> Result<(), ()> {
41 LLVMRustResult::Success => Ok(()),
42 LLVMRustResult::Failure => Err(()),
47 pub fn AddFunctionAttrStringValue(llfn: &'a Value,
52 LLVMRustAddFunctionAttrStringValue(llfn,
59 #[derive(Copy, Clone)]
60 pub enum AttributePlace {
67 pub fn as_uint(self) -> c_uint {
69 AttributePlace::ReturnValue => 0,
70 AttributePlace::Argument(i) => 1 + i,
71 AttributePlace::Function => !0,
76 #[derive(Copy, Clone, PartialEq)]
78 pub enum CodeGenOptSize {
79 CodeGenOptSizeNone = 0,
80 CodeGenOptSizeDefault = 1,
81 CodeGenOptSizeAggressive = 2,
84 impl FromStr for ArchiveKind {
87 fn from_str(s: &str) -> Result<Self, Self::Err> {
89 "gnu" => Ok(ArchiveKind::K_GNU),
90 "bsd" => Ok(ArchiveKind::K_BSD),
91 "coff" => Ok(ArchiveKind::K_COFF),
98 pub struct RustString {
99 bytes: RefCell<Vec<u8>>,
102 /// Appending to a Rust string -- used by RawRustStringOstream.
104 pub unsafe extern "C" fn LLVMRustStringWriteImpl(sr: &RustString,
107 let slice = slice::from_raw_parts(ptr as *const u8, size as usize);
109 sr.bytes.borrow_mut().extend_from_slice(slice);
112 pub fn SetInstructionCallConv(instr: &'a Value, cc: CallConv) {
114 LLVMSetInstructionCallConv(instr, cc as c_uint);
117 pub fn SetFunctionCallConv(fn_: &'a Value, cc: CallConv) {
119 LLVMSetFunctionCallConv(fn_, cc as c_uint);
123 // Externally visible symbols that might appear in multiple codegen units need to appear in
124 // their own comdat section so that the duplicates can be discarded at link time. This can for
125 // example happen for generics when using multiple codegen units. This function simply uses the
126 // value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the
128 // For more details on COMDAT sections see e.g. http://www.airs.com/blog/archives/52
129 pub fn SetUniqueComdat(llmod: &Module, val: &'a Value) {
131 LLVMRustSetComdat(llmod, val, LLVMGetValueName(val));
135 pub fn UnsetComdat(val: &'a Value) {
137 LLVMRustUnsetComdat(val);
141 pub fn SetUnnamedAddr(global: &'a Value, unnamed: bool) {
143 LLVMSetUnnamedAddr(global, unnamed as Bool);
147 pub fn set_thread_local(global: &'a Value, is_thread_local: bool) {
149 LLVMSetThreadLocal(global, is_thread_local as Bool);
152 pub fn set_thread_local_mode(global: &'a Value, mode: ThreadLocalMode) {
154 LLVMSetThreadLocalMode(global, mode);
159 pub fn apply_llfn(&self, idx: AttributePlace, llfn: &Value) {
160 unsafe { LLVMRustAddFunctionAttribute(llfn, idx.as_uint(), *self) }
163 pub fn apply_callsite(&self, idx: AttributePlace, callsite: &Value) {
164 unsafe { LLVMRustAddCallSiteAttribute(callsite, idx.as_uint(), *self) }
167 pub fn unapply_llfn(&self, idx: AttributePlace, llfn: &Value) {
168 unsafe { LLVMRustRemoveFunctionAttributes(llfn, idx.as_uint(), *self) }
171 pub fn toggle_llfn(&self, idx: AttributePlace, llfn: &Value, set: bool) {
173 self.apply_llfn(idx, llfn);
175 self.unapply_llfn(idx, llfn);
180 // Memory-managed interface to object files.
182 pub struct ObjectFile {
183 pub llof: &'static mut ffi::ObjectFile,
186 unsafe impl Send for ObjectFile {}
189 // This will take ownership of llmb
190 pub fn new(llmb: &'static mut MemoryBuffer) -> Option<ObjectFile> {
192 let llof = LLVMCreateObjectFile(llmb)?;
193 Some(ObjectFile { llof })
198 impl Drop for ObjectFile {
201 LLVMDisposeObjectFile(&mut *(self.llof as *mut _));
206 // Memory-managed interface to section iterators.
208 pub struct SectionIter<'a> {
209 pub llsi: &'a mut SectionIterator<'a>,
212 impl Drop for SectionIter<'a> {
215 LLVMDisposeSectionIterator(&mut *(self.llsi as *mut _));
220 pub fn mk_section_iter(llof: &'a ffi::ObjectFile) -> SectionIter<'a> {
221 unsafe { SectionIter { llsi: LLVMGetSections(llof) } }
224 /// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
225 pub fn get_param(llfn: &'a Value, index: c_uint) -> &'a Value {
227 assert!(index < LLVMCountParams(llfn),
228 "out of bounds argument access: {} out of {} arguments", index, LLVMCountParams(llfn));
229 LLVMGetParam(llfn, index)
233 pub fn build_string(f: impl FnOnce(&RustString)) -> Result<String, FromUtf8Error> {
234 let sr = RustString {
235 bytes: RefCell::new(Vec::new()),
238 String::from_utf8(sr.bytes.into_inner())
241 pub fn twine_to_string(tr: &Twine) -> String {
243 build_string(|s| LLVMRustWriteTwineToString(tr, s))
244 .expect("got a non-UTF8 Twine from LLVM")
248 pub fn last_error() -> Option<String> {
250 let cstr = LLVMRustGetLastError();
254 let err = CStr::from_ptr(cstr).to_bytes();
255 let err = String::from_utf8_lossy(err).to_string();
256 libc::free(cstr as *mut _);
262 pub struct OperandBundleDef<'a> {
263 pub raw: &'a mut ffi::OperandBundleDef<'a>,
266 impl OperandBundleDef<'a> {
267 pub fn new(name: &str, vals: &[&'a Value]) -> Self {
268 let name = SmallCStr::new(name);
270 LLVMRustBuildOperandBundleDef(name.as_ptr(), vals.as_ptr(), vals.len() as c_uint)
272 OperandBundleDef { raw: def }
276 impl Drop for OperandBundleDef<'a> {
279 LLVMRustFreeOperandBundleDef(&mut *(self.raw as *mut _));