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)]
16 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
18 html_root_url = "https://doc.rust-lang.org/nightly/")]
21 #![feature(box_syntax)]
22 #![feature(concat_idents)]
24 #![feature(link_args)]
25 #![feature(static_nobundle)]
27 // See librustc_cratesio_shim/Cargo.toml for a comment explaining this.
28 #[allow(unused_extern_crates)]
29 extern crate rustc_cratesio_shim;
32 extern crate bitflags;
35 pub use self::IntPredicate::*;
36 pub use self::RealPredicate::*;
37 pub use self::TypeKind::*;
38 pub use self::AtomicRmwBinOp::*;
39 pub use self::MetadataType::*;
40 pub use self::CodeGenOptSize::*;
41 pub use self::CallConv::*;
42 pub use self::Linkage::*;
44 use std::str::FromStr;
46 use std::ffi::{CString, CStr};
47 use std::cell::RefCell;
48 use libc::{c_uint, c_char, size_t};
57 pub fn into_result(self) -> Result<(), ()> {
59 LLVMRustResult::Success => Ok(()),
60 LLVMRustResult::Failure => Err(()),
65 pub fn AddFunctionAttrStringValue(llfn: ValueRef,
70 LLVMRustAddFunctionAttrStringValue(llfn,
78 #[derive(Copy, Clone)]
79 pub enum AttributePlace {
85 pub fn ReturnValue() -> Self {
86 AttributePlace::Argument(0)
89 pub fn as_uint(self) -> c_uint {
91 AttributePlace::Function => !0,
92 AttributePlace::Argument(i) => i,
97 #[derive(Copy, Clone, PartialEq)]
99 pub enum CodeGenOptSize {
100 CodeGenOptSizeNone = 0,
101 CodeGenOptSizeDefault = 1,
102 CodeGenOptSizeAggressive = 2,
105 impl FromStr for ArchiveKind {
108 fn from_str(s: &str) -> Result<Self, Self::Err> {
110 "gnu" => Ok(ArchiveKind::K_GNU),
111 "mips64" => Ok(ArchiveKind::K_MIPS64),
112 "bsd" => Ok(ArchiveKind::K_BSD),
113 "coff" => Ok(ArchiveKind::K_COFF),
119 #[allow(missing_copy_implementations)]
120 pub enum RustString_opaque {}
121 type RustStringRef = *mut RustString_opaque;
122 type RustStringRepr = *mut RefCell<Vec<u8>>;
124 /// Appending to a Rust string -- used by RawRustStringOstream.
126 pub unsafe extern "C" fn LLVMRustStringWriteImpl(sr: RustStringRef,
129 let slice = slice::from_raw_parts(ptr as *const u8, size as usize);
131 let sr = sr as RustStringRepr;
132 (*sr).borrow_mut().extend_from_slice(slice);
135 pub fn SetInstructionCallConv(instr: ValueRef, cc: CallConv) {
137 LLVMSetInstructionCallConv(instr, cc as c_uint);
140 pub fn SetFunctionCallConv(fn_: ValueRef, cc: CallConv) {
142 LLVMSetFunctionCallConv(fn_, cc as c_uint);
146 // Externally visible symbols that might appear in multiple translation units need to appear in
147 // their own comdat section so that the duplicates can be discarded at link time. This can for
148 // example happen for generics when using multiple codegen units. This function simply uses the
149 // value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the
151 // For more details on COMDAT sections see e.g. http://www.airs.com/blog/archives/52
152 pub fn SetUniqueComdat(llmod: ModuleRef, val: ValueRef) {
154 LLVMRustSetComdat(llmod, val, LLVMGetValueName(val));
158 pub fn UnsetComdat(val: ValueRef) {
160 LLVMRustUnsetComdat(val);
164 pub fn SetUnnamedAddr(global: ValueRef, unnamed: bool) {
166 LLVMSetUnnamedAddr(global, unnamed as Bool);
170 pub fn set_thread_local(global: ValueRef, is_thread_local: bool) {
172 LLVMSetThreadLocal(global, is_thread_local as Bool);
177 pub fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) {
178 unsafe { LLVMRustAddFunctionAttribute(llfn, idx.as_uint(), *self) }
181 pub fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) {
182 unsafe { LLVMRustAddCallSiteAttribute(callsite, idx.as_uint(), *self) }
185 pub fn unapply_llfn(&self, idx: AttributePlace, llfn: ValueRef) {
186 unsafe { LLVMRustRemoveFunctionAttributes(llfn, idx.as_uint(), *self) }
189 pub fn toggle_llfn(&self, idx: AttributePlace, llfn: ValueRef, set: bool) {
191 self.apply_llfn(idx, llfn);
193 self.unapply_llfn(idx, llfn);
198 // Memory-managed interface to target data.
204 impl Drop for TargetData {
207 LLVMDisposeTargetData(self.lltd);
212 fn mk_target_data(string_rep: &str) -> TargetData {
213 let string_rep = CString::new(string_rep).unwrap();
214 TargetData { lltd: unsafe { LLVMCreateTargetData(string_rep.as_ptr()) } }
217 // Memory-managed interface to object files.
219 pub struct ObjectFile {
220 pub llof: ObjectFileRef,
224 // This will take ownership of llmb
225 pub fn new(llmb: MemoryBufferRef) -> Option<ObjectFile> {
227 let llof = LLVMCreateObjectFile(llmb);
228 if llof as isize == 0 {
229 // LLVMCreateObjectFile took ownership of llmb
233 Some(ObjectFile { llof: llof })
238 impl Drop for ObjectFile {
241 LLVMDisposeObjectFile(self.llof);
246 // Memory-managed interface to section iterators.
248 pub struct SectionIter {
249 pub llsi: SectionIteratorRef,
252 impl Drop for SectionIter {
255 LLVMDisposeSectionIterator(self.llsi);
260 pub fn mk_section_iter(llof: ObjectFileRef) -> SectionIter {
261 unsafe { SectionIter { llsi: LLVMGetSections(llof) } }
264 /// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
265 pub fn get_param(llfn: ValueRef, index: c_uint) -> ValueRef {
267 assert!(index < LLVMCountParams(llfn),
268 "out of bounds argument access: {} out of {} arguments", index, LLVMCountParams(llfn));
269 LLVMGetParam(llfn, index)
273 fn get_params(llfn: ValueRef) -> Vec<ValueRef> {
275 let num_params = LLVMCountParams(llfn);
276 let mut params = Vec::with_capacity(num_params as usize);
277 for idx in 0..num_params {
278 params.push(LLVMGetParam(llfn, idx));
285 pub fn build_string<F>(f: F) -> Option<String>
286 where F: FnOnce(RustStringRef)
288 let mut buf = RefCell::new(Vec::new());
289 f(&mut buf as RustStringRepr as RustStringRef);
290 String::from_utf8(buf.into_inner()).ok()
293 pub unsafe fn twine_to_string(tr: TwineRef) -> String {
294 build_string(|s| LLVMRustWriteTwineToString(tr, s)).expect("got a non-UTF8 Twine from LLVM")
297 pub unsafe fn debug_loc_to_string(c: ContextRef, tr: DebugLocRef) -> String {
298 build_string(|s| LLVMRustWriteDebugLocToString(c, tr, s))
299 .expect("got a non-UTF8 DebugLoc from LLVM")
302 pub fn initialize_available_targets() {
303 macro_rules! init_target(
304 ($cfg:meta, $($method:ident),*) => { {
319 init_target!(llvm_component = "x86",
320 LLVMInitializeX86TargetInfo,
321 LLVMInitializeX86Target,
322 LLVMInitializeX86TargetMC,
323 LLVMInitializeX86AsmPrinter,
324 LLVMInitializeX86AsmParser);
325 init_target!(llvm_component = "arm",
326 LLVMInitializeARMTargetInfo,
327 LLVMInitializeARMTarget,
328 LLVMInitializeARMTargetMC,
329 LLVMInitializeARMAsmPrinter,
330 LLVMInitializeARMAsmParser);
331 init_target!(llvm_component = "aarch64",
332 LLVMInitializeAArch64TargetInfo,
333 LLVMInitializeAArch64Target,
334 LLVMInitializeAArch64TargetMC,
335 LLVMInitializeAArch64AsmPrinter,
336 LLVMInitializeAArch64AsmParser);
337 init_target!(llvm_component = "mips",
338 LLVMInitializeMipsTargetInfo,
339 LLVMInitializeMipsTarget,
340 LLVMInitializeMipsTargetMC,
341 LLVMInitializeMipsAsmPrinter,
342 LLVMInitializeMipsAsmParser);
343 init_target!(llvm_component = "powerpc",
344 LLVMInitializePowerPCTargetInfo,
345 LLVMInitializePowerPCTarget,
346 LLVMInitializePowerPCTargetMC,
347 LLVMInitializePowerPCAsmPrinter,
348 LLVMInitializePowerPCAsmParser);
349 init_target!(llvm_component = "systemz",
350 LLVMInitializeSystemZTargetInfo,
351 LLVMInitializeSystemZTarget,
352 LLVMInitializeSystemZTargetMC,
353 LLVMInitializeSystemZAsmPrinter,
354 LLVMInitializeSystemZAsmParser);
355 init_target!(llvm_component = "jsbackend",
356 LLVMInitializeJSBackendTargetInfo,
357 LLVMInitializeJSBackendTarget,
358 LLVMInitializeJSBackendTargetMC);
359 init_target!(llvm_component = "msp430",
360 LLVMInitializeMSP430TargetInfo,
361 LLVMInitializeMSP430Target,
362 LLVMInitializeMSP430TargetMC,
363 LLVMInitializeMSP430AsmPrinter);
364 init_target!(llvm_component = "sparc",
365 LLVMInitializeSparcTargetInfo,
366 LLVMInitializeSparcTarget,
367 LLVMInitializeSparcTargetMC,
368 LLVMInitializeSparcAsmPrinter,
369 LLVMInitializeSparcAsmParser);
370 init_target!(llvm_component = "nvptx",
371 LLVMInitializeNVPTXTargetInfo,
372 LLVMInitializeNVPTXTarget,
373 LLVMInitializeNVPTXTargetMC,
374 LLVMInitializeNVPTXAsmPrinter);
375 init_target!(llvm_component = "hexagon",
376 LLVMInitializeHexagonTargetInfo,
377 LLVMInitializeHexagonTarget,
378 LLVMInitializeHexagonTargetMC,
379 LLVMInitializeHexagonAsmPrinter,
380 LLVMInitializeHexagonAsmParser);
381 init_target!(llvm_component = "webassembly",
382 LLVMInitializeWebAssemblyTargetInfo,
383 LLVMInitializeWebAssemblyTarget,
384 LLVMInitializeWebAssemblyTargetMC,
385 LLVMInitializeWebAssemblyAsmPrinter);
388 pub fn last_error() -> Option<String> {
390 let cstr = LLVMRustGetLastError();
394 let err = CStr::from_ptr(cstr).to_bytes();
395 let err = String::from_utf8_lossy(err).to_string();
396 libc::free(cstr as *mut _);
402 pub struct OperandBundleDef {
403 inner: OperandBundleDefRef,
406 impl OperandBundleDef {
407 pub fn new(name: &str, vals: &[ValueRef]) -> OperandBundleDef {
408 let name = CString::new(name).unwrap();
410 LLVMRustBuildOperandBundleDef(name.as_ptr(), vals.as_ptr(), vals.len() as c_uint)
412 OperandBundleDef { inner: def }
415 pub fn raw(&self) -> OperandBundleDefRef {
420 impl Drop for OperandBundleDef {
423 LLVMRustFreeOperandBundleDef(self.inner);