use super::HashMap;
use crate::data_context::DataDescription;
use core::fmt::Display;
use cranelift_codegen::binemit::{CodeOffset, Reloc};
use cranelift_codegen::entity::{entity_impl, PrimaryMap};
use cranelift_codegen::ir::function::{Function, VersionMarker};
use cranelift_codegen::settings::SetError;
use cranelift_codegen::MachReloc;
use cranelift_codegen::{ir, isa, CodegenError, CompileError, Context};
use cranelift_control::ControlPlane;
use std::borrow::{Cow, ToOwned};
use std::string::String;
#[derive(Clone)]
pub struct ModuleReloc {
    pub offset: CodeOffset,
    pub kind: Reloc,
    pub name: ModuleExtName,
    pub addend: i64,
}
impl ModuleReloc {
    pub fn from_mach_reloc(mach_reloc: &MachReloc, func: &Function) -> Self {
        let name = match mach_reloc.name {
            ir::ExternalName::User(reff) => {
                let name = &func.params.user_named_funcs()[reff];
                ModuleExtName::user(name.namespace, name.index)
            }
            ir::ExternalName::TestCase(_) => unimplemented!(),
            ir::ExternalName::LibCall(libcall) => ModuleExtName::LibCall(libcall),
            ir::ExternalName::KnownSymbol(ks) => ModuleExtName::KnownSymbol(ks),
        };
        Self {
            offset: mach_reloc.offset,
            kind: mach_reloc.kind,
            name,
            addend: mach_reloc.addend,
        }
    }
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FuncId(u32);
entity_impl!(FuncId, "funcid");
impl From<FuncId> for ModuleExtName {
    fn from(id: FuncId) -> Self {
        Self::User {
            namespace: 0,
            index: id.0,
        }
    }
}
impl FuncId {
    pub fn from_name(name: &ModuleExtName) -> FuncId {
        if let ModuleExtName::User { namespace, index } = name {
            debug_assert_eq!(*namespace, 0);
            FuncId::from_u32(*index)
        } else {
            panic!("unexpected name in DataId::from_name")
        }
    }
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DataId(u32);
entity_impl!(DataId, "dataid");
impl From<DataId> for ModuleExtName {
    fn from(id: DataId) -> Self {
        Self::User {
            namespace: 1,
            index: id.0,
        }
    }
}
impl DataId {
    pub fn from_name(name: &ModuleExtName) -> DataId {
        if let ModuleExtName::User { namespace, index } = name {
            debug_assert_eq!(*namespace, 1);
            DataId::from_u32(*index)
        } else {
            panic!("unexpected name in DataId::from_name")
        }
    }
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Linkage {
    Import,
    Local,
    Preemptible,
    Hidden,
    Export,
}
impl Linkage {
    fn merge(a: Self, b: Self) -> Self {
        match a {
            Self::Export => Self::Export,
            Self::Hidden => match b {
                Self::Export => Self::Export,
                Self::Preemptible => Self::Preemptible,
                _ => Self::Hidden,
            },
            Self::Preemptible => match b {
                Self::Export => Self::Export,
                _ => Self::Preemptible,
            },
            Self::Local => match b {
                Self::Export => Self::Export,
                Self::Hidden => Self::Hidden,
                Self::Preemptible => Self::Preemptible,
                Self::Local | Self::Import => Self::Local,
            },
            Self::Import => b,
        }
    }
    pub fn is_definable(self) -> bool {
        match self {
            Self::Import => false,
            Self::Local | Self::Preemptible | Self::Hidden | Self::Export => true,
        }
    }
    pub fn is_final(self) -> bool {
        match self {
            Self::Import | Self::Preemptible => false,
            Self::Local | Self::Hidden | Self::Export => true,
        }
    }
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
#[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FuncOrDataId {
    Func(FuncId),
    Data(DataId),
}
impl From<FuncOrDataId> for ModuleExtName {
    fn from(id: FuncOrDataId) -> Self {
        match id {
            FuncOrDataId::Func(funcid) => Self::from(funcid),
            FuncOrDataId::Data(dataid) => Self::from(dataid),
        }
    }
}
#[derive(Debug)]
#[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FunctionDeclaration {
    #[allow(missing_docs)]
    pub name: Option<String>,
    #[allow(missing_docs)]
    pub linkage: Linkage,
    #[allow(missing_docs)]
    pub signature: ir::Signature,
}
impl FunctionDeclaration {
    pub fn linkage_name(&self, id: FuncId) -> Cow<'_, str> {
        match &self.name {
            Some(name) => Cow::Borrowed(name),
            None => Cow::Owned(format!(".Lfn{:x}", id.as_u32())),
        }
    }
    fn merge(
        &mut self,
        id: FuncId,
        linkage: Linkage,
        sig: &ir::Signature,
    ) -> Result<(), ModuleError> {
        self.linkage = Linkage::merge(self.linkage, linkage);
        if &self.signature != sig {
            return Err(ModuleError::IncompatibleSignature(
                self.linkage_name(id).into_owned(),
                self.signature.clone(),
                sig.clone(),
            ));
        }
        Ok(())
    }
}
#[derive(Debug)]
pub enum ModuleError {
    Undeclared(String),
    IncompatibleDeclaration(String),
    IncompatibleSignature(String, ir::Signature, ir::Signature),
    DuplicateDefinition(String),
    InvalidImportDefinition(String),
    Compilation(CodegenError),
    Allocation {
        message: &'static str,
        err: std::io::Error,
    },
    Backend(anyhow::Error),
    Flag(SetError),
}
impl<'a> From<CompileError<'a>> for ModuleError {
    fn from(err: CompileError<'a>) -> Self {
        Self::Compilation(err.inner)
    }
}
impl std::error::Error for ModuleError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Undeclared { .. }
            | Self::IncompatibleDeclaration { .. }
            | Self::IncompatibleSignature { .. }
            | Self::DuplicateDefinition { .. }
            | Self::InvalidImportDefinition { .. } => None,
            Self::Compilation(source) => Some(source),
            Self::Allocation { err: source, .. } => Some(source),
            Self::Backend(source) => Some(&**source),
            Self::Flag(source) => Some(source),
        }
    }
}
impl std::fmt::Display for ModuleError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Undeclared(name) => {
                write!(f, "Undeclared identifier: {}", name)
            }
            Self::IncompatibleDeclaration(name) => {
                write!(f, "Incompatible declaration of identifier: {}", name,)
            }
            Self::IncompatibleSignature(name, prev_sig, new_sig) => {
                write!(
                    f,
                    "Function {} signature {:?} is incompatible with previous declaration {:?}",
                    name, new_sig, prev_sig,
                )
            }
            Self::DuplicateDefinition(name) => {
                write!(f, "Duplicate definition of identifier: {}", name)
            }
            Self::InvalidImportDefinition(name) => {
                write!(
                    f,
                    "Invalid to define identifier declared as an import: {}",
                    name,
                )
            }
            Self::Compilation(err) => {
                write!(f, "Compilation error: {}", err)
            }
            Self::Allocation { message, err } => {
                write!(f, "Allocation error: {}: {}", message, err)
            }
            Self::Backend(err) => write!(f, "Backend error: {}", err),
            Self::Flag(err) => write!(f, "Flag error: {}", err),
        }
    }
}
impl std::convert::From<CodegenError> for ModuleError {
    fn from(source: CodegenError) -> Self {
        Self::Compilation { 0: source }
    }
}
impl std::convert::From<SetError> for ModuleError {
    fn from(source: SetError) -> Self {
        Self::Flag { 0: source }
    }
}
pub type ModuleResult<T> = Result<T, ModuleError>;
#[derive(Debug)]
#[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DataDeclaration {
    #[allow(missing_docs)]
    pub name: Option<String>,
    #[allow(missing_docs)]
    pub linkage: Linkage,
    #[allow(missing_docs)]
    pub writable: bool,
    #[allow(missing_docs)]
    pub tls: bool,
}
impl DataDeclaration {
    pub fn linkage_name(&self, id: DataId) -> Cow<'_, str> {
        match &self.name {
            Some(name) => Cow::Borrowed(name),
            None => Cow::Owned(format!(".Ldata{:x}", id.as_u32())),
        }
    }
    fn merge(&mut self, linkage: Linkage, writable: bool, tls: bool) {
        self.linkage = Linkage::merge(self.linkage, linkage);
        self.writable = self.writable || writable;
        assert_eq!(
            self.tls, tls,
            "Can't change TLS data object to normal or in the opposite way",
        );
    }
}
#[derive(Clone, Debug)]
#[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ModuleExtName {
    User {
        namespace: u32,
        index: u32,
    },
    LibCall(ir::LibCall),
    KnownSymbol(ir::KnownSymbol),
}
impl ModuleExtName {
    pub fn user(namespace: u32, index: u32) -> Self {
        Self::User { namespace, index }
    }
}
impl Display for ModuleExtName {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::User { namespace, index } => write!(f, "u{}:{}", namespace, index),
            Self::LibCall(lc) => write!(f, "%{}", lc),
            Self::KnownSymbol(ks) => write!(f, "{}", ks),
        }
    }
}
#[derive(Debug, Default)]
pub struct ModuleDeclarations {
    _version_marker: VersionMarker,
    names: HashMap<String, FuncOrDataId>,
    functions: PrimaryMap<FuncId, FunctionDeclaration>,
    data_objects: PrimaryMap<DataId, DataDeclaration>,
}
#[cfg(feature = "enable-serde")]
mod serialize {
    use super::*;
    use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Unexpected, Visitor};
    use serde::ser::{Serialize, SerializeStruct, Serializer};
    use std::fmt;
    fn get_names<E: Error>(
        functions: &PrimaryMap<FuncId, FunctionDeclaration>,
        data_objects: &PrimaryMap<DataId, DataDeclaration>,
    ) -> Result<HashMap<String, FuncOrDataId>, E> {
        let mut names = HashMap::new();
        for (func_id, decl) in functions.iter() {
            if let Some(name) = &decl.name {
                let old = names.insert(name.clone(), FuncOrDataId::Func(func_id));
                if old.is_some() {
                    return Err(E::invalid_value(
                        Unexpected::Other("duplicate name"),
                        &"FunctionDeclaration's with no duplicate names",
                    ));
                }
            }
        }
        for (data_id, decl) in data_objects.iter() {
            if let Some(name) = &decl.name {
                let old = names.insert(name.clone(), FuncOrDataId::Data(data_id));
                if old.is_some() {
                    return Err(E::invalid_value(
                        Unexpected::Other("duplicate name"),
                        &"DataDeclaration's with no duplicate names",
                    ));
                }
            }
        }
        Ok(names)
    }
    impl Serialize for ModuleDeclarations {
        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
            let ModuleDeclarations {
                _version_marker,
                functions,
                data_objects,
                names: _,
            } = self;
            let mut state = s.serialize_struct("ModuleDeclarations", 4)?;
            state.serialize_field("_version_marker", _version_marker)?;
            state.serialize_field("functions", functions)?;
            state.serialize_field("data_objects", data_objects)?;
            state.end()
        }
    }
    enum ModuleDeclarationsField {
        VersionMarker,
        Functions,
        DataObjects,
        Ignore,
    }
    struct ModuleDeclarationsFieldVisitor;
    impl<'de> serde::de::Visitor<'de> for ModuleDeclarationsFieldVisitor {
        type Value = ModuleDeclarationsField;
        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("field identifier")
        }
        fn visit_u64<E: Error>(self, val: u64) -> Result<Self::Value, E> {
            match val {
                0u64 => Ok(ModuleDeclarationsField::VersionMarker),
                1u64 => Ok(ModuleDeclarationsField::Functions),
                2u64 => Ok(ModuleDeclarationsField::DataObjects),
                _ => Ok(ModuleDeclarationsField::Ignore),
            }
        }
        fn visit_str<E: Error>(self, val: &str) -> Result<Self::Value, E> {
            match val {
                "_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
                "functions" => Ok(ModuleDeclarationsField::Functions),
                "data_objects" => Ok(ModuleDeclarationsField::DataObjects),
                _ => Ok(ModuleDeclarationsField::Ignore),
            }
        }
        fn visit_bytes<E: Error>(self, val: &[u8]) -> Result<Self::Value, E> {
            match val {
                b"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
                b"functions" => Ok(ModuleDeclarationsField::Functions),
                b"data_objects" => Ok(ModuleDeclarationsField::DataObjects),
                _ => Ok(ModuleDeclarationsField::Ignore),
            }
        }
    }
    impl<'de> Deserialize<'de> for ModuleDeclarationsField {
        #[inline]
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            d.deserialize_identifier(ModuleDeclarationsFieldVisitor)
        }
    }
    struct ModuleDeclarationsVisitor;
    impl<'de> Visitor<'de> for ModuleDeclarationsVisitor {
        type Value = ModuleDeclarations;
        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("struct ModuleDeclarations")
        }
        #[inline]
        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
            let _version_marker = match seq.next_element()? {
                Some(val) => val,
                None => {
                    return Err(Error::invalid_length(
                        0usize,
                        &"struct ModuleDeclarations with 4 elements",
                    ));
                }
            };
            let functions = match seq.next_element()? {
                Some(val) => val,
                None => {
                    return Err(Error::invalid_length(
                        2usize,
                        &"struct ModuleDeclarations with 4 elements",
                    ));
                }
            };
            let data_objects = match seq.next_element()? {
                Some(val) => val,
                None => {
                    return Err(Error::invalid_length(
                        3usize,
                        &"struct ModuleDeclarations with 4 elements",
                    ));
                }
            };
            let names = get_names(&functions, &data_objects)?;
            Ok(ModuleDeclarations {
                _version_marker,
                names,
                functions,
                data_objects,
            })
        }
        #[inline]
        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
            let mut _version_marker: Option<VersionMarker> = None;
            let mut functions: Option<PrimaryMap<FuncId, FunctionDeclaration>> = None;
            let mut data_objects: Option<PrimaryMap<DataId, DataDeclaration>> = None;
            while let Some(key) = map.next_key::<ModuleDeclarationsField>()? {
                match key {
                    ModuleDeclarationsField::VersionMarker => {
                        if _version_marker.is_some() {
                            return Err(Error::duplicate_field("_version_marker"));
                        }
                        _version_marker = Some(map.next_value()?);
                    }
                    ModuleDeclarationsField::Functions => {
                        if functions.is_some() {
                            return Err(Error::duplicate_field("functions"));
                        }
                        functions = Some(map.next_value()?);
                    }
                    ModuleDeclarationsField::DataObjects => {
                        if data_objects.is_some() {
                            return Err(Error::duplicate_field("data_objects"));
                        }
                        data_objects = Some(map.next_value()?);
                    }
                    _ => {
                        map.next_value::<serde::de::IgnoredAny>()?;
                    }
                }
            }
            let _version_marker = match _version_marker {
                Some(_version_marker) => _version_marker,
                None => return Err(Error::missing_field("_version_marker")),
            };
            let functions = match functions {
                Some(functions) => functions,
                None => return Err(Error::missing_field("functions")),
            };
            let data_objects = match data_objects {
                Some(data_objects) => data_objects,
                None => return Err(Error::missing_field("data_objects")),
            };
            let names = get_names(&functions, &data_objects)?;
            Ok(ModuleDeclarations {
                _version_marker,
                names,
                functions,
                data_objects,
            })
        }
    }
    impl<'de> Deserialize<'de> for ModuleDeclarations {
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            d.deserialize_struct(
                "ModuleDeclarations",
                &["_version_marker", "functions", "data_objects"],
                ModuleDeclarationsVisitor,
            )
        }
    }
}
impl ModuleDeclarations {
    pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
        self.names.get(name).copied()
    }
    pub fn get_functions(&self) -> impl Iterator<Item = (FuncId, &FunctionDeclaration)> {
        self.functions.iter()
    }
    pub fn is_function(name: &ModuleExtName) -> bool {
        match name {
            ModuleExtName::User { namespace, .. } => *namespace == 0,
            ModuleExtName::LibCall(_) | ModuleExtName::KnownSymbol(_) => {
                panic!("unexpected module ext name")
            }
        }
    }
    pub fn get_function_decl(&self, func_id: FuncId) -> &FunctionDeclaration {
        &self.functions[func_id]
    }
    pub fn get_data_objects(&self) -> impl Iterator<Item = (DataId, &DataDeclaration)> {
        self.data_objects.iter()
    }
    pub fn get_data_decl(&self, data_id: DataId) -> &DataDeclaration {
        &self.data_objects[data_id]
    }
    pub fn declare_function(
        &mut self,
        name: &str,
        linkage: Linkage,
        signature: &ir::Signature,
    ) -> ModuleResult<(FuncId, Linkage)> {
        use super::hash_map::Entry::*;
        match self.names.entry(name.to_owned()) {
            Occupied(entry) => match *entry.get() {
                FuncOrDataId::Func(id) => {
                    let existing = &mut self.functions[id];
                    existing.merge(id, linkage, signature)?;
                    Ok((id, existing.linkage))
                }
                FuncOrDataId::Data(..) => {
                    Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
                }
            },
            Vacant(entry) => {
                let id = self.functions.push(FunctionDeclaration {
                    name: Some(name.to_owned()),
                    linkage,
                    signature: signature.clone(),
                });
                entry.insert(FuncOrDataId::Func(id));
                Ok((id, self.functions[id].linkage))
            }
        }
    }
    pub fn declare_anonymous_function(
        &mut self,
        signature: &ir::Signature,
    ) -> ModuleResult<FuncId> {
        let id = self.functions.push(FunctionDeclaration {
            name: None,
            linkage: Linkage::Local,
            signature: signature.clone(),
        });
        Ok(id)
    }
    pub fn declare_data(
        &mut self,
        name: &str,
        linkage: Linkage,
        writable: bool,
        tls: bool,
    ) -> ModuleResult<(DataId, Linkage)> {
        use super::hash_map::Entry::*;
        match self.names.entry(name.to_owned()) {
            Occupied(entry) => match *entry.get() {
                FuncOrDataId::Data(id) => {
                    let existing = &mut self.data_objects[id];
                    existing.merge(linkage, writable, tls);
                    Ok((id, existing.linkage))
                }
                FuncOrDataId::Func(..) => {
                    Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
                }
            },
            Vacant(entry) => {
                let id = self.data_objects.push(DataDeclaration {
                    name: Some(name.to_owned()),
                    linkage,
                    writable,
                    tls,
                });
                entry.insert(FuncOrDataId::Data(id));
                Ok((id, self.data_objects[id].linkage))
            }
        }
    }
    pub fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
        let id = self.data_objects.push(DataDeclaration {
            name: None,
            linkage: Linkage::Local,
            writable,
            tls,
        });
        Ok(id)
    }
}
pub trait Module {
    fn isa(&self) -> &dyn isa::TargetIsa;
    fn declarations(&self) -> &ModuleDeclarations;
    fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
        self.declarations().get_name(name)
    }
    fn target_config(&self) -> isa::TargetFrontendConfig {
        self.isa().frontend_config()
    }
    fn make_context(&self) -> Context {
        let mut ctx = Context::new();
        ctx.func.signature.call_conv = self.isa().default_call_conv();
        ctx
    }
    fn clear_context(&self, ctx: &mut Context) {
        ctx.clear();
        ctx.func.signature.call_conv = self.isa().default_call_conv();
    }
    fn make_signature(&self) -> ir::Signature {
        ir::Signature::new(self.isa().default_call_conv())
    }
    fn clear_signature(&self, sig: &mut ir::Signature) {
        sig.clear(self.isa().default_call_conv());
    }
    fn declare_function(
        &mut self,
        name: &str,
        linkage: Linkage,
        signature: &ir::Signature,
    ) -> ModuleResult<FuncId>;
    fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId>;
    fn declare_data(
        &mut self,
        name: &str,
        linkage: Linkage,
        writable: bool,
        tls: bool,
    ) -> ModuleResult<DataId>;
    fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId>;
    fn declare_func_in_func(&mut self, func_id: FuncId, func: &mut ir::Function) -> ir::FuncRef {
        let decl = &self.declarations().functions[func_id];
        let signature = func.import_signature(decl.signature.clone());
        let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
            namespace: 0,
            index: func_id.as_u32(),
        });
        let colocated = decl.linkage.is_final();
        func.import_function(ir::ExtFuncData {
            name: ir::ExternalName::user(user_name_ref),
            signature,
            colocated,
        })
    }
    fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
        let decl = &self.declarations().data_objects[data];
        let colocated = decl.linkage.is_final();
        let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
            namespace: 1,
            index: data.as_u32(),
        });
        func.create_global_value(ir::GlobalValueData::Symbol {
            name: ir::ExternalName::user(user_name_ref),
            offset: ir::immediates::Imm64::new(0),
            colocated,
            tls: decl.tls,
        })
    }
    fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
        data.import_function(ModuleExtName::user(0, func_id.as_u32()))
    }
    fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
        data.import_global_value(ModuleExtName::user(1, data_id.as_u32()))
    }
    fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
        self.define_function_with_control_plane(func, ctx, &mut ControlPlane::default())
    }
    fn define_function_with_control_plane(
        &mut self,
        func: FuncId,
        ctx: &mut Context,
        ctrl_plane: &mut ControlPlane,
    ) -> ModuleResult<()>;
    fn define_function_bytes(
        &mut self,
        func_id: FuncId,
        func: &ir::Function,
        alignment: u64,
        bytes: &[u8],
        relocs: &[MachReloc],
    ) -> ModuleResult<()>;
    fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()>;
}
impl<M: Module> Module for &mut M {
    fn isa(&self) -> &dyn isa::TargetIsa {
        (**self).isa()
    }
    fn declarations(&self) -> &ModuleDeclarations {
        (**self).declarations()
    }
    fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
        (**self).get_name(name)
    }
    fn target_config(&self) -> isa::TargetFrontendConfig {
        (**self).target_config()
    }
    fn make_context(&self) -> Context {
        (**self).make_context()
    }
    fn clear_context(&self, ctx: &mut Context) {
        (**self).clear_context(ctx)
    }
    fn make_signature(&self) -> ir::Signature {
        (**self).make_signature()
    }
    fn clear_signature(&self, sig: &mut ir::Signature) {
        (**self).clear_signature(sig)
    }
    fn declare_function(
        &mut self,
        name: &str,
        linkage: Linkage,
        signature: &ir::Signature,
    ) -> ModuleResult<FuncId> {
        (**self).declare_function(name, linkage, signature)
    }
    fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {
        (**self).declare_anonymous_function(signature)
    }
    fn declare_data(
        &mut self,
        name: &str,
        linkage: Linkage,
        writable: bool,
        tls: bool,
    ) -> ModuleResult<DataId> {
        (**self).declare_data(name, linkage, writable, tls)
    }
    fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
        (**self).declare_anonymous_data(writable, tls)
    }
    fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
        (**self).declare_func_in_func(func, in_func)
    }
    fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
        (**self).declare_data_in_func(data, func)
    }
    fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
        (**self).declare_func_in_data(func_id, data)
    }
    fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
        (**self).declare_data_in_data(data_id, data)
    }
    fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
        (**self).define_function(func, ctx)
    }
    fn define_function_with_control_plane(
        &mut self,
        func: FuncId,
        ctx: &mut Context,
        ctrl_plane: &mut ControlPlane,
    ) -> ModuleResult<()> {
        (**self).define_function_with_control_plane(func, ctx, ctrl_plane)
    }
    fn define_function_bytes(
        &mut self,
        func_id: FuncId,
        func: &ir::Function,
        alignment: u64,
        bytes: &[u8],
        relocs: &[MachReloc],
    ) -> ModuleResult<()> {
        (**self).define_function_bytes(func_id, func, alignment, bytes, relocs)
    }
    fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {
        (**self).define_data(data_id, data)
    }
}