Path: blob/main/cranelift/module/src/module.rs
1692 views
//! Defines `Module` and related types.12// TODO: Should `ir::Function` really have a `name`?34// TODO: Factor out `ir::Function`'s `ext_funcs` and `global_values` into a struct5// shared with `DataDescription`?67use super::HashMap;8use crate::data_context::DataDescription;9use core::fmt::Display;10use cranelift_codegen::binemit::{CodeOffset, Reloc};11use cranelift_codegen::entity::{PrimaryMap, entity_impl};12use cranelift_codegen::ir::ExternalName;13use cranelift_codegen::ir::function::{Function, VersionMarker};14use cranelift_codegen::settings::SetError;15use cranelift_codegen::{16CodegenError, CompileError, Context, FinalizedMachReloc, FinalizedRelocTarget, ir, isa,17};18use cranelift_control::ControlPlane;19use std::borrow::{Cow, ToOwned};20use std::boxed::Box;21use std::string::String;2223/// A module relocation.24#[derive(Clone)]25pub struct ModuleReloc {26/// The offset at which the relocation applies, *relative to the27/// containing section*.28pub offset: CodeOffset,29/// The kind of relocation.30pub kind: Reloc,31/// The external symbol / name to which this relocation refers.32pub name: ModuleRelocTarget,33/// The addend to add to the symbol value.34pub addend: i64,35}3637impl ModuleReloc {38/// Converts a `FinalizedMachReloc` produced from a `Function` into a `ModuleReloc`.39pub fn from_mach_reloc(40mach_reloc: &FinalizedMachReloc,41func: &Function,42func_id: FuncId,43) -> Self {44let name = match mach_reloc.target {45FinalizedRelocTarget::ExternalName(ExternalName::User(reff)) => {46let name = &func.params.user_named_funcs()[reff];47ModuleRelocTarget::user(name.namespace, name.index)48}49FinalizedRelocTarget::ExternalName(ExternalName::TestCase(_)) => unimplemented!(),50FinalizedRelocTarget::ExternalName(ExternalName::LibCall(libcall)) => {51ModuleRelocTarget::LibCall(libcall)52}53FinalizedRelocTarget::ExternalName(ExternalName::KnownSymbol(ks)) => {54ModuleRelocTarget::KnownSymbol(ks)55}56FinalizedRelocTarget::Func(offset) => {57ModuleRelocTarget::FunctionOffset(func_id, offset)58}59};60Self {61offset: mach_reloc.offset,62kind: mach_reloc.kind,63name,64addend: mach_reloc.addend,65}66}67}6869/// A function identifier for use in the `Module` interface.70#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]71#[cfg_attr(72feature = "enable-serde",73derive(serde_derive::Serialize, serde_derive::Deserialize)74)]75pub struct FuncId(u32);76entity_impl!(FuncId, "funcid");7778/// Function identifiers are namespace 0 in `ir::ExternalName`79impl From<FuncId> for ModuleRelocTarget {80fn from(id: FuncId) -> Self {81Self::User {82namespace: 0,83index: id.0,84}85}86}8788impl FuncId {89/// Get the `FuncId` for the function named by `name`.90pub fn from_name(name: &ModuleRelocTarget) -> FuncId {91if let ModuleRelocTarget::User { namespace, index } = name {92debug_assert_eq!(*namespace, 0);93FuncId::from_u32(*index)94} else {95panic!("unexpected name in DataId::from_name")96}97}98}99100/// A data object identifier for use in the `Module` interface.101#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]102#[cfg_attr(103feature = "enable-serde",104derive(serde_derive::Serialize, serde_derive::Deserialize)105)]106pub struct DataId(u32);107entity_impl!(DataId, "dataid");108109/// Data identifiers are namespace 1 in `ir::ExternalName`110impl From<DataId> for ModuleRelocTarget {111fn from(id: DataId) -> Self {112Self::User {113namespace: 1,114index: id.0,115}116}117}118119impl DataId {120/// Get the `DataId` for the data object named by `name`.121pub fn from_name(name: &ModuleRelocTarget) -> DataId {122if let ModuleRelocTarget::User { namespace, index } = name {123debug_assert_eq!(*namespace, 1);124DataId::from_u32(*index)125} else {126panic!("unexpected name in DataId::from_name")127}128}129}130131/// Linkage refers to where an entity is defined and who can see it.132#[derive(Copy, Clone, Debug, PartialEq, Eq)]133#[cfg_attr(134feature = "enable-serde",135derive(serde_derive::Serialize, serde_derive::Deserialize)136)]137pub enum Linkage {138/// Defined outside of a module.139Import,140/// Defined inside the module, but not visible outside it.141Local,142/// Defined inside the module, visible outside it, and may be preempted.143Preemptible,144/// Defined inside the module, visible inside the current static linkage unit, but not outside.145///146/// A static linkage unit is the combination of all object files passed to a linker to create147/// an executable or dynamic library.148Hidden,149/// Defined inside the module, and visible outside it.150Export,151}152153impl Linkage {154fn merge(a: Self, b: Self) -> Self {155match a {156Self::Export => Self::Export,157Self::Hidden => match b {158Self::Export => Self::Export,159Self::Preemptible => Self::Preemptible,160_ => Self::Hidden,161},162Self::Preemptible => match b {163Self::Export => Self::Export,164_ => Self::Preemptible,165},166Self::Local => match b {167Self::Export => Self::Export,168Self::Hidden => Self::Hidden,169Self::Preemptible => Self::Preemptible,170Self::Local | Self::Import => Self::Local,171},172Self::Import => b,173}174}175176/// Test whether this linkage can have a definition.177pub fn is_definable(self) -> bool {178match self {179Self::Import => false,180Self::Local | Self::Preemptible | Self::Hidden | Self::Export => true,181}182}183184/// Test whether this linkage will have a definition that cannot be preempted.185pub fn is_final(self) -> bool {186match self {187Self::Import | Self::Preemptible => false,188Self::Local | Self::Hidden | Self::Export => true,189}190}191}192193/// A declared name may refer to either a function or data declaration194#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]195#[cfg_attr(196feature = "enable-serde",197derive(serde_derive::Serialize, serde_derive::Deserialize)198)]199pub enum FuncOrDataId {200/// When it's a FuncId201Func(FuncId),202/// When it's a DataId203Data(DataId),204}205206/// Mapping to `ModuleExtName` is trivial based on the `FuncId` and `DataId` mapping.207impl From<FuncOrDataId> for ModuleRelocTarget {208fn from(id: FuncOrDataId) -> Self {209match id {210FuncOrDataId::Func(funcid) => Self::from(funcid),211FuncOrDataId::Data(dataid) => Self::from(dataid),212}213}214}215216/// Information about a function which can be called.217#[derive(Debug)]218#[cfg_attr(219feature = "enable-serde",220derive(serde_derive::Serialize, serde_derive::Deserialize)221)]222#[expect(missing_docs, reason = "self-describing fields")]223pub struct FunctionDeclaration {224pub name: Option<String>,225pub linkage: Linkage,226pub signature: ir::Signature,227}228229impl FunctionDeclaration {230/// The linkage name of the function.231///232/// Synthesized from the given function id if it is an anonymous function.233pub fn linkage_name(&self, id: FuncId) -> Cow<'_, str> {234match &self.name {235Some(name) => Cow::Borrowed(name),236// Symbols starting with .L are completely omitted from the symbol table after linking.237// Using hexadecimal instead of decimal for slightly smaller symbol names and often238// slightly faster linking.239None => Cow::Owned(format!(".Lfn{:x}", id.as_u32())),240}241}242243fn merge(244&mut self,245id: FuncId,246linkage: Linkage,247sig: &ir::Signature,248) -> Result<(), ModuleError> {249self.linkage = Linkage::merge(self.linkage, linkage);250if &self.signature != sig {251return Err(ModuleError::IncompatibleSignature(252self.linkage_name(id).into_owned(),253self.signature.clone(),254sig.clone(),255));256}257Ok(())258}259}260261/// Error messages for all `Module` methods262#[derive(Debug)]263pub enum ModuleError {264/// Indicates an identifier was used before it was declared265Undeclared(String),266267/// Indicates an identifier was used as data/function first, but then used as the other268IncompatibleDeclaration(String),269270/// Indicates a function identifier was declared with a271/// different signature than declared previously272IncompatibleSignature(String, ir::Signature, ir::Signature),273274/// Indicates an identifier was defined more than once275DuplicateDefinition(String),276277/// Indicates an identifier was defined, but was declared as an import278InvalidImportDefinition(String),279280/// Wraps a `cranelift-codegen` error281Compilation(CodegenError),282283/// Memory allocation failure from a backend284Allocation {285/// Tell where the allocation came from286message: &'static str,287/// Io error the allocation failed with288err: std::io::Error,289},290291/// Wraps a generic error from a backend292Backend(anyhow::Error),293294/// Wraps an error from a flag definition.295Flag(SetError),296}297298impl<'a> From<CompileError<'a>> for ModuleError {299fn from(err: CompileError<'a>) -> Self {300Self::Compilation(err.inner)301}302}303304// This is manually implementing Error and Display instead of using thiserror to reduce the amount305// of dependencies used by Cranelift.306impl std::error::Error for ModuleError {307fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {308match self {309Self::Undeclared { .. }310| Self::IncompatibleDeclaration { .. }311| Self::IncompatibleSignature { .. }312| Self::DuplicateDefinition { .. }313| Self::InvalidImportDefinition { .. } => None,314Self::Compilation(source) => Some(source),315Self::Allocation { err: source, .. } => Some(source),316Self::Backend(source) => Some(&**source),317Self::Flag(source) => Some(source),318}319}320}321322impl std::fmt::Display for ModuleError {323fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {324match self {325Self::Undeclared(name) => {326write!(f, "Undeclared identifier: {name}")327}328Self::IncompatibleDeclaration(name) => {329write!(f, "Incompatible declaration of identifier: {name}",)330}331Self::IncompatibleSignature(name, prev_sig, new_sig) => {332write!(333f,334"Function {name} signature {new_sig:?} is incompatible with previous declaration {prev_sig:?}",335)336}337Self::DuplicateDefinition(name) => {338write!(f, "Duplicate definition of identifier: {name}")339}340Self::InvalidImportDefinition(name) => {341write!(342f,343"Invalid to define identifier declared as an import: {name}",344)345}346Self::Compilation(err) => {347write!(f, "Compilation error: {err}")348}349Self::Allocation { message, err } => {350write!(f, "Allocation error: {message}: {err}")351}352Self::Backend(err) => write!(f, "Backend error: {err}"),353Self::Flag(err) => write!(f, "Flag error: {err}"),354}355}356}357358impl std::convert::From<CodegenError> for ModuleError {359fn from(source: CodegenError) -> Self {360Self::Compilation { 0: source }361}362}363364impl std::convert::From<SetError> for ModuleError {365fn from(source: SetError) -> Self {366Self::Flag { 0: source }367}368}369370/// A convenient alias for a `Result` that uses `ModuleError` as the error type.371pub type ModuleResult<T> = Result<T, ModuleError>;372373/// Information about a data object which can be accessed.374#[derive(Debug)]375#[cfg_attr(376feature = "enable-serde",377derive(serde_derive::Serialize, serde_derive::Deserialize)378)]379#[expect(missing_docs, reason = "self-describing fields")]380pub struct DataDeclaration {381pub name: Option<String>,382pub linkage: Linkage,383pub writable: bool,384pub tls: bool,385}386387impl DataDeclaration {388/// The linkage name of the data object.389///390/// Synthesized from the given data id if it is an anonymous function.391pub fn linkage_name(&self, id: DataId) -> Cow<'_, str> {392match &self.name {393Some(name) => Cow::Borrowed(name),394// Symbols starting with .L are completely omitted from the symbol table after linking.395// Using hexadecimal instead of decimal for slightly smaller symbol names and often396// slightly faster linking.397None => Cow::Owned(format!(".Ldata{:x}", id.as_u32())),398}399}400401fn merge(&mut self, linkage: Linkage, writable: bool, tls: bool) {402self.linkage = Linkage::merge(self.linkage, linkage);403self.writable = self.writable || writable;404assert_eq!(405self.tls, tls,406"Can't change TLS data object to normal or in the opposite way",407);408}409}410411/// A translated `ExternalName` into something global we can handle.412#[derive(Clone, Debug)]413#[cfg_attr(414feature = "enable-serde",415derive(serde_derive::Serialize, serde_derive::Deserialize)416)]417pub enum ModuleRelocTarget {418/// User defined function, converted from `ExternalName::User`.419User {420/// Arbitrary.421namespace: u32,422/// Arbitrary.423index: u32,424},425/// Call into a library function.426LibCall(ir::LibCall),427/// Symbols known to the linker.428KnownSymbol(ir::KnownSymbol),429/// A offset inside a function430FunctionOffset(FuncId, CodeOffset),431}432433impl ModuleRelocTarget {434/// Creates a user-defined external name.435pub fn user(namespace: u32, index: u32) -> Self {436Self::User { namespace, index }437}438}439440impl Display for ModuleRelocTarget {441fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {442match self {443Self::User { namespace, index } => write!(f, "u{namespace}:{index}"),444Self::LibCall(lc) => write!(f, "%{lc}"),445Self::KnownSymbol(ks) => write!(f, "{ks}"),446Self::FunctionOffset(fname, offset) => write!(f, "{fname}+{offset}"),447}448}449}450451/// This provides a view to the state of a module which allows `ir::ExternalName`s to be translated452/// into `FunctionDeclaration`s and `DataDeclaration`s.453#[derive(Debug, Default)]454pub struct ModuleDeclarations {455/// A version marker used to ensure that serialized clif ir is never deserialized with a456/// different version of Cranelift.457// Note: This must be the first field to ensure that Serde will deserialize it before458// attempting to deserialize other fields that are potentially changed between versions.459_version_marker: VersionMarker,460461names: HashMap<String, FuncOrDataId>,462functions: PrimaryMap<FuncId, FunctionDeclaration>,463data_objects: PrimaryMap<DataId, DataDeclaration>,464}465466#[cfg(feature = "enable-serde")]467mod serialize {468// This is manually implementing Serialize and Deserialize to avoid serializing the names field,469// which can be entirely reconstructed from the functions and data_objects fields, saving space.470471use super::*;472473use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Unexpected, Visitor};474use serde::ser::{Serialize, SerializeStruct, Serializer};475use std::fmt;476477fn get_names<E: Error>(478functions: &PrimaryMap<FuncId, FunctionDeclaration>,479data_objects: &PrimaryMap<DataId, DataDeclaration>,480) -> Result<HashMap<String, FuncOrDataId>, E> {481let mut names = HashMap::new();482for (func_id, decl) in functions.iter() {483if let Some(name) = &decl.name {484let old = names.insert(name.clone(), FuncOrDataId::Func(func_id));485if old.is_some() {486return Err(E::invalid_value(487Unexpected::Other("duplicate name"),488&"FunctionDeclaration's with no duplicate names",489));490}491}492}493for (data_id, decl) in data_objects.iter() {494if let Some(name) = &decl.name {495let old = names.insert(name.clone(), FuncOrDataId::Data(data_id));496if old.is_some() {497return Err(E::invalid_value(498Unexpected::Other("duplicate name"),499&"DataDeclaration's with no duplicate names",500));501}502}503}504Ok(names)505}506507impl Serialize for ModuleDeclarations {508fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {509let ModuleDeclarations {510_version_marker,511functions,512data_objects,513names: _,514} = self;515516let mut state = s.serialize_struct("ModuleDeclarations", 4)?;517state.serialize_field("_version_marker", _version_marker)?;518state.serialize_field("functions", functions)?;519state.serialize_field("data_objects", data_objects)?;520state.end()521}522}523524enum ModuleDeclarationsField {525VersionMarker,526Functions,527DataObjects,528Ignore,529}530531struct ModuleDeclarationsFieldVisitor;532533impl<'de> serde::de::Visitor<'de> for ModuleDeclarationsFieldVisitor {534type Value = ModuleDeclarationsField;535536fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {537f.write_str("field identifier")538}539540fn visit_u64<E: Error>(self, val: u64) -> Result<Self::Value, E> {541match val {5420u64 => Ok(ModuleDeclarationsField::VersionMarker),5431u64 => Ok(ModuleDeclarationsField::Functions),5442u64 => Ok(ModuleDeclarationsField::DataObjects),545_ => Ok(ModuleDeclarationsField::Ignore),546}547}548549fn visit_str<E: Error>(self, val: &str) -> Result<Self::Value, E> {550match val {551"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),552"functions" => Ok(ModuleDeclarationsField::Functions),553"data_objects" => Ok(ModuleDeclarationsField::DataObjects),554_ => Ok(ModuleDeclarationsField::Ignore),555}556}557558fn visit_bytes<E: Error>(self, val: &[u8]) -> Result<Self::Value, E> {559match val {560b"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),561b"functions" => Ok(ModuleDeclarationsField::Functions),562b"data_objects" => Ok(ModuleDeclarationsField::DataObjects),563_ => Ok(ModuleDeclarationsField::Ignore),564}565}566}567568impl<'de> Deserialize<'de> for ModuleDeclarationsField {569#[inline]570fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {571d.deserialize_identifier(ModuleDeclarationsFieldVisitor)572}573}574575struct ModuleDeclarationsVisitor;576577impl<'de> Visitor<'de> for ModuleDeclarationsVisitor {578type Value = ModuleDeclarations;579580fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {581f.write_str("struct ModuleDeclarations")582}583584#[inline]585fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {586let _version_marker = match seq.next_element()? {587Some(val) => val,588None => {589return Err(Error::invalid_length(5900usize,591&"struct ModuleDeclarations with 4 elements",592));593}594};595let functions = match seq.next_element()? {596Some(val) => val,597None => {598return Err(Error::invalid_length(5992usize,600&"struct ModuleDeclarations with 4 elements",601));602}603};604let data_objects = match seq.next_element()? {605Some(val) => val,606None => {607return Err(Error::invalid_length(6083usize,609&"struct ModuleDeclarations with 4 elements",610));611}612};613let names = get_names(&functions, &data_objects)?;614Ok(ModuleDeclarations {615_version_marker,616names,617functions,618data_objects,619})620}621622#[inline]623fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {624let mut _version_marker: Option<VersionMarker> = None;625let mut functions: Option<PrimaryMap<FuncId, FunctionDeclaration>> = None;626let mut data_objects: Option<PrimaryMap<DataId, DataDeclaration>> = None;627while let Some(key) = map.next_key::<ModuleDeclarationsField>()? {628match key {629ModuleDeclarationsField::VersionMarker => {630if _version_marker.is_some() {631return Err(Error::duplicate_field("_version_marker"));632}633_version_marker = Some(map.next_value()?);634}635ModuleDeclarationsField::Functions => {636if functions.is_some() {637return Err(Error::duplicate_field("functions"));638}639functions = Some(map.next_value()?);640}641ModuleDeclarationsField::DataObjects => {642if data_objects.is_some() {643return Err(Error::duplicate_field("data_objects"));644}645data_objects = Some(map.next_value()?);646}647_ => {648map.next_value::<serde::de::IgnoredAny>()?;649}650}651}652let _version_marker = match _version_marker {653Some(_version_marker) => _version_marker,654None => return Err(Error::missing_field("_version_marker")),655};656let functions = match functions {657Some(functions) => functions,658None => return Err(Error::missing_field("functions")),659};660let data_objects = match data_objects {661Some(data_objects) => data_objects,662None => return Err(Error::missing_field("data_objects")),663};664let names = get_names(&functions, &data_objects)?;665Ok(ModuleDeclarations {666_version_marker,667names,668functions,669data_objects,670})671}672}673674impl<'de> Deserialize<'de> for ModuleDeclarations {675fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {676d.deserialize_struct(677"ModuleDeclarations",678&["_version_marker", "functions", "data_objects"],679ModuleDeclarationsVisitor,680)681}682}683}684685impl ModuleDeclarations {686/// Get the module identifier for a given name, if that name687/// has been declared.688pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {689self.names.get(name).copied()690}691692/// Get an iterator of all function declarations693pub fn get_functions(&self) -> impl Iterator<Item = (FuncId, &FunctionDeclaration)> {694self.functions.iter()695}696697/// Return whether `name` names a function, rather than a data object.698pub fn is_function(name: &ModuleRelocTarget) -> bool {699match name {700ModuleRelocTarget::User { namespace, .. } => *namespace == 0,701ModuleRelocTarget::LibCall(_)702| ModuleRelocTarget::KnownSymbol(_)703| ModuleRelocTarget::FunctionOffset(..) => {704panic!("unexpected module ext name")705}706}707}708709/// Get the `FunctionDeclaration` for the function named by `name`.710pub fn get_function_decl(&self, func_id: FuncId) -> &FunctionDeclaration {711&self.functions[func_id]712}713714/// Get an iterator of all data declarations715pub fn get_data_objects(&self) -> impl Iterator<Item = (DataId, &DataDeclaration)> {716self.data_objects.iter()717}718719/// Get the `DataDeclaration` for the data object named by `name`.720pub fn get_data_decl(&self, data_id: DataId) -> &DataDeclaration {721&self.data_objects[data_id]722}723724/// Declare a function in this module.725pub fn declare_function(726&mut self,727name: &str,728linkage: Linkage,729signature: &ir::Signature,730) -> ModuleResult<(FuncId, Linkage)> {731// TODO: Can we avoid allocating names so often?732use super::hash_map::Entry::*;733match self.names.entry(name.to_owned()) {734Occupied(entry) => match *entry.get() {735FuncOrDataId::Func(id) => {736let existing = &mut self.functions[id];737existing.merge(id, linkage, signature)?;738Ok((id, existing.linkage))739}740FuncOrDataId::Data(..) => {741Err(ModuleError::IncompatibleDeclaration(name.to_owned()))742}743},744Vacant(entry) => {745let id = self.functions.push(FunctionDeclaration {746name: Some(name.to_owned()),747linkage,748signature: signature.clone(),749});750entry.insert(FuncOrDataId::Func(id));751Ok((id, self.functions[id].linkage))752}753}754}755756/// Declare an anonymous function in this module.757pub fn declare_anonymous_function(758&mut self,759signature: &ir::Signature,760) -> ModuleResult<FuncId> {761let id = self.functions.push(FunctionDeclaration {762name: None,763linkage: Linkage::Local,764signature: signature.clone(),765});766Ok(id)767}768769/// Declare a data object in this module.770pub fn declare_data(771&mut self,772name: &str,773linkage: Linkage,774writable: bool,775tls: bool,776) -> ModuleResult<(DataId, Linkage)> {777// TODO: Can we avoid allocating names so often?778use super::hash_map::Entry::*;779match self.names.entry(name.to_owned()) {780Occupied(entry) => match *entry.get() {781FuncOrDataId::Data(id) => {782let existing = &mut self.data_objects[id];783existing.merge(linkage, writable, tls);784Ok((id, existing.linkage))785}786787FuncOrDataId::Func(..) => {788Err(ModuleError::IncompatibleDeclaration(name.to_owned()))789}790},791Vacant(entry) => {792let id = self.data_objects.push(DataDeclaration {793name: Some(name.to_owned()),794linkage,795writable,796tls,797});798entry.insert(FuncOrDataId::Data(id));799Ok((id, self.data_objects[id].linkage))800}801}802}803804/// Declare an anonymous data object in this module.805pub fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {806let id = self.data_objects.push(DataDeclaration {807name: None,808linkage: Linkage::Local,809writable,810tls,811});812Ok(id)813}814}815816/// A `Module` is a utility for collecting functions and data objects, and linking them together.817pub trait Module {818/// Return the `TargetIsa` to compile for.819fn isa(&self) -> &dyn isa::TargetIsa;820821/// Get all declarations in this module.822fn declarations(&self) -> &ModuleDeclarations;823824/// Get the module identifier for a given name, if that name825/// has been declared.826fn get_name(&self, name: &str) -> Option<FuncOrDataId> {827self.declarations().get_name(name)828}829830/// Return the target information needed by frontends to produce Cranelift IR831/// for the current target.832fn target_config(&self) -> isa::TargetFrontendConfig {833self.isa().frontend_config()834}835836/// Create a new `Context` initialized for use with this `Module`.837///838/// This ensures that the `Context` is initialized with the default calling839/// convention for the `TargetIsa`.840fn make_context(&self) -> Context {841let mut ctx = Context::new();842ctx.func.signature.call_conv = self.isa().default_call_conv();843ctx844}845846/// Clear the given `Context` and reset it for use with a new function.847///848/// This ensures that the `Context` is initialized with the default calling849/// convention for the `TargetIsa`.850fn clear_context(&self, ctx: &mut Context) {851ctx.clear();852ctx.func.signature.call_conv = self.isa().default_call_conv();853}854855/// Create a new empty `Signature` with the default calling convention for856/// the `TargetIsa`, to which parameter and return types can be added for857/// declaring a function to be called by this `Module`.858fn make_signature(&self) -> ir::Signature {859ir::Signature::new(self.isa().default_call_conv())860}861862/// Clear the given `Signature` and reset for use with a new function.863///864/// This ensures that the `Signature` is initialized with the default865/// calling convention for the `TargetIsa`.866fn clear_signature(&self, sig: &mut ir::Signature) {867sig.clear(self.isa().default_call_conv());868}869870/// Declare a function in this module.871fn declare_function(872&mut self,873name: &str,874linkage: Linkage,875signature: &ir::Signature,876) -> ModuleResult<FuncId>;877878/// Declare an anonymous function in this module.879fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId>;880881/// Declare a data object in this module.882fn declare_data(883&mut self,884name: &str,885linkage: Linkage,886writable: bool,887tls: bool,888) -> ModuleResult<DataId>;889890/// Declare an anonymous data object in this module.891fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId>;892893/// Use this when you're building the IR of a function to reference a function.894///895/// TODO: Coalesce redundant decls and signatures.896/// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.897fn declare_func_in_func(&mut self, func_id: FuncId, func: &mut ir::Function) -> ir::FuncRef {898let decl = &self.declarations().functions[func_id];899let signature = func.import_signature(decl.signature.clone());900let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {901namespace: 0,902index: func_id.as_u32(),903});904let colocated = decl.linkage.is_final();905func.import_function(ir::ExtFuncData {906name: ir::ExternalName::user(user_name_ref),907signature,908colocated,909})910}911912/// Use this when you're building the IR of a function to reference a data object.913///914/// TODO: Same as above.915fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {916let decl = &self.declarations().data_objects[data];917let colocated = decl.linkage.is_final();918let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {919namespace: 1,920index: data.as_u32(),921});922func.create_global_value(ir::GlobalValueData::Symbol {923name: ir::ExternalName::user(user_name_ref),924offset: ir::immediates::Imm64::new(0),925colocated,926tls: decl.tls,927})928}929930/// TODO: Same as above.931fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {932data.import_function(ModuleRelocTarget::user(0, func_id.as_u32()))933}934935/// TODO: Same as above.936fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {937data.import_global_value(ModuleRelocTarget::user(1, data_id.as_u32()))938}939940/// Define a function, producing the function body from the given `Context`.941///942/// Returns the size of the function's code and constant data.943///944/// Unlike [`define_function_with_control_plane`] this uses a default [`ControlPlane`] for945/// convenience.946///947/// Note: After calling this function the given `Context` will contain the compiled function.948///949/// [`define_function_with_control_plane`]: Self::define_function_with_control_plane950fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {951self.define_function_with_control_plane(func, ctx, &mut ControlPlane::default())952}953954/// Define a function, producing the function body from the given `Context`.955///956/// Returns the size of the function's code and constant data.957///958/// Note: After calling this function the given `Context` will contain the compiled function.959fn define_function_with_control_plane(960&mut self,961func: FuncId,962ctx: &mut Context,963ctrl_plane: &mut ControlPlane,964) -> ModuleResult<()>;965966/// Define a function, taking the function body from the given `bytes`.967///968/// This function is generally only useful if you need to precisely specify969/// the emitted instructions for some reason; otherwise, you should use970/// `define_function`.971///972/// Returns the size of the function's code.973fn define_function_bytes(974&mut self,975func_id: FuncId,976alignment: u64,977bytes: &[u8],978relocs: &[ModuleReloc],979) -> ModuleResult<()>;980981/// Define a data object, producing the data contents from the given `DataDescription`.982fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()>;983}984985impl<M: Module + ?Sized> Module for &mut M {986fn isa(&self) -> &dyn isa::TargetIsa {987(**self).isa()988}989990fn declarations(&self) -> &ModuleDeclarations {991(**self).declarations()992}993994fn get_name(&self, name: &str) -> Option<FuncOrDataId> {995(**self).get_name(name)996}997998fn target_config(&self) -> isa::TargetFrontendConfig {999(**self).target_config()1000}10011002fn make_context(&self) -> Context {1003(**self).make_context()1004}10051006fn clear_context(&self, ctx: &mut Context) {1007(**self).clear_context(ctx)1008}10091010fn make_signature(&self) -> ir::Signature {1011(**self).make_signature()1012}10131014fn clear_signature(&self, sig: &mut ir::Signature) {1015(**self).clear_signature(sig)1016}10171018fn declare_function(1019&mut self,1020name: &str,1021linkage: Linkage,1022signature: &ir::Signature,1023) -> ModuleResult<FuncId> {1024(**self).declare_function(name, linkage, signature)1025}10261027fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {1028(**self).declare_anonymous_function(signature)1029}10301031fn declare_data(1032&mut self,1033name: &str,1034linkage: Linkage,1035writable: bool,1036tls: bool,1037) -> ModuleResult<DataId> {1038(**self).declare_data(name, linkage, writable, tls)1039}10401041fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {1042(**self).declare_anonymous_data(writable, tls)1043}10441045fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {1046(**self).declare_func_in_func(func, in_func)1047}10481049fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {1050(**self).declare_data_in_func(data, func)1051}10521053fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {1054(**self).declare_func_in_data(func_id, data)1055}10561057fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {1058(**self).declare_data_in_data(data_id, data)1059}10601061fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {1062(**self).define_function(func, ctx)1063}10641065fn define_function_with_control_plane(1066&mut self,1067func: FuncId,1068ctx: &mut Context,1069ctrl_plane: &mut ControlPlane,1070) -> ModuleResult<()> {1071(**self).define_function_with_control_plane(func, ctx, ctrl_plane)1072}10731074fn define_function_bytes(1075&mut self,1076func_id: FuncId,1077alignment: u64,1078bytes: &[u8],1079relocs: &[ModuleReloc],1080) -> ModuleResult<()> {1081(**self).define_function_bytes(func_id, alignment, bytes, relocs)1082}10831084fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {1085(**self).define_data(data_id, data)1086}1087}10881089impl<M: Module + ?Sized> Module for Box<M> {1090fn isa(&self) -> &dyn isa::TargetIsa {1091(**self).isa()1092}10931094fn declarations(&self) -> &ModuleDeclarations {1095(**self).declarations()1096}10971098fn get_name(&self, name: &str) -> Option<FuncOrDataId> {1099(**self).get_name(name)1100}11011102fn target_config(&self) -> isa::TargetFrontendConfig {1103(**self).target_config()1104}11051106fn make_context(&self) -> Context {1107(**self).make_context()1108}11091110fn clear_context(&self, ctx: &mut Context) {1111(**self).clear_context(ctx)1112}11131114fn make_signature(&self) -> ir::Signature {1115(**self).make_signature()1116}11171118fn clear_signature(&self, sig: &mut ir::Signature) {1119(**self).clear_signature(sig)1120}11211122fn declare_function(1123&mut self,1124name: &str,1125linkage: Linkage,1126signature: &ir::Signature,1127) -> ModuleResult<FuncId> {1128(**self).declare_function(name, linkage, signature)1129}11301131fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {1132(**self).declare_anonymous_function(signature)1133}11341135fn declare_data(1136&mut self,1137name: &str,1138linkage: Linkage,1139writable: bool,1140tls: bool,1141) -> ModuleResult<DataId> {1142(**self).declare_data(name, linkage, writable, tls)1143}11441145fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {1146(**self).declare_anonymous_data(writable, tls)1147}11481149fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {1150(**self).declare_func_in_func(func, in_func)1151}11521153fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {1154(**self).declare_data_in_func(data, func)1155}11561157fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {1158(**self).declare_func_in_data(func_id, data)1159}11601161fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {1162(**self).declare_data_in_data(data_id, data)1163}11641165fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {1166(**self).define_function(func, ctx)1167}11681169fn define_function_with_control_plane(1170&mut self,1171func: FuncId,1172ctx: &mut Context,1173ctrl_plane: &mut ControlPlane,1174) -> ModuleResult<()> {1175(**self).define_function_with_control_plane(func, ctx, ctrl_plane)1176}11771178fn define_function_bytes(1179&mut self,1180func_id: FuncId,1181alignment: u64,1182bytes: &[u8],1183relocs: &[ModuleReloc],1184) -> ModuleResult<()> {1185(**self).define_function_bytes(func_id, alignment, bytes, relocs)1186}11871188fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {1189(**self).define_data(data_id, data)1190}1191}119211931194