1use crate::component::*;
31use crate::error::Result;
32use crate::prelude::*;
33use crate::{
34 EntityIndex, EntityRef, ModuleInternedTypeIndex, PanicOnOom as _, PrimaryMap, Trap, WasmValType,
35};
36use cranelift_entity::EntitySet;
37use cranelift_entity::packed_option::PackedOption;
38use indexmap::IndexMap;
39use info::LinearMemoryOptions;
40use std::collections::HashMap;
41use std::hash::Hash;
42use std::ops::Index;
43use wasmparser::component_types::ComponentCoreModuleTypeId;
44
45#[derive(Default)]
47pub struct ComponentDfg {
48 pub import_types: PrimaryMap<ImportIndex, (String, ComponentExtern)>,
50
51 pub imports: PrimaryMap<RuntimeImportIndex, (ImportIndex, Vec<String>)>,
53
54 pub exports: IndexMap<String, (Export, ComponentExternData)>,
56
57 pub trampolines: Intern<TrampolineIndex, (ModuleInternedTypeIndex, Trampoline)>,
60
61 pub unsafe_intrinsics: [PackedOption<ModuleInternedTypeIndex>; UnsafeIntrinsic::len() as usize],
64
65 pub reallocs: Intern<ReallocId, CoreDef>,
68
69 pub callbacks: Intern<CallbackId, CoreDef>,
71
72 pub post_returns: Intern<PostReturnId, CoreDef>,
74
75 pub memories: Intern<MemoryId, CoreExport<MemoryIndex>>,
77
78 pub tables: Intern<TableId, CoreExport<TableIndex>>,
80
81 pub adapters: Intern<AdapterId, Adapter>,
87
88 pub instances: PrimaryMap<InstanceId, Instance>,
95
96 pub num_runtime_component_instances: u32,
99
100 pub adapter_modules: PrimaryMap<AdapterModuleId, (StaticModuleIndex, Vec<CoreDef>)>,
110
111 pub adapter_partitionings: PrimaryMap<AdapterId, (AdapterModuleId, EntityIndex)>,
122
123 pub resources: PrimaryMap<DefinedResourceIndex, Resource>,
129
130 pub imported_resources: PrimaryMap<ResourceIndex, RuntimeImportIndex>,
134
135 pub num_future_tables: usize,
137
138 pub num_stream_tables: usize,
140
141 pub num_error_context_tables: usize,
144
145 pub side_effects: Vec<SideEffect>,
152
153 pub options: Intern<OptionsId, CanonicalOptions>,
156
157 pub transparent_adapters: EntitySet<AdapterId>,
160}
161
162pub enum SideEffect {
164 Instance(InstanceId, RuntimeComponentInstanceIndex),
171
172 Resource(DefinedResourceIndex),
179}
180
181#[derive(Clone, Copy, Default)]
187pub enum AbstractInstantiations<'a> {
188 Many,
190
191 One(&'a [info::CoreDef]),
194
195 #[default]
197 None,
198}
199
200impl AbstractInstantiations<'_> {
201 pub fn join(&mut self, other: Self) {
205 *self = match (*self, other) {
206 (Self::Many, _) | (_, Self::Many) => Self::Many,
207 (Self::One(a), Self::One(b)) if a == b => Self::One(a),
208 (Self::One(_), Self::One(_)) => Self::Many,
209 (Self::One(a), Self::None) | (Self::None, Self::One(a)) => Self::One(a),
210 (Self::None, Self::None) => Self::None,
211 }
212 }
213}
214
215macro_rules! id {
216 ($(pub struct $name:ident(u32);)*) => ($(
217 #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
218 #[expect(missing_docs, reason = "tedious to document")]
219 pub struct $name(u32);
220 cranelift_entity::entity_impl!($name);
221 )*)
222}
223
224id! {
225 pub struct InstanceId(u32);
226 pub struct MemoryId(u32);
227 pub struct TableId(u32);
228 pub struct ReallocId(u32);
229 pub struct CallbackId(u32);
230 pub struct AdapterId(u32);
231 pub struct PostReturnId(u32);
232 pub struct AdapterModuleId(u32);
233 pub struct OptionsId(u32);
234}
235
236#[expect(missing_docs, reason = "tedious to document variants")]
238pub enum Instance {
239 Static(StaticModuleIndex, Box<[CoreDef]>),
240 Import(
241 RuntimeImportIndex,
242 IndexMap<String, IndexMap<String, CoreDef>>,
243 ),
244}
245
246#[expect(missing_docs, reason = "tedious to document variants")]
248pub enum Export {
249 LiftedFunction {
250 ty: TypeFuncIndex,
251 func: CoreDef,
252 options: OptionsId,
253 },
254 ModuleStatic {
255 ty: ComponentCoreModuleTypeId,
256 index: StaticModuleIndex,
257 },
258 ModuleImport {
259 ty: TypeModuleIndex,
260 import: RuntimeImportIndex,
261 },
262 Instance {
263 ty: TypeComponentInstanceIndex,
264 exports: IndexMap<String, (Export, ComponentExternData)>,
265 },
266 Type(TypeDef),
267}
268
269#[derive(Debug, Clone, Hash, Eq, PartialEq)]
271#[expect(missing_docs, reason = "tedious to document variants")]
272pub enum CoreDef {
273 Export(CoreExport<EntityIndex>),
274 InstanceFlags(RuntimeComponentInstanceIndex),
275 Trampoline(TrampolineIndex),
276 UnsafeIntrinsic(ModuleInternedTypeIndex, UnsafeIntrinsic),
277
278 Adapter(AdapterId),
287}
288
289impl<T> From<CoreExport<T>> for CoreDef
290where
291 EntityIndex: From<T>,
292{
293 fn from(export: CoreExport<T>) -> CoreDef {
294 CoreDef::Export(export.map_index(|i| i.into()))
295 }
296}
297
298#[derive(Debug, Clone, Hash, Eq, PartialEq)]
300#[expect(missing_docs, reason = "self-describing fields")]
301pub struct CoreExport<T> {
302 pub instance: InstanceId,
303 pub item: ExportItem<T>,
304}
305
306#[derive(Debug, Clone, Hash, Eq, PartialEq)]
308#[expect(missing_docs, reason = "self-describing variants")]
309pub enum ExportItem<T> {
310 Index(T),
311 Name(String),
312}
313
314impl<T> CoreExport<T> {
315 #[expect(missing_docs, reason = "self-describing function")]
316 pub fn map_index<U>(self, f: impl FnOnce(T) -> U) -> CoreExport<U> {
317 CoreExport {
318 instance: self.instance,
319 item: match self.item {
320 ExportItem::Index(i) => ExportItem::Index(f(i)),
321 ExportItem::Name(s) => ExportItem::Name(s),
322 },
323 }
324 }
325}
326
327#[derive(Clone, PartialEq, Eq, Hash)]
329#[expect(missing_docs, reason = "self-describing fields")]
330pub enum Trampoline {
331 LowerImport {
332 import: RuntimeImportIndex,
333 options: OptionsId,
334 lower_ty: TypeFuncIndex,
335 },
336 Transcoder {
337 op: Transcode,
338 from: MemoryId,
339 from64: bool,
340 to: MemoryId,
341 to64: bool,
342 },
343 ResourceNew {
344 instance: RuntimeComponentInstanceIndex,
345 ty: TypeResourceTableIndex,
346 },
347 ResourceRep {
348 instance: RuntimeComponentInstanceIndex,
349 ty: TypeResourceTableIndex,
350 },
351 ResourceDrop {
352 instance: RuntimeComponentInstanceIndex,
353 ty: TypeResourceTableIndex,
354 },
355 BackpressureInc {
356 instance: RuntimeComponentInstanceIndex,
357 },
358 BackpressureDec {
359 instance: RuntimeComponentInstanceIndex,
360 },
361 TaskReturn {
362 instance: RuntimeComponentInstanceIndex,
363 results: TypeTupleIndex,
364 options: OptionsId,
365 },
366 TaskCancel {
367 instance: RuntimeComponentInstanceIndex,
368 },
369 WaitableSetNew {
370 instance: RuntimeComponentInstanceIndex,
371 },
372 WaitableSetWait {
373 instance: RuntimeComponentInstanceIndex,
374 options: OptionsId,
375 },
376 WaitableSetPoll {
377 instance: RuntimeComponentInstanceIndex,
378 options: OptionsId,
379 },
380 WaitableSetDrop {
381 instance: RuntimeComponentInstanceIndex,
382 },
383 WaitableJoin {
384 instance: RuntimeComponentInstanceIndex,
385 },
386 SubtaskDrop {
387 instance: RuntimeComponentInstanceIndex,
388 },
389 SubtaskCancel {
390 instance: RuntimeComponentInstanceIndex,
391 async_: bool,
392 },
393 StreamNew {
394 instance: RuntimeComponentInstanceIndex,
395 ty: TypeStreamTableIndex,
396 },
397 StreamRead {
398 instance: RuntimeComponentInstanceIndex,
399 ty: TypeStreamTableIndex,
400 options: OptionsId,
401 },
402 StreamWrite {
403 instance: RuntimeComponentInstanceIndex,
404 ty: TypeStreamTableIndex,
405 options: OptionsId,
406 },
407 StreamCancelRead {
408 instance: RuntimeComponentInstanceIndex,
409 ty: TypeStreamTableIndex,
410 async_: bool,
411 },
412 StreamCancelWrite {
413 instance: RuntimeComponentInstanceIndex,
414 ty: TypeStreamTableIndex,
415 async_: bool,
416 },
417 StreamDropReadable {
418 instance: RuntimeComponentInstanceIndex,
419 ty: TypeStreamTableIndex,
420 },
421 StreamDropWritable {
422 instance: RuntimeComponentInstanceIndex,
423 ty: TypeStreamTableIndex,
424 },
425 FutureNew {
426 instance: RuntimeComponentInstanceIndex,
427 ty: TypeFutureTableIndex,
428 },
429 FutureRead {
430 instance: RuntimeComponentInstanceIndex,
431 ty: TypeFutureTableIndex,
432 options: OptionsId,
433 },
434 FutureWrite {
435 instance: RuntimeComponentInstanceIndex,
436 ty: TypeFutureTableIndex,
437 options: OptionsId,
438 },
439 FutureCancelRead {
440 instance: RuntimeComponentInstanceIndex,
441 ty: TypeFutureTableIndex,
442 async_: bool,
443 },
444 FutureCancelWrite {
445 instance: RuntimeComponentInstanceIndex,
446 ty: TypeFutureTableIndex,
447 async_: bool,
448 },
449 FutureDropReadable {
450 instance: RuntimeComponentInstanceIndex,
451 ty: TypeFutureTableIndex,
452 },
453 FutureDropWritable {
454 instance: RuntimeComponentInstanceIndex,
455 ty: TypeFutureTableIndex,
456 },
457 ErrorContextNew {
458 instance: RuntimeComponentInstanceIndex,
459 ty: TypeComponentLocalErrorContextTableIndex,
460 options: OptionsId,
461 },
462 ErrorContextDebugMessage {
463 instance: RuntimeComponentInstanceIndex,
464 ty: TypeComponentLocalErrorContextTableIndex,
465 options: OptionsId,
466 },
467 ErrorContextDrop {
468 instance: RuntimeComponentInstanceIndex,
469 ty: TypeComponentLocalErrorContextTableIndex,
470 },
471 ResourceTransferOwn,
472 ResourceTransferBorrow,
473 ResourceTransferBorrowToOwner {
474 ty: TypeResourceTableIndex,
475 },
476 PrepareCall {
477 memory: Option<MemoryId>,
478 },
479 StartCall {
480 callback: Option<CallbackId>,
481 post_return: Option<PostReturnId>,
482 },
483 FutureTransfer,
484 StreamTransfer,
485 ErrorContextTransfer,
486 Trap(Trap),
487 HostcallFuel,
488 EnterSyncCall,
489 ExitSyncCall,
490 ThreadIndex {
491 instance: RuntimeComponentInstanceIndex,
492 },
493 ThreadNewIndirect {
494 instance: RuntimeComponentInstanceIndex,
495 start_func_ty_idx: ModuleInternedTypeIndex,
496 start_func_table_id: TableId,
497 },
498 ThreadResumeLater {
499 instance: RuntimeComponentInstanceIndex,
500 },
501 ThreadSuspend {
502 instance: RuntimeComponentInstanceIndex,
503 },
504 ThreadYield {
505 instance: RuntimeComponentInstanceIndex,
506 },
507 ThreadSuspendThenResume {
508 instance: RuntimeComponentInstanceIndex,
509 },
510 ThreadYieldThenResume {
511 instance: RuntimeComponentInstanceIndex,
512 },
513 ThreadSuspendThenPromote {
514 instance: RuntimeComponentInstanceIndex,
515 },
516 ThreadYieldThenPromote {
517 instance: RuntimeComponentInstanceIndex,
518 },
519}
520
521#[derive(Copy, Clone, Hash, Eq, PartialEq)]
522#[expect(missing_docs, reason = "self-describing fields")]
523pub struct FutureInfo {
524 pub instance: RuntimeComponentInstanceIndex,
525 pub payload_type: Option<InterfaceType>,
526}
527
528#[derive(Copy, Clone, Hash, Eq, PartialEq)]
529#[expect(missing_docs, reason = "self-describing fields")]
530pub struct StreamInfo {
531 pub instance: RuntimeComponentInstanceIndex,
532 pub payload_type: InterfaceType,
533}
534
535#[derive(Clone, Hash, Eq, PartialEq)]
537#[expect(missing_docs, reason = "self-describing fields")]
538pub enum CanonicalOptionsDataModel {
539 Gc {},
540 LinearMemory {
541 memory: Option<MemoryId>,
542 realloc: Option<ReallocId>,
543 },
544}
545
546#[derive(Clone, Hash, Eq, PartialEq)]
548#[expect(missing_docs, reason = "self-describing fields")]
549pub struct CanonicalOptions {
550 pub instance: RuntimeComponentInstanceIndex,
551 pub string_encoding: StringEncoding,
552 pub callback: Option<CallbackId>,
553 pub post_return: Option<PostReturnId>,
554 pub async_: bool,
555 pub core_type: ModuleInternedTypeIndex,
556 pub data_model: CanonicalOptionsDataModel,
557}
558
559#[expect(missing_docs, reason = "self-describing fields")]
561pub struct Resource {
562 pub rep: WasmValType,
563 pub dtor: Option<CoreDef>,
564 pub instance: RuntimeComponentInstanceIndex,
565}
566
567pub struct Intern<K: EntityRef, V> {
573 intern_map: HashMap<V, K>,
574 key_map: PrimaryMap<K, V>,
575}
576
577impl<K, V> Intern<K, V>
578where
579 K: EntityRef,
580{
581 pub fn push(&mut self, value: V) -> K
588 where
589 V: Hash + Eq + Clone,
590 {
591 *self
592 .intern_map
593 .entry(value.clone())
594 .or_insert_with(|| self.key_map.push(value))
595 }
596
597 pub fn iter(&self) -> impl Iterator<Item = (K, &V)> {
599 self.key_map.iter()
600 }
601}
602
603impl<K: EntityRef, V> Index<K> for Intern<K, V> {
604 type Output = V;
605 fn index(&self, key: K) -> &V {
606 &self.key_map[key]
607 }
608}
609
610impl<K: EntityRef, V> Default for Intern<K, V> {
611 fn default() -> Intern<K, V> {
612 Intern {
613 intern_map: HashMap::new(),
614 key_map: PrimaryMap::new(),
615 }
616 }
617}
618
619impl ComponentDfg {
620 pub fn finish(
623 self,
624 wasmtime_types: &mut ComponentTypesBuilder,
625 wasmparser_types: wasmparser::types::TypesRef<'_>,
626 ) -> Result<ComponentTranslation> {
627 let mut linearize = LinearizeDfg {
628 dfg: &self,
629 initializers: Vec::new(),
630 runtime_memories: Default::default(),
631 runtime_tables: Default::default(),
632 runtime_post_return: Default::default(),
633 runtime_reallocs: Default::default(),
634 runtime_callbacks: Default::default(),
635 runtime_instances: Default::default(),
636 num_lowerings: 0,
637 unsafe_intrinsics: Default::default(),
638 trampolines: Default::default(),
639 trampoline_defs: Default::default(),
640 trampoline_map: Default::default(),
641 options: Default::default(),
642 options_map: Default::default(),
643 };
644
645 for item in linearize.dfg.side_effects.iter() {
649 linearize.side_effect(item);
650 }
651
652 let mut export_items = PrimaryMap::new();
655 let mut exports = NameMap::default();
656 for (name, (export, data)) in self.exports.iter() {
657 let export =
658 linearize.export(export, &mut export_items, wasmtime_types, wasmparser_types)?;
659 exports.insert(
660 name,
661 &mut NameMapNoIntern,
662 false,
663 (export, data.try_clone()?),
664 )?;
665 }
666
667 Ok(ComponentTranslation {
672 trampolines: linearize.trampoline_defs,
673 component: Component {
674 exports,
675 export_items: export_items.into(),
676 initializers: linearize.initializers.into(),
677 unsafe_intrinsics: linearize.unsafe_intrinsics,
678 trampolines: linearize.trampolines.into(),
679 num_lowerings: linearize.num_lowerings,
680 options: linearize.options.into(),
681
682 num_runtime_memories: linearize.runtime_memories.len() as u32,
683 num_runtime_tables: linearize.runtime_tables.len() as u32,
684 num_runtime_post_returns: linearize.runtime_post_return.len() as u32,
685 num_runtime_reallocs: linearize.runtime_reallocs.len() as u32,
686 num_runtime_callbacks: linearize.runtime_callbacks.len() as u32,
687 num_runtime_instances: linearize.runtime_instances.len() as u32,
688 imports: self
689 .imports
690 .into_iter()
691 .map(|(_, (import, path))| {
692 let path = path.into_iter().map(TryString::from).try_collect()?;
693 Ok((import, path))
694 })
695 .try_collect::<_, OutOfMemory>()?,
696 import_types: self
697 .import_types
698 .into_iter()
699 .map(|(_, (name, ty))| (TryString::from(name), ty))
700 .try_collect()?,
701 num_runtime_component_instances: self.num_runtime_component_instances,
702 num_future_tables: self.num_future_tables,
703 num_stream_tables: self.num_stream_tables,
704 num_error_context_tables: self.num_error_context_tables,
705 num_resources: (self.resources.len() + self.imported_resources.len()) as u32,
706 imported_resources: self.imported_resources.into(),
707 defined_resource_instances: self
708 .resources
709 .iter()
710 .map(|(_, r)| r.instance)
711 .try_collect()?,
712 },
713 })
714 }
715
716 pub fn resource_index(&self, defined: DefinedResourceIndex) -> ResourceIndex {
719 ResourceIndex::from_u32(defined.as_u32() + (self.imported_resources.len() as u32))
720 }
721
722 pub fn defined_resource_index(&self, idx: ResourceIndex) -> Option<DefinedResourceIndex> {
725 let idx = idx
726 .as_u32()
727 .checked_sub(u32::try_from(self.imported_resources.len()).unwrap())?;
728 Some(DefinedResourceIndex::from_u32(idx))
729 }
730
731 pub fn defined_resource_instance(
734 &self,
735 idx: ResourceIndex,
736 ) -> Option<RuntimeComponentInstanceIndex> {
737 Some(self.resources[self.defined_resource_index(idx)?].instance)
738 }
739}
740
741struct LinearizeDfg<'a> {
742 dfg: &'a ComponentDfg,
743 initializers: Vec<GlobalInitializer>,
744 unsafe_intrinsics: [PackedOption<ModuleInternedTypeIndex>; UnsafeIntrinsic::len() as usize],
745 trampolines: PrimaryMap<TrampolineIndex, ModuleInternedTypeIndex>,
746 trampoline_defs: PrimaryMap<TrampolineIndex, info::Trampoline>,
747 options: PrimaryMap<OptionsIndex, info::CanonicalOptions>,
748 trampoline_map: HashMap<TrampolineIndex, TrampolineIndex>,
749 runtime_memories: HashMap<MemoryId, RuntimeMemoryIndex>,
750 runtime_tables: HashMap<TableId, RuntimeTableIndex>,
751 runtime_reallocs: HashMap<ReallocId, RuntimeReallocIndex>,
752 runtime_callbacks: HashMap<CallbackId, RuntimeCallbackIndex>,
753 runtime_post_return: HashMap<PostReturnId, RuntimePostReturnIndex>,
754 runtime_instances: HashMap<RuntimeInstance, RuntimeInstanceIndex>,
755 options_map: HashMap<OptionsId, OptionsIndex>,
756 num_lowerings: u32,
757}
758
759#[derive(Copy, Clone, Hash, Eq, PartialEq)]
760enum RuntimeInstance {
761 Normal(InstanceId),
762 Adapter(AdapterModuleId),
763}
764
765impl LinearizeDfg<'_> {
766 fn side_effect(&mut self, effect: &SideEffect) {
767 match effect {
768 SideEffect::Instance(i, ci) => {
769 self.instantiate(*i, &self.dfg.instances[*i], *ci);
770 }
771 SideEffect::Resource(i) => {
772 self.resource(*i, &self.dfg.resources[*i]);
773 }
774 }
775 }
776
777 fn instantiate(
778 &mut self,
779 instance: InstanceId,
780 args: &Instance,
781 component_instance: RuntimeComponentInstanceIndex,
782 ) {
783 log::trace!("creating instance {instance:?}");
784 let instantiation = match args {
785 Instance::Static(index, args) => InstantiateModule::Static(
786 *index,
787 args.iter()
788 .map(|def| self.core_def(def))
789 .try_collect()
790 .panic_on_oom(),
791 ),
792 Instance::Import(index, args) => InstantiateModule::Import(
793 *index,
794 args.iter()
795 .map(|(module, values)| {
796 let values = values
797 .iter()
798 .map(|(name, def)| {
799 Ok((TryString::try_from(name.as_str())?, self.core_def(def)))
800 })
801 .try_collect::<_, OutOfMemory>()?;
802 Ok((TryString::try_from(module.as_str())?, values))
803 })
804 .try_collect::<_, OutOfMemory>()
805 .panic_on_oom(),
806 ),
807 };
808 let index = RuntimeInstanceIndex::new(self.runtime_instances.len());
809 self.initializers.push(GlobalInitializer::InstantiateModule(
810 instantiation,
811 Some(component_instance),
812 ));
813 let prev = self
814 .runtime_instances
815 .insert(RuntimeInstance::Normal(instance), index);
816 assert!(prev.is_none());
817 }
818
819 fn resource(&mut self, index: DefinedResourceIndex, resource: &Resource) {
820 let dtor = resource.dtor.as_ref().map(|dtor| self.core_def(dtor));
821 self.initializers
822 .push(GlobalInitializer::Resource(info::Resource {
823 dtor,
824 index,
825 rep: resource.rep,
826 instance: resource.instance,
827 }));
828 }
829
830 fn export(
831 &mut self,
832 export: &Export,
833 items: &mut PrimaryMap<ExportIndex, info::Export>,
834 wasmtime_types: &mut ComponentTypesBuilder,
835 wasmparser_types: wasmparser::types::TypesRef<'_>,
836 ) -> Result<ExportIndex> {
837 let item = match export {
838 Export::LiftedFunction { ty, func, options } => {
839 let func = self.core_def(func);
840 let options = self.options(*options);
841 info::Export::LiftedFunction {
842 ty: *ty,
843 func,
844 options,
845 }
846 }
847 Export::ModuleStatic { ty, index } => info::Export::ModuleStatic {
848 ty: wasmtime_types.convert_module(wasmparser_types, *ty)?,
849 index: *index,
850 },
851 Export::ModuleImport { ty, import } => info::Export::ModuleImport {
852 ty: *ty,
853 import: *import,
854 },
855 Export::Instance { ty, exports } => info::Export::Instance {
856 ty: *ty,
857 exports: {
858 let mut map = NameMap::default();
859 for (name, (export, data)) in exports {
860 let export =
861 self.export(export, items, wasmtime_types, wasmparser_types)?;
862 map.insert(
863 name,
864 &mut NameMapNoIntern,
865 false,
866 (export, data.try_clone()?),
867 )?;
868 }
869 map
870 },
871 },
872 Export::Type(def) => info::Export::Type(*def),
873 };
874 Ok(items.push(item))
875 }
876
877 fn options(&mut self, options: OptionsId) -> OptionsIndex {
878 self.intern_no_init(
879 options,
880 |me| &mut me.options_map,
881 |me, options| me.convert_options(options),
882 )
883 }
884
885 fn convert_options(&mut self, options: OptionsId) -> OptionsIndex {
886 let options = &self.dfg.options[options];
887 let data_model = match options.data_model {
888 CanonicalOptionsDataModel::Gc {} => info::CanonicalOptionsDataModel::Gc {},
889 CanonicalOptionsDataModel::LinearMemory { memory, realloc } => {
890 info::CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
891 memory: memory.map(|mem| self.runtime_memory(mem)),
892 realloc: realloc.map(|mem| self.runtime_realloc(mem)),
893 })
894 }
895 };
896 let callback = options.callback.map(|mem| self.runtime_callback(mem));
897 let post_return = options.post_return.map(|mem| self.runtime_post_return(mem));
898 let options = info::CanonicalOptions {
899 instance: options.instance,
900 string_encoding: options.string_encoding,
901 callback,
902 post_return,
903 async_: options.async_,
904 core_type: options.core_type,
905 data_model,
906 };
907 self.options.push(options)
908 }
909
910 fn runtime_memory(&mut self, mem: MemoryId) -> RuntimeMemoryIndex {
911 self.intern(
912 mem,
913 |me| &mut me.runtime_memories,
914 |me, mem| me.core_export(&me.dfg.memories[mem]),
915 |index, export| GlobalInitializer::ExtractMemory(ExtractMemory { index, export }),
916 )
917 }
918
919 fn runtime_table(&mut self, table: TableId) -> RuntimeTableIndex {
920 self.intern(
921 table,
922 |me| &mut me.runtime_tables,
923 |me, table| me.core_export(&me.dfg.tables[table]),
924 |index, export| GlobalInitializer::ExtractTable(ExtractTable { index, export }),
925 )
926 }
927
928 fn runtime_realloc(&mut self, realloc: ReallocId) -> RuntimeReallocIndex {
929 self.intern(
930 realloc,
931 |me| &mut me.runtime_reallocs,
932 |me, realloc| me.core_def(&me.dfg.reallocs[realloc]),
933 |index, def| GlobalInitializer::ExtractRealloc(ExtractRealloc { index, def }),
934 )
935 }
936
937 fn runtime_callback(&mut self, callback: CallbackId) -> RuntimeCallbackIndex {
938 self.intern(
939 callback,
940 |me| &mut me.runtime_callbacks,
941 |me, callback| me.core_def(&me.dfg.callbacks[callback]),
942 |index, def| GlobalInitializer::ExtractCallback(ExtractCallback { index, def }),
943 )
944 }
945
946 fn runtime_post_return(&mut self, post_return: PostReturnId) -> RuntimePostReturnIndex {
947 self.intern(
948 post_return,
949 |me| &mut me.runtime_post_return,
950 |me, post_return| me.core_def(&me.dfg.post_returns[post_return]),
951 |index, def| GlobalInitializer::ExtractPostReturn(ExtractPostReturn { index, def }),
952 )
953 }
954
955 fn core_def(&mut self, def: &CoreDef) -> info::CoreDef {
956 match def {
957 CoreDef::Export(e) => info::CoreDef::Export(self.core_export(e)),
958 CoreDef::InstanceFlags(i) => info::CoreDef::InstanceFlags(*i),
959 CoreDef::Adapter(id) => info::CoreDef::Export(self.adapter(*id)),
960 CoreDef::Trampoline(index) => info::CoreDef::Trampoline(self.trampoline(*index)),
961 CoreDef::UnsafeIntrinsic(ty, i) => {
962 let index = usize::try_from(i.index()).unwrap();
963 if self.unsafe_intrinsics[index].is_none() {
964 self.unsafe_intrinsics[index] = Some(*ty).into();
965 }
966 info::CoreDef::UnsafeIntrinsic(*i)
967 }
968 }
969 }
970
971 fn trampoline(&mut self, index: TrampolineIndex) -> TrampolineIndex {
972 if let Some(idx) = self.trampoline_map.get(&index) {
973 return *idx;
974 }
975 let (signature, trampoline) = &self.dfg.trampolines[index];
976 let trampoline = match trampoline {
977 Trampoline::LowerImport {
978 import,
979 options,
980 lower_ty,
981 } => {
982 let index = LoweredIndex::from_u32(self.num_lowerings);
983 self.num_lowerings += 1;
984 self.initializers.push(GlobalInitializer::LowerImport {
985 index,
986 import: *import,
987 });
988 info::Trampoline::LowerImport {
989 index,
990 options: self.options(*options),
991 lower_ty: *lower_ty,
992 }
993 }
994 Trampoline::Transcoder {
995 op,
996 from,
997 from64,
998 to,
999 to64,
1000 } => info::Trampoline::Transcoder {
1001 op: *op,
1002 from: self.runtime_memory(*from),
1003 from64: *from64,
1004 to: self.runtime_memory(*to),
1005 to64: *to64,
1006 },
1007 Trampoline::ResourceNew { instance, ty } => info::Trampoline::ResourceNew {
1008 instance: *instance,
1009 ty: *ty,
1010 },
1011 Trampoline::ResourceDrop { instance, ty } => info::Trampoline::ResourceDrop {
1012 instance: *instance,
1013 ty: *ty,
1014 },
1015 Trampoline::ResourceRep { instance, ty } => info::Trampoline::ResourceRep {
1016 instance: *instance,
1017 ty: *ty,
1018 },
1019 Trampoline::BackpressureInc { instance } => info::Trampoline::BackpressureInc {
1020 instance: *instance,
1021 },
1022 Trampoline::BackpressureDec { instance } => info::Trampoline::BackpressureDec {
1023 instance: *instance,
1024 },
1025 Trampoline::TaskReturn {
1026 instance,
1027 results,
1028 options,
1029 } => info::Trampoline::TaskReturn {
1030 instance: *instance,
1031 results: *results,
1032 options: self.options(*options),
1033 },
1034 Trampoline::TaskCancel { instance } => info::Trampoline::TaskCancel {
1035 instance: *instance,
1036 },
1037 Trampoline::WaitableSetNew { instance } => info::Trampoline::WaitableSetNew {
1038 instance: *instance,
1039 },
1040 Trampoline::WaitableSetWait { instance, options } => {
1041 info::Trampoline::WaitableSetWait {
1042 instance: *instance,
1043 options: self.options(*options),
1044 }
1045 }
1046 Trampoline::WaitableSetPoll { instance, options } => {
1047 info::Trampoline::WaitableSetPoll {
1048 instance: *instance,
1049 options: self.options(*options),
1050 }
1051 }
1052 Trampoline::WaitableSetDrop { instance } => info::Trampoline::WaitableSetDrop {
1053 instance: *instance,
1054 },
1055 Trampoline::WaitableJoin { instance } => info::Trampoline::WaitableJoin {
1056 instance: *instance,
1057 },
1058 Trampoline::SubtaskDrop { instance } => info::Trampoline::SubtaskDrop {
1059 instance: *instance,
1060 },
1061 Trampoline::SubtaskCancel { instance, async_ } => info::Trampoline::SubtaskCancel {
1062 instance: *instance,
1063 async_: *async_,
1064 },
1065 Trampoline::StreamNew { instance, ty } => info::Trampoline::StreamNew {
1066 instance: *instance,
1067 ty: *ty,
1068 },
1069 Trampoline::StreamRead {
1070 instance,
1071 ty,
1072 options,
1073 } => info::Trampoline::StreamRead {
1074 instance: *instance,
1075 ty: *ty,
1076 options: self.options(*options),
1077 },
1078 Trampoline::StreamWrite {
1079 instance,
1080 ty,
1081 options,
1082 } => info::Trampoline::StreamWrite {
1083 instance: *instance,
1084 ty: *ty,
1085 options: self.options(*options),
1086 },
1087 Trampoline::StreamCancelRead {
1088 instance,
1089 ty,
1090 async_,
1091 } => info::Trampoline::StreamCancelRead {
1092 instance: *instance,
1093 ty: *ty,
1094 async_: *async_,
1095 },
1096 Trampoline::StreamCancelWrite {
1097 instance,
1098 ty,
1099 async_,
1100 } => info::Trampoline::StreamCancelWrite {
1101 instance: *instance,
1102 ty: *ty,
1103 async_: *async_,
1104 },
1105 Trampoline::StreamDropReadable { instance, ty } => {
1106 info::Trampoline::StreamDropReadable {
1107 instance: *instance,
1108 ty: *ty,
1109 }
1110 }
1111 Trampoline::StreamDropWritable { instance, ty } => {
1112 info::Trampoline::StreamDropWritable {
1113 instance: *instance,
1114 ty: *ty,
1115 }
1116 }
1117 Trampoline::FutureNew { instance, ty } => info::Trampoline::FutureNew {
1118 instance: *instance,
1119 ty: *ty,
1120 },
1121 Trampoline::FutureRead {
1122 instance,
1123 ty,
1124 options,
1125 } => info::Trampoline::FutureRead {
1126 instance: *instance,
1127 ty: *ty,
1128 options: self.options(*options),
1129 },
1130 Trampoline::FutureWrite {
1131 instance,
1132 ty,
1133 options,
1134 } => info::Trampoline::FutureWrite {
1135 instance: *instance,
1136 ty: *ty,
1137 options: self.options(*options),
1138 },
1139 Trampoline::FutureCancelRead {
1140 instance,
1141 ty,
1142 async_,
1143 } => info::Trampoline::FutureCancelRead {
1144 instance: *instance,
1145 ty: *ty,
1146 async_: *async_,
1147 },
1148 Trampoline::FutureCancelWrite {
1149 instance,
1150 ty,
1151 async_,
1152 } => info::Trampoline::FutureCancelWrite {
1153 instance: *instance,
1154 ty: *ty,
1155 async_: *async_,
1156 },
1157 Trampoline::FutureDropReadable { instance, ty } => {
1158 info::Trampoline::FutureDropReadable {
1159 instance: *instance,
1160 ty: *ty,
1161 }
1162 }
1163 Trampoline::FutureDropWritable { instance, ty } => {
1164 info::Trampoline::FutureDropWritable {
1165 instance: *instance,
1166 ty: *ty,
1167 }
1168 }
1169 Trampoline::ErrorContextNew {
1170 instance,
1171 ty,
1172 options,
1173 } => info::Trampoline::ErrorContextNew {
1174 instance: *instance,
1175 ty: *ty,
1176 options: self.options(*options),
1177 },
1178 Trampoline::ErrorContextDebugMessage {
1179 instance,
1180 ty,
1181 options,
1182 } => info::Trampoline::ErrorContextDebugMessage {
1183 instance: *instance,
1184 ty: *ty,
1185 options: self.options(*options),
1186 },
1187 Trampoline::ErrorContextDrop { instance, ty } => info::Trampoline::ErrorContextDrop {
1188 instance: *instance,
1189 ty: *ty,
1190 },
1191 Trampoline::ResourceTransferOwn => info::Trampoline::ResourceTransferOwn,
1192 Trampoline::ResourceTransferBorrow => info::Trampoline::ResourceTransferBorrow,
1193 Trampoline::ResourceTransferBorrowToOwner { ty } => {
1194 info::Trampoline::ResourceTransferBorrowToOwner { ty: *ty }
1195 }
1196 Trampoline::PrepareCall { memory } => info::Trampoline::PrepareCall {
1197 memory: memory.map(|v| self.runtime_memory(v)),
1198 },
1199 Trampoline::StartCall {
1200 callback,
1201 post_return,
1202 } => info::Trampoline::StartCall {
1203 callback: callback.map(|v| self.runtime_callback(v)),
1204 post_return: post_return.map(|v| self.runtime_post_return(v)),
1205 },
1206 Trampoline::FutureTransfer => info::Trampoline::FutureTransfer,
1207 Trampoline::StreamTransfer => info::Trampoline::StreamTransfer,
1208 Trampoline::ErrorContextTransfer => info::Trampoline::ErrorContextTransfer,
1209 Trampoline::Trap(trap) => info::Trampoline::Trap(*trap),
1210 Trampoline::HostcallFuel => info::Trampoline::HostcallFuel,
1211 Trampoline::EnterSyncCall => info::Trampoline::EnterSyncCall,
1212 Trampoline::ExitSyncCall => info::Trampoline::ExitSyncCall,
1213 Trampoline::ThreadIndex { instance } => info::Trampoline::ThreadIndex {
1214 instance: *instance,
1215 },
1216 Trampoline::ThreadNewIndirect {
1217 instance,
1218 start_func_ty_idx,
1219 start_func_table_id,
1220 } => info::Trampoline::ThreadNewIndirect {
1221 instance: *instance,
1222 start_func_ty_idx: *start_func_ty_idx,
1223 start_func_table_idx: self.runtime_table(*start_func_table_id),
1224 },
1225 Trampoline::ThreadResumeLater { instance } => info::Trampoline::ThreadResumeLater {
1226 instance: *instance,
1227 },
1228 Trampoline::ThreadSuspend { instance } => info::Trampoline::ThreadSuspend {
1229 instance: *instance,
1230 },
1231 Trampoline::ThreadYield { instance } => info::Trampoline::ThreadYield {
1232 instance: *instance,
1233 },
1234 Trampoline::ThreadSuspendThenResume { instance } => {
1235 info::Trampoline::ThreadSuspendThenResume {
1236 instance: *instance,
1237 }
1238 }
1239 Trampoline::ThreadYieldThenResume { instance } => {
1240 info::Trampoline::ThreadYieldThenResume {
1241 instance: *instance,
1242 }
1243 }
1244 Trampoline::ThreadSuspendThenPromote { instance } => {
1245 info::Trampoline::ThreadSuspendThenPromote {
1246 instance: *instance,
1247 }
1248 }
1249 Trampoline::ThreadYieldThenPromote { instance } => {
1250 info::Trampoline::ThreadYieldThenPromote {
1251 instance: *instance,
1252 }
1253 }
1254 };
1255 let i1 = self.trampolines.push(*signature);
1256 let i2 = self.trampoline_defs.push(trampoline);
1257 assert_eq!(i1, i2);
1258 self.trampoline_map.insert(index, i1);
1259 i1
1260 }
1261
1262 fn core_export<T>(&mut self, export: &CoreExport<T>) -> info::CoreExport<T>
1263 where
1264 T: Clone,
1265 {
1266 let instance = export.instance;
1267 log::trace!("referencing export of {instance:?}");
1268 info::CoreExport {
1269 instance: self.runtime_instances[&RuntimeInstance::Normal(instance)],
1270 item: match &export.item {
1271 ExportItem::Index(i) => info::ExportItem::Index(i.clone()),
1272 ExportItem::Name(name) => info::ExportItem::Name(name.clone().into()),
1273 },
1274 }
1275 }
1276
1277 fn adapter(&mut self, adapter: AdapterId) -> info::CoreExport<EntityIndex> {
1278 let (adapter_module, entity_index) = self.dfg.adapter_partitionings[adapter];
1279
1280 let instance = self.adapter_module(adapter_module);
1284
1285 info::CoreExport {
1287 instance,
1288 item: info::ExportItem::Index(entity_index),
1289 }
1290 }
1291
1292 fn adapter_module(&mut self, adapter_module: AdapterModuleId) -> RuntimeInstanceIndex {
1293 self.intern(
1294 RuntimeInstance::Adapter(adapter_module),
1295 |me| &mut me.runtime_instances,
1296 |me, _| {
1297 log::debug!("instantiating {adapter_module:?}");
1298 let (module_index, args) = &me.dfg.adapter_modules[adapter_module];
1299 let args = args
1300 .iter()
1301 .map(|arg| me.core_def(arg))
1302 .try_collect()
1303 .panic_on_oom();
1304 let instantiate = InstantiateModule::Static(*module_index, args);
1305 GlobalInitializer::InstantiateModule(instantiate, None)
1306 },
1307 |_, init| init,
1308 )
1309 }
1310
1311 fn intern<K, V, T>(
1326 &mut self,
1327 key: K,
1328 map: impl Fn(&mut Self) -> &mut HashMap<K, V>,
1329 generate: impl FnOnce(&mut Self, K) -> T,
1330 init: impl FnOnce(V, T) -> GlobalInitializer,
1331 ) -> V
1332 where
1333 K: Hash + Eq + Copy,
1334 V: EntityRef,
1335 {
1336 self.intern_(key, map, generate, |me, key, val| {
1337 me.initializers.push(init(key, val));
1338 })
1339 }
1340
1341 fn intern_no_init<K, V, T>(
1342 &mut self,
1343 key: K,
1344 map: impl Fn(&mut Self) -> &mut HashMap<K, V>,
1345 generate: impl FnOnce(&mut Self, K) -> T,
1346 ) -> V
1347 where
1348 K: Hash + Eq + Copy,
1349 V: EntityRef,
1350 {
1351 self.intern_(key, map, generate, |_me, _key, _val| {})
1352 }
1353
1354 fn intern_<K, V, T>(
1355 &mut self,
1356 key: K,
1357 map: impl Fn(&mut Self) -> &mut HashMap<K, V>,
1358 generate: impl FnOnce(&mut Self, K) -> T,
1359 init: impl FnOnce(&mut Self, V, T),
1360 ) -> V
1361 where
1362 K: Hash + Eq + Copy,
1363 V: EntityRef,
1364 {
1365 if let Some(val) = map(self).get(&key) {
1366 return *val;
1367 }
1368 let tmp = generate(self, key);
1369 let index = V::new(map(self).len());
1370 init(self, index, tmp);
1371 let prev = map(self).insert(key, index);
1372 assert!(prev.is_none());
1373 index
1374 }
1375}