1 //! Defines `Module` and related types.
2 
3 // TODO: Should `ir::Function` really have a `name`?
4 
5 // TODO: Factor out `ir::Function`'s `ext_funcs` and `global_values` into a struct
6 // shared with `DataDescription`?
7 
8 use super::HashMap;
9 use crate::data_context::DataDescription;
10 use core::fmt::Display;
11 use cranelift_codegen::binemit::{CodeOffset, Reloc};
12 use cranelift_codegen::entity::{entity_impl, PrimaryMap};
13 use cranelift_codegen::ir::function::{Function, VersionMarker};
14 use cranelift_codegen::ir::ExternalName;
15 use cranelift_codegen::settings::SetError;
16 use cranelift_codegen::{
17     ir, isa, CodegenError, CompileError, Context, FinalizedMachReloc, FinalizedRelocTarget,
18 };
19 use cranelift_control::ControlPlane;
20 use std::borrow::{Cow, ToOwned};
21 use std::string::String;
22 
23 /// A module relocation.
24 #[derive(Clone)]
25 pub struct ModuleReloc {
26     /// The offset at which the relocation applies, *relative to the
27     /// containing section*.
28     pub offset: CodeOffset,
29     /// The kind of relocation.
30     pub kind: Reloc,
31     /// The external symbol / name to which this relocation refers.
32     pub name: ModuleRelocTarget,
33     /// The addend to add to the symbol value.
34     pub addend: i64,
35 }
36 
37 impl ModuleReloc {
38     /// Converts a `FinalizedMachReloc` produced from a `Function` into a `ModuleReloc`.
39     pub fn from_mach_reloc(
40         mach_reloc: &FinalizedMachReloc,
41         func: &Function,
42         func_id: FuncId,
43     ) -> Self {
44         let name = match mach_reloc.target {
45             FinalizedRelocTarget::ExternalName(ExternalName::User(reff)) => {
46                 let name = &func.params.user_named_funcs()[reff];
47                 ModuleRelocTarget::user(name.namespace, name.index)
48             }
49             FinalizedRelocTarget::ExternalName(ExternalName::TestCase(_)) => unimplemented!(),
50             FinalizedRelocTarget::ExternalName(ExternalName::LibCall(libcall)) => {
51                 ModuleRelocTarget::LibCall(libcall)
52             }
53             FinalizedRelocTarget::ExternalName(ExternalName::KnownSymbol(ks)) => {
54                 ModuleRelocTarget::KnownSymbol(ks)
55             }
56             FinalizedRelocTarget::Func(offset) => {
57                 ModuleRelocTarget::FunctionOffset(func_id, offset)
58             }
59         };
60         Self {
61             offset: mach_reloc.offset,
62             kind: mach_reloc.kind,
63             name,
64             addend: mach_reloc.addend,
65         }
66     }
67 }
68 
69 /// A function identifier for use in the `Module` interface.
70 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
71 #[cfg_attr(
72     feature = "enable-serde",
73     derive(serde_derive::Serialize, serde_derive::Deserialize)
74 )]
75 pub struct FuncId(u32);
76 entity_impl!(FuncId, "funcid");
77 
78 /// Function identifiers are namespace 0 in `ir::ExternalName`
79 impl From<FuncId> for ModuleRelocTarget {
80     fn from(id: FuncId) -> Self {
81         Self::User {
82             namespace: 0,
83             index: id.0,
84         }
85     }
86 }
87 
88 impl FuncId {
89     /// Get the `FuncId` for the function named by `name`.
90     pub fn from_name(name: &ModuleRelocTarget) -> FuncId {
91         if let ModuleRelocTarget::User { namespace, index } = name {
92             debug_assert_eq!(*namespace, 0);
93             FuncId::from_u32(*index)
94         } else {
95             panic!("unexpected name in DataId::from_name")
96         }
97     }
98 }
99 
100 /// A data object identifier for use in the `Module` interface.
101 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
102 #[cfg_attr(
103     feature = "enable-serde",
104     derive(serde_derive::Serialize, serde_derive::Deserialize)
105 )]
106 pub struct DataId(u32);
107 entity_impl!(DataId, "dataid");
108 
109 /// Data identifiers are namespace 1 in `ir::ExternalName`
110 impl From<DataId> for ModuleRelocTarget {
111     fn from(id: DataId) -> Self {
112         Self::User {
113             namespace: 1,
114             index: id.0,
115         }
116     }
117 }
118 
119 impl DataId {
120     /// Get the `DataId` for the data object named by `name`.
121     pub fn from_name(name: &ModuleRelocTarget) -> DataId {
122         if let ModuleRelocTarget::User { namespace, index } = name {
123             debug_assert_eq!(*namespace, 1);
124             DataId::from_u32(*index)
125         } else {
126             panic!("unexpected name in DataId::from_name")
127         }
128     }
129 }
130 
131 /// Linkage refers to where an entity is defined and who can see it.
132 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
133 #[cfg_attr(
134     feature = "enable-serde",
135     derive(serde_derive::Serialize, serde_derive::Deserialize)
136 )]
137 pub enum Linkage {
138     /// Defined outside of a module.
139     Import,
140     /// Defined inside the module, but not visible outside it.
141     Local,
142     /// Defined inside the module, visible outside it, and may be preempted.
143     Preemptible,
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 create
147     /// an executable or dynamic library.
148     Hidden,
149     /// Defined inside the module, and visible outside it.
150     Export,
151 }
152 
153 impl Linkage {
154     fn merge(a: Self, b: Self) -> Self {
155         match a {
156             Self::Export => Self::Export,
157             Self::Hidden => match b {
158                 Self::Export => Self::Export,
159                 Self::Preemptible => Self::Preemptible,
160                 _ => Self::Hidden,
161             },
162             Self::Preemptible => match b {
163                 Self::Export => Self::Export,
164                 _ => Self::Preemptible,
165             },
166             Self::Local => match b {
167                 Self::Export => Self::Export,
168                 Self::Hidden => Self::Hidden,
169                 Self::Preemptible => Self::Preemptible,
170                 Self::Local | Self::Import => Self::Local,
171             },
172             Self::Import => b,
173         }
174     }
175 
176     /// Test whether this linkage can have a definition.
177     pub fn is_definable(self) -> bool {
178         match self {
179             Self::Import => false,
180             Self::Local | Self::Preemptible | Self::Hidden | Self::Export => true,
181         }
182     }
183 
184     /// Test whether this linkage will have a definition that cannot be preempted.
185     pub fn is_final(self) -> bool {
186         match self {
187             Self::Import | Self::Preemptible => false,
188             Self::Local | Self::Hidden | Self::Export => true,
189         }
190     }
191 }
192 
193 /// A declared name may refer to either a function or data declaration
194 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
195 #[cfg_attr(
196     feature = "enable-serde",
197     derive(serde_derive::Serialize, serde_derive::Deserialize)
198 )]
199 pub enum FuncOrDataId {
200     /// When it's a FuncId
201     Func(FuncId),
202     /// When it's a DataId
203     Data(DataId),
204 }
205 
206 /// Mapping to `ModuleExtName` is trivial based on the `FuncId` and `DataId` mapping.
207 impl From<FuncOrDataId> for ModuleRelocTarget {
208     fn from(id: FuncOrDataId) -> Self {
209         match id {
210             FuncOrDataId::Func(funcid) => Self::from(funcid),
211             FuncOrDataId::Data(dataid) => Self::from(dataid),
212         }
213     }
214 }
215 
216 /// Information about a function which can be called.
217 #[derive(Debug)]
218 #[cfg_attr(
219     feature = "enable-serde",
220     derive(serde_derive::Serialize, serde_derive::Deserialize)
221 )]
222 pub struct FunctionDeclaration {
223     #[allow(missing_docs)]
224     pub name: Option<String>,
225     #[allow(missing_docs)]
226     pub linkage: Linkage,
227     #[allow(missing_docs)]
228     pub signature: ir::Signature,
229 }
230 
231 impl FunctionDeclaration {
232     /// The linkage name of the function.
233     ///
234     /// Synthesized from the given function id if it is an anonymous function.
235     pub fn linkage_name(&self, id: FuncId) -> Cow<'_, str> {
236         match &self.name {
237             Some(name) => Cow::Borrowed(name),
238             // Symbols starting with .L are completely omitted from the symbol table after linking.
239             // Using hexadecimal instead of decimal for slightly smaller symbol names and often
240             // slightly faster linking.
241             None => Cow::Owned(format!(".Lfn{:x}", id.as_u32())),
242         }
243     }
244 
245     fn merge(
246         &mut self,
247         id: FuncId,
248         linkage: Linkage,
249         sig: &ir::Signature,
250     ) -> Result<(), ModuleError> {
251         self.linkage = Linkage::merge(self.linkage, linkage);
252         if &self.signature != sig {
253             return Err(ModuleError::IncompatibleSignature(
254                 self.linkage_name(id).into_owned(),
255                 self.signature.clone(),
256                 sig.clone(),
257             ));
258         }
259         Ok(())
260     }
261 }
262 
263 /// Error messages for all `Module` methods
264 #[derive(Debug)]
265 pub enum ModuleError {
266     /// Indicates an identifier was used before it was declared
267     Undeclared(String),
268 
269     /// Indicates an identifier was used as data/function first, but then used as the other
270     IncompatibleDeclaration(String),
271 
272     /// Indicates a function identifier was declared with a
273     /// different signature than declared previously
274     IncompatibleSignature(String, ir::Signature, ir::Signature),
275 
276     /// Indicates an identifier was defined more than once
277     DuplicateDefinition(String),
278 
279     /// Indicates an identifier was defined, but was declared as an import
280     InvalidImportDefinition(String),
281 
282     /// Wraps a `cranelift-codegen` error
283     Compilation(CodegenError),
284 
285     /// Memory allocation failure from a backend
286     Allocation {
287         /// Tell where the allocation came from
288         message: &'static str,
289         /// Io error the allocation failed with
290         err: std::io::Error,
291     },
292 
293     /// Wraps a generic error from a backend
294     Backend(anyhow::Error),
295 
296     /// Wraps an error from a flag definition.
297     Flag(SetError),
298 }
299 
300 impl<'a> From<CompileError<'a>> for ModuleError {
301     fn from(err: CompileError<'a>) -> Self {
302         Self::Compilation(err.inner)
303     }
304 }
305 
306 // This is manually implementing Error and Display instead of using thiserror to reduce the amount
307 // of dependencies used by Cranelift.
308 impl std::error::Error for ModuleError {
309     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
310         match self {
311             Self::Undeclared { .. }
312             | Self::IncompatibleDeclaration { .. }
313             | Self::IncompatibleSignature { .. }
314             | Self::DuplicateDefinition { .. }
315             | Self::InvalidImportDefinition { .. } => None,
316             Self::Compilation(source) => Some(source),
317             Self::Allocation { err: source, .. } => Some(source),
318             Self::Backend(source) => Some(&**source),
319             Self::Flag(source) => Some(source),
320         }
321     }
322 }
323 
324 impl std::fmt::Display for ModuleError {
325     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
326         match self {
327             Self::Undeclared(name) => {
328                 write!(f, "Undeclared identifier: {}", name)
329             }
330             Self::IncompatibleDeclaration(name) => {
331                 write!(f, "Incompatible declaration of identifier: {}", name,)
332             }
333             Self::IncompatibleSignature(name, prev_sig, new_sig) => {
334                 write!(
335                     f,
336                     "Function {} signature {:?} is incompatible with previous declaration {:?}",
337                     name, new_sig, prev_sig,
338                 )
339             }
340             Self::DuplicateDefinition(name) => {
341                 write!(f, "Duplicate definition of identifier: {}", name)
342             }
343             Self::InvalidImportDefinition(name) => {
344                 write!(
345                     f,
346                     "Invalid to define identifier declared as an import: {}",
347                     name,
348                 )
349             }
350             Self::Compilation(err) => {
351                 write!(f, "Compilation error: {}", err)
352             }
353             Self::Allocation { message, err } => {
354                 write!(f, "Allocation error: {}: {}", message, err)
355             }
356             Self::Backend(err) => write!(f, "Backend error: {}", err),
357             Self::Flag(err) => write!(f, "Flag error: {}", err),
358         }
359     }
360 }
361 
362 impl std::convert::From<CodegenError> for ModuleError {
363     fn from(source: CodegenError) -> Self {
364         Self::Compilation { 0: source }
365     }
366 }
367 
368 impl std::convert::From<SetError> for ModuleError {
369     fn from(source: SetError) -> Self {
370         Self::Flag { 0: source }
371     }
372 }
373 
374 /// A convenient alias for a `Result` that uses `ModuleError` as the error type.
375 pub type ModuleResult<T> = Result<T, ModuleError>;
376 
377 /// Information about a data object which can be accessed.
378 #[derive(Debug)]
379 #[cfg_attr(
380     feature = "enable-serde",
381     derive(serde_derive::Serialize, serde_derive::Deserialize)
382 )]
383 pub struct DataDeclaration {
384     #[allow(missing_docs)]
385     pub name: Option<String>,
386     #[allow(missing_docs)]
387     pub linkage: Linkage,
388     #[allow(missing_docs)]
389     pub writable: bool,
390     #[allow(missing_docs)]
391     pub tls: bool,
392 }
393 
394 impl DataDeclaration {
395     /// The linkage name of the data object.
396     ///
397     /// Synthesized from the given data id if it is an anonymous function.
398     pub fn linkage_name(&self, id: DataId) -> Cow<'_, str> {
399         match &self.name {
400             Some(name) => Cow::Borrowed(name),
401             // Symbols starting with .L are completely omitted from the symbol table after linking.
402             // Using hexadecimal instead of decimal for slightly smaller symbol names and often
403             // slightly faster linking.
404             None => Cow::Owned(format!(".Ldata{:x}", id.as_u32())),
405         }
406     }
407 
408     fn merge(&mut self, linkage: Linkage, writable: bool, tls: bool) {
409         self.linkage = Linkage::merge(self.linkage, linkage);
410         self.writable = self.writable || writable;
411         assert_eq!(
412             self.tls, tls,
413             "Can't change TLS data object to normal or in the opposite way",
414         );
415     }
416 }
417 
418 /// A translated `ExternalName` into something global we can handle.
419 #[derive(Clone, Debug)]
420 #[cfg_attr(
421     feature = "enable-serde",
422     derive(serde_derive::Serialize, serde_derive::Deserialize)
423 )]
424 pub enum ModuleRelocTarget {
425     /// User defined function, converted from `ExternalName::User`.
426     User {
427         /// Arbitrary.
428         namespace: u32,
429         /// Arbitrary.
430         index: u32,
431     },
432     /// Call into a library function.
433     LibCall(ir::LibCall),
434     /// Symbols known to the linker.
435     KnownSymbol(ir::KnownSymbol),
436     /// A offset inside a function
437     FunctionOffset(FuncId, CodeOffset),
438 }
439 
440 impl ModuleRelocTarget {
441     /// Creates a user-defined external name.
442     pub fn user(namespace: u32, index: u32) -> Self {
443         Self::User { namespace, index }
444     }
445 }
446 
447 impl Display for ModuleRelocTarget {
448     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
449         match self {
450             Self::User { namespace, index } => write!(f, "u{}:{}", namespace, index),
451             Self::LibCall(lc) => write!(f, "%{}", lc),
452             Self::KnownSymbol(ks) => write!(f, "{}", ks),
453             Self::FunctionOffset(fname, offset) => write!(f, "{fname}+{offset}"),
454         }
455     }
456 }
457 
458 /// This provides a view to the state of a module which allows `ir::ExternalName`s to be translated
459 /// into `FunctionDeclaration`s and `DataDeclaration`s.
460 #[derive(Debug, Default)]
461 pub struct ModuleDeclarations {
462     /// A version marker used to ensure that serialized clif ir is never deserialized with a
463     /// different version of Cranelift.
464     // Note: This must be the first field to ensure that Serde will deserialize it before
465     // attempting to deserialize other fields that are potentially changed between versions.
466     _version_marker: VersionMarker,
467 
468     names: HashMap<String, FuncOrDataId>,
469     functions: PrimaryMap<FuncId, FunctionDeclaration>,
470     data_objects: PrimaryMap<DataId, DataDeclaration>,
471 }
472 
473 #[cfg(feature = "enable-serde")]
474 mod serialize {
475     // This is manually implementing Serialize and Deserialize to avoid serializing the names field,
476     // which can be entirely reconstructed from the functions and data_objects fields, saving space.
477 
478     use super::*;
479 
480     use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Unexpected, Visitor};
481     use serde::ser::{Serialize, SerializeStruct, Serializer};
482     use std::fmt;
483 
484     fn get_names<E: Error>(
485         functions: &PrimaryMap<FuncId, FunctionDeclaration>,
486         data_objects: &PrimaryMap<DataId, DataDeclaration>,
487     ) -> Result<HashMap<String, FuncOrDataId>, E> {
488         let mut names = HashMap::new();
489         for (func_id, decl) in functions.iter() {
490             if let Some(name) = &decl.name {
491                 let old = names.insert(name.clone(), FuncOrDataId::Func(func_id));
492                 if old.is_some() {
493                     return Err(E::invalid_value(
494                         Unexpected::Other("duplicate name"),
495                         &"FunctionDeclaration's with no duplicate names",
496                     ));
497                 }
498             }
499         }
500         for (data_id, decl) in data_objects.iter() {
501             if let Some(name) = &decl.name {
502                 let old = names.insert(name.clone(), FuncOrDataId::Data(data_id));
503                 if old.is_some() {
504                     return Err(E::invalid_value(
505                         Unexpected::Other("duplicate name"),
506                         &"DataDeclaration's with no duplicate names",
507                     ));
508                 }
509             }
510         }
511         Ok(names)
512     }
513 
514     impl Serialize for ModuleDeclarations {
515         fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
516             let ModuleDeclarations {
517                 _version_marker,
518                 functions,
519                 data_objects,
520                 names: _,
521             } = self;
522 
523             let mut state = s.serialize_struct("ModuleDeclarations", 4)?;
524             state.serialize_field("_version_marker", _version_marker)?;
525             state.serialize_field("functions", functions)?;
526             state.serialize_field("data_objects", data_objects)?;
527             state.end()
528         }
529     }
530 
531     enum ModuleDeclarationsField {
532         VersionMarker,
533         Functions,
534         DataObjects,
535         Ignore,
536     }
537 
538     struct ModuleDeclarationsFieldVisitor;
539 
540     impl<'de> serde::de::Visitor<'de> for ModuleDeclarationsFieldVisitor {
541         type Value = ModuleDeclarationsField;
542 
543         fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
544             f.write_str("field identifier")
545         }
546 
547         fn visit_u64<E: Error>(self, val: u64) -> Result<Self::Value, E> {
548             match val {
549                 0u64 => Ok(ModuleDeclarationsField::VersionMarker),
550                 1u64 => Ok(ModuleDeclarationsField::Functions),
551                 2u64 => Ok(ModuleDeclarationsField::DataObjects),
552                 _ => Ok(ModuleDeclarationsField::Ignore),
553             }
554         }
555 
556         fn visit_str<E: Error>(self, val: &str) -> Result<Self::Value, E> {
557             match val {
558                 "_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
559                 "functions" => Ok(ModuleDeclarationsField::Functions),
560                 "data_objects" => Ok(ModuleDeclarationsField::DataObjects),
561                 _ => Ok(ModuleDeclarationsField::Ignore),
562             }
563         }
564 
565         fn visit_bytes<E: Error>(self, val: &[u8]) -> Result<Self::Value, E> {
566             match val {
567                 b"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
568                 b"functions" => Ok(ModuleDeclarationsField::Functions),
569                 b"data_objects" => Ok(ModuleDeclarationsField::DataObjects),
570                 _ => Ok(ModuleDeclarationsField::Ignore),
571             }
572         }
573     }
574 
575     impl<'de> Deserialize<'de> for ModuleDeclarationsField {
576         #[inline]
577         fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
578             d.deserialize_identifier(ModuleDeclarationsFieldVisitor)
579         }
580     }
581 
582     struct ModuleDeclarationsVisitor;
583 
584     impl<'de> Visitor<'de> for ModuleDeclarationsVisitor {
585         type Value = ModuleDeclarations;
586 
587         fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
588             f.write_str("struct ModuleDeclarations")
589         }
590 
591         #[inline]
592         fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
593             let _version_marker = match seq.next_element()? {
594                 Some(val) => val,
595                 None => {
596                     return Err(Error::invalid_length(
597                         0usize,
598                         &"struct ModuleDeclarations with 4 elements",
599                     ));
600                 }
601             };
602             let functions = match seq.next_element()? {
603                 Some(val) => val,
604                 None => {
605                     return Err(Error::invalid_length(
606                         2usize,
607                         &"struct ModuleDeclarations with 4 elements",
608                     ));
609                 }
610             };
611             let data_objects = match seq.next_element()? {
612                 Some(val) => val,
613                 None => {
614                     return Err(Error::invalid_length(
615                         3usize,
616                         &"struct ModuleDeclarations with 4 elements",
617                     ));
618                 }
619             };
620             let names = get_names(&functions, &data_objects)?;
621             Ok(ModuleDeclarations {
622                 _version_marker,
623                 names,
624                 functions,
625                 data_objects,
626             })
627         }
628 
629         #[inline]
630         fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
631             let mut _version_marker: Option<VersionMarker> = None;
632             let mut functions: Option<PrimaryMap<FuncId, FunctionDeclaration>> = None;
633             let mut data_objects: Option<PrimaryMap<DataId, DataDeclaration>> = None;
634             while let Some(key) = map.next_key::<ModuleDeclarationsField>()? {
635                 match key {
636                     ModuleDeclarationsField::VersionMarker => {
637                         if _version_marker.is_some() {
638                             return Err(Error::duplicate_field("_version_marker"));
639                         }
640                         _version_marker = Some(map.next_value()?);
641                     }
642                     ModuleDeclarationsField::Functions => {
643                         if functions.is_some() {
644                             return Err(Error::duplicate_field("functions"));
645                         }
646                         functions = Some(map.next_value()?);
647                     }
648                     ModuleDeclarationsField::DataObjects => {
649                         if data_objects.is_some() {
650                             return Err(Error::duplicate_field("data_objects"));
651                         }
652                         data_objects = Some(map.next_value()?);
653                     }
654                     _ => {
655                         map.next_value::<serde::de::IgnoredAny>()?;
656                     }
657                 }
658             }
659             let _version_marker = match _version_marker {
660                 Some(_version_marker) => _version_marker,
661                 None => return Err(Error::missing_field("_version_marker")),
662             };
663             let functions = match functions {
664                 Some(functions) => functions,
665                 None => return Err(Error::missing_field("functions")),
666             };
667             let data_objects = match data_objects {
668                 Some(data_objects) => data_objects,
669                 None => return Err(Error::missing_field("data_objects")),
670             };
671             let names = get_names(&functions, &data_objects)?;
672             Ok(ModuleDeclarations {
673                 _version_marker,
674                 names,
675                 functions,
676                 data_objects,
677             })
678         }
679     }
680 
681     impl<'de> Deserialize<'de> for ModuleDeclarations {
682         fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
683             d.deserialize_struct(
684                 "ModuleDeclarations",
685                 &["_version_marker", "functions", "data_objects"],
686                 ModuleDeclarationsVisitor,
687             )
688         }
689     }
690 }
691 
692 impl ModuleDeclarations {
693     /// Get the module identifier for a given name, if that name
694     /// has been declared.
695     pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
696         self.names.get(name).copied()
697     }
698 
699     /// Get an iterator of all function declarations
700     pub fn get_functions(&self) -> impl Iterator<Item = (FuncId, &FunctionDeclaration)> {
701         self.functions.iter()
702     }
703 
704     /// Return whether `name` names a function, rather than a data object.
705     pub fn is_function(name: &ModuleRelocTarget) -> bool {
706         match name {
707             ModuleRelocTarget::User { namespace, .. } => *namespace == 0,
708             ModuleRelocTarget::LibCall(_)
709             | ModuleRelocTarget::KnownSymbol(_)
710             | ModuleRelocTarget::FunctionOffset(..) => {
711                 panic!("unexpected module ext name")
712             }
713         }
714     }
715 
716     /// Get the `FunctionDeclaration` for the function named by `name`.
717     pub fn get_function_decl(&self, func_id: FuncId) -> &FunctionDeclaration {
718         &self.functions[func_id]
719     }
720 
721     /// Get an iterator of all data declarations
722     pub fn get_data_objects(&self) -> impl Iterator<Item = (DataId, &DataDeclaration)> {
723         self.data_objects.iter()
724     }
725 
726     /// Get the `DataDeclaration` for the data object named by `name`.
727     pub fn get_data_decl(&self, data_id: DataId) -> &DataDeclaration {
728         &self.data_objects[data_id]
729     }
730 
731     /// Declare a function in this module.
732     pub fn declare_function(
733         &mut self,
734         name: &str,
735         linkage: Linkage,
736         signature: &ir::Signature,
737     ) -> ModuleResult<(FuncId, Linkage)> {
738         // TODO: Can we avoid allocating names so often?
739         use super::hash_map::Entry::*;
740         match self.names.entry(name.to_owned()) {
741             Occupied(entry) => match *entry.get() {
742                 FuncOrDataId::Func(id) => {
743                     let existing = &mut self.functions[id];
744                     existing.merge(id, linkage, signature)?;
745                     Ok((id, existing.linkage))
746                 }
747                 FuncOrDataId::Data(..) => {
748                     Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
749                 }
750             },
751             Vacant(entry) => {
752                 let id = self.functions.push(FunctionDeclaration {
753                     name: Some(name.to_owned()),
754                     linkage,
755                     signature: signature.clone(),
756                 });
757                 entry.insert(FuncOrDataId::Func(id));
758                 Ok((id, self.functions[id].linkage))
759             }
760         }
761     }
762 
763     /// Declare an anonymous function in this module.
764     pub fn declare_anonymous_function(
765         &mut self,
766         signature: &ir::Signature,
767     ) -> ModuleResult<FuncId> {
768         let id = self.functions.push(FunctionDeclaration {
769             name: None,
770             linkage: Linkage::Local,
771             signature: signature.clone(),
772         });
773         Ok(id)
774     }
775 
776     /// Declare a data object in this module.
777     pub fn declare_data(
778         &mut self,
779         name: &str,
780         linkage: Linkage,
781         writable: bool,
782         tls: bool,
783     ) -> ModuleResult<(DataId, Linkage)> {
784         // TODO: Can we avoid allocating names so often?
785         use super::hash_map::Entry::*;
786         match self.names.entry(name.to_owned()) {
787             Occupied(entry) => match *entry.get() {
788                 FuncOrDataId::Data(id) => {
789                     let existing = &mut self.data_objects[id];
790                     existing.merge(linkage, writable, tls);
791                     Ok((id, existing.linkage))
792                 }
793 
794                 FuncOrDataId::Func(..) => {
795                     Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
796                 }
797             },
798             Vacant(entry) => {
799                 let id = self.data_objects.push(DataDeclaration {
800                     name: Some(name.to_owned()),
801                     linkage,
802                     writable,
803                     tls,
804                 });
805                 entry.insert(FuncOrDataId::Data(id));
806                 Ok((id, self.data_objects[id].linkage))
807             }
808         }
809     }
810 
811     /// Declare an anonymous data object in this module.
812     pub fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
813         let id = self.data_objects.push(DataDeclaration {
814             name: None,
815             linkage: Linkage::Local,
816             writable,
817             tls,
818         });
819         Ok(id)
820     }
821 }
822 
823 /// A `Module` is a utility for collecting functions and data objects, and linking them together.
824 pub trait Module {
825     /// Return the `TargetIsa` to compile for.
826     fn isa(&self) -> &dyn isa::TargetIsa;
827 
828     /// Get all declarations in this module.
829     fn declarations(&self) -> &ModuleDeclarations;
830 
831     /// Get the module identifier for a given name, if that name
832     /// has been declared.
833     fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
834         self.declarations().get_name(name)
835     }
836 
837     /// Return the target information needed by frontends to produce Cranelift IR
838     /// for the current target.
839     fn target_config(&self) -> isa::TargetFrontendConfig {
840         self.isa().frontend_config()
841     }
842 
843     /// Create a new `Context` initialized for use with this `Module`.
844     ///
845     /// This ensures that the `Context` is initialized with the default calling
846     /// convention for the `TargetIsa`.
847     fn make_context(&self) -> Context {
848         let mut ctx = Context::new();
849         ctx.func.signature.call_conv = self.isa().default_call_conv();
850         ctx
851     }
852 
853     /// Clear the given `Context` and reset it for use with a new function.
854     ///
855     /// This ensures that the `Context` is initialized with the default calling
856     /// convention for the `TargetIsa`.
857     fn clear_context(&self, ctx: &mut Context) {
858         ctx.clear();
859         ctx.func.signature.call_conv = self.isa().default_call_conv();
860     }
861 
862     /// Create a new empty `Signature` with the default calling convention for
863     /// the `TargetIsa`, to which parameter and return types can be added for
864     /// declaring a function to be called by this `Module`.
865     fn make_signature(&self) -> ir::Signature {
866         ir::Signature::new(self.isa().default_call_conv())
867     }
868 
869     /// Clear the given `Signature` and reset for use with a new function.
870     ///
871     /// This ensures that the `Signature` is initialized with the default
872     /// calling convention for the `TargetIsa`.
873     fn clear_signature(&self, sig: &mut ir::Signature) {
874         sig.clear(self.isa().default_call_conv());
875     }
876 
877     /// Declare a function in this module.
878     fn declare_function(
879         &mut self,
880         name: &str,
881         linkage: Linkage,
882         signature: &ir::Signature,
883     ) -> ModuleResult<FuncId>;
884 
885     /// Declare an anonymous function in this module.
886     fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId>;
887 
888     /// Declare a data object in this module.
889     fn declare_data(
890         &mut self,
891         name: &str,
892         linkage: Linkage,
893         writable: bool,
894         tls: bool,
895     ) -> ModuleResult<DataId>;
896 
897     /// Declare an anonymous data object in this module.
898     fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId>;
899 
900     /// Use this when you're building the IR of a function to reference a function.
901     ///
902     /// TODO: Coalesce redundant decls and signatures.
903     /// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.
904     fn declare_func_in_func(&mut self, func_id: FuncId, func: &mut ir::Function) -> ir::FuncRef {
905         let decl = &self.declarations().functions[func_id];
906         let signature = func.import_signature(decl.signature.clone());
907         let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
908             namespace: 0,
909             index: func_id.as_u32(),
910         });
911         let colocated = decl.linkage.is_final();
912         func.import_function(ir::ExtFuncData {
913             name: ir::ExternalName::user(user_name_ref),
914             signature,
915             colocated,
916         })
917     }
918 
919     /// Use this when you're building the IR of a function to reference a data object.
920     ///
921     /// TODO: Same as above.
922     fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
923         let decl = &self.declarations().data_objects[data];
924         let colocated = decl.linkage.is_final();
925         let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
926             namespace: 1,
927             index: data.as_u32(),
928         });
929         func.create_global_value(ir::GlobalValueData::Symbol {
930             name: ir::ExternalName::user(user_name_ref),
931             offset: ir::immediates::Imm64::new(0),
932             colocated,
933             tls: decl.tls,
934         })
935     }
936 
937     /// TODO: Same as above.
938     fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
939         data.import_function(ModuleRelocTarget::user(0, func_id.as_u32()))
940     }
941 
942     /// TODO: Same as above.
943     fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
944         data.import_global_value(ModuleRelocTarget::user(1, data_id.as_u32()))
945     }
946 
947     /// Define a function, producing the function body from the given `Context`.
948     ///
949     /// Returns the size of the function's code and constant data.
950     ///
951     /// Unlike [`define_function_with_control_plane`] this uses a default [`ControlPlane`] for
952     /// convenience.
953     ///
954     /// Note: After calling this function the given `Context` will contain the compiled function.
955     ///
956     /// [`define_function_with_control_plane`]: Self::define_function_with_control_plane
957     fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
958         self.define_function_with_control_plane(func, ctx, &mut ControlPlane::default())
959     }
960 
961     /// Define a function, producing the function body from the given `Context`.
962     ///
963     /// Returns the size of the function's code and constant data.
964     ///
965     /// Note: After calling this function the given `Context` will contain the compiled function.
966     fn define_function_with_control_plane(
967         &mut self,
968         func: FuncId,
969         ctx: &mut Context,
970         ctrl_plane: &mut ControlPlane,
971     ) -> ModuleResult<()>;
972 
973     /// Define a function, taking the function body from the given `bytes`.
974     ///
975     /// This function is generally only useful if you need to precisely specify
976     /// the emitted instructions for some reason; otherwise, you should use
977     /// `define_function`.
978     ///
979     /// Returns the size of the function's code.
980     fn define_function_bytes(
981         &mut self,
982         func_id: FuncId,
983         func: &ir::Function,
984         alignment: u64,
985         bytes: &[u8],
986         relocs: &[FinalizedMachReloc],
987     ) -> ModuleResult<()>;
988 
989     /// Define a data object, producing the data contents from the given `DataContext`.
990     fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()>;
991 }
992 
993 impl<M: Module> Module for &mut M {
994     fn isa(&self) -> &dyn isa::TargetIsa {
995         (**self).isa()
996     }
997 
998     fn declarations(&self) -> &ModuleDeclarations {
999         (**self).declarations()
1000     }
1001 
1002     fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
1003         (**self).get_name(name)
1004     }
1005 
1006     fn target_config(&self) -> isa::TargetFrontendConfig {
1007         (**self).target_config()
1008     }
1009 
1010     fn make_context(&self) -> Context {
1011         (**self).make_context()
1012     }
1013 
1014     fn clear_context(&self, ctx: &mut Context) {
1015         (**self).clear_context(ctx)
1016     }
1017 
1018     fn make_signature(&self) -> ir::Signature {
1019         (**self).make_signature()
1020     }
1021 
1022     fn clear_signature(&self, sig: &mut ir::Signature) {
1023         (**self).clear_signature(sig)
1024     }
1025 
1026     fn declare_function(
1027         &mut self,
1028         name: &str,
1029         linkage: Linkage,
1030         signature: &ir::Signature,
1031     ) -> ModuleResult<FuncId> {
1032         (**self).declare_function(name, linkage, signature)
1033     }
1034 
1035     fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {
1036         (**self).declare_anonymous_function(signature)
1037     }
1038 
1039     fn declare_data(
1040         &mut self,
1041         name: &str,
1042         linkage: Linkage,
1043         writable: bool,
1044         tls: bool,
1045     ) -> ModuleResult<DataId> {
1046         (**self).declare_data(name, linkage, writable, tls)
1047     }
1048 
1049     fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
1050         (**self).declare_anonymous_data(writable, tls)
1051     }
1052 
1053     fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
1054         (**self).declare_func_in_func(func, in_func)
1055     }
1056 
1057     fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
1058         (**self).declare_data_in_func(data, func)
1059     }
1060 
1061     fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
1062         (**self).declare_func_in_data(func_id, data)
1063     }
1064 
1065     fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
1066         (**self).declare_data_in_data(data_id, data)
1067     }
1068 
1069     fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
1070         (**self).define_function(func, ctx)
1071     }
1072 
1073     fn define_function_with_control_plane(
1074         &mut self,
1075         func: FuncId,
1076         ctx: &mut Context,
1077         ctrl_plane: &mut ControlPlane,
1078     ) -> ModuleResult<()> {
1079         (**self).define_function_with_control_plane(func, ctx, ctrl_plane)
1080     }
1081 
1082     fn define_function_bytes(
1083         &mut self,
1084         func_id: FuncId,
1085         func: &ir::Function,
1086         alignment: u64,
1087         bytes: &[u8],
1088         relocs: &[FinalizedMachReloc],
1089     ) -> ModuleResult<()> {
1090         (**self).define_function_bytes(func_id, func, alignment, bytes, relocs)
1091     }
1092 
1093     fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {
1094         (**self).define_data(data_id, data)
1095     }
1096 }
1097