moved crates in lib/ to src/, renamed crates, modified some files' text (#660)

moved crates in lib/ to src/, renamed crates, modified some files' text (#660)
This commit is contained in:
lazypassion
2019-01-28 18:56:54 -05:00
committed by Dan Gohman
parent 54959cf5bb
commit 747ad3c4c5
508 changed files with 94 additions and 92 deletions

View File

@@ -0,0 +1,420 @@
//! Defines `FaerieBackend`.
use crate::container;
use crate::traps::{FaerieTrapManifest, FaerieTrapSink};
use cranelift_codegen::binemit::{Addend, CodeOffset, NullTrapSink, Reloc, RelocSink};
use cranelift_codegen::isa::TargetIsa;
use cranelift_codegen::{self, binemit, ir};
use cranelift_module::{
Backend, DataContext, DataDescription, Init, Linkage, ModuleError, ModuleNamespace,
ModuleResult,
};
use faerie;
use failure::Error;
use std::fs::File;
use target_lexicon::Triple;
#[derive(Debug)]
/// Setting to enable collection of traps. Setting this to `Enabled` in
/// `FaerieBuilder` means that a `FaerieTrapManifest` will be present
/// in the `FaerieProduct`.
pub enum FaerieTrapCollection {
/// `FaerieProduct::trap_manifest` will be `None`
Disabled,
/// `FaerieProduct::trap_manifest` will be `Some`
Enabled,
}
/// A builder for `FaerieBackend`.
pub struct FaerieBuilder {
isa: Box<TargetIsa>,
name: String,
collect_traps: FaerieTrapCollection,
libcall_names: Box<Fn(ir::LibCall) -> String>,
}
impl FaerieBuilder {
/// Create a new `FaerieBuilder` using the given Cranelift target, that
/// can be passed to
/// [`Module::new`](cranelift_module/struct.Module.html#method.new].
///
/// Faerie output requires that TargetIsa have PIC (Position Independent Code) enabled.
///
/// `collect_traps` setting determines whether trap information is collected in a
/// `FaerieTrapManifest` available in the `FaerieProduct`.
///
/// The `libcall_names` function provides a way to translate `cranelift_codegen`'s `ir::LibCall`
/// enum to symbols. LibCalls are inserted in the IR as part of the legalization for certain
/// floating point instructions, and for stack probes. If you don't know what to use for this
/// argument, use `FaerieBuilder::default_libcall_names()`.
pub fn new(
isa: Box<TargetIsa>,
name: String,
collect_traps: FaerieTrapCollection,
libcall_names: Box<Fn(ir::LibCall) -> String>,
) -> ModuleResult<Self> {
if !isa.flags().is_pic() {
return Err(ModuleError::Backend(
"faerie requires TargetIsa be PIC".to_owned(),
));
}
Ok(Self {
isa,
name,
collect_traps,
libcall_names,
})
}
/// Default names for `ir::LibCall`s. A function by this name is imported into the object as
/// part of the translation of a `ir::ExternalName::LibCall` variant.
pub fn default_libcall_names() -> Box<Fn(ir::LibCall) -> String> {
Box::new(move |libcall| match libcall {
ir::LibCall::Probestack => "__cranelift_probestack".to_owned(),
ir::LibCall::CeilF32 => "ceilf".to_owned(),
ir::LibCall::CeilF64 => "ceil".to_owned(),
ir::LibCall::FloorF32 => "floorf".to_owned(),
ir::LibCall::FloorF64 => "floor".to_owned(),
ir::LibCall::TruncF32 => "truncf".to_owned(),
ir::LibCall::TruncF64 => "trunc".to_owned(),
ir::LibCall::NearestF32 => "nearbyintf".to_owned(),
ir::LibCall::NearestF64 => "nearbyint".to_owned(),
ir::LibCall::Memcpy => "memcpy".to_owned(),
ir::LibCall::Memset => "memset".to_owned(),
ir::LibCall::Memmove => "memmove".to_owned(),
})
}
}
/// A `FaerieBackend` implements `Backend` and emits ".o" files using the `faerie` library.
///
/// See the `FaerieBuilder` for a convenient way to construct `FaerieBackend` instances.
pub struct FaerieBackend {
isa: Box<TargetIsa>,
artifact: faerie::Artifact,
trap_manifest: Option<FaerieTrapManifest>,
libcall_names: Box<Fn(ir::LibCall) -> String>,
}
pub struct FaerieCompiledFunction {}
pub struct FaerieCompiledData {}
impl Backend for FaerieBackend {
type Builder = FaerieBuilder;
type CompiledFunction = FaerieCompiledFunction;
type CompiledData = FaerieCompiledData;
// There's no need to return individual artifacts; we're writing them into
// the output file instead.
type FinalizedFunction = ();
type FinalizedData = ();
/// The returned value here provides functions for emitting object files
/// to memory and files.
type Product = FaerieProduct;
/// Create a new `FaerieBackend` using the given Cranelift target.
fn new(builder: FaerieBuilder) -> Self {
Self {
artifact: faerie::Artifact::new(builder.isa.triple().clone(), builder.name),
isa: builder.isa,
trap_manifest: match builder.collect_traps {
FaerieTrapCollection::Enabled => Some(FaerieTrapManifest::new()),
FaerieTrapCollection::Disabled => None,
},
libcall_names: builder.libcall_names,
}
}
fn isa(&self) -> &TargetIsa {
&*self.isa
}
fn declare_function(&mut self, name: &str, linkage: Linkage) {
self.artifact
.declare(name, translate_function_linkage(linkage))
.expect("inconsistent declarations");
}
fn declare_data(&mut self, name: &str, linkage: Linkage, writable: bool) {
self.artifact
.declare(name, translate_data_linkage(linkage, writable))
.expect("inconsistent declarations");
}
fn define_function(
&mut self,
name: &str,
ctx: &cranelift_codegen::Context,
namespace: &ModuleNamespace<Self>,
code_size: u32,
) -> ModuleResult<FaerieCompiledFunction> {
let mut code: Vec<u8> = vec![0; code_size as usize];
// Non-lexical lifetimes would obviate the braces here.
{
let mut reloc_sink = FaerieRelocSink {
triple: self.isa.triple().clone(),
artifact: &mut self.artifact,
name,
namespace,
libcall_names: &*self.libcall_names,
};
if let Some(ref mut trap_manifest) = self.trap_manifest {
let mut trap_sink = FaerieTrapSink::new(name, code_size);
unsafe {
ctx.emit_to_memory(
&*self.isa,
code.as_mut_ptr(),
&mut reloc_sink,
&mut trap_sink,
)
};
trap_manifest.add_sink(trap_sink);
} else {
let mut trap_sink = NullTrapSink {};
unsafe {
ctx.emit_to_memory(
&*self.isa,
code.as_mut_ptr(),
&mut reloc_sink,
&mut trap_sink,
)
};
}
}
self.artifact
.define(name, code)
.expect("inconsistent declaration");
Ok(FaerieCompiledFunction {})
}
fn define_data(
&mut self,
name: &str,
_writable: bool,
data_ctx: &DataContext,
namespace: &ModuleNamespace<Self>,
) -> ModuleResult<FaerieCompiledData> {
let &DataDescription {
ref init,
ref function_decls,
ref data_decls,
ref function_relocs,
ref data_relocs,
} = data_ctx.description();
let size = init.size();
let mut bytes = Vec::with_capacity(size);
match *init {
Init::Uninitialized => {
panic!("data is not initialized yet");
}
Init::Zeros { .. } => {
bytes.resize(size, 0);
}
Init::Bytes { ref contents } => {
bytes.extend_from_slice(contents);
}
}
for &(offset, id) in function_relocs {
let to = &namespace.get_function_decl(&function_decls[id]).name;
self.artifact
.link(faerie::Link {
from: name,
to,
at: u64::from(offset),
})
.map_err(|e| ModuleError::Backend(e.to_string()))?;
}
for &(offset, id, addend) in data_relocs {
debug_assert_eq!(
addend, 0,
"faerie doesn't support addends in data section relocations yet"
);
let to = &namespace.get_data_decl(&data_decls[id]).name;
self.artifact
.link(faerie::Link {
from: name,
to,
at: u64::from(offset),
})
.map_err(|e| ModuleError::Backend(e.to_string()))?;
}
self.artifact
.define(name, bytes)
.expect("inconsistent declaration");
Ok(FaerieCompiledData {})
}
fn write_data_funcaddr(
&mut self,
_data: &mut FaerieCompiledData,
_offset: usize,
_what: ir::FuncRef,
) {
unimplemented!()
}
fn write_data_dataaddr(
&mut self,
_data: &mut FaerieCompiledData,
_offset: usize,
_what: ir::GlobalValue,
_usize: binemit::Addend,
) {
unimplemented!()
}
fn finalize_function(
&mut self,
_func: &FaerieCompiledFunction,
_namespace: &ModuleNamespace<Self>,
) {
// Nothing to do.
}
fn get_finalized_function(&self, _func: &FaerieCompiledFunction) {
// Nothing to do.
}
fn finalize_data(&mut self, _data: &FaerieCompiledData, _namespace: &ModuleNamespace<Self>) {
// Nothing to do.
}
fn get_finalized_data(&self, _data: &FaerieCompiledData) {
// Nothing to do.
}
fn publish(&mut self) {
// Nothing to do.
}
fn finish(self) -> FaerieProduct {
FaerieProduct {
artifact: self.artifact,
trap_manifest: self.trap_manifest,
}
}
}
/// This is the output of `Module`'s
/// [`finish`](../cranelift_module/struct.Module.html#method.finish) function.
/// It provides functions for writing out the object file to memory or a file.
pub struct FaerieProduct {
/// Faerie artifact with all functions, data, and links from the module defined
pub artifact: faerie::Artifact,
/// Optional trap manifest. Contains `FaerieTrapManifest` when `FaerieBuilder.collect_traps` is
/// set to `FaerieTrapCollection::Enabled`.
pub trap_manifest: Option<FaerieTrapManifest>,
}
impl FaerieProduct {
/// Return the name of the output file. This is the name passed into `new`.
pub fn name(&self) -> &str {
&self.artifact.name
}
/// Call `emit` on the faerie `Artifact`, producing bytes in memory.
pub fn emit(&self) -> Result<Vec<u8>, Error> {
self.artifact.emit()
}
/// Call `write` on the faerie `Artifact`, writing to a file.
pub fn write(&self, sink: File) -> Result<(), Error> {
self.artifact.write(sink)
}
}
fn translate_function_linkage(linkage: Linkage) -> faerie::Decl {
match linkage {
Linkage::Import => faerie::Decl::FunctionImport,
Linkage::Local => faerie::Decl::Function { global: false },
Linkage::Preemptible | Linkage::Export => faerie::Decl::Function { global: true },
}
}
fn translate_data_linkage(linkage: Linkage, writable: bool) -> faerie::Decl {
match linkage {
Linkage::Import => faerie::Decl::DataImport,
Linkage::Local => faerie::Decl::Data {
global: false,
writable,
},
Linkage::Export => faerie::Decl::Data {
global: true,
writable,
},
Linkage::Preemptible => {
unimplemented!("faerie doesn't support preemptible globals yet");
}
}
}
struct FaerieRelocSink<'a> {
triple: Triple,
artifact: &'a mut faerie::Artifact,
name: &'a str,
namespace: &'a ModuleNamespace<'a, FaerieBackend>,
libcall_names: &'a Fn(ir::LibCall) -> String,
}
impl<'a> RelocSink for FaerieRelocSink<'a> {
fn reloc_ebb(&mut self, _offset: CodeOffset, _reloc: Reloc, _ebb_offset: CodeOffset) {
unimplemented!();
}
fn reloc_external(
&mut self,
offset: CodeOffset,
reloc: Reloc,
name: &ir::ExternalName,
addend: Addend,
) {
let ref_name: String = match *name {
ir::ExternalName::User { .. } => {
if self.namespace.is_function(name) {
self.namespace.get_function_decl(name).name.clone()
} else {
self.namespace.get_data_decl(name).name.clone()
}
}
ir::ExternalName::LibCall(ref libcall) => {
let sym = (self.libcall_names)(*libcall);
self.artifact
.declare(sym.clone(), faerie::Decl::FunctionImport)
.expect("faerie declaration of libcall");
sym
}
_ => panic!("invalid ExternalName {}", name),
};
let (raw_reloc, raw_addend) = container::raw_relocation(reloc, &self.triple);
// TODO: Handle overflow.
let final_addend = addend + raw_addend;
let addend_i32 = final_addend as i32;
debug_assert!(i64::from(addend_i32) == final_addend);
self.artifact
.link_with(
faerie::Link {
from: self.name,
to: &ref_name,
at: u64::from(offset),
},
faerie::Reloc::Raw {
reloc: raw_reloc,
addend: addend_i32,
},
)
.expect("faerie relocation error");
}
fn reloc_jt(&mut self, _offset: CodeOffset, _reloc: Reloc, _jt: ir::JumpTable) {
unimplemented!();
}
}

View File

@@ -0,0 +1,65 @@
//! Utilities for working with Faerie container formats.
use cranelift_codegen::binemit::Reloc;
use target_lexicon::{Architecture, BinaryFormat, Triple};
/// An object file format.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Format {
/// The ELF object file format.
ELF,
/// The Mach-O object file format.
MachO,
}
/// Translate from a Cranelift `Reloc` to a raw object-file-format-specific
/// relocation code and relocation-implied addend.
pub fn raw_relocation(reloc: Reloc, triple: &Triple) -> (u32, i64) {
match triple.binary_format {
BinaryFormat::Elf => {
use goblin::elf;
(
match triple.architecture {
Architecture::X86_64 => {
match reloc {
Reloc::Abs4 => elf::reloc::R_X86_64_32,
Reloc::Abs8 => elf::reloc::R_X86_64_64,
Reloc::X86PCRel4 | Reloc::X86CallPCRel4 => elf::reloc::R_X86_64_PC32,
// TODO: Get Cranelift to tell us when we can use
// R_X86_64_GOTPCRELX/R_X86_64_REX_GOTPCRELX.
Reloc::X86CallPLTRel4 => elf::reloc::R_X86_64_PLT32,
Reloc::X86GOTPCRel4 => elf::reloc::R_X86_64_GOTPCREL,
_ => unimplemented!(),
}
}
_ => unimplemented!("unsupported architecture: {}", triple),
},
// Most ELF relocations do not include an implicit addend.
0,
)
}
BinaryFormat::Macho => {
use goblin::mach;
match triple.architecture {
Architecture::X86_64 => {
match reloc {
Reloc::Abs8 => (u32::from(mach::relocation::R_ABS), 0),
// Mach-O doesn't need us to distinguish between PC-relative calls
// and PLT calls, but it does need us to distinguish between calls
// and non-calls. And, it includes the 4-byte addend implicitly.
Reloc::X86PCRel4 => (u32::from(mach::relocation::X86_64_RELOC_SIGNED), 4),
Reloc::X86CallPCRel4 | Reloc::X86CallPLTRel4 => {
(u32::from(mach::relocation::X86_64_RELOC_BRANCH), 4)
}
Reloc::X86GOTPCRel4 => {
(u32::from(mach::relocation::X86_64_RELOC_GOT_LOAD), 4)
}
_ => unimplemented!("unsupported mach-o reloc: {}", reloc),
}
}
_ => unimplemented!("unsupported architecture: {}", triple),
}
}
_ => unimplemented!("unsupported format"),
}
}

View File

@@ -0,0 +1,39 @@
//! Top-level lib.rs for `cranelift_faerie`.
//!
//! Users of this module should not have to depend on faerie directly.
#![deny(
missing_docs,
trivial_numeric_casts,
unused_extern_crates,
unstable_features
)]
#![warn(unused_import_braces)]
#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))]
#![cfg_attr(
feature = "cargo-clippy",
allow(clippy::new_without_default, clippy::new_without_default_derive)
)]
#![cfg_attr(
feature = "cargo-clippy",
warn(
clippy::float_arithmetic,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
clippy::print_stdout,
clippy::unicode_not_nfc,
clippy::use_self
)
)]
mod backend;
mod container;
pub mod traps;
pub use crate::backend::{FaerieBackend, FaerieBuilder, FaerieProduct, FaerieTrapCollection};
pub use crate::container::Format;
/// Version number of this crate.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

View File

@@ -0,0 +1,63 @@
//! Faerie trap manifests record every `TrapCode` that cranelift outputs during code generation,
//! for every function in the module. This data may be useful at runtime.
use cranelift_codegen::{binemit, ir};
/// Record of the arguments cranelift passes to `TrapSink::trap`
pub struct FaerieTrapSite {
/// Offset into function
pub offset: binemit::CodeOffset,
/// Source location given to cranelift
pub srcloc: ir::SourceLoc,
/// Trap code, as determined by cranelift
pub code: ir::TrapCode,
}
/// Record of the trap sites for a given function
pub struct FaerieTrapSink {
/// Name of function
pub name: String,
/// Total code size of function
pub code_size: u32,
/// All trap sites collected in function
pub sites: Vec<FaerieTrapSite>,
}
impl FaerieTrapSink {
/// Create an empty `FaerieTrapSink`
pub fn new(name: &str, code_size: u32) -> Self {
Self {
sites: Vec::new(),
name: name.to_owned(),
code_size,
}
}
}
impl binemit::TrapSink for FaerieTrapSink {
fn trap(&mut self, offset: binemit::CodeOffset, srcloc: ir::SourceLoc, code: ir::TrapCode) {
self.sites.push(FaerieTrapSite {
offset,
srcloc,
code,
});
}
}
/// Collection of all `FaerieTrapSink`s for the module
pub struct FaerieTrapManifest {
/// All `FaerieTrapSink` for the module
pub sinks: Vec<FaerieTrapSink>,
}
impl FaerieTrapManifest {
/// Create an empty `FaerieTrapManifest`
pub fn new() -> Self {
Self { sinks: Vec::new() }
}
/// Put a `FaerieTrapSink` into manifest
pub fn add_sink(&mut self, sink: FaerieTrapSink) {
self.sinks.push(sink);
}
}