1use super::cfg::{assemble_dispatch_loop, goto_block, set_next_block, Blocks};
16use super::encode::*;
17use super::kind::{self, FieldLayout, FieldNested, Kind, KindTable, ParamShape};
18use super::regsplit;
19use super::WasmLowerError;
20use crate::semantics::builtins::BuiltinId;
21use crate::vm::instruction::{
22 BoundaryType, CompiledFunction, CompiledProgram, Constant, EnumTypeDef, Op, StructTypeDef,
23};
24use crate::vm::reach::{CodeLayout, HostEntries};
25use crate::Interner;
26use logicaffeine_language::analysis::{PolicyCondition, PolicyRegistry};
27
28mod absence;
29mod display;
30mod exact;
31mod roots;
32mod tower;
33
34type R<T> = std::result::Result<T, WasmLowerError>;
35
36const HEAP_PAGES: u32 = 64;
40
41const FREE_TABLE_BASE: i32 = 16;
52
53const FREE_CLASSES: i32 = 128;
66
67const POWER_CLASSES: i32 = 20;
73const POWER_MIN: i32 = 11;
74
75#[derive(Default)]
93struct TextPool {
94 by_bytes: std::collections::HashMap<Vec<u8>, i32>,
95 image: Vec<u8>,
97}
98
99impl TextPool {
100 fn intern(&mut self, bytes: &[u8]) -> i32 {
102 if let Some(a) = self.by_bytes.get(bytes) {
103 return *a;
104 }
105 let addr = STATIC_BASE + self.image.len() as i32;
106 let len = bytes.len() as i32;
107 self.image.extend_from_slice(&len.to_le_bytes());
110 self.image.extend_from_slice(&len.to_le_bytes());
111 self.image.extend_from_slice(&(addr + 16).to_le_bytes());
112 self.image.extend_from_slice(&0i32.to_le_bytes());
113 self.image.extend_from_slice(bytes);
114 while self.image.len() % 8 != 0 {
116 self.image.push(0);
117 }
118 self.by_bytes.insert(bytes.to_vec(), addr);
119 addr
120 }
121}
122
123const STATIC_BASE: i32 = FREE_TABLE_BASE + (FREE_CLASSES + POWER_CLASSES) * 4;
126
127const HEAP_START: i32 = STATIC_BASE;
130
131const NET_INBOX_ADDR: i32 = 8;
135
136macro_rules! host_fns {
153 ($( $(#[$attr:meta])* $variant:ident = $field:literal, ($($p:ident),*) -> ($($r:ident),*); )*) => {
154 #[derive(Clone, Copy, PartialEq, Eq)]
156 enum HostFn { $( $(#[$attr])* $variant, )* }
157
158 const HOST_FNS: &[HostFn] = &[ $( HostFn::$variant, )* ];
164
165 impl HostFn {
166 fn field(self) -> &'static str {
167 match self { $( HostFn::$variant => $field, )* }
168 }
169 fn params(self) -> Vec<u8> {
170 match self { $( HostFn::$variant => vec![$($p),*], )* }
171 }
172 fn results(self) -> Vec<u8> {
173 match self { $( HostFn::$variant => vec![$($r),*], )* }
174 }
175 fn retained_params(self) -> Vec<usize> {
180 let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($p)),*], )* };
181 spelled
182 .iter()
183 .enumerate()
184 .filter(|(_, p)| **p == "CALLBACK" || **p == "KEPT")
185 .map(|(i, _)| i)
186 .collect()
187 }
188 fn registers_callback(self) -> bool {
190 let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($p)),*], )* };
191 spelled.contains(&"CALLBACK")
192 }
193 fn returns_host_text(self) -> bool {
196 let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($r)),*], )* };
197 spelled.contains(&"HOST_TEXT")
198 }
199 fn returns_host_seq(self) -> bool {
202 let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($r)),*], )* };
203 spelled.contains(&"HOST_SEQ")
204 }
205 }
206 };
207}
208
209const CALLBACK: u8 = I32;
212
213const HOST_TEXT: u8 = I32;
217
218const HOST_SEQ: u8 = I32;
223
224host_fns! {
225 PrintI64 = "print_i64", (I64) -> ();
226 PrintBool = "print_bool", (I32) -> ();
227 PrintChar = "print_char", (I64) -> ();
231 PrintF64 = "print_f64", (F64) -> ();
232 PrintDate = "print_date", (I32) -> ();
235 PrintMoment = "print_moment", (I64) -> ();
236 PrintDuration = "print_duration", (I64) -> ();
239 PrintTime = "print_time", (I64) -> ();
240 PowFf = "pow_ff", (F64,F64) -> (F64);
242 PowFi = "pow_fi", (F64,I64) -> (F64);
245 Today = "today", () -> (I32);
248 Now = "now", () -> (I64);
249 RandomInt = "random_int", (I64,I64) -> (I64);
253 PrintSeqI64 = "print_seq_i64", (I32) -> ();
258 PrintSeqBool = "print_seq_bool", (I32) -> ();
262 PrintSeqWord32 = "print_seq_word32", (I32) -> ();
267 PrintSeqWord64 = "print_seq_word64", (I32) -> ();
268 PrintSeqF64 = "print_seq_f64", (I32) -> ();
269 PrintText = "print_text", (I32) -> ();
273 PrintSeqText = "print_seq_text", (I32) -> ();
277 PrintSetI64 = "print_set_i64", (I32) -> ();
283 FmtI64Into = "fmt_i64_into", (I32,I64) -> (I32);
288 FmtF64Into = "fmt_f64_into", (I32,F64) -> (I32);
293 FmtBoolInto = "fmt_bool_into", (I32,I64) -> (I32);
295 FmtF64PrecInto = "fmt_f64_prec_into", (I32,F64,I32) -> (I32);
299 FmtAlignInto = "fmt_align_into", (I32,I32,I32,I32) -> (I32);
305 Args = "args", () -> (I32);
309 ReadReals = "read_reals", (I32) -> (I32);
313 ParseInt = "parse_int", (I32) -> (I64);
316 TextContains = "text_contains", (I32,I32) -> (I64);
319 FmtSeqI64Into = "fmt_seq_i64_into", (I32,I32) -> (I32);
324 FmtSeqBoolInto = "fmt_seq_bool_into", (I32,I32) -> (I32);
328 FmtSetI64Into = "fmt_set_i64_into", (I32,I32) -> (I32);
331 PrintSetText = "print_set_text", (I32) -> ();
335 PrintRational = "print_rational", (I64,I64) -> ();
338 PrintNothing = "print_nothing", () -> ();
342 ParseFloat = "parse_float", (I32) -> (F64);
345 ParseTimestamp = "parse_timestamp", (I32) -> (I64);
348 TemporalComponent = "temporal_component", (I64,I32) -> (I64);
353 TemporalComponentDate = "temporal_component_date", (I32,I32) -> (I64);
360 PrintWord = "print_word", (I64) -> ();
364 BigintFromI64 = "logos_rt_bigint_from_i64", (I64) -> (I32);
369 BigintPow = "logos_rt_bigint_pow", (I32,I64) -> (I32);
372 BigintToText = "logos_rt_bigint_to_text", (I32) -> (I32);
376 BigintMul = "logos_rt_bigint_mul", (I32,I32) -> (I32);
379 BigintAdd = "logos_rt_bigint_add", (I32,I32) -> (I32);
381 BigintSub = "logos_rt_bigint_sub", (I32,I32) -> (I32);
384 BigintDiv = "logos_rt_bigint_div", (I32,I32) -> (I32);
387 BigintMod = "logos_rt_bigint_mod", (I32,I32) -> (I32);
390 ComplexFromI64 = "logos_rt_complex_from_i64", (I64,I64) -> (I32);
395 ComplexAdd = "logos_rt_complex_add", (I32,I32) -> (I32);
396 ComplexSub = "logos_rt_complex_sub", (I32,I32) -> (I32);
397 ComplexMul = "logos_rt_complex_mul", (I32,I32) -> (I32);
398 ComplexToText = "logos_rt_complex_to_text", (I32) -> (I32);
399 ComplexAbs = "logos_rt_complex_abs", (I32) -> (F64);
402 ComplexFromF64 = "logos_rt_complex_from_f64", (F64,F64) -> (I32);
406 ComplexReF64 = "logos_rt_complex_re_f64", (I32) -> (F64);
407 ComplexImF64 = "logos_rt_complex_im_f64", (I32) -> (F64);
408 ModularFromI64 = "logos_rt_modular_from_i64", (I64,I64) -> (I32);
411 ModularAdd = "logos_rt_modular_add", (I32,I32) -> (I32);
412 ModularSub = "logos_rt_modular_sub", (I32,I32) -> (I32);
413 ModularMul = "logos_rt_modular_mul", (I32,I32) -> (I32);
414 ModularDiv = "logos_rt_modular_div", (I32,I32) -> (I32);
415 ModularPow = "logos_rt_modular_pow", (I32,I64) -> (I32);
416 ModularToText = "logos_rt_modular_to_text", (I32) -> (I32);
417 DecimalFromText = "logos_rt_decimal_from_text", (I32) -> (I32);
420 DecimalFromI64 = "logos_rt_decimal_from_i64", (I64) -> (I32);
421 DecimalAdd = "logos_rt_decimal_add", (I32,I32) -> (I32);
422 DecimalSub = "logos_rt_decimal_sub", (I32,I32) -> (I32);
423 DecimalMul = "logos_rt_decimal_mul", (I32,I32) -> (I32);
424 DecimalToText = "logos_rt_decimal_to_text", (I32) -> (I32);
425 MoneyFromDecimal = "logos_rt_money_from_decimal", (I32,I32) -> (I32);
428 MoneyFromI64 = "logos_rt_money_from_i64", (I64,I32) -> (I32);
429 MoneyAdd = "logos_rt_money_add", (I32,I32) -> (I32);
430 MoneySub = "logos_rt_money_sub", (I32,I32) -> (I32);
431 MoneyToText = "logos_rt_money_to_text", (I32) -> (I32);
432 QuantityOfI64 = "logos_rt_quantity_of_i64", (I64,I32) -> (I32);
433 QuantityConvert = "logos_rt_quantity_convert", (I32,I32) -> (I32);
434 QuantityAdd = "logos_rt_quantity_add", (I32,I32) -> (I32);
435 QuantitySub = "logos_rt_quantity_sub", (I32,I32) -> (I32);
436 QuantityMul = "logos_rt_quantity_mul", (I32,I32) -> (I32);
437 QuantityDiv = "logos_rt_quantity_div", (I32,I32) -> (I32);
438 QuantityToText = "logos_rt_quantity_to_text", (I32) -> (I32);
439 RationalFromI64 = "logos_rt_rational_from_i64", (I64) -> (I32);
440 RationalFromBigint = "logos_rt_rational_from_bigint", (I32) -> (I32);
441 RationalAdd = "logos_rt_rational_add", (I32,I32) -> (I32);
442 RationalSub = "logos_rt_rational_sub", (I32,I32) -> (I32);
443 RationalMul = "logos_rt_rational_mul", (I32,I32) -> (I32);
444 RationalDiv = "logos_rt_rational_div", (I32,I32) -> (I32);
445 RationalToText = "logos_rt_rational_to_text", (I32) -> (I32);
446 RationalFloor = "logos_rt_rational_floor", (I32) -> (I32);
447 RationalCeil = "logos_rt_rational_ceil", (I32) -> (I32);
448 RationalRound = "logos_rt_rational_round", (I32) -> (I32);
449 RationalAbs = "logos_rt_rational_abs", (I32) -> (I32);
450 UuidParse = "logos_rt_uuid_parse", (I32) -> (I32);
451 UuidNil = "logos_rt_uuid_nil", () -> (I32);
452 UuidMax = "logos_rt_uuid_max", () -> (I32);
453 UuidDns = "logos_rt_uuid_dns", () -> (I32);
454 UuidUrl = "logos_rt_uuid_url", () -> (I32);
455 UuidOid = "logos_rt_uuid_oid", () -> (I32);
456 UuidX500 = "logos_rt_uuid_x500", () -> (I32);
457 UuidVersion = "logos_rt_uuid_version", (I32) -> (I64);
458 UuidEq = "logos_rt_uuid_eq", (I32,I32) -> (I32);
459 UuidToText = "logos_rt_uuid_to_text", (I32) -> (I32);
460 UuidFromPtr = "logos_rt_uuid_from_ptr", (I32) -> (I32);
461 PrintSpan = "print_span", (I64) -> ();
462 MomentAddSpan = "logos_rt_moment_add_span", (I64,I32,I32) -> (I64);
463 DateAddSpan = "logos_rt_date_add_span", (I32,I32,I32) -> (I32);
464 FormatTimestampRt = "logos_rt_format_timestamp", (I64) -> (I32);
465 MonthsBetweenRt = "logos_rt_months_between", (I64,I64) -> (I64);
466 YearsBetweenRt = "logos_rt_years_between", (I64,I64) -> (I64);
467 MakeDateRt = "logos_rt_make_date", (I64,I64,I64) -> (I32);
468 MakeMomentRt = "logos_rt_make_moment", (I64,I64,I64,I64,I64,I64) -> (I64);
469 InZoneRt = "logos_rt_in_zone", (I64,I32) -> (I32);
470 LocalInstantRt = "logos_rt_local_instant", (I64,I32) -> (I64);
471 Lanes16FromBytes = "logos_rt_lanes16_from_bytes", (I32) -> (I32);
472 Lanes8FromWords = "logos_rt_lanes8_from_words", (I32) -> (I32);
473 Lanes4W64FromWords = "logos_rt_lanes4w64_from_words", (I32) -> (I32);
474 LanesSplat16 = "logos_rt_lanes_splat16", (I64) -> (I32);
475 LanesSplat8 = "logos_rt_lanes_splat8", (I64) -> (I32);
476 LanesToSeq = "logos_rt_lanes_to_seq", (I32) -> (I32);
477 LanesShuffle = "logos_rt_lanes_shuffle", (I32,I32) -> (I32);
478 LanesInterleaveLo = "logos_rt_lanes_interleave_lo", (I32,I32) -> (I32);
479 LanesInterleaveHi = "logos_rt_lanes_interleave_hi", (I32,I32) -> (I32);
480 LanesByteAdd = "logos_rt_lanes_byte_add", (I32,I32) -> (I32);
481 LanesMaddubs = "logos_rt_lanes_maddubs", (I32,I32) -> (I32);
482 LanesPackus = "logos_rt_lanes_packus", (I32,I32) -> (I32);
483 LanesShrBytes = "logos_rt_lanes_shr_bytes", (I32,I64) -> (I32);
484 DecimalToRational = "logos_rt_decimal_to_rational", (I32) -> (I32);
485 MoneySetRate = "logos_rt_set_rate", (I32,I32) -> (I32);
486 MoneyToCurrency = "logos_rt_to_currency", (I32,I32) -> (I32);
487 MoneySetRatesInt = "logos_rt_set_rates_int", (I32) -> (I32);
488 MoneySetRatesRational = "logos_rt_set_rates_rational", (I32) -> (I32);
489 MoneySetRatesDecimal = "logos_rt_set_rates_decimal", (I32) -> (I32);
490 WriteWireResidual = "write_wire_residual", (I32,I32) -> (I64);
491 LogosRtFail = "logos_rt_fail", (I32) -> ();
495 LogosRtFailAt = "logos_rt_fail_at", (I32,I64) -> ();
500 WireBytesInt = "logos_rt_wire_bytes_int", (I64) -> (I32);
501 WireBytesBool = "logos_rt_wire_bytes_bool", (I64) -> (I32);
502 WireBytesFloat = "logos_rt_wire_bytes_float", (F64) -> (I32);
503 WireBytesText = "logos_rt_wire_bytes_text", (I32) -> (I32);
504 ReadWireFrame = "read_wire_frame", (I32,I32) -> (I32);
505 ReadWireProgramRt = "logos_rt_read_wire_program", (I32,I32) -> (I32);
506 DynamicToText = "logos_rt_dynamic_to_text", (I32) -> (I32);
507 RunAccepted = "logos_rt_run_accepted", (I32,I64,I64,I64) -> (I64);
508 Sha1Rnds4 = "logos_rt_sha1rnds4", (I32,I32,I64) -> (I32);
509 Sha1Msg1 = "logos_rt_sha1msg1", (I32,I32) -> (I32);
510 Sha1Msg2 = "logos_rt_sha1msg2", (I32,I32) -> (I32);
511 Sha1Nexte = "logos_rt_sha1nexte", (I32,I32) -> (I32);
512 Lanes4Add = "logos_rt_lanes4_add", (I32,I32) -> (I32);
513 Lanes4Xor = "logos_rt_lanes4_xor", (I32,I32) -> (I32);
514 RtAlloc = "logos_rt_alloc", (I32) -> (I32);
518 Obs = "obs", (I32,I64,I64,I64) -> ();
526 DomBody = "dom_body", () -> (I64);
531 DomCreateElement = "dom_create_element", (I32) -> (I64);
533 DomCreateTextNode = "dom_create_text_node", (I32) -> (I64);
535 DomSetText = "dom_set_text", (I64,I32) -> ();
537 DomSetHtml = "dom_set_html", (I64,I32) -> ();
539 DomClearChildren = "dom_clear_children", (I64) -> ();
541 DomOnMessage = "dom_on_message", (I32, CALLBACK) -> ();
547 DomSetAttribute = "dom_set_attribute", (I64,I32,I32) -> ();
549 DomSetBoolAttribute = "dom_set_bool_attribute", (I64,I32,I64) -> ();
560 DomAppendChild = "dom_append_child", (I64,I64) -> ();
562 DomGetText = "dom_get_text", (I64) -> (HOST_TEXT);
564 DomGetValue = "dom_get_value", (I64) -> (HOST_TEXT);
566 DomSetValue = "dom_set_value", (I64,I32) -> ();
568 DomSetChecked = "dom_set_checked", (I64,I64) -> ();
574 DomPreventDefault = "dom_prevent_default", (I64,I32) -> ();
575 StorageSet = "storage_set", (I32,I32,I32) -> ();
581 StorageGet = "storage_get", (I32,I32) -> (HOST_TEXT);
582 StorageRemove = "storage_remove", (I32,I32) -> ();
583 DomApply = "dom_apply", (I32) -> ();
590 DomApplyWords = "dom_apply_words", (I32,I64,I32,I64) -> (I64);
595 DomQuerySelector = "dom_query_selector", (I32) -> (I64);
597 DomAddEventListener = "dom_add_event_listener", (I64,I32,CALLBACK) -> ();
600 DomListenFlags = "dom_listen_flags", (I64,I32,I64) -> ();
606 DomEventValue = "dom_event_value", (I64) -> (HOST_TEXT);
608 DomEventKey = "dom_event_key", (I64) -> (HOST_TEXT);
610 DomEventTarget = "dom_event_target", (I64) -> (I64);
612 DomFetchStart = "dom_fetch_start", (I32,CALLBACK) -> ();
615 DomResponseText = "dom_response_text", () -> (HOST_TEXT);
617 DomFetchSend = "dom_fetch_send", (I32,I32,I32,I32,CALLBACK) -> (I64);
625 DomResponseStatus = "dom_response_status", (I64) -> (I64);
627 DomResponseBody = "dom_response_body", (I64) -> (HOST_TEXT);
629 DomResponseHeader = "dom_response_header", (I64,I32) -> (HOST_TEXT);
632 DomResponseError = "dom_response_error", (I64) -> (HOST_TEXT);
635 DomFetchAbort = "dom_fetch_abort", (I64) -> ();
637 DomFetchSetTimeout = "dom_fetch_set_timeout", (I64,I64) -> ();
639 DomRoutePath = "dom_route_path", () -> (HOST_TEXT);
646 DomRouteQuery = "dom_route_query", (I32) -> (HOST_TEXT);
648 DomNavigate = "dom_navigate", (I32) -> ();
650 DomAssignLocation = "dom_assign_location", (I32) -> ();
653 DomReplaceRoute = "dom_replace_route", (I32) -> ();
655 DomOnRoute = "dom_on_route", (CALLBACK) -> ();
658 DomSetTitle = "dom_set_title", (I32) -> ();
663 DomSetHeadHtml = "dom_set_head_html", (I32) -> ();
668 DomReload = "dom_reload", () -> ();
670 DomGoBack = "dom_go_back", () -> ();
673 DomGetAttribute = "dom_get_attribute", (I64,I32) -> (HOST_TEXT);
677 DomOnWindowEvent = "dom_on_window_event", (I32,CALLBACK) -> ();
682 DomScrollGap = "dom_scroll_gap", (I64) -> (I64);
686 DomSetInterval = "dom_set_interval", (I64,CALLBACK) -> ();
689 DomEventFileName = "dom_event_file_name", (I64) -> (HOST_TEXT);
692 DomEventFileSize = "dom_event_file_size", (I64) -> (I64);
695 DomEventFileType = "dom_event_file_type", (I64) -> (HOST_TEXT);
698 DomEventFileBytes = "dom_event_file_bytes", (I64) -> (HOST_SEQ);
702 DomElementCommand = "dom_element_command", (I64,I32) -> ();
706 DomClipboardWrite = "dom_clipboard_write", (I32) -> ();
708 DomDownloadFile = "dom_download_file", (I32,I32) -> ();
710 DomNotify = "dom_notify", (I32,I32) -> ();
712 DomPublish = "dom_publish", (I32,I32) -> ();
724 DomNoteTurn = "dom_note_turn", (I32,I32,I32,I32) -> ();
729 DomJournalDetail = "dom_journal_detail", () -> (I64);
733 DomWakeAfter = "dom_wake_after", (I64) -> ();
736 DomEnterValue = "dom_enter_value", (I32, I32, I32) -> (I64);
741 DomPageEntry = "dom_page_entry", (I64, I32, I32) -> (I64);
747 ExactBox = "exact_box", (I64) -> (I64);
755 ExactNarrow = "exact_narrow", (I64) -> (I64);
758 ExactAdd = "exact_add", (I64, I64) -> (I64);
760 ExactSub = "exact_sub", (I64, I64) -> (I64);
761 ExactMul = "exact_mul", (I64, I64) -> (I64);
762 ExactDiv = "exact_div", (I64, I64) -> (I64);
765 ExactMod = "exact_mod", (I64, I64) -> (I64);
766 ExactFloorDiv = "exact_floordiv", (I64, I64) -> (I64);
767 ExactPow = "exact_pow", (I64, I64) -> (I64);
770 ExactCmp = "exact_cmp", (I64, I64) -> (I32);
772 ExactF64 = "exact_f64", (I64) -> (F64);
774 ExactClone = "exact_clone", (I64) -> (I64);
776 ExactDrop = "exact_drop", (I64) -> ();
778 PrintExact = "print_exact", (I64) -> ();
780 ExactText = "exact_text", (I64) -> (HOST_TEXT);
782 EnvLen = "env_len", (I32) -> (I32);
787 EnvInto = "env_into", (I32, I32) -> (I32);
791 TimeNow = "time_now", () -> (I64);
794 ValueInt = "logos_rt_value_int", (I64) -> (I32);
799 ValueFloat = "logos_rt_value_float", (F64) -> (I32);
800 ValueBool = "logos_rt_value_bool", (I32) -> (I32);
801 ValueNothing = "logos_rt_value_nothing", () -> (I32);
802 ValueDate = "logos_rt_value_date", (I32) -> (I32);
803 ValueMoment = "logos_rt_value_moment", (I64) -> (I32);
804 ValueTime = "logos_rt_value_time", (I64) -> (I32);
805 ValueSpan = "logos_rt_value_span", (I32, I32) -> (I32);
806 ValueList = "logos_rt_value_list", (I32, I32) -> (I32);
807 ValueClone = "logos_rt_value_clone", (I32) -> (I32);
808 ValuePush = "logos_rt_value_push", (I32, I32) -> (I32);
810 ValueSetItem = "logos_rt_value_set_item", (I32, I32, I32) -> (I32);
811 ValuePop = "logos_rt_value_pop", (I32) -> (I32);
812 ValueItems = "logos_rt_value_items", (I32) -> (I32);
813 ValueItemAt = "logos_rt_value_item_at", (I32, I64) -> (I32);
814 ValueSlice = "logos_rt_value_slice", (I32, I32, I32) -> (I32);
815 ValueAdd = "logos_rt_value_add", (I32, I32) -> (I32);
816 ValueSub = "logos_rt_value_sub", (I32, I32) -> (I32);
817 ValueMul = "logos_rt_value_mul", (I32, I32) -> (I32);
818 ValueDiv = "logos_rt_value_div", (I32, I32) -> (I32);
819 ValueExactDiv = "logos_rt_value_exact_div", (I32, I32) -> (I32);
820 ValueFloorDiv = "logos_rt_value_floor_div", (I32, I32) -> (I32);
821 ValueRem = "logos_rt_value_rem", (I32, I32) -> (I32);
822 ValuePow = "logos_rt_value_pow", (I32, I32) -> (I32);
823 ValueApproxEq = "logos_rt_value_approx_eq", (I32, I32) -> (I32);
824 ValueSeqConcat = "logos_rt_value_seq_concat", (I32, I32) -> (I32);
825 ValueBitAnd = "logos_rt_value_bit_and", (I32, I32) -> (I32);
826 ValueBitOr = "logos_rt_value_bit_or", (I32, I32) -> (I32);
827 ValueBitXor = "logos_rt_value_bit_xor", (I32, I32) -> (I32);
828 ValueShl = "logos_rt_value_shl", (I32, I32) -> (I32);
829 ValueShr = "logos_rt_value_shr", (I32, I32) -> (I32);
830 ValueMin = "logos_rt_value_min", (I32, I32) -> (I32);
831 ValueMax = "logos_rt_value_max", (I32, I32) -> (I32);
832 ValuePower = "logos_rt_value_power", (I32, I32) -> (I32);
833 ValueItem = "logos_rt_value_item", (I32, I32) -> (I32);
834 ValueEq = "logos_rt_value_eq", (I32, I32) -> (I32);
835 ValueNe = "logos_rt_value_ne", (I32, I32) -> (I32);
836 ValueLt = "logos_rt_value_lt", (I32, I32) -> (I32);
837 ValueGt = "logos_rt_value_gt", (I32, I32) -> (I32);
838 ValueLe = "logos_rt_value_le", (I32, I32) -> (I32);
839 ValueGe = "logos_rt_value_ge", (I32, I32) -> (I32);
840 ValueNot = "logos_rt_value_not", (I32) -> (I32);
841 ValueAbs = "logos_rt_value_abs", (I32) -> (I32);
842 ValueSqrt = "logos_rt_value_sqrt", (I32) -> (I32);
843 ValueFloor = "logos_rt_value_floor", (I32) -> (I32);
844 ValueCeil = "logos_rt_value_ceil", (I32) -> (I32);
845 ValueRound = "logos_rt_value_round", (I32) -> (I32);
846 ValueOfBigint = "logos_rt_value_of_bigint", (I32) -> (I32);
850 ValueOfRational = "logos_rt_value_of_rational", (I32) -> (I32);
851 ValueOfDecimal = "logos_rt_value_of_decimal", (I32) -> (I32);
852 ValueTupleOf = "logos_rt_value_tuple_of", (I32) -> (I32);
853 ValueApply = "logos_rt_value_apply", (I32, I32) -> (I32);
854 ValueDefine = "logos_rt_value_define", (I32, I64, I32, I32) -> (I32);
858 ValueChecked = "logos_rt_value_checked", (I32) -> (I32);
861 ValueToText = "logos_rt_value_to_text", (I32) -> (I32);
863 ValueOfText = "logos_rt_value_of_text", (I32) -> (I32);
864 ValueLengthI64 = "logos_rt_value_length_i64", (I32) -> (I64);
865 ValueTruthI32 = "logos_rt_value_truth_i32", (I32) -> (I32);
867 ValueContainsI64 = "logos_rt_value_contains_i64", (I32, I32) -> (I64);
868 ValueToI64 = "logos_rt_value_to_i64", (I32) -> (I64);
870 ValueIntegerAt = "logos_rt_value_integer_at", (I32, I32) -> (I64);
873 RationalCmp = "logos_rt_rational_cmp", (I32, I32) -> (I32);
875 RationalQuotient = "logos_rt_rational_quotient", (I32, I32) -> (I32);
877 RationalFloorQuotient = "logos_rt_rational_floor_quotient", (I32, I32) -> (I32);
879 RationalRemainder = "logos_rt_rational_remainder", (I32, I32) -> (I32);
881 RationalPower = "logos_rt_rational_power", (I32, I32) -> (I32);
883 RationalBitwise = "logos_rt_rational_bitwise", (I32, I32, I32) -> (I64);
885 RationalCmpF64 = "logos_rt_rational_cmp_f64", (I32, F64) -> (I32);
887 RationalToF64 = "logos_rt_rational_to_f64", (I32) -> (F64);
889 RationalAsI64 = "logos_rt_rational_as_i64", (I32, I32) -> (I64);
892}
893
894fn set_rates_value_kind(ops: &[Op], target: u16, kinds: &KindTable) -> Option<Kind> {
899 let mut aliases = std::collections::HashSet::new();
900 aliases.insert(target);
901 let mut changed = true;
902 while changed {
903 changed = false;
904 for op in ops {
905 if let Op::Move { dst, src } = op {
906 if aliases.contains(dst) && aliases.insert(*src) {
907 changed = true;
908 }
909 if aliases.contains(src) && aliases.insert(*dst) {
910 changed = true;
911 }
912 }
913 }
914 }
915 ops.iter().find_map(|op| match op {
916 Op::SetIndex {
917 collection, value, ..
918 } if aliases.contains(collection) => kinds.get(*value as usize),
919 _ => None,
920 })
921}
922
923fn wire_bytes_host_fn(arg_kind: Option<Kind>) -> Option<HostFn> {
927 match arg_kind {
928 Some(Kind::Int) => Some(HostFn::WireBytesInt),
929 Some(Kind::Bool) => Some(HostFn::WireBytesBool),
930 Some(Kind::Float) => Some(HostFn::WireBytesFloat),
931 Some(Kind::Text) => Some(HostFn::WireBytesText),
932 _ => None,
933 }
934}
935
936fn dom_import_of(b: BuiltinId) -> Option<HostFn> {
941 Some(match b {
942 BuiltinId::DomBody => HostFn::DomBody,
943 BuiltinId::DomCreateElement => HostFn::DomCreateElement,
944 BuiltinId::DomCreateTextNode => HostFn::DomCreateTextNode,
945 BuiltinId::DomSetText => HostFn::DomSetText,
946 BuiltinId::DomSetHtml => HostFn::DomSetHtml,
947 BuiltinId::DomClearChildren => HostFn::DomClearChildren,
948 BuiltinId::DomOnMessage => HostFn::DomOnMessage,
949 BuiltinId::DomAppendChild => HostFn::DomAppendChild,
950 BuiltinId::DomGetText => HostFn::DomGetText,
951 BuiltinId::DomGetValue => HostFn::DomGetValue,
952 BuiltinId::DomSetValue => HostFn::DomSetValue,
953 BuiltinId::DomSetChecked => HostFn::DomSetChecked,
954 BuiltinId::DomPreventDefault => HostFn::DomPreventDefault,
955 BuiltinId::StorageSet => HostFn::StorageSet,
956 BuiltinId::StorageGet => HostFn::StorageGet,
957 BuiltinId::StorageGetOr => HostFn::StorageGet,
958 BuiltinId::StorageRemove => HostFn::StorageRemove,
959 BuiltinId::DomApplyPatches => HostFn::DomApply,
960 BuiltinId::DomApplyWords => HostFn::DomApplyWords,
961 BuiltinId::DomQuerySelector => HostFn::DomQuerySelector,
962 BuiltinId::DomAddEventListener => HostFn::DomAddEventListener,
963 BuiltinId::DomListenFlags => HostFn::DomListenFlags,
964 BuiltinId::DomEnterValue => HostFn::DomEnterValue,
965 BuiltinId::DomDispatchEntry => HostFn::DomPageEntry,
966 BuiltinId::DomEventValue => HostFn::DomEventValue,
967 BuiltinId::DomEventKey => HostFn::DomEventKey,
968 BuiltinId::DomEventTarget => HostFn::DomEventTarget,
969 BuiltinId::DomFetchText => HostFn::DomFetchStart,
970 BuiltinId::DomResponseText => HostFn::DomResponseText,
971 BuiltinId::DomFetchSend => HostFn::DomFetchSend,
972 BuiltinId::DomResponseStatus => HostFn::DomResponseStatus,
973 BuiltinId::DomResponseBody => HostFn::DomResponseBody,
974 BuiltinId::DomResponseHeader => HostFn::DomResponseHeader,
975 BuiltinId::DomResponseError => HostFn::DomResponseError,
976 BuiltinId::DomFetchAbort => HostFn::DomFetchAbort,
977 BuiltinId::DomFetchSetTimeout => HostFn::DomFetchSetTimeout,
978 BuiltinId::DomRoutePath => HostFn::DomRoutePath,
979 BuiltinId::DomRouteQuery => HostFn::DomRouteQuery,
980 BuiltinId::DomNavigate => HostFn::DomNavigate,
981 BuiltinId::DomAssignLocation => HostFn::DomAssignLocation,
982 BuiltinId::DomSetTitle => HostFn::DomSetTitle,
983 BuiltinId::DomSetHeadHtml => HostFn::DomSetHeadHtml,
984 BuiltinId::DomReload => HostFn::DomReload,
985 BuiltinId::DomGoBack => HostFn::DomGoBack,
986 BuiltinId::DomGetAttribute => HostFn::DomGetAttribute,
987 BuiltinId::DomOnWindowEvent => HostFn::DomOnWindowEvent,
988 BuiltinId::DomScrollGap => HostFn::DomScrollGap,
989 BuiltinId::DomSetInterval => HostFn::DomSetInterval,
990 BuiltinId::DomEventFileName => HostFn::DomEventFileName,
991 BuiltinId::DomEventFileSize => HostFn::DomEventFileSize,
992 BuiltinId::DomEventFileType => HostFn::DomEventFileType,
993 BuiltinId::DomEventFileBytes => HostFn::DomEventFileBytes,
994 BuiltinId::DomElementCommand => HostFn::DomElementCommand,
995 BuiltinId::DomClipboardWrite => HostFn::DomClipboardWrite,
996 BuiltinId::DomDownloadFile => HostFn::DomDownloadFile,
997 BuiltinId::DomNotify => HostFn::DomNotify,
998 BuiltinId::DomPublish => HostFn::DomPublish,
999 BuiltinId::NoteTurn => HostFn::DomNoteTurn,
1000 BuiltinId::DomJournalDetail => HostFn::DomJournalDetail,
1001 BuiltinId::DomWakeAfter => HostFn::DomWakeAfter,
1002 BuiltinId::DomReplaceRoute => HostFn::DomReplaceRoute,
1003 BuiltinId::DomOnRoute => HostFn::DomOnRoute,
1004 _ => return None,
1005 })
1006}
1007
1008fn lanes_v_host_fn(b: BuiltinId) -> Option<HostFn> {
1012 Some(match b {
1013 BuiltinId::Lanes16Word8Make => HostFn::Lanes16FromBytes,
1014 BuiltinId::Lanes8Word32 => HostFn::Lanes8FromWords,
1015 BuiltinId::Lanes4Word64 => HostFn::Lanes4W64FromWords,
1016 BuiltinId::Splat16Word8 => HostFn::LanesSplat16,
1017 BuiltinId::Splat8Word32 => HostFn::LanesSplat8,
1018 BuiltinId::SeqOfLanes16W8 | BuiltinId::SeqOfLanes8 => HostFn::LanesToSeq,
1019 BuiltinId::Shuffle16 => HostFn::LanesShuffle,
1020 BuiltinId::InterleaveLo16 => HostFn::LanesInterleaveLo,
1021 BuiltinId::InterleaveHi16 => HostFn::LanesInterleaveHi,
1022 BuiltinId::ByteAdd16 => HostFn::LanesByteAdd,
1023 BuiltinId::Maddubs16 => HostFn::LanesMaddubs,
1024 BuiltinId::Packus16 => HostFn::LanesPackus,
1025 BuiltinId::ShrBytes16 => HostFn::LanesShrBytes,
1026 _ => return None,
1027 })
1028}
1029
1030pub fn host_import_names() -> Vec<&'static str> {
1038 HOST_FNS.iter().map(|h| h.field()).collect()
1039}
1040
1041pub fn runtime_export_names() -> Vec<&'static str> {
1045 fn listed(f: RuntimeFn) -> RuntimeFn {
1047 match f {
1048 RuntimeFn::Alloc
1049 | RuntimeFn::Free
1050 | RuntimeFn::HeapAllocated
1051 | RuntimeFn::HeapUsed
1052 | RuntimeFn::IterUnwind
1053 | RuntimeFn::TextNew
1054 | RuntimeFn::SeqNew
1055 | RuntimeFn::SeqSlot
1056 | RuntimeFn::SeqPushSlot
1057 | RuntimeFn::SeqClone
1058 | RuntimeFn::SeqOwn
1059 | RuntimeFn::TextEq
1060 | RuntimeFn::TextConcat
1061 | RuntimeFn::MapClone
1062 | RuntimeFn::MapOwn
1063 | RuntimeFn::MapPut
1064 | RuntimeFn::MapFind
1065 | RuntimeFn::MapAt
1066 | RuntimeFn::AddChecked
1067 | RuntimeFn::SubChecked
1068 | RuntimeFn::MulChecked
1069 | RuntimeFn::ExactAdd
1070 | RuntimeFn::ExactSub
1071 | RuntimeFn::ExactMul
1072 | RuntimeFn::ExactAddW
1073 | RuntimeFn::ExactSubW
1074 | RuntimeFn::ExactMulW
1075 | RuntimeFn::ExactTag
1076 | RuntimeFn::ExactRelease
1077 | RuntimeFn::ExactNarrow
1078 | RuntimeFn::ExactClone
1079 | RuntimeFn::ExactSeqPromote
1080 | RuntimeFn::ExactCell
1081 | RuntimeFn::ExactCompare
1082 | RuntimeFn::ExactSeqAt
1083 | RuntimeFn::ExactSeqStore
1084 | RuntimeFn::ExactMapPromoteKey
1085 | RuntimeFn::ExactMapPromoteValue
1086 | RuntimeFn::NewHeader
1087 | RuntimeFn::Share
1088 | RuntimeFn::TurnRetain
1089 | RuntimeFn::Retain
1090 | RuntimeFn::RetainChildren
1091 | RuntimeFn::Release
1092 | RuntimeFn::Safepoint
1093 | RuntimeFn::FreeObject
1094 | RuntimeFn::Census
1095 | RuntimeFn::CensusVisit
1096 | RuntimeFn::ClosureRetain
1097 | RuntimeFn::ClosureRelease => f,
1098 }
1099 }
1100 let runtime = [
1101 RuntimeFn::Alloc,
1102 RuntimeFn::Free,
1103 RuntimeFn::HeapAllocated,
1104 RuntimeFn::HeapUsed,
1105 RuntimeFn::IterUnwind,
1106 RuntimeFn::TextNew,
1107 RuntimeFn::SeqNew,
1108 RuntimeFn::SeqSlot,
1109 RuntimeFn::SeqPushSlot,
1110 RuntimeFn::SeqClone,
1111 RuntimeFn::SeqOwn,
1112 RuntimeFn::TextEq,
1113 RuntimeFn::TextConcat,
1114 RuntimeFn::MapClone,
1115 RuntimeFn::MapOwn,
1116 RuntimeFn::MapPut,
1117 RuntimeFn::MapFind,
1118 RuntimeFn::MapAt,
1119 RuntimeFn::AddChecked,
1120 RuntimeFn::SubChecked,
1121 RuntimeFn::MulChecked,
1122 RuntimeFn::ExactAdd,
1123 RuntimeFn::ExactSub,
1124 RuntimeFn::ExactMul,
1125 RuntimeFn::ExactAddW,
1126 RuntimeFn::ExactSubW,
1127 RuntimeFn::ExactMulW,
1128 RuntimeFn::ExactTag,
1129 RuntimeFn::ExactRelease,
1130 RuntimeFn::ExactNarrow,
1131 RuntimeFn::ExactClone,
1132 RuntimeFn::ExactSeqPromote,
1133 RuntimeFn::ExactCell,
1134 RuntimeFn::ExactCompare,
1135 RuntimeFn::ExactSeqAt,
1136 RuntimeFn::ExactSeqStore,
1137 RuntimeFn::ExactMapPromoteKey,
1138 RuntimeFn::ExactMapPromoteValue,
1139 RuntimeFn::NewHeader,
1140 RuntimeFn::Share,
1141 RuntimeFn::TurnRetain,
1142 RuntimeFn::Retain,
1143 RuntimeFn::RetainChildren,
1144 RuntimeFn::Release,
1145 RuntimeFn::Safepoint,
1146 RuntimeFn::FreeObject,
1147 RuntimeFn::Census,
1148 RuntimeFn::CensusVisit,
1149 RuntimeFn::ClosureRetain,
1150 RuntimeFn::ClosureRelease,
1151 ];
1152 [
1153 "main",
1154 "memory",
1155 "__heap_ptr",
1156 "__logos_call_closure",
1157 "__logos_render",
1158 ]
1159 .into_iter()
1160 .chain(runtime.into_iter().filter_map(|f| listed(f).export()))
1161 .collect()
1162}
1163
1164pub fn host_text_import_names() -> Vec<&'static str> {
1167 HOST_FNS
1168 .iter()
1169 .filter(|h| h.returns_host_text())
1170 .map(|h| h.field())
1171 .collect()
1172}
1173
1174pub fn host_seq_import_names() -> Vec<&'static str> {
1177 HOST_FNS
1178 .iter()
1179 .filter(|h| h.returns_host_seq())
1180 .map(|h| h.field())
1181 .collect()
1182}
1183
1184pub fn host_import_signatures() -> Vec<(&'static str, Vec<u8>, Vec<u8>)> {
1193 HOST_FNS
1194 .iter()
1195 .map(|h| (h.field(), h.params(), h.results()))
1196 .collect()
1197}
1198
1199impl HostFn {
1200 fn for_show(k: Kind) -> Option<HostFn> {
1204 Some(match k {
1205 Kind::Nothing => HostFn::PrintNothing,
1206 Kind::Int => HostFn::PrintI64,
1207 Kind::Bool => HostFn::PrintBool,
1208 Kind::Char => HostFn::PrintChar,
1209 Kind::Float => HostFn::PrintF64,
1210 Kind::Date => HostFn::PrintDate,
1211 Kind::Moment => HostFn::PrintMoment,
1212 Kind::Duration => HostFn::PrintDuration,
1213 Kind::Time => HostFn::PrintTime,
1214 Kind::Span => HostFn::PrintSpan,
1215 Kind::SeqInt => HostFn::PrintSeqI64,
1216 Kind::SeqBool => HostFn::PrintSeqBool,
1217 Kind::SeqWord32 => HostFn::PrintSeqWord32,
1218 Kind::SeqWord64 => HostFn::PrintSeqWord64,
1219 Kind::SeqFloat => HostFn::PrintSeqF64,
1220 Kind::SeqText => HostFn::PrintSeqText,
1221 Kind::SeqAny => HostFn::PrintSeqI64,
1223 Kind::SeqHandle => return None,
1227 Kind::Text => HostFn::PrintText,
1228 Kind::Struct => return None,
1232 Kind::Set => HostFn::PrintSetI64,
1235 Kind::SetText | Kind::CrdtSetText => HostFn::PrintSetText,
1236 Kind::CrdtCounter => return None,
1240 Kind::Map => return None,
1244 Kind::Enum => return None,
1246 Kind::Closure => return None,
1248 Kind::BigInt => return None,
1251 Kind::Complex => return None,
1253 Kind::Modular => return None,
1255 Kind::Decimal => return None,
1257 Kind::Money => return None,
1259 Kind::Quantity => return None,
1260 Kind::Uuid => return None,
1261 Kind::Lanes => return None,
1262 Kind::LanesV => return None,
1264 Kind::Tower => return None,
1266 Kind::Dynamic => return None,
1269 Kind::Tuple => return None,
1272 Kind::SeqStruct => return None,
1275 Kind::SeqEnum => return None,
1278 Kind::SeqSeqInt => return None,
1281 Kind::Rational => return None,
1284 Kind::Optional => return None,
1287 Kind::Word32 | Kind::Word64 => return None,
1290 })
1291 }
1292}
1293
1294#[derive(Default)]
1296struct TypeTable {
1297 sigs: Vec<(Vec<u8>, Vec<u8>)>,
1298}
1299
1300impl TypeTable {
1301 fn intern(&mut self, params: Vec<u8>, results: Vec<u8>) -> u32 {
1302 if let Some(i) = self
1303 .sigs
1304 .iter()
1305 .position(|(p, r)| *p == params && *r == results)
1306 {
1307 return i as u32;
1308 }
1309 self.sigs.push((params, results));
1310 (self.sigs.len() - 1) as u32
1311 }
1312
1313 fn encode(&self) -> Vec<u8> {
1314 let mut out = Vec::new();
1315 leb_u32(&mut out, self.sigs.len() as u32);
1316 for (params, results) in &self.sigs {
1317 out.push(0x60); leb_u32(&mut out, params.len() as u32);
1319 out.extend_from_slice(params);
1320 leb_u32(&mut out, results.len() as u32);
1321 out.extend_from_slice(results);
1322 }
1323 out
1324 }
1325}
1326
1327struct Plan {
1332 ops: Vec<Op>,
1333 kinds: KindTable,
1334 num_params: u32,
1335 num_regs: u32,
1336 result: Option<Kind>,
1337 reachable_blocks: Vec<bool>,
1338 structs: kind::StructLayout,
1341 cow_inserts: Vec<bool>,
1344 reg_shape: std::collections::HashMap<u16, kind::ParamShape>,
1348 return_closure: Option<u16>,
1352 iter_iterable: Vec<Option<usize>>,
1355 range_loops: std::collections::HashMap<u16, (u16, u16)>,
1358 place: PlaceSites,
1360 transient: Vec<bool>,
1363 declared: std::collections::HashMap<u16, BoundaryType>,
1367 inout: Vec<u16>,
1371 exact: Vec<bool>,
1374 params_tagged: Vec<bool>,
1376 ret_tagged: bool,
1378 absence: bool,
1379 absence_regs: Vec<bool>,
1380 absence_globals: Vec<bool>,
1381 tower: tower::Towers,
1383 stub: bool,
1388}
1389
1390impl Plan {
1391 fn stub() -> Plan {
1393 Plan {
1394 ops: Vec::new(),
1395 kinds: KindTable::empty(),
1396 num_params: 0,
1397 num_regs: 0,
1398 result: None,
1399 reachable_blocks: Vec::new(),
1400 structs: kind::StructLayout::default(),
1401 cow_inserts: Vec::new(),
1402 reg_shape: std::collections::HashMap::new(),
1403 return_closure: None,
1404 iter_iterable: Vec::new(),
1405 range_loops: std::collections::HashMap::new(),
1406 place: PlaceSites::default(),
1407 transient: Vec::new(),
1408 declared: std::collections::HashMap::new(),
1409 inout: Vec::new(),
1410 exact: Vec::new(),
1411 params_tagged: Vec::new(),
1412 ret_tagged: false,
1413 absence: false,
1414 absence_regs: Vec::new(),
1415 absence_globals: Vec::new(),
1416 tower: tower::Towers::default(),
1417 stub: true,
1418 }
1419 }
1420}
1421
1422fn range_loop_registers(
1425 ops: &[Op],
1426 functions: &[CompiledFunction],
1427) -> std::collections::HashMap<u16, (u16, u16)> {
1428 let mut defs = std::collections::HashMap::<u16, usize>::new();
1429 let mut uses = std::collections::HashMap::<u16, usize>::new();
1430 for op in ops {
1431 let (d, u) = crate::vm::instruction::op_def_uses(op, functions);
1432 for r in d {
1433 *defs.entry(r).or_default() += 1;
1434 }
1435 for r in u {
1436 *uses.entry(r).or_default() += 1;
1437 }
1438 }
1439 let mut incoming = vec![0_usize; ops.len()];
1442 for (pc, op) in ops.iter().enumerate() {
1443 for next in crate::vm::instruction::op_successors(op, pc, ops.len()) {
1444 if let Some(count) = incoming.get_mut(next) {
1445 *count += 1;
1446 }
1447 }
1448 }
1449 ops.windows(2)
1450 .enumerate()
1451 .filter_map(|(pc, pair)| match (&pair[0], &pair[1]) {
1452 (Op::NewRange { dst, start, end }, Op::IterPrepare { iterable })
1453 if dst == iterable
1454 && defs.get(dst) == Some(&1)
1455 && uses.get(dst) == Some(&1)
1456 && incoming[pc + 1] == 1 =>
1457 {
1458 Some((*dst, (*start, *end)))
1459 }
1460 _ => None,
1461 })
1462 .collect()
1463}
1464
1465#[derive(Default)]
1479struct PlaceSites {
1480 field_at: Vec<Option<u32>>,
1483 take: Vec<bool>,
1485 clear: Vec<bool>,
1487 put_back: Vec<bool>,
1489}
1490
1491#[derive(Clone, Copy, PartialEq)]
1494enum PlaceKey {
1495 Field(u32),
1496 Item(u16),
1497 Global(u16),
1498}
1499
1500impl PlaceSites {
1501 fn of(ops: &[Op], constants: &[Constant], functions: &[CompiledFunction]) -> PlaceSites {
1502 let n = ops.len();
1503 let Some(blocks) = super::cfg::Blocks::new(ops) else {
1504 return PlaceSites::default();
1505 };
1506 let const_at = |pc: usize, reg: u16| -> Option<u32> {
1510 let mut j = pc;
1511 while j > 0 && !blocks.is_leader(j) {
1512 j -= 1;
1513 if let Op::LoadConst { dst, idx } = ops[j] {
1514 if dst == reg {
1515 return Some(idx);
1516 }
1517 continue;
1518 }
1519 if crate::vm::instruction::op_def_uses(&ops[j], functions)
1520 .0
1521 .contains(®)
1522 {
1523 return None;
1524 }
1525 }
1526 None
1527 };
1528 let text_const = |c: u32| matches!(constants.get(c as usize), Some(Constant::Text(_)));
1529 let is_nothing = |c: Option<u32>| {
1530 c.is_some_and(|c| matches!(constants.get(c as usize), Some(Constant::Nothing)))
1531 };
1532 let same_name = |a: u32, b: u32| matches!((constants.get(a as usize), constants.get(b as usize)), (Some(Constant::Text(x)), Some(Constant::Text(y))) if x == y);
1533 let mut field_at = vec![None; n];
1534 for (pc, op) in ops.iter().enumerate() {
1535 if let Op::SetIndex { index, .. } | Op::SetIndexUnchecked { index, .. } = *op {
1536 field_at[pc] = const_at(pc, index).filter(|&c| text_const(c));
1537 }
1538 }
1539 let writes = |at: usize, parent: u16, key: PlaceKey| -> bool {
1542 match (ops[at], key) {
1543 (
1544 Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. },
1545 PlaceKey::Field(f),
1546 ) => collection == parent && field_at[at].is_some_and(|c| same_name(c, f)),
1547 (
1548 Op::SetIndex {
1549 collection, index, ..
1550 }
1551 | Op::SetIndexUnchecked {
1552 collection, index, ..
1553 },
1554 PlaceKey::Item(r),
1555 ) => collection == parent && index == r,
1556 (Op::GlobalSet { idx, .. }, PlaceKey::Global(g)) => idx == g,
1557 _ => false,
1558 }
1559 };
1560 let set_value = |at: usize| match ops[at] {
1561 Op::SetIndex { value, .. } | Op::SetIndexUnchecked { value, .. } => Some(value),
1562 Op::GlobalSet { src, .. } => Some(src),
1563 _ => None,
1564 };
1565 let mut take = vec![false; n];
1566 let mut clear = vec![false; n];
1567 let mut put_back = vec![false; n];
1568 let mut taken: Vec<(u16, PlaceKey, u16)> = Vec::new();
1569 for (pc, op) in ops.iter().enumerate() {
1570 let read = match *op {
1571 Op::GetField { dst, obj, field } => Some((dst, obj, PlaceKey::Field(field))),
1572 Op::Index {
1573 dst,
1574 collection,
1575 index,
1576 }
1577 | Op::IndexUnchecked {
1578 dst,
1579 collection,
1580 index,
1581 } => Some((dst, collection, PlaceKey::Item(index))),
1582 Op::GlobalGet { dst, idx } => Some((dst, 0, PlaceKey::Global(idx))),
1583 _ => None,
1584 };
1585 if let Some((dst, parent, key)) = read {
1586 let next = ops[pc + 1..]
1587 .iter()
1588 .position(|o| !matches!(o, Op::LoadConst { .. }))
1589 .map(|i| pc + 1 + i);
1590 if let Some(at) = next {
1591 if writes(at, parent, key)
1592 && is_nothing(set_value(at).and_then(|v| const_at(at, v)))
1593 {
1594 take[pc] = true;
1595 clear[at] = true;
1596 taken.push((parent, key, dst));
1597 continue;
1598 }
1599 }
1600 if let PlaceKey::Global(g) = key {
1604 if stored_back(ops, pc, g, dst) {
1605 take[pc] = true;
1606 taken.push((parent, key, dst));
1607 }
1608 }
1609 continue;
1610 }
1611 if clear[pc] {
1612 continue;
1613 }
1614 if let Some(value) = set_value(pc) {
1615 let back = taken
1616 .iter()
1617 .position(|&(parent, key, d)| d == value && writes(pc, parent, key));
1618 if let Some(i) = back {
1619 put_back[pc] = true;
1620 taken.remove(i);
1621 }
1622 }
1623 }
1624 PlaceSites {
1625 field_at,
1626 take,
1627 clear,
1628 put_back,
1629 }
1630 }
1631}
1632
1633fn declared_registers(
1636 structs: &kind::StructLayout,
1637 seeded: Vec<(usize, u16, BoundaryType)>,
1638 param_types: &[Option<BoundaryType>],
1639) -> std::collections::HashMap<u16, BoundaryType> {
1640 let mut declared: std::collections::HashMap<u16, BoundaryType> = param_types
1641 .iter()
1642 .enumerate()
1643 .filter_map(|(i, t)| t.clone().map(|t| (i as u16, t)))
1644 .collect();
1645 for (_, reg, bt) in seeded {
1646 declared.entry(reg).or_insert(bt);
1647 }
1648 for (reg, bt) in &structs.reg_declared {
1649 declared.entry(*reg).or_insert_with(|| bt.clone());
1650 }
1651 declared
1652}
1653
1654fn transient_reads(ops: &[Op], num_regs: u32, functions: &[CompiledFunction]) -> Vec<bool> {
1669 let mut transient = vec![true; num_regs as usize];
1670 let Some(blocks) = super::cfg::Blocks::new(ops) else {
1671 return vec![false; num_regs as usize];
1672 };
1673 let mut clean: std::collections::HashSet<crate::vm::instruction::Reg> =
1676 std::collections::HashSet::new();
1677 for (pc, op) in ops.iter().enumerate() {
1678 if blocks.is_leader(pc) {
1679 clean.clear();
1680 }
1681 let (defs, uses) = crate::vm::instruction::op_def_uses(op, functions);
1682 let pure = pure_read_operands(op, functions);
1683 for r in uses {
1684 if !pure.contains(&r) || !clean.contains(&r) {
1685 if let Some(t) = transient.get_mut(r as usize) {
1686 *t = false;
1687 }
1688 }
1689 }
1690 if !leaves_the_heap_alone(op) {
1691 clean.clear();
1692 }
1693 for r in defs {
1694 clean.insert(r);
1695 }
1696 }
1697 transient
1698}
1699
1700fn pure_read_operands(op: &Op, functions: &[CompiledFunction]) -> Vec<crate::vm::instruction::Reg> {
1706 match *op {
1707 Op::CallBuiltin {
1708 builtin,
1709 args_start,
1710 arg_count,
1711 ..
1712 } => match dom_import_of(builtin) {
1713 Some(host) => {
1714 let kept = host.retained_params();
1715 (0..arg_count)
1716 .filter(|i| !kept.contains(&usize::from(*i)))
1717 .map(|i| args_start + i)
1718 .collect()
1719 }
1720 None => Vec::new(),
1721 },
1722 Op::Index {
1723 collection, index, ..
1724 }
1725 | Op::IndexUnchecked {
1726 collection, index, ..
1727 } => vec![collection, index],
1728 Op::Length { collection, .. } => vec![collection],
1729 Op::Contains {
1730 collection, value, ..
1731 } => vec![collection, value],
1732 Op::GetField { obj, .. } => vec![obj],
1733 Op::Show { src }
1734 | Op::Not { src, .. }
1735 | Op::FormatValue { src, .. }
1736 | Op::DeepClone { src, .. } => vec![src],
1737 Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => vec![cond],
1738 Op::SliceOp {
1739 collection,
1740 start,
1741 end,
1742 ..
1743 } => vec![collection, start, end],
1744 Op::Add { lhs, rhs, .. }
1745 | Op::Sub { lhs, rhs, .. }
1746 | Op::Mul { lhs, rhs, .. }
1747 | Op::Div { lhs, rhs, .. }
1748 | Op::ExactDiv { lhs, rhs, .. }
1749 | Op::FloorDiv { lhs, rhs, .. }
1750 | Op::Mod { lhs, rhs, .. }
1751 | Op::Pow { lhs, rhs, .. }
1752 | Op::Lt { lhs, rhs, .. }
1753 | Op::Gt { lhs, rhs, .. }
1754 | Op::LtEq { lhs, rhs, .. }
1755 | Op::GtEq { lhs, rhs, .. }
1756 | Op::Eq { lhs, rhs, .. }
1757 | Op::NotEq { lhs, rhs, .. }
1758 | Op::ApproxEq { lhs, rhs, .. }
1759 | Op::Concat { lhs, rhs, .. }
1760 | Op::SeqConcat { lhs, rhs, .. }
1761 | Op::UnionOp { lhs, rhs, .. }
1762 | Op::IntersectOp { lhs, rhs, .. } => vec![lhs, rhs],
1763 Op::Call { .. } => crate::vm::instruction::op_def_uses(op, functions).1,
1764 _ => Vec::new(),
1765 }
1766}
1767
1768fn leaves_the_heap_alone(op: &Op) -> bool {
1770 matches!(
1771 op,
1772 Op::LoadConst { .. }
1773 | Op::Move { .. }
1774 | Op::Add { .. }
1775 | Op::Sub { .. }
1776 | Op::Mul { .. }
1777 | Op::Div { .. }
1778 | Op::ExactDiv { .. }
1779 | Op::FloorDiv { .. }
1780 | Op::Mod { .. }
1781 | Op::Pow { .. }
1782 | Op::DivPow2 { .. }
1783 | Op::MagicDivU { .. }
1784 | Op::Lt { .. }
1785 | Op::Gt { .. }
1786 | Op::LtEq { .. }
1787 | Op::GtEq { .. }
1788 | Op::Eq { .. }
1789 | Op::NotEq { .. }
1790 | Op::ApproxEq { .. }
1791 | Op::Not { .. }
1792 | Op::Concat { .. }
1793 | Op::SeqConcat { .. }
1794 | Op::BitXor { .. }
1795 | Op::BitAnd { .. }
1796 | Op::BitOr { .. }
1797 | Op::Shl { .. }
1798 | Op::Shr { .. }
1799 | Op::Index { .. }
1800 | Op::IndexUnchecked { .. }
1801 | Op::Length { .. }
1802 | Op::Contains { .. }
1803 | Op::GetField { .. }
1804 | Op::GlobalGet { .. }
1805 | Op::FormatValue { .. }
1806 | Op::SliceOp { .. }
1807 | Op::DeepClone { .. }
1808 | Op::UnionOp { .. }
1809 | Op::IntersectOp { .. }
1810 | Op::NewList { .. }
1811 | Op::NewEmptyList { .. }
1812 | Op::NewEmptyListWithCapacity { .. }
1813 | Op::NewEmptyListI32 { .. }
1814 | Op::NewEmptyListFixed { .. }
1815 | Op::NewEmptySet { .. }
1816 | Op::NewEmptyMap { .. }
1817 | Op::NewEmptyMapWithCapacity { .. }
1818 | Op::NewRange { .. }
1819 | Op::NewTuple { .. }
1820 | Op::NewStruct { .. }
1821 | Op::NewInductive { .. }
1822 | Op::TestArm { .. }
1823 | Op::BindArm { .. }
1824 | Op::Show { .. }
1825 | Op::LoadToday { .. }
1826 | Op::LoadNow { .. }
1827 | Op::Jump { .. }
1828 | Op::JumpIfFalse { .. }
1829 | Op::JumpIfTrue { .. }
1830 )
1831}
1832
1833fn stored_back(ops: &[Op], pc: usize, g: u16, dst: u16) -> bool {
1836 for op in &ops[pc + 1..] {
1837 match *op {
1838 Op::GlobalSet { idx, src } if idx == g && src == dst => return true,
1839 Op::GlobalGet { idx, .. } if idx == g => return false,
1840 Op::Call { .. }
1841 | Op::CallValue { .. }
1842 | Op::CallBuiltin { .. }
1843 | Op::Jump { .. }
1844 | Op::JumpIfFalse { .. }
1845 | Op::JumpIfTrue { .. }
1846 | Op::IterNext { .. }
1847 | Op::Return { .. }
1848 | Op::ReturnNothing
1849 | Op::Halt => return false,
1850 _ => {}
1851 }
1852 }
1853 false
1854}
1855
1856fn record_field_slot(plan: &Plan, obj: u16, field: u32) -> Option<usize> {
1859 if let Some(ParamShape::Struct(layout)) = plan.reg_shape.get(&obj) {
1860 return layout.iter().position(|(f, _, _)| *f == field);
1861 }
1862 plan.structs
1863 .reg_layout
1864 .get(&obj)?
1865 .iter()
1866 .position(|(f, _)| *f == field)
1867}
1868
1869fn infer_with_reachability(
1874 ops: &[Op],
1875 constants: &[Constant],
1876 struct_types: &[StructTypeDef],
1877 enum_types: &[EnumTypeDef],
1878 fn_return_types: &[Option<BoundaryType>],
1879 num_regs: usize,
1880 seeds: &[Option<Kind>],
1881 ret_of: &dyn Fn(usize) -> Option<Kind>,
1882 global_of: &dyn Fn(u16) -> Option<Kind>,
1883 closure_ret: &dyn Fn(usize) -> Option<Kind>,
1884 ret_layout: &dyn Fn(u16) -> Option<FieldLayout>,
1885 fn_return_closure: &dyn Fn(u16) -> Option<u16>,
1886 param_layouts: &[(u16, ParamShape)],
1887 param_closures: &[(u16, u16)],
1888 global_layout: &dyn Fn(u16) -> Option<FieldLayout>,
1889 global_declared: &dyn Fn(u16) -> Option<BoundaryType>,
1890 linked: bool,
1891 functions: &[crate::vm::instruction::CompiledFunction],
1892 inout: &[u16],
1893) -> R<(KindTable, Vec<bool>, Vec<bool>)> {
1894 let blocks = Blocks::new(ops).ok_or(WasmLowerError::Unsupported(
1895 "jump target escapes the function",
1896 ))?;
1897 let (pc_reach, block_reach) = reachability(ops, &blocks);
1898 let bigint_demand = kind::bigint_demanded_regs(ops, functions, linked);
1901 let dead_clears = regsplit::unobserved_nothing_writes(ops, constants, functions, inout);
1905 let kind_reach: Vec<_> = pc_reach
1906 .iter()
1907 .enumerate()
1908 .map(|(pc, &reachable)| reachable && !dead_clears.contains(&pc))
1909 .collect();
1910 let kinds = kind::infer(
1911 ops,
1912 constants,
1913 struct_types,
1914 enum_types,
1915 fn_return_types,
1916 num_regs,
1917 seeds,
1918 ret_of,
1919 global_of,
1920 closure_ret,
1921 ret_layout,
1922 fn_return_closure,
1923 param_layouts,
1924 param_closures,
1925 global_layout,
1926 global_declared,
1927 &kind_reach,
1928 linked,
1929 &bigint_demand,
1930 )?;
1931 Ok((kinds, pc_reach, block_reach))
1932}
1933
1934fn reachability(ops: &[Op], blocks: &Blocks) -> (Vec<bool>, Vec<bool>) {
1937 let nb = blocks.num_blocks();
1938 let mut block_reach = vec![false; nb];
1939 let mut stack = vec![0usize];
1940 while let Some(k) = stack.pop() {
1941 if block_reach[k] {
1942 continue;
1943 }
1944 block_reach[k] = true;
1945 for s in block_successors(ops, blocks, k) {
1946 if !block_reach[s] {
1947 stack.push(s);
1948 }
1949 }
1950 }
1951 let mut pc_reach = vec![false; ops.len()];
1952 for (k, &live) in block_reach.iter().enumerate() {
1953 if live {
1954 for pc in blocks.start(k)..blocks.end(k) {
1955 pc_reach[pc] = true;
1956 }
1957 }
1958 }
1959 (pc_reach, block_reach)
1960}
1961
1962fn block_successors(ops: &[Op], blocks: &Blocks, k: usize) -> Vec<usize> {
1964 let n = ops.len();
1965 let fallthrough = |pc: usize| -> Vec<usize> {
1966 if pc + 1 < n {
1967 vec![blocks.block_of(pc + 1)]
1968 } else {
1969 vec![]
1970 }
1971 };
1972 for pc in blocks.start(k)..blocks.end(k) {
1973 match ops[pc] {
1974 Op::Jump { target } => return vec![blocks.block_of(target)],
1975 Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
1976 let mut s = vec![blocks.block_of(target)];
1977 s.extend(fallthrough(pc));
1978 return s;
1979 }
1980 Op::IterNext { exit, .. } => {
1983 let mut s = vec![blocks.block_of(exit)];
1984 s.extend(fallthrough(pc));
1985 return s;
1986 }
1987 Op::Return { .. }
1988 | Op::ReturnNothing
1989 | Op::Halt
1990 | Op::FailWith { .. }
1991 | Op::CallBuiltin {
1992 builtin:
1993 BuiltinId::Fail
1994 | BuiltinId::FailReason
1995 | BuiltinId::VfsMount
1996 | BuiltinId::VfsWriteFile,
1997 ..
1998 } => return vec![],
1999 _ => {}
2000 }
2001 }
2002 if blocks.end(k) < n {
2004 vec![blocks.block_of(blocks.end(k))]
2005 } else {
2006 vec![]
2007 }
2008}
2009
2010pub const VFS_IN_THE_BROWSER: &str =
2013 "a page in the browser has no file system: mounting a journal and writing a file run on the compiled tiers";
2014
2015pub fn assemble_program(
2019 program: &CompiledProgram,
2020 policies: &PolicyRegistry,
2021 interner: &Interner,
2022) -> R<Vec<u8>> {
2023 assemble_program_impl(
2024 program,
2025 policies,
2026 interner,
2027 false,
2028 Reclaim::Counted,
2029 &HostEntries::default(),
2030 )
2031}
2032
2033pub fn assemble_program_with(
2038 program: &CompiledProgram,
2039 policies: &PolicyRegistry,
2040 interner: &Interner,
2041 entries: &HostEntries,
2042) -> R<Vec<u8>> {
2043 assemble_program_impl(
2044 program,
2045 policies,
2046 interner,
2047 false,
2048 Reclaim::Counted,
2049 entries,
2050 )
2051}
2052
2053pub fn assemble_program_checked(
2057 program: &CompiledProgram,
2058 policies: &PolicyRegistry,
2059 interner: &Interner,
2060 entries: &HostEntries,
2061) -> R<Vec<u8>> {
2062 assemble_program_impl(
2063 program,
2064 policies,
2065 interner,
2066 false,
2067 Reclaim::Checked,
2068 entries,
2069 )
2070}
2071
2072#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2075enum Reclaim {
2076 Off,
2078 Counted,
2081 Checked,
2084}
2085
2086pub(crate) fn assemble_program_linked(
2094 program: &CompiledProgram,
2095 policies: &PolicyRegistry,
2096 interner: &Interner,
2097) -> R<Vec<u8>> {
2098 assemble_program_impl(
2099 program,
2100 policies,
2101 interner,
2102 true,
2103 Reclaim::Off,
2104 &HostEntries::default(),
2105 )
2106}
2107
2108fn within_function(
2112 e: WasmLowerError,
2113 program: &CompiledProgram,
2114 interner: &Interner,
2115 fi: Option<usize>,
2116) -> WasmLowerError {
2117 let name = match fi {
2118 None => "Main".to_string(),
2119 Some(fi) => match program.functions.get(fi).map(|f| interner.resolve(f.name)) {
2120 Some(name) if !name.is_empty() => format!("`{name}`"),
2121 _ => format!("function #{fi}"),
2122 },
2123 };
2124 let what = match e {
2125 WasmLowerError::Unsupported(what) => what.to_string(),
2126 WasmLowerError::UnsupportedOwned(what) => what,
2127 };
2128 WasmLowerError::UnsupportedOwned(format!("{what} (in {name})"))
2129}
2130
2131fn assemble_program_impl(
2132 program: &CompiledProgram,
2133 policies: &PolicyRegistry,
2134 interner: &Interner,
2135 linked: bool,
2136 reclaim: Reclaim,
2137 entries: &HostEntries,
2138) -> R<Vec<u8>> {
2139 if !linked && crate::vm::tower::reaches(program) {
2140 return Err(WasmLowerError::UnsupportedOwned(tower::REFUSAL.to_string()));
2141 }
2142 let layout = crate::vm::reach::code_layout(program).map_err(WasmLowerError::Unsupported)?;
2144 let ret_of = |fi: usize| -> Option<Kind> { declared_result(program, fi) };
2145 let no_closure = |_: usize| -> Option<Kind> { None };
2146 let no_ret_layout = |_: u16| -> Option<FieldLayout> { None };
2147 let no_ret_closure = |_: u16| -> Option<u16> { None };
2148 let no_param_origin = |_: usize, _: usize| -> Option<u16> { None };
2149 let no_exact_param = |_: usize, _: usize| false;
2150
2151 let num_globals = program.globals.len();
2154 let no_globals = |_: u16| None;
2155 let no_global_layout = |_: u16| -> Option<FieldLayout> { None };
2156 let no_global_declared = |_: u16| -> Option<BoundaryType> { None };
2160 let no_caps: Vec<Vec<Option<Kind>>> = Vec::new();
2161 let main_p1 = plan_main(
2162 program,
2163 &layout,
2164 &ret_of,
2165 &no_globals,
2166 &no_closure,
2167 &no_ret_layout,
2168 &no_ret_closure,
2169 &no_global_layout,
2170 &no_global_declared,
2171 linked,
2172 )?;
2173 let global_kinds_cell: std::cell::RefCell<Vec<Option<Kind>>> = std::cell::RefCell::new({
2181 let mut gk = vec![None; num_globals];
2182 for (pc, op) in main_p1.ops.iter().enumerate() {
2183 if main_p1.place.clear[pc] || main_p1.place.put_back[pc] {
2187 continue;
2188 }
2189 if let Op::GlobalSet { idx, src } = *op {
2190 if let Some(k) = main_p1.kinds.get(src as usize) {
2191 if k != Kind::Nothing {
2192 gk[idx as usize] = Some(k);
2193 }
2194 }
2195 }
2196 }
2197 for (idx, k) in gk.iter_mut().enumerate() {
2198 let declared = program
2199 .global_types
2200 .get(idx)
2201 .and_then(|t| t.as_ref())
2202 .and_then(kind::boundary_to_kind);
2203 if let Some(d) = declared {
2204 if k.map_or(true, |k| k.wasm_valtype() == d.wasm_valtype()) {
2205 *k = Some(d);
2206 }
2207 }
2208 }
2209 gk
2210 });
2211 let global_of =
2212 |idx: u16| -> Option<Kind> { global_kinds_cell.borrow().get(idx as usize).copied().flatten() };
2213 let global_layouts: Vec<Option<FieldLayout>> = {
2220 let mut gl = vec![None; num_globals];
2221 for op in &main_p1.ops {
2222 if let Op::GlobalSet { idx, src } = *op {
2223 if main_p1.kinds.get(src as usize) == Some(Kind::Struct) {
2224 gl[idx as usize] = global_struct_layout(
2225 &main_p1,
2226 src,
2227 &program.struct_types,
2228 &program.constants,
2229 );
2230 }
2231 }
2232 }
2233 gl
2234 };
2235 let global_layout_of =
2236 |idx: u16| -> Option<FieldLayout> { global_layouts.get(idx as usize).cloned().flatten() };
2237 let global_declared_of = |idx: u16| -> Option<BoundaryType> {
2252 program.global_types.get(idx as usize).cloned().flatten()
2253 };
2254 let global_closures: Vec<Option<u16>> = {
2258 let mut gc = vec![None; num_globals];
2259 for op in &main_p1.ops {
2260 if let Op::GlobalSet { idx, src } = *op {
2261 if let Some(&c) = main_p1.structs.closure_of.get(&src) {
2262 gc[idx as usize] = Some(c);
2263 }
2264 }
2265 }
2266 gc
2267 };
2268 let global_closure_of =
2269 |idx: u16| -> Option<u16> { global_closures.get(idx as usize).copied().flatten() };
2270
2271 let no_shapes: Vec<Vec<Option<ParamShape>>> = Vec::new();
2282 let no_capture_closures: Vec<Vec<Option<u16>>> = Vec::new();
2283 let mut plans: Vec<Option<Plan>> = (0..program.functions.len()).map(|_| None).collect();
2284 for fi in 0..program.functions.len() {
2285 if !layout.is_closure[fi] {
2286 plans[fi] = plan_function(
2295 program,
2296 fi,
2297 &layout,
2298 &ret_of,
2299 &global_of,
2300 &no_closure,
2301 &no_ret_layout,
2302 &no_ret_closure,
2303 &no_global_layout,
2304 &no_global_declared,
2305 &no_param_origin,
2306 &no_exact_param,
2307 &no_caps,
2308 &no_shapes,
2309 &no_capture_closures,
2310 false,
2311 linked,
2312 )
2313 .ok();
2314 }
2315 }
2316 let mut capture_kinds: Vec<Vec<Option<Kind>>> = Vec::new();
2317 let mut capture_shapes: Vec<Vec<Option<ParamShape>>> = Vec::new();
2318 let mut capture_closures: Vec<Vec<Option<u16>>> = Vec::new();
2319 let mut exact_args: Vec<Vec<bool>> = program
2320 .functions
2321 .iter()
2322 .map(|f| vec![false; f.param_count as usize])
2323 .collect();
2324 for _ in 0..(program.functions.len() + 4) {
2325 let (ck, cs, cc) =
2326 extract_capture_kinds(program, &main_p1, &plans, &global_of, &global_closure_of);
2327 capture_kinds = ck;
2328 capture_shapes = cs;
2329 capture_closures = cc;
2330 let cur_results: Vec<Option<Kind>> = plans
2331 .iter()
2332 .map(|p| p.as_ref().and_then(|p| p.result))
2333 .collect();
2334 let cur_layouts: Vec<Option<FieldLayout>> = plans
2335 .iter()
2336 .map(|p| {
2337 p.as_ref().and_then(|p| {
2338 fn_return_struct_layout(p, &program.struct_types, &program.constants)
2339 })
2340 })
2341 .collect();
2342 let cur_ret_closures: Vec<Option<u16>> = plans
2343 .iter()
2344 .map(|p| p.as_ref().and_then(|p| p.return_closure))
2345 .collect();
2346 let closure_ret = |fi: usize| cur_results.get(fi).copied().flatten();
2347 let ret_of_i = |fi: usize| {
2348 cur_results
2349 .get(fi)
2350 .copied()
2351 .flatten()
2352 .or_else(|| declared_result(program, fi))
2353 };
2354 let ret_layout_of = |func: u16| cur_layouts.get(func as usize).cloned().flatten();
2355 let ret_closure_of = |func: u16| cur_ret_closures.get(func as usize).copied().flatten();
2356 let main_iter = plan_main(
2361 program,
2362 &layout,
2363 &ret_of_i,
2364 &global_of,
2365 &closure_ret,
2366 &ret_layout_of,
2367 &ret_closure_of,
2368 &global_layout_of,
2369 &global_declared_of,
2370 linked,
2371 )
2372 .ok();
2373 let mut scan_plans: Vec<&Plan> = vec![main_iter.as_ref().unwrap_or(&main_p1)];
2374 scan_plans.extend(plans.iter().flatten());
2375 let param_origins = compute_param_origins(program, &scan_plans);
2376 let param_origin = |fi: usize, pi: usize| {
2377 param_origins
2378 .get(fi)
2379 .and_then(|v| v.get(pi))
2380 .copied()
2381 .flatten()
2382 };
2383 let mut progress = exact_arguments(program, &scan_plans, &mut exact_args);
2384 let exact_param = |fi: usize, pi: usize| exact_args.get(fi).and_then(|v| v.get(pi)).copied().unwrap_or(false);
2385 for fi in 0..program.functions.len() {
2386 if let Ok(p) = plan_function(
2387 program,
2388 fi,
2389 &layout,
2390 &ret_of_i,
2391 &global_of,
2392 &closure_ret,
2393 &ret_layout_of,
2394 &ret_closure_of,
2395 &global_layout_of,
2396 &global_declared_of,
2397 ¶m_origin,
2398 &exact_param,
2399 &capture_kinds,
2400 &capture_shapes,
2401 &capture_closures,
2402 false,
2403 linked,
2404 ) {
2405 let changed = plans[fi].as_ref().map_or(true, |x| {
2406 x.result != p.result || x.return_closure != p.return_closure
2407 });
2408 if changed {
2409 progress = true;
2410 }
2411 plans[fi] = Some(p);
2412 }
2413 }
2414 if linked {
2417 let regions = main_iter.iter().chain(plans.iter().flatten());
2418 progress |= tower::exact_globals(regions, &mut global_kinds_cell.borrow_mut());
2419 }
2420 if !progress {
2421 break;
2422 }
2423 }
2424 let fns1: Vec<Plan> = plans
2430 .into_iter()
2431 .map(|p| p.unwrap_or_else(Plan::stub))
2432 .collect();
2433
2434 let fn_results_p1: Vec<Option<Kind>> = fns1.iter().map(|p| p.result).collect();
2439 let ret_layouts: Vec<Option<FieldLayout>> = fns1
2440 .iter()
2441 .map(|p| fn_return_struct_layout(p, &program.struct_types, &program.constants))
2442 .collect();
2443 let ret_closures: Vec<Option<u16>> = fns1.iter().map(|p| p.return_closure).collect();
2444 let closure_ret = |fi: usize| -> Option<Kind> { fn_results_p1.get(fi).copied().flatten() };
2445 let ret_of_inferred = |fi: usize| -> Option<Kind> {
2446 fn_results_p1
2447 .get(fi)
2448 .copied()
2449 .flatten()
2450 .or_else(|| declared_result(program, fi))
2451 };
2452 let ret_layout_of =
2453 |func: u16| -> Option<FieldLayout> { ret_layouts.get(func as usize).cloned().flatten() };
2454 let ret_closure_of =
2455 |func: u16| -> Option<u16> { ret_closures.get(func as usize).copied().flatten() };
2456 let mut main = plan_main(
2459 program,
2460 &layout,
2461 &ret_of_inferred,
2462 &global_of,
2463 &closure_ret,
2464 &ret_layout_of,
2465 &ret_closure_of,
2466 &global_layout_of,
2467 &global_declared_of,
2468 linked,
2469 )
2470 .map_err(|e| within_function(e, program, interner, None))?;
2471 let scan_plans: Vec<&Plan> = std::iter::once(&main).chain(fns1.iter()).collect();
2472 let param_origins = compute_param_origins(program, &scan_plans);
2473 let param_origin = |fi: usize, pi: usize| {
2474 param_origins
2475 .get(fi)
2476 .and_then(|v| v.get(pi))
2477 .copied()
2478 .flatten()
2479 };
2480 exact_arguments(program, &scan_plans, &mut exact_args);
2481 let exact_param = |fi: usize, pi: usize| exact_args.get(fi).and_then(|v| v.get(pi)).copied().unwrap_or(false);
2482 let reachable = crate::vm::reach::reach_with(program, &layout, interner, entries).functions;
2487 let mut fns: Vec<Plan> = {
2488 let mut v = Vec::with_capacity(program.functions.len());
2489 for fi in 0..program.functions.len() {
2490 if !reachable[fi] {
2491 if std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some() {
2492 if let Some(f) = program.functions.get(fi) {
2493 eprintln!(
2494 "[wasm] stubbed (unreachable from Main): '{}'",
2495 interner.resolve(f.name)
2496 );
2497 }
2498 }
2499 v.push(Plan::stub());
2500 continue;
2501 }
2502 match plan_function(
2503 program,
2504 fi,
2505 &layout,
2506 &ret_of_inferred,
2507 &global_of,
2508 &closure_ret,
2509 &ret_layout_of,
2510 &ret_closure_of,
2511 &global_layout_of,
2512 &global_declared_of,
2513 ¶m_origin,
2514 &exact_param,
2515 &capture_kinds,
2516 &capture_shapes,
2517 &capture_closures,
2518 true,
2519 linked,
2520 ) {
2521 Ok(p) => v.push(p),
2522 Err(e) => return Err(within_function(e, program, interner, Some(fi))),
2523 }
2524 }
2525 v
2526 };
2527 if tower::decide(program, &mut main, &mut fns, &global_kinds_cell.borrow()) && !linked {
2528 return Err(WasmLowerError::UnsupportedOwned(tower::RATIONAL_LISTS.to_string()));
2529 }
2530 let entry_names = entries.names();
2533 let raw_boundary: Vec<bool> = program
2534 .functions
2535 .iter()
2536 .map(|f| entry_names.iter().any(|n| interner.resolve(f.name) == n))
2537 .collect();
2538 let exact_sig = exact::decide(
2539 program,
2540 &mut main,
2541 &mut fns,
2542 &raw_boundary,
2543 num_globals,
2544 linked,
2545 );
2546 let presence_enabled =
2547 absence::decide(&mut main, &mut fns, &program.constants, num_globals, linked);
2548
2549 let loads_text = |op: &Op| match op {
2558 Op::LoadConst { idx, .. } | Op::FailWith { msg: idx } => {
2559 matches!(
2560 program.constants.get(*idx as usize),
2561 Some(Constant::Text(_))
2562 )
2563 }
2564 Op::CallBuiltin {
2567 builtin: BuiltinId::Fail | BuiltinId::FailReason,
2568 ..
2569 } => true,
2570 Op::CallBuiltin {
2571 builtin: BuiltinId::VfsMount | BuiltinId::VfsWriteFile,
2572 ..
2573 } => true,
2574 _ => false,
2575 };
2576 let concats_text = |p: &Plan, op: &Op| match *op {
2579 Op::Add { dst, .. } | Op::AddAssign { dst, .. } => {
2580 p.kinds.get(dst as usize) == Some(Kind::Text)
2581 }
2582 _ => false,
2583 };
2584 let shown_shapes = {
2586 let plans: Vec<&Plan> = std::iter::once(&main).chain(fns.iter()).collect();
2587 display::ShownTable::new(display::ShownTable::collect(
2588 &plans,
2589 &program.struct_types,
2590 &program.enum_types,
2591 ))
2592 };
2593 let uses_heap = shown_shapes.len() > 0
2594 || std::iter::once(&main).chain(fns.iter()).any(|p| p.tower.holds())
2595 || std::iter::once(&main).chain(fns.iter()).any(|p| {
2596 p.ops
2597 .iter()
2598 .any(|op| op_uses_heap(op) || loads_text(op) || concats_text(p, op))
2599 });
2600 let uses_iter = std::iter::once(&main)
2601 .chain(fns.iter())
2602 .any(|p| p.ops.iter().any(|op| matches!(op, Op::IterPrepare { .. })));
2603 let has_closures = layout.is_closure.iter().any(|&c| c);
2609
2610 let mut used = Vec::new();
2612 tower::note_imports(std::iter::once(&main).chain(fns.iter()), &mut used);
2613 let note = |h: HostFn, used: &mut Vec<HostFn>| {
2614 if !used.contains(&h) {
2615 used.push(h);
2616 }
2617 };
2618 let note_fmt_kind = |k: Option<Kind>, used: &mut Vec<HostFn>| match k {
2622 Some(Kind::Int) => note(HostFn::FmtI64Into, used),
2623 Some(Kind::Float) => note(HostFn::FmtF64Into, used),
2624 Some(Kind::Bool) => note(HostFn::FmtBoolInto, used),
2625 Some(Kind::SeqInt | Kind::SeqAny) => note(HostFn::FmtSeqI64Into, used),
2627 Some(Kind::SeqBool) => note(HostFn::FmtSeqBoolInto, used),
2629 Some(Kind::Set) => note(HostFn::FmtSetI64Into, used),
2630 Some(Kind::BigInt) => note(HostFn::BigintToText, used),
2632 _ => {}
2633 };
2634 let note_operand_fmt = |plan: &Plan, r: u16, used: &mut Vec<HostFn>| {
2636 note_fmt_kind(plan.kinds.get(r as usize), used)
2637 };
2638 for plan in std::iter::once(&main).chain(fns.iter()) {
2639 for (pc, op) in plan.ops.iter().enumerate() {
2640 if linked {
2641 let field_write = match *op {
2642 Op::StructInsert { obj, value, .. } => plan
2643 .structs
2644 .slot
2645 .get(pc)
2646 .copied()
2647 .flatten()
2648 .map(|slot| (obj, slot as usize, value)),
2649 Op::SetIndex {
2650 collection, value, ..
2651 }
2652 | Op::SetIndexUnchecked {
2653 collection, value, ..
2654 } => plan
2655 .place
2656 .field_at
2657 .get(pc)
2658 .copied()
2659 .flatten()
2660 .and_then(|field| record_field_slot(plan, collection, field))
2661 .map(|slot| (collection, slot, value)),
2662 _ => None,
2663 };
2664 if let Some((obj, slot, value)) = field_write {
2665 let rational_field = declared_record_slot_kind(
2666 &plan.structs,
2667 &program.struct_types,
2668 &program.constants,
2669 obj,
2670 slot,
2671 ) == Some(Kind::Rational);
2672 match plan.kinds.get(value as usize) {
2673 Some(Kind::Int) if rational_field => note(HostFn::RationalFromI64, &mut used),
2674 Some(Kind::BigInt) if rational_field => note(HostFn::RationalFromBigint, &mut used),
2675 _ => {}
2676 }
2677 }
2678 if let Op::Call {
2680 func,
2681 args_start,
2682 arg_count,
2683 ..
2684 }
2685 | Op::Spawn {
2686 func,
2687 args_start,
2688 arg_count,
2689 }
2690 | Op::SpawnHandle {
2691 func,
2692 args_start,
2693 arg_count,
2694 ..
2695 } = *op
2696 {
2697 let callee = fns.get(func as usize);
2698 for a in 0..arg_count {
2699 if callee.and_then(|f| f.kinds.get(a as usize)) == Some(Kind::Rational) {
2700 match plan.kinds.get((args_start + a) as usize) {
2701 Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
2702 Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
2703 _ => {}
2704 }
2705 }
2706 }
2707 }
2708 if let Op::Lt { lhs, rhs, .. }
2710 | Op::Gt { lhs, rhs, .. }
2711 | Op::LtEq { lhs, rhs, .. }
2712 | Op::GtEq { lhs, rhs, .. }
2713 | Op::Eq { lhs, rhs, .. }
2714 | Op::NotEq { lhs, rhs, .. } = *op
2715 {
2716 let kind = |r: u16| plan.kinds.get(r as usize);
2717 if (kind(lhs) == Some(Kind::Rational) || kind(rhs) == Some(Kind::Rational))
2718 && (kind(lhs) == Some(Kind::Float) || kind(rhs) == Some(Kind::Float))
2719 {
2720 note(HostFn::RationalCmpF64, &mut used);
2721 } else if kind(lhs) == Some(Kind::Rational) || kind(rhs) == Some(Kind::Rational) {
2722 note(HostFn::RationalCmp, &mut used);
2723 for r in [lhs, rhs] {
2724 match kind(r) {
2725 Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
2726 Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
2727 _ => {}
2728 }
2729 }
2730 }
2731 }
2732 }
2733 match *op {
2734 Op::Show { src } => {
2740 if let Some(elems) = plan.structs.tuple_layouts.get(&src) {
2741 note(HostFn::PrintText, &mut used);
2744 for &e in elems {
2745 note_operand_fmt(plan, e, &mut used);
2746 }
2747 } else if plan.kinds.get(src as usize) == Some(Kind::Enum) {
2748 note(HostFn::PrintText, &mut used);
2752 if let Some(def) = plan
2753 .structs
2754 .ind_type_of
2755 .get(&src)
2756 .and_then(|tn| program.enum_types.iter().find(|e| &e.name == tn))
2757 {
2758 for v in &def.variants {
2759 for ft in &v.field_types {
2760 note_fmt_kind(kind::boundary_to_kind(ft), &mut used);
2761 }
2762 }
2763 }
2764 } else if plan.kinds.get(src as usize) == Some(Kind::Map) {
2765 note(HostFn::PrintText, &mut used);
2768 if let MapShowKinds::Entries(k, v) = map_show_kinds(plan, src) {
2769 note_fmt_kind(k, &mut used);
2770 note_fmt_kind(v, &mut used);
2771 }
2772 } else if plan.kinds.get(src as usize) == Some(Kind::SeqSeqInt) {
2773 note(HostFn::PrintText, &mut used);
2776 note(HostFn::FmtSeqI64Into, &mut used);
2777 } else if plan.kinds.get(src as usize) == Some(Kind::SeqEnum) {
2778 note(HostFn::PrintText, &mut used);
2781 if let Some(def) = plan
2782 .structs
2783 .seq_elem_ind_type
2784 .get(&src)
2785 .and_then(|tn| program.enum_types.iter().find(|e| &e.name == tn))
2786 {
2787 for v in &def.variants {
2788 for ft in &v.field_types {
2789 note_fmt_kind(kind::boundary_to_kind(ft), &mut used);
2790 }
2791 }
2792 }
2793 } else if plan.kinds.get(src as usize) == Some(Kind::Struct) {
2794 note(HostFn::PrintText, &mut used);
2797 if let Some(def) = plan
2798 .structs
2799 .struct_name_of
2800 .get(&src)
2801 .and_then(|tn| program.struct_types.iter().find(|s| &s.name == tn))
2802 {
2803 for (_, bt) in &def.fields {
2804 note_fmt_kind(kind::boundary_to_kind(bt), &mut used);
2805 }
2806 }
2807 } else if plan.kinds.get(src as usize) == Some(Kind::SeqStruct) {
2808 note(HostFn::PrintText, &mut used);
2811 if let Some(def) = plan
2812 .structs
2813 .seq_elem_struct_name
2814 .get(&src)
2815 .and_then(|tn| program.struct_types.iter().find(|s| &s.name == tn))
2816 {
2817 for (_, bt) in &def.fields {
2818 note_fmt_kind(kind::boundary_to_kind(bt), &mut used);
2819 }
2820 }
2821 } else if plan.kinds.get(src as usize) == Some(Kind::Rational) {
2822 if linked {
2826 note(HostFn::RationalToText, &mut used);
2827 note(HostFn::PrintText, &mut used);
2828 } else {
2829 note(HostFn::PrintRational, &mut used);
2830 }
2831 } else if plan.kinds.get(src as usize) == Some(Kind::Optional) {
2832 note(HostFn::PrintNothing, &mut used);
2835 let inner = plan
2836 .structs
2837 .opt_inner
2838 .get(&src)
2839 .copied()
2840 .unwrap_or(Kind::Int);
2841 if let Some(h) = HostFn::for_show(inner) {
2842 note(h, &mut used);
2843 }
2844 } else if matches!(
2845 plan.kinds.get(src as usize),
2846 Some(Kind::Word32) | Some(Kind::Word64)
2847 ) {
2848 note(HostFn::PrintWord, &mut used);
2850 } else if plan.kinds.get(src as usize) == Some(Kind::BigInt) {
2851 note(HostFn::BigintToText, &mut used);
2853 note(HostFn::PrintText, &mut used);
2854 } else if plan.kinds.get(src as usize) == Some(Kind::Complex) {
2855 note(HostFn::ComplexToText, &mut used);
2857 note(HostFn::PrintText, &mut used);
2858 } else if plan.kinds.get(src as usize) == Some(Kind::Modular) {
2859 note(HostFn::ModularToText, &mut used);
2860 note(HostFn::PrintText, &mut used);
2861 } else if plan.kinds.get(src as usize) == Some(Kind::Decimal) {
2862 note(HostFn::DecimalToText, &mut used);
2863 note(HostFn::PrintText, &mut used);
2864 } else if plan.kinds.get(src as usize) == Some(Kind::Money) {
2865 note(HostFn::MoneyToText, &mut used);
2866 note(HostFn::PrintText, &mut used);
2867 } else if plan.kinds.get(src as usize) == Some(Kind::Quantity) {
2868 note(HostFn::QuantityToText, &mut used);
2869 note(HostFn::PrintText, &mut used);
2870 } else if plan.kinds.get(src as usize) == Some(Kind::Uuid) {
2871 note(HostFn::UuidToText, &mut used);
2872 note(HostFn::PrintText, &mut used);
2873 } else if plan.kinds.get(src as usize) == Some(Kind::Dynamic) {
2874 note(HostFn::DynamicToText, &mut used);
2876 note(HostFn::PrintText, &mut used);
2877 } else if let Some(h) = plan.kinds.get(src as usize).and_then(HostFn::for_show)
2878 {
2879 note(h, &mut used);
2880 }
2881 }
2882 Op::CallBuiltin {
2883 builtin: BuiltinId::Pow,
2884 args_start,
2885 ..
2886 } => {
2887 let bk = plan.kinds.get(args_start as usize);
2888 let ek = plan.kinds.get((args_start + 1) as usize);
2889 if let Some(h) = pow_host_for(bk, ek) {
2890 note(h, &mut used);
2891 }
2892 }
2893 Op::Pow { dst, lhs, rhs } if plan.kinds.get(dst as usize) != Some(Kind::Rational) => {
2897 let bk = plan.kinds.get(lhs as usize);
2898 let ek = plan.kinds.get(rhs as usize);
2899 if linked && bk == Some(Kind::Int) && ek == Some(Kind::Int) {
2900 note(HostFn::BigintFromI64, &mut used);
2901 note(HostFn::BigintPow, &mut used);
2902 } else if let Some(h) = pow_host_for(bk, ek) {
2903 note(h, &mut used);
2904 }
2905 }
2906 Op::Mul { dst, lhs, rhs }
2910 | Op::Add { dst, lhs, rhs }
2911 | Op::Sub { dst, lhs, rhs }
2912 | Op::Div { dst, lhs, rhs }
2913 | Op::Mod { dst, lhs, rhs }
2914 if linked && plan.kinds.get(dst as usize) == Some(Kind::BigInt) =>
2915 {
2916 note(
2917 match *op {
2918 Op::Add { .. } => HostFn::BigintAdd,
2919 Op::Sub { .. } => HostFn::BigintSub,
2920 Op::Div { .. } => HostFn::BigintDiv,
2921 Op::Mod { .. } => HostFn::BigintMod,
2922 _ => HostFn::BigintMul,
2923 },
2924 &mut used,
2925 );
2926 if plan.kinds.get(lhs as usize) == Some(Kind::Int)
2927 || plan.kinds.get(rhs as usize) == Some(Kind::Int)
2928 {
2929 note(HostFn::BigintFromI64, &mut used);
2930 }
2931 }
2932 Op::Add { dst, lhs, rhs }
2935 | Op::Sub { dst, lhs, rhs }
2936 | Op::Mul { dst, lhs, rhs }
2937 if linked && plan.kinds.get(dst as usize) == Some(Kind::Complex) =>
2938 {
2939 note(
2940 match *op {
2941 Op::Add { .. } => HostFn::ComplexAdd,
2942 Op::Sub { .. } => HostFn::ComplexSub,
2943 _ => HostFn::ComplexMul,
2944 },
2945 &mut used,
2946 );
2947 if plan.kinds.get(lhs as usize) == Some(Kind::Int)
2948 || plan.kinds.get(rhs as usize) == Some(Kind::Int)
2949 {
2950 note(HostFn::ComplexFromI64, &mut used);
2951 }
2952 }
2953 Op::CallBuiltin {
2956 builtin: BuiltinId::Complex,
2957 args_start,
2958 ..
2959 } if linked => {
2960 if plan.kinds.get(args_start as usize) == Some(Kind::Int)
2961 && plan.kinds.get((args_start + 1) as usize) == Some(Kind::Int)
2962 {
2963 note(HostFn::ComplexFromI64, &mut used);
2964 } else {
2965 note(HostFn::ComplexFromF64, &mut used);
2966 }
2967 }
2968 Op::CallBuiltin {
2970 builtin: BuiltinId::Abs,
2971 args_start,
2972 ..
2973 } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Complex) => {
2974 note(HostFn::ComplexAbs, &mut used);
2975 }
2976 Op::CallBuiltin {
2978 builtin: BuiltinId::RealPart,
2979 args_start,
2980 ..
2981 } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Complex) => {
2982 note(HostFn::ComplexReF64, &mut used);
2983 }
2984 Op::CallBuiltin {
2985 builtin: BuiltinId::ImagPart,
2986 args_start,
2987 ..
2988 } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Complex) => {
2989 note(HostFn::ComplexImF64, &mut used);
2990 }
2991 Op::Add { dst, lhs, rhs }
2992 | Op::Sub { dst, lhs, rhs }
2993 | Op::Mul { dst, lhs, rhs }
2994 if linked && plan.kinds.get(dst as usize) == Some(Kind::Modular) =>
2995 {
2996 note(
2997 match *op {
2998 Op::Add { .. } => HostFn::ModularAdd,
2999 Op::Sub { .. } => HostFn::ModularSub,
3000 _ => HostFn::ModularMul,
3001 },
3002 &mut used,
3003 );
3004 if plan.kinds.get(lhs as usize) == Some(Kind::Int)
3005 || plan.kinds.get(rhs as usize) == Some(Kind::Int)
3006 {
3007 note(HostFn::ModularFromI64, &mut used);
3008 }
3009 }
3010 Op::CallBuiltin {
3011 builtin: BuiltinId::Modular,
3012 ..
3013 } if linked => note(HostFn::ModularFromI64, &mut used),
3014 Op::Div { dst, .. } | Op::ExactDiv { dst, .. }
3016 if linked && plan.kinds.get(dst as usize) == Some(Kind::Modular) =>
3017 {
3018 note(HostFn::ModularDiv, &mut used);
3019 }
3020 Op::Add { dst, lhs, rhs }
3021 | Op::Sub { dst, lhs, rhs }
3022 | Op::Mul { dst, lhs, rhs }
3023 if linked && plan.kinds.get(dst as usize) == Some(Kind::Decimal) =>
3024 {
3025 note(
3026 match *op {
3027 Op::Add { .. } => HostFn::DecimalAdd,
3028 Op::Sub { .. } => HostFn::DecimalSub,
3029 _ => HostFn::DecimalMul,
3030 },
3031 &mut used,
3032 );
3033 if plan.kinds.get(lhs as usize) == Some(Kind::Int)
3034 || plan.kinds.get(rhs as usize) == Some(Kind::Int)
3035 {
3036 note(HostFn::DecimalFromI64, &mut used);
3037 }
3038 }
3039 Op::CallBuiltin {
3040 builtin: BuiltinId::Decimal,
3041 ..
3042 } if linked => note(HostFn::DecimalFromText, &mut used),
3043 Op::Add { dst, lhs, rhs } | Op::Sub { dst, lhs, rhs }
3044 if linked && plan.kinds.get(dst as usize) == Some(Kind::Money) =>
3045 {
3046 let _ = (lhs, rhs);
3047 note(
3048 match *op {
3049 Op::Add { .. } => HostFn::MoneyAdd,
3050 _ => HostFn::MoneySub,
3051 },
3052 &mut used,
3053 );
3054 }
3055 Op::CallBuiltin {
3056 builtin: BuiltinId::Money,
3057 ..
3058 } if linked => {
3059 note(HostFn::MoneyFromDecimal, &mut used);
3060 note(HostFn::MoneyFromI64, &mut used);
3061 }
3062 Op::Add { dst, lhs, rhs }
3063 | Op::Sub { dst, lhs, rhs }
3064 | Op::Mul { dst, lhs, rhs }
3065 | Op::Div { dst, lhs, rhs }
3066 if linked && plan.kinds.get(dst as usize) == Some(Kind::Quantity) =>
3067 {
3068 let _ = (lhs, rhs);
3069 note(
3070 match *op {
3071 Op::Add { .. } => HostFn::QuantityAdd,
3072 Op::Sub { .. } => HostFn::QuantitySub,
3073 Op::Mul { .. } => HostFn::QuantityMul,
3074 _ => HostFn::QuantityDiv,
3075 },
3076 &mut used,
3077 );
3078 }
3079 Op::CallBuiltin {
3080 builtin: BuiltinId::Quantity,
3081 ..
3082 } if linked => note(HostFn::QuantityOfI64, &mut used),
3083 Op::CallBuiltin {
3084 builtin: BuiltinId::Convert,
3085 ..
3086 } if linked => note(HostFn::QuantityConvert, &mut used),
3087 Op::Add { dst, lhs, rhs }
3091 | Op::Sub { dst, lhs, rhs }
3092 | Op::Mul { dst, lhs, rhs }
3093 | Op::Div { dst, lhs, rhs }
3094 if linked && plan.kinds.get(dst as usize) == Some(Kind::Rational) =>
3095 {
3096 note(
3097 match *op {
3098 Op::Add { .. } => HostFn::RationalAdd,
3099 Op::Sub { .. } => HostFn::RationalSub,
3100 Op::Mul { .. } => HostFn::RationalMul,
3101 _ => HostFn::RationalQuotient,
3102 },
3103 &mut used,
3104 );
3105 for r in [lhs, rhs] {
3106 match plan.kinds.get(r as usize) {
3107 Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3108 Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3109 _ => {}
3110 }
3111 }
3112 }
3113 Op::Mod { dst, lhs, rhs } | Op::FloorDiv { dst, lhs, rhs } | Op::Pow { dst, lhs, rhs }
3116 if linked && plan.kinds.get(dst as usize) == Some(Kind::Rational) =>
3117 {
3118 note(
3119 match *op {
3120 Op::Mod { .. } => HostFn::RationalRemainder,
3121 Op::FloorDiv { .. } => HostFn::RationalFloorQuotient,
3122 _ => HostFn::RationalPower,
3123 },
3124 &mut used,
3125 );
3126 for r in [lhs, rhs] {
3127 match plan.kinds.get(r as usize) {
3128 Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3129 Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3130 _ => {}
3131 }
3132 }
3133 }
3134 Op::BitXor { lhs, rhs, .. } | Op::BitAnd { lhs, rhs, .. } | Op::BitOr { lhs, rhs, .. }
3136 if linked
3137 && (plan.kinds.get(lhs as usize) == Some(Kind::Rational)
3138 || plan.kinds.get(rhs as usize) == Some(Kind::Rational)) =>
3139 {
3140 note(HostFn::RationalBitwise, &mut used);
3141 for r in [lhs, rhs] {
3142 match plan.kinds.get(r as usize) {
3143 Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3144 Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3145 _ => {}
3146 }
3147 }
3148 }
3149 Op::Add { dst, lhs, rhs }
3151 | Op::Sub { dst, lhs, rhs }
3152 | Op::Mul { dst, lhs, rhs }
3153 | Op::Div { dst, lhs, rhs }
3154 if linked
3155 && plan.kinds.get(dst as usize) == Some(Kind::Float)
3156 && (plan.kinds.get(lhs as usize) == Some(Kind::Rational)
3157 || plan.kinds.get(rhs as usize) == Some(Kind::Rational)) =>
3158 {
3159 note(HostFn::RationalToF64, &mut used);
3160 }
3161 Op::ExactDiv { lhs, rhs, .. } if linked => {
3164 note(HostFn::RationalDiv, &mut used);
3165 for r in [lhs, rhs] {
3166 match plan.kinds.get(r as usize) {
3167 Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3168 Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3169 _ => {}
3170 }
3171 }
3172 }
3173 Op::CallBuiltin {
3175 builtin:
3176 b @ (BuiltinId::Floor | BuiltinId::Ceil | BuiltinId::Round | BuiltinId::Abs),
3177 args_start,
3178 ..
3179 } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Rational) => {
3180 note(
3181 match b {
3182 BuiltinId::Floor => HostFn::RationalFloor,
3183 BuiltinId::Ceil => HostFn::RationalCeil,
3184 BuiltinId::Round => HostFn::RationalRound,
3185 _ => HostFn::RationalAbs,
3186 },
3187 &mut used,
3188 );
3189 }
3190 Op::CallBuiltin {
3192 builtin:
3193 b @ (BuiltinId::Uuid
3194 | BuiltinId::UuidNil
3195 | BuiltinId::UuidMax
3196 | BuiltinId::UuidDns
3197 | BuiltinId::UuidUrl
3198 | BuiltinId::UuidOid
3199 | BuiltinId::UuidX500
3200 | BuiltinId::UuidVersion),
3201 ..
3202 } if linked => {
3203 note(
3204 match b {
3205 BuiltinId::Uuid => HostFn::UuidParse,
3206 BuiltinId::UuidNil => HostFn::UuidNil,
3207 BuiltinId::UuidMax => HostFn::UuidMax,
3208 BuiltinId::UuidDns => HostFn::UuidDns,
3209 BuiltinId::UuidUrl => HostFn::UuidUrl,
3210 BuiltinId::UuidOid => HostFn::UuidOid,
3211 BuiltinId::UuidX500 => HostFn::UuidX500,
3212 _ => HostFn::UuidVersion,
3213 },
3214 &mut used,
3215 );
3216 }
3217 Op::CallBuiltin {
3219 builtin: BuiltinId::UuidFromBytes,
3220 ..
3221 } if linked => note(HostFn::UuidFromPtr, &mut used),
3222 Op::CallBuiltin {
3224 builtin:
3225 b @ (BuiltinId::Sha1Rnds4
3226 | BuiltinId::Sha1Msg1
3227 | BuiltinId::Sha1Msg2
3228 | BuiltinId::Sha1Nexte),
3229 ..
3230 } if linked => {
3231 note(
3232 match b {
3233 BuiltinId::Sha1Rnds4 => HostFn::Sha1Rnds4,
3234 BuiltinId::Sha1Msg1 => HostFn::Sha1Msg1,
3235 BuiltinId::Sha1Msg2 => HostFn::Sha1Msg2,
3236 _ => HostFn::Sha1Nexte,
3237 },
3238 &mut used,
3239 );
3240 }
3241 Op::Add { lhs, .. }
3243 if linked && plan.kinds.get(lhs as usize) == Some(Kind::Lanes) =>
3244 {
3245 note(HostFn::Lanes4Add, &mut used)
3246 }
3247 Op::AddAssign { dst, .. }
3248 if linked && plan.kinds.get(dst as usize) == Some(Kind::Lanes) =>
3249 {
3250 note(HostFn::Lanes4Add, &mut used)
3251 }
3252 Op::BitXor { lhs, .. }
3254 if linked && plan.kinds.get(lhs as usize) == Some(Kind::Lanes) =>
3255 {
3256 note(HostFn::Lanes4Xor, &mut used)
3257 }
3258 Op::Add { lhs, rhs, .. } | Op::Sub { lhs, rhs, .. }
3260 if linked
3261 && (plan.kinds.get(lhs as usize) == Some(Kind::Span)
3262 || plan.kinds.get(rhs as usize) == Some(Kind::Span)) =>
3263 {
3264 let base = if plan.kinds.get(lhs as usize) == Some(Kind::Span) {
3265 rhs
3266 } else {
3267 lhs
3268 };
3269 note(
3270 if plan.kinds.get(base as usize) == Some(Kind::Date) {
3271 HostFn::DateAddSpan
3272 } else {
3273 HostFn::MomentAddSpan
3274 },
3275 &mut used,
3276 );
3277 }
3278 Op::Eq { lhs, rhs, .. } | Op::NotEq { lhs, rhs, .. }
3280 if linked
3281 && plan.kinds.get(lhs as usize) == Some(Kind::Uuid)
3282 && plan.kinds.get(rhs as usize) == Some(Kind::Uuid) =>
3283 {
3284 note(HostFn::UuidEq, &mut used);
3285 }
3286 Op::LoadToday { .. } => note(HostFn::Today, &mut used),
3287 Op::LoadNow { .. } => note(HostFn::Now, &mut used),
3288 Op::CallBuiltin {
3289 builtin: BuiltinId::RandomInt,
3290 ..
3291 } => note(HostFn::RandomInt, &mut used),
3292 Op::CallBuiltin {
3293 builtin: BuiltinId::EnvHas,
3294 ..
3295 } => note(HostFn::EnvLen, &mut used),
3296 Op::CallBuiltin {
3297 builtin: BuiltinId::EnvValue,
3298 ..
3299 } => {
3300 note(HostFn::EnvLen, &mut used);
3301 note(HostFn::EnvInto, &mut used);
3302 }
3303 Op::CallBuiltin {
3304 builtin: BuiltinId::TimeNow,
3305 ..
3306 } => note(HostFn::TimeNow, &mut used),
3307 Op::Args { .. } => note(HostFn::Args, &mut used),
3308 Op::FailWith { .. } => note(HostFn::LogosRtFail, &mut used),
3312 Op::CallBuiltin {
3315 builtin: BuiltinId::Fail | BuiltinId::FailReason,
3316 args_start,
3317 ..
3318 } => {
3319 note(HostFn::LogosRtFail, &mut used);
3320 note_operand_fmt(plan, args_start, &mut used);
3321 }
3322 Op::CallBuiltin {
3325 builtin: BuiltinId::VfsMount | BuiltinId::VfsWriteFile,
3326 ..
3327 } => note(HostFn::LogosRtFail, &mut used),
3328 Op::Div { .. }
3332 | Op::Mod { .. }
3333 | Op::Index { .. }
3334 | Op::IndexUnchecked { .. }
3335 | Op::SetIndex { .. }
3336 | Op::SetIndexUnchecked { .. } => note(HostFn::LogosRtFailAt, &mut used),
3337 Op::CallBuiltin {
3338 builtin: BuiltinId::ParseInt,
3339 ..
3340 } => note(HostFn::ParseInt, &mut used),
3341 Op::CallBuiltin {
3342 builtin: BuiltinId::Contains,
3343 ..
3344 } => note(HostFn::TextContains, &mut used),
3345 Op::CallBuiltin {
3346 builtin: BuiltinId::DomSetAttribute,
3347 args_start,
3348 ..
3349 } => {
3350 if plan.kinds.get(args_start as usize + 2) == Some(Kind::Bool) {
3351 note(HostFn::DomSetBoolAttribute, &mut used)
3352 } else {
3353 note(HostFn::DomSetAttribute, &mut used)
3354 }
3355 }
3356 Op::CallBuiltin { builtin, .. } if dom_import_of(builtin).is_some() => note(
3357 dom_import_of(builtin).expect("guarded by the arm"),
3358 &mut used,
3359 ),
3360 Op::CallBuiltin {
3361 builtin: BuiltinId::ParseFloat,
3362 ..
3363 } => note(HostFn::ParseFloat, &mut used),
3364 Op::CallBuiltin {
3365 builtin: BuiltinId::ReadReals,
3366 ..
3367 } => note(HostFn::ReadReals, &mut used),
3368 Op::CallBuiltin {
3369 builtin: BuiltinId::ParseTimestamp,
3370 ..
3371 } => note(HostFn::ParseTimestamp, &mut used),
3372 Op::CallBuiltin {
3374 builtin: BuiltinId::WriteWireResidual,
3375 ..
3376 } => note(HostFn::WriteWireResidual, &mut used),
3377 Op::CallBuiltin {
3380 builtin: BuiltinId::FormatTimestamp,
3381 ..
3382 } if linked => note(HostFn::FormatTimestampRt, &mut used),
3383 Op::CallBuiltin {
3384 builtin: BuiltinId::MonthsBetween,
3385 ..
3386 } if linked => note(HostFn::MonthsBetweenRt, &mut used),
3387 Op::CallBuiltin {
3388 builtin: BuiltinId::YearsBetween,
3389 ..
3390 } if linked => note(HostFn::YearsBetweenRt, &mut used),
3391 Op::CallBuiltin {
3392 builtin: BuiltinId::MakeDate,
3393 ..
3394 } if linked => note(HostFn::MakeDateRt, &mut used),
3395 Op::CallBuiltin {
3396 builtin: BuiltinId::MakeMoment,
3397 ..
3398 } if linked => note(HostFn::MakeMomentRt, &mut used),
3399 Op::CallBuiltin {
3401 builtin: BuiltinId::InZone,
3402 ..
3403 } if linked => note(HostFn::InZoneRt, &mut used),
3404 Op::CallBuiltin {
3405 builtin: BuiltinId::LocalInstant,
3406 ..
3407 } if linked => note(HostFn::LocalInstantRt, &mut used),
3408 Op::CallBuiltin { builtin: b, .. } if linked && lanes_v_host_fn(b).is_some() => {
3411 note(lanes_v_host_fn(b).unwrap(), &mut used)
3412 }
3413 Op::CallBuiltin {
3418 builtin: BuiltinId::ToCurrency,
3419 ..
3420 } if linked => note(HostFn::MoneyToCurrency, &mut used),
3421 Op::CallBuiltin {
3422 builtin: BuiltinId::SetRate,
3423 args_start,
3424 ..
3425 } if linked => {
3426 note(HostFn::MoneySetRate, &mut used);
3427 match plan.kinds.get((args_start + 1) as usize) {
3428 Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3429 Some(Kind::Decimal) => note(HostFn::DecimalToRational, &mut used),
3430 _ => {}
3431 }
3432 }
3433 Op::CallBuiltin {
3434 builtin: BuiltinId::SetRates,
3435 ..
3436 } if linked => {
3437 note(HostFn::MoneySetRatesInt, &mut used);
3438 note(HostFn::MoneySetRatesRational, &mut used);
3439 note(HostFn::MoneySetRatesDecimal, &mut used);
3440 }
3441 Op::CallBuiltin {
3443 builtin: BuiltinId::WireBytes,
3444 args_start,
3445 ..
3446 } if linked => {
3447 if let Some(h) = wire_bytes_host_fn(plan.kinds.get(args_start as usize)) {
3448 note(h, &mut used);
3449 }
3450 }
3451 Op::CallBuiltin {
3454 builtin: BuiltinId::ReadWireProgram,
3455 ..
3456 } if linked => {
3457 note(HostFn::ReadWireFrame, &mut used);
3458 note(HostFn::ReadWireProgramRt, &mut used);
3459 note(HostFn::RtAlloc, &mut used);
3463 }
3464 Op::CallBuiltin {
3465 builtin: BuiltinId::RunAccepted,
3466 ..
3467 } if linked => note(HostFn::RunAccepted, &mut used),
3468 Op::CallBuiltin {
3469 builtin:
3470 BuiltinId::YearOf
3471 | BuiltinId::MonthOf
3472 | BuiltinId::DayOf
3473 | BuiltinId::WeekdayOf
3474 | BuiltinId::HourOf
3475 | BuiltinId::MinuteOf
3476 | BuiltinId::SecondOf
3477 | BuiltinId::WeekOf
3478 | BuiltinId::QuarterOf,
3479 args_start,
3480 ..
3481 } => {
3482 if plan.kinds.get(args_start as usize) == Some(Kind::Date) {
3485 note(HostFn::TemporalComponentDate, &mut used);
3486 } else {
3487 note(HostFn::TemporalComponent, &mut used);
3488 }
3489 }
3490 Op::CallBuiltin {
3492 builtin: BuiltinId::Format,
3493 args_start,
3494 arg_count,
3495 ..
3496 } if arg_count > 0 => {
3497 note_operand_fmt(plan, args_start, &mut used);
3498 }
3499 Op::Concat { lhs, rhs, .. } => {
3502 note_operand_fmt(plan, lhs, &mut used);
3503 note_operand_fmt(plan, rhs, &mut used);
3504 }
3505 Op::Add { dst, lhs, rhs } if plan.kinds.get(dst as usize) == Some(Kind::Text) => {
3506 note_operand_fmt(plan, lhs, &mut used);
3507 note_operand_fmt(plan, rhs, &mut used);
3508 }
3509 Op::AddAssign { dst, src } if plan.kinds.get(dst as usize) == Some(Kind::Text) => {
3510 note_operand_fmt(plan, dst, &mut used);
3511 note_operand_fmt(plan, src, &mut used);
3512 }
3513 Op::FormatValue { src, spec, .. } => {
3519 let spec_s = match spec {
3520 u32::MAX => None,
3521 idx => match program.constants.get(idx as usize) {
3522 Some(Constant::Text(s)) => Some(s.as_str()),
3523 _ => None,
3524 },
3525 };
3526 match spec_s {
3527 Some(s) if s.starts_with('.') => note(HostFn::FmtF64PrecInto, &mut used),
3528 Some(_) => {
3529 note(HostFn::FmtAlignInto, &mut used);
3530 note_fmt_kind(plan.kinds.get(src as usize), &mut used);
3531 }
3532 None => note_fmt_kind(plan.kinds.get(src as usize), &mut used),
3533 }
3534 }
3535 Op::Obs { .. } => note(HostFn::Obs, &mut used),
3538 _ => {}
3539 }
3540 }
3541 }
3542 for k in shown_shapes.leaf_kinds(&program.struct_types, &program.enum_types) {
3548 note_fmt_kind(Some(k), &mut used);
3549 }
3550 {
3551 let plans: Vec<&Plan> = std::iter::once(&main).chain(fns.iter()).collect();
3552 exact::note_imports(&plans, &mut |h| note(h, &mut used));
3553 if presence_enabled {
3554 note(HostFn::PrintNothing, &mut used);
3555 }
3556 if exact_sig.sequence_ints() {
3557 note(HostFn::ExactText, &mut used);
3558 note(HostFn::PrintText, &mut used);
3559 }
3560 }
3561 let host_entered: Vec<usize> = program
3562 .functions
3563 .iter()
3564 .enumerate()
3565 .filter(|(_, f)| entry_names.iter().any(|n| interner.resolve(f.name) == n))
3566 .map(|(at, _)| at)
3567 .collect();
3568 let takes_host_text = used.iter().any(|h| h.returns_host_text())
3569 || host_entered.iter().any(|&at| {
3570 let plan = &fns[at];
3571 (0..plan.num_params as usize).any(|r| plan.kinds.get(r) == Some(Kind::Text))
3572 });
3573 let takes_host_seq = used.iter().any(|h| h.returns_host_seq());
3575 let uses_heap = uses_heap || takes_host_text || takes_host_seq;
3576 if linked && (uses_heap || uses_iter) {
3579 note(HostFn::RtAlloc, &mut used);
3580 }
3581 if uses_heap && !linked {
3585 note(HostFn::LogosRtFailAt, &mut used);
3586 }
3587 let imports: Vec<HostFn> = HOST_FNS
3589 .iter()
3590 .copied()
3591 .filter(|h| used.contains(h))
3592 .collect();
3593 let host_index =
3594 |h: HostFn| -> Option<u32> { imports.iter().position(|x| *x == h).map(|i| i as u32) };
3595 let num_imports = imports.len() as u32;
3596 let main_index = num_imports;
3597 let fn_base = num_imports + 1; let mut types = TypeTable::default();
3601 let host_type: Vec<u32> = imports
3602 .iter()
3603 .map(|h| types.intern(h.params(), h.results()))
3604 .collect();
3605 let main_type = types.intern(vec![], result_valtypes(main.result));
3606 let mut fn_types: Vec<u32> = Vec::with_capacity(fns.len());
3607 let fn_stubbed: Vec<bool> = fns.iter().map(|p| p.stub).collect();
3608 let mut fn_param_valtypes: Vec<Vec<u8>> = Vec::with_capacity(fns.len());
3609 let mut fn_param_kinds: Vec<Vec<Option<Kind>>> = Vec::with_capacity(fns.len());
3610 for p in &fns {
3611 let params: Vec<u8> = (0..p.num_params)
3612 .map(|r| p.kinds.valtype(r as usize))
3613 .collect();
3614 fn_types.push(types.intern(params.clone(), plan_results(p)));
3615 fn_param_valtypes.push(params);
3616 fn_param_kinds.push((0..p.num_params).map(|r| p.kinds.get(r as usize)).collect());
3617 }
3618 let emit_trampoline = has_closures && !linked;
3623 let trampoline_type = emit_trampoline.then(|| types.intern(vec![I32, I64], vec![I64]));
3624 let emit_definer = linked && std::iter::once(&main).chain(fns.iter()).any(tower::defines_reals);
3627 let definer_type = emit_definer.then(|| types.intern(vec![I32, I64], vec![I32]));
3628 let mut shown_shapes = shown_shapes;
3630 shown_shapes.place(fn_base + fns.len() as u32 + u32::from(emit_trampoline));
3631 let shown_type = (shown_shapes.len() > 0).then(|| types.intern(vec![I32], vec![I32]));
3632 let emit_heap_fns = uses_heap && !linked;
3635 let interactive = emit_heap_fns
3639 && (imports.iter().any(|h| h.registers_callback()) || !host_entered.is_empty());
3640 let runtime = emit_heap_fns.then(|| {
3643 Runtime::layout(
3644 num_imports + 1 + fns.len() as u32 + u32::from(emit_trampoline) + shown_shapes.len(),
3645 interactive,
3646 takes_host_text,
3647 takes_host_seq,
3648 uses_iter,
3649 exact::on(&main),
3650 reclaim,
3651 &mut types,
3652 )
3653 });
3654
3655 let heap_global = num_globals as u32; let iter_global = heap_global + u32::from(uses_heap); let retain_global = iter_global + u32::from(uses_iter);
3662 let retain_base = (emit_heap_fns && reclaim != Reclaim::Off).then_some(retain_global);
3663 let uses_counters = std::iter::once(&main).chain(fns.iter()).any(|p| {
3664 p.ops
3665 .iter()
3666 .any(|op| matches!(op, Op::NewCrdt { kind: 4 | 5, .. }))
3667 });
3668 let replica_global =
3669 uses_counters.then_some(retain_global + 3 * u32::from(retain_base.is_some()));
3670 let callback_base = (retain_base.is_some() && has_closures)
3672 .then_some(retain_global + 3 * u32::from(retain_base.is_some()) + u32::from(uses_counters));
3673 let fn_results: Vec<Option<Kind>> = fns.iter().map(|p| p.result).collect();
3674 let fn_inout: Vec<Vec<u16>> = fns.iter().map(|p| p.inout.clone()).collect();
3675 let rt_alloc = if linked && uses_heap {
3679 host_index(HostFn::RtAlloc)
3680 } else {
3681 None
3682 };
3683 let global_kinds: Vec<Option<Kind>> = global_kinds_cell.borrow().clone();
3684 let global_valtypes: Vec<u8> = global_kinds
3685 .iter()
3686 .map(|gk| gk.map(Kind::wasm_valtype).unwrap_or(I64))
3687 .collect();
3688 let text_pool_cell = std::cell::RefCell::new(TextPool::default());
3689 let text_pool = (!linked).then_some(&text_pool_cell);
3690 let shared_maps = std::iter::once(&main).chain(fns.iter()).any(|p| {
3691 p.ops
3692 .iter()
3693 .any(|op| matches!(op, Op::NewCrdt { kind: 6, .. }))
3694 });
3695 let absence_base = presence_enabled.then_some(
3696 num_globals as u32
3697 + u32::from(uses_heap)
3698 + u32::from(uses_iter)
3699 + 3 * u32::from(retain_base.is_some())
3700 + u32::from(uses_counters)
3701 + 2 * u32::from(callback_base.is_some()),
3702 );
3703 let may_safepoint = may_safepoint(&fns);
3704 let ctx = Ctx {
3705 absence_base,
3706 constants: &program.constants,
3707 global_valtypes: &global_valtypes,
3708 global_kinds: &global_kinds,
3709 runtime: runtime.as_ref(),
3710 shared_maps,
3711 text_pool,
3712 host_index: &host_index,
3713 fn_base,
3714 heap_global,
3715 iter_global,
3716 replica_global,
3717 uses_iter,
3718 fn_type: &fn_types,
3719 fn_param_valtypes: &fn_param_valtypes,
3720 fn_param_kinds: &fn_param_kinds,
3721 fn_stubbed: &fn_stubbed,
3722 fn_results: &fn_results,
3723 fn_inout: &fn_inout,
3724 functions: &program.functions,
3725 capture_kinds: &capture_kinds,
3726 enum_types: &program.enum_types,
3727 struct_types: &program.struct_types,
3728 policies,
3729 interner,
3730 linked,
3731 rt_alloc,
3732 retain_base,
3733 shown: &shown_shapes,
3734 exact: &exact_sig,
3735 hot: std::cell::Cell::new(false),
3736 batch_reclaim: !interactive && retain_base.is_some(),
3737 may_safepoint: &may_safepoint,
3738 };
3739 let main_body =
3740 emit_body(&main, &ctx).map_err(|e| within_function(e, program, interner, None))?;
3741 let mut fn_bodies = Vec::with_capacity(fns.len());
3742 for (fi, p) in fns.iter().enumerate() {
3743 fn_bodies
3744 .push(emit_body(p, &ctx).map_err(|e| within_function(e, program, interner, Some(fi)))?);
3745 }
3746 let mut shown_bodies = Vec::with_capacity(shown_shapes.len() as usize);
3747 for shape in shown_shapes.shapes() {
3748 shown_bodies.push(display::emit_display_fn(shape, &ctx)?);
3749 }
3750 let trampoline_body = emit_trampoline
3752 .then(|| emit_closure_trampoline(&fns, program, &fn_types, &ctx, callback_base))
3753 .transpose()?;
3754 let trampoline_index = fn_base + fns.len() as u32;
3755 let definer_body = emit_definer.then(|| tower::emit_defining_reader(&fns, &ctx)).transpose()?;
3756
3757 let mut module = vec![0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00];
3759 section(&mut module, 1, &types.encode());
3760
3761 let mut imp = Vec::new();
3766 leb_u32(&mut imp, imports.len() as u32 + u32::from(linked));
3767 for (i, h) in imports.iter().enumerate() {
3768 encode_name(&mut imp, "env");
3769 encode_name(&mut imp, h.field());
3770 imp.push(0x00); leb_u32(&mut imp, host_type[i]);
3772 }
3773 if linked {
3774 encode_name(&mut imp, "env");
3775 encode_name(&mut imp, "__linear_memory");
3776 imp.push(0x02); imp.push(0x00); leb_u32(&mut imp, 0); }
3780 section(&mut module, 2, &imp);
3781
3782 let runtime_count = runtime.as_ref().map_or(0, |r| r.fns.len() as u32);
3785 let mut func = Vec::new();
3786 leb_u32(
3787 &mut func,
3788 1 + fns.len() as u32
3789 + u32::from(emit_trampoline)
3790 + shown_shapes.len()
3791 + runtime_count
3792 + u32::from(emit_definer),
3793 );
3794 leb_u32(&mut func, main_type);
3795 for t in &fn_types {
3796 leb_u32(&mut func, *t);
3797 }
3798 if let Some(tt) = trampoline_type {
3799 leb_u32(&mut func, tt);
3800 }
3801 if let Some(st) = shown_type {
3802 for _ in 0..shown_shapes.len() {
3803 leb_u32(&mut func, st);
3804 }
3805 }
3806 if let Some(r) = &runtime {
3807 for t in &r.types {
3808 leb_u32(&mut func, *t);
3809 }
3810 }
3811 if let Some(dt) = definer_type {
3812 leb_u32(&mut func, dt);
3813 }
3814 section(&mut module, 3, &func);
3815
3816 if has_closures && !linked {
3820 let mut table = Vec::new();
3821 leb_u32(&mut table, 1); table.push(0x70); table.push(0x00); leb_u32(&mut table, fns.len() as u32); section(&mut module, 4, &table);
3826 }
3827
3828 if uses_heap && !linked {
3836 let mut mem = Vec::new();
3837 leb_u32(&mut mem, 1); mem.push(0x00); leb_u32(&mut mem, HEAP_PAGES); section(&mut module, 5, &mem);
3841 }
3842
3843 let heap_base = HEAP_START + text_pool_cell.borrow().image.len() as i32;
3846
3847 if num_globals > 0 || uses_heap || uses_iter || retain_base.is_some() || uses_counters {
3850 let mut glob = Vec::new();
3851 leb_u32(
3852 &mut glob,
3853 num_globals as u32
3854 + u32::from(uses_heap)
3855 + u32::from(uses_iter)
3856 + 3 * u32::from(retain_base.is_some())
3857 + u32::from(uses_counters)
3858 + 2 * u32::from(callback_base.is_some())
3859 + if presence_enabled {
3860 num_globals as u32
3861 } else {
3862 0
3863 },
3864 );
3865 for gk in &global_kinds {
3866 let vt = gk.map(Kind::wasm_valtype).unwrap_or(I64);
3867 glob.push(vt);
3868 glob.push(0x01); if vt == F64 {
3873 glob.push(0x44); glob.extend_from_slice(&0f64.to_le_bytes());
3875 } else if vt == I32 {
3876 i32_const(&mut glob, 0);
3877 } else {
3878 glob.push(0x42); leb_i64(&mut glob, 0);
3880 }
3881 glob.push(0x0B); }
3883 if uses_heap {
3884 glob.push(I32);
3888 glob.push(0x01); i32_const(&mut glob, if linked { 0 } else { heap_base });
3890 glob.push(0x0B);
3891 }
3892 if uses_iter {
3893 glob.push(I32);
3896 glob.push(0x01); i32_const(&mut glob, 0);
3898 glob.push(0x0B);
3899 }
3900 if retain_base.is_some() {
3901 for _ in 0..3 {
3904 glob.push(I32);
3905 glob.push(0x01); i32_const(&mut glob, 0);
3907 glob.push(0x0B);
3908 }
3909 }
3910 if uses_counters {
3911 glob.push(I64);
3912 glob.push(0x01);
3913 i64c(&mut glob, 0);
3914 glob.push(0x0B);
3915 }
3916 if callback_base.is_some() {
3917 for _ in 0..2 {
3918 glob.push(I32);
3919 glob.push(0x01);
3920 i32_const(&mut glob, 0);
3921 glob.push(0x0B);
3922 }
3923 }
3924 if presence_enabled {
3925 for _ in 0..num_globals {
3926 glob.extend([I32, 0x01]);
3927 i32_const(&mut glob, 1);
3928 glob.push(0x0b);
3929 }
3930 }
3931 section(&mut module, 6, &glob);
3932 }
3933
3934 let export_memory = uses_heap && !linked;
3937 let render_index = program
3942 .functions
3943 .iter()
3944 .position(|f| interner.resolve(f.name) == "render")
3945 .map(|p| fn_base + p as u32);
3946 let host_entries: Vec<(String, u32)> = entries
3952 .names()
3953 .into_iter()
3954 .filter_map(|name| {
3955 let at = program
3956 .functions
3957 .iter()
3958 .position(|f| interner.resolve(f.name) == name)?;
3959 Some((name, fn_base + at as u32))
3960 })
3961 .collect();
3962 const EXPORT_FUNC: u8 = 0x00;
3963 const EXPORT_MEMORY: u8 = 0x02;
3964 const EXPORT_GLOBAL: u8 = 0x03;
3965 let mut exports: Vec<(&str, u8, u32)> = vec![("main", EXPORT_FUNC, main_index)];
3966 if export_memory {
3967 exports.push(("memory", EXPORT_MEMORY, 0));
3968 }
3969 if emit_trampoline {
3970 exports.push(("__logos_call_closure", EXPORT_FUNC, trampoline_index));
3971 }
3972 if let Some(ri) = render_index {
3973 exports.push(("__logos_render", EXPORT_FUNC, ri));
3974 }
3975 for (name, index) in &host_entries {
3976 exports.push((name.as_str(), EXPORT_FUNC, *index));
3977 }
3978 if uses_heap && !linked {
3979 exports.push(("__heap_ptr", EXPORT_GLOBAL, heap_global));
3980 }
3981 if let Some(r) = &runtime {
3982 for (i, f) in r.fns.iter().enumerate() {
3983 if let Some(name) = f.export() {
3984 exports.push((name, EXPORT_FUNC, r.first + i as u32));
3985 }
3986 }
3987 }
3988 if emit_definer {
3989 let definer_index =
3990 fn_base + fns.len() as u32 + u32::from(emit_trampoline) + shown_shapes.len() + runtime_count;
3991 exports.push((tower::DEFINER_SYMBOL, EXPORT_FUNC, definer_index));
3992 }
3993 let mut export = Vec::new();
3994 leb_u32(&mut export, exports.len() as u32);
3995 for (name, kind, index) in &exports {
3996 encode_name(&mut export, name);
3997 export.push(*kind);
3998 leb_u32(&mut export, *index);
3999 }
4000 section(&mut module, 7, &export);
4001
4002 if has_closures && !linked {
4006 let mut elem = Vec::new();
4007 leb_u32(&mut elem, 1); leb_u32(&mut elem, 0); elem.push(0x41); leb_i32(&mut elem, 0);
4011 elem.push(0x0B); leb_u32(&mut elem, fns.len() as u32);
4013 for i in 0..fns.len() as u32 {
4014 leb_u32(&mut elem, fn_base + i);
4015 }
4016 section(&mut module, 9, &elem);
4017 }
4018
4019 let mut code = Vec::new();
4022 leb_u32(
4023 &mut code,
4024 1 + fn_bodies.len() as u32
4025 + u32::from(emit_trampoline)
4026 + shown_shapes.len()
4027 + runtime_count
4028 + u32::from(emit_definer),
4029 );
4030 for entry in std::iter::once(&main_body).chain(fn_bodies.iter()) {
4031 leb_u32(&mut code, entry.len() as u32);
4032 code.extend_from_slice(entry);
4033 }
4034 if let Some(tb) = &trampoline_body {
4035 leb_u32(&mut code, tb.len() as u32);
4036 code.extend_from_slice(tb);
4037 }
4038 for body in &shown_bodies {
4039 leb_u32(&mut code, body.len() as u32);
4040 code.extend_from_slice(body);
4041 }
4042 if let Some(r) = &runtime {
4043 let env = RuntimeEnv {
4044 heap_global,
4045 iter_global,
4046 heap_base,
4047 fail_at: host_index(HostFn::LogosRtFailAt)
4048 .expect("a self-contained heap always imports logos_rt_fail_at"),
4049 exact_drop: host_index(HostFn::ExactDrop),
4050 exact_clone: host_index(HostFn::ExactClone),
4051 exact_cmp: host_index(HostFn::ExactCmp),
4052 exact_host: (|| {
4053 Some([
4054 host_index(HostFn::ExactBox)?,
4055 host_index(HostFn::ExactAdd)?,
4056 host_index(HostFn::ExactSub)?,
4057 host_index(HostFn::ExactMul)?,
4058 host_index(HostFn::ExactNarrow)?,
4059 host_index(HostFn::ExactClone)?,
4060 ])
4061 })(),
4062 retain_base,
4063 callback_base,
4064 global_kinds: global_kinds.clone(),
4065 shared_maps,
4066 runtime: r,
4067 };
4068 for body in r.bodies(&env) {
4069 leb_u32(&mut code, body.len() as u32);
4070 code.extend_from_slice(&body);
4071 }
4072 }
4073 if let Some(db) = &definer_body {
4074 leb_u32(&mut code, db.len() as u32);
4075 code.extend_from_slice(db);
4076 }
4077 section(&mut module, 10, &code);
4078
4079 {
4082 let image = text_pool_cell.borrow();
4083 if !image.image.is_empty() {
4084 let mut data = Vec::new();
4085 leb_u32(&mut data, 1); leb_u32(&mut data, 0); i32_const(&mut data, STATIC_BASE);
4088 data.push(0x0B); leb_u32(&mut data, image.image.len() as u32);
4090 data.extend_from_slice(&image.image);
4091 section(&mut module, 11, &data);
4092 }
4093 }
4094
4095 Ok(module)
4096}
4097
4098fn declared_result(program: &CompiledProgram, fi: usize) -> Option<Kind> {
4101 let f = program.functions.get(fi)?;
4102 f.return_type
4103 .as_ref()
4104 .and_then(kind::boundary_to_kind)
4105 .or_else(|| f.ret_kind.map(Kind::from_slot))
4106}
4107
4108fn child_holes(closure_ranges: &[(usize, usize)], start: usize, end: usize) -> Vec<(usize, usize)> {
4111 closure_ranges
4112 .iter()
4113 .copied()
4114 .filter(|&(e, t)| {
4115 e >= start
4116 && t <= end
4117 && (e, t) != (start, end)
4118 && !closure_ranges.iter().any(|&(e2, t2)| {
4119 (e2, t2) != (e, t) && e2 <= e && t <= t2 && e2 >= start && t2 <= end
4120 })
4121 })
4122 .collect()
4123}
4124
4125fn extract_region(code: &[Op], start: usize, end: usize, holes: &[(usize, usize)]) -> R<Vec<Op>> {
4129 let in_hole = |pc: usize| holes.iter().any(|&(s, e)| pc >= s && pc < e);
4130 let mut new_index = vec![usize::MAX; end];
4131 let mut kept = Vec::new();
4132 for pc in start..end {
4133 if !in_hole(pc) {
4134 new_index[pc] = kept.len();
4135 kept.push(pc);
4136 }
4137 }
4138 let rebase = |t: usize| -> R<usize> {
4139 if t >= start && t < end && new_index[t] != usize::MAX {
4140 Ok(new_index[t])
4141 } else {
4142 Err(WasmLowerError::Unsupported(
4143 "jump target escapes the function",
4144 ))
4145 }
4146 };
4147 let mut ops = Vec::with_capacity(kept.len());
4148 for &pc in &kept {
4149 ops.push(match code[pc] {
4150 Op::Jump { target } => Op::Jump {
4151 target: rebase(target)?,
4152 },
4153 Op::JumpIfFalse { cond, target } => Op::JumpIfFalse {
4154 cond,
4155 target: rebase(target)?,
4156 },
4157 Op::JumpIfTrue { cond, target } => Op::JumpIfTrue {
4158 cond,
4159 target: rebase(target)?,
4160 },
4161 Op::IterNext { dst, exit } => Op::IterNext {
4162 dst,
4163 exit: rebase(exit)?,
4164 },
4165 other => other,
4166 });
4167 }
4168 Ok(ops)
4169}
4170
4171fn plan_main(
4174 program: &CompiledProgram,
4175 layout: &CodeLayout,
4176 ret_of: &dyn Fn(usize) -> Option<Kind>,
4177 global_of: &dyn Fn(u16) -> Option<Kind>,
4178 closure_ret: &dyn Fn(usize) -> Option<Kind>,
4179 ret_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4180 fn_return_closure: &dyn Fn(u16) -> Option<u16>,
4181 global_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4182 global_declared: &dyn Fn(u16) -> Option<BoundaryType>,
4183 linked: bool,
4184) -> R<Plan> {
4185 let holes = child_holes(&layout.closure_ranges, 0, layout.main_end);
4186 let ops = extract_region(&program.code, 0, layout.main_end, &holes)?;
4187 let num_regs = program.register_count as u32;
4188 let (mut ops, num_regs, placed) = regsplit::split_registers(&ops, num_regs, 0, &program.functions);
4191 let fn_return_types = fn_return_types(program);
4192 let mut main_kind_seeds: Vec<Option<Kind>> = vec![None; num_regs as usize];
4196 let mut main_seeds: Vec<(u16, ParamShape)> = Vec::new();
4197 let main_declared = seed_declarations(
4198 program,
4199 &ops,
4200 ®ion_declarations(program, 0, layout.main_end, &holes, &placed),
4201 &mut main_kind_seeds,
4202 &mut main_seeds,
4203 );
4204 let (kinds, _pc_reach, reachable_blocks) = infer_with_reachability(
4205 &ops,
4206 &program.constants,
4207 &program.struct_types,
4208 &program.enum_types,
4209 &fn_return_types,
4210 num_regs as usize,
4211 &main_kind_seeds,
4212 ret_of,
4213 global_of,
4214 closure_ret,
4215 ret_layout,
4216 fn_return_closure,
4217 &main_seeds,
4218 &[],
4219 global_layout,
4220 global_declared,
4221 linked,
4222 &program.functions,
4223 &[],
4224 )?;
4225 let structs = kind::struct_layout(
4226 &ops,
4227 &program.constants,
4228 &program.struct_types,
4229 &program.enum_types,
4230 &fn_return_types,
4231 ret_layout,
4232 fn_return_closure,
4233 &main_seeds,
4234 &[],
4235 global_layout,
4236 global_declared,
4237 &main_declared,
4238 );
4239 let cow_inserts = cow_struct_inserts(&ops, &kinds, num_regs, &program.functions);
4240 let reg_shape = complete_reg_shape(&structs, &kinds, program);
4241 let iter_iterable = kind::iter_pairing(&ops);
4242 let place = PlaceSites::of(&ops, &program.constants, &program.functions);
4243 let transient = transient_reads(&ops, num_regs, &program.functions);
4244 let declared = declared_registers(&structs, main_declared, &[]);
4245 let range_loops = range_loop_registers(&ops, &program.functions);
4246 if linked {
4247 accumulate_as_add(&mut ops, &kinds);
4248 }
4249 let mut plan = Plan {
4250 range_loops,
4251 ops,
4252 kinds,
4253 num_params: 0,
4254 num_regs,
4255 result: None,
4256 reachable_blocks,
4257 structs,
4258 cow_inserts,
4259 reg_shape,
4260 return_closure: None,
4261 iter_iterable,
4262 place,
4263 transient,
4264 declared,
4265 inout: Vec::new(),
4266 exact: Vec::new(),
4267 params_tagged: Vec::new(),
4268 ret_tagged: false,
4269 absence: false,
4270 absence_regs: Vec::new(),
4271 absence_globals: Vec::new(),
4272 tower: tower::Towers::default(),
4273 stub: false,
4274 };
4275 tower::settle(&mut plan, program, linked)?;
4276 Ok(plan)
4277}
4278
4279fn accumulate_as_add(ops: &mut [Op], kinds: &KindTable) {
4283 for op in ops.iter_mut() {
4284 if let Op::AddAssign { dst, src } = *op {
4285 if matches!(
4286 kinds.get(dst as usize),
4287 Some(
4288 Kind::Rational
4289 | Kind::BigInt
4290 | Kind::Complex
4291 | Kind::Modular
4292 | Kind::Decimal
4293 | Kind::Money
4294 | Kind::Quantity
4295 )
4296 ) {
4297 *op = Op::Add {
4298 dst,
4299 lhs: dst,
4300 rhs: src,
4301 };
4302 }
4303 }
4304 }
4305}
4306
4307fn fn_return_types(program: &CompiledProgram) -> Vec<Option<BoundaryType>> {
4310 program
4311 .functions
4312 .iter()
4313 .map(|f| f.return_type.clone())
4314 .collect()
4315}
4316
4317fn complete_reg_shape(
4322 structs: &kind::StructLayout,
4323 kinds: &KindTable,
4324 program: &CompiledProgram,
4325) -> std::collections::HashMap<u16, ParamShape> {
4326 let mut out = structs.reg_shape.clone();
4327 for (reg, value_reg) in &structs.map_set_value {
4328 if !out.contains_key(reg) {
4329 if let Some(vk) = kinds.get(*value_reg as usize) {
4330 let key = structs
4335 .map_set_key
4336 .get(reg)
4337 .and_then(|k| kinds.get(*k as usize));
4338 out.insert(
4339 *reg,
4340 ParamShape::Map {
4341 key,
4342 value: vk,
4343 layout: None,
4344 },
4345 );
4346 }
4347 }
4348 }
4349 for (reg, elems) in &structs.tuple_layouts {
4350 if !out.contains_key(reg) {
4351 if let Some(ks) = elems
4352 .iter()
4353 .map(|e| kinds.get(*e as usize))
4354 .collect::<Option<Vec<Kind>>>()
4355 {
4356 if !ks.windows(2).all(|w| w[0] == w[1]) {
4358 out.insert(*reg, ParamShape::Tuple(ks));
4359 }
4360 }
4361 }
4362 }
4363 for (reg, name) in &structs.ind_type_of {
4364 if !out.contains_key(reg) {
4365 if let Some(shape) = kind::enum_shape_of_name(name, &program.enum_types) {
4366 out.insert(*reg, ParamShape::Enum(shape));
4367 }
4368 }
4369 }
4370 out
4371}
4372
4373fn extract_capture_kinds(
4380 program: &CompiledProgram,
4381 main_p1: &Plan,
4382 region_plans: &[Option<Plan>],
4383 global_of: &dyn Fn(u16) -> Option<Kind>,
4384 global_closure_of: &dyn Fn(u16) -> Option<u16>,
4385) -> (
4386 Vec<Vec<Option<Kind>>>,
4387 Vec<Vec<Option<ParamShape>>>,
4388 Vec<Vec<Option<u16>>>,
4389) {
4390 let mut kinds: Vec<Vec<Option<Kind>>> = program
4391 .functions
4392 .iter()
4393 .map(|f| {
4394 f.captures
4395 .iter()
4396 .map(|(_, g)| g.and_then(|gi| global_of(gi)))
4397 .collect()
4398 })
4399 .collect();
4400 let mut shapes: Vec<Vec<Option<ParamShape>>> = program
4401 .functions
4402 .iter()
4403 .map(|f| vec![None; f.captures.len()])
4404 .collect();
4405 let mut closures: Vec<Vec<Option<u16>>> = program
4410 .functions
4411 .iter()
4412 .map(|f| {
4413 f.captures
4414 .iter()
4415 .map(|(_, g)| g.and_then(|gi| global_closure_of(gi)))
4416 .collect()
4417 })
4418 .collect();
4419 for plan in std::iter::once(main_p1).chain(region_plans.iter().flatten()) {
4420 for op in &plan.ops {
4421 if let Op::MakeClosure {
4422 func, locals_start, ..
4423 } = *op
4424 {
4425 let fi = func as usize;
4426 let mut local_k: u16 = 0;
4427 for (k, (_sym, global)) in program.functions[fi].captures.iter().enumerate() {
4428 if global.is_none() {
4429 let reg = locals_start + local_k;
4430 local_k += 1;
4431 if let Some(kind) = plan.kinds.get(reg as usize) {
4432 kinds[fi][k] = Some(kind);
4433 }
4434 if let Some(shape) = plan.reg_shape.get(®) {
4440 shapes[fi][k] = Some(shape.clone());
4441 }
4442 if let Some(&c) = plan.structs.closure_of.get(®) {
4445 closures[fi][k] = Some(c);
4446 }
4447 }
4448 }
4449 }
4450 }
4451 }
4452 (kinds, shapes, closures)
4453}
4454
4455#[allow(clippy::too_many_arguments)]
4461fn plan_function(
4462 program: &CompiledProgram,
4463 fi: usize,
4464 layout: &CodeLayout,
4465 ret_of: &dyn Fn(usize) -> Option<Kind>,
4466 global_of: &dyn Fn(u16) -> Option<Kind>,
4467 closure_ret: &dyn Fn(usize) -> Option<Kind>,
4468 ret_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4469 fn_return_closure: &dyn Fn(u16) -> Option<u16>,
4470 global_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4471 global_declared: &dyn Fn(u16) -> Option<BoundaryType>,
4472 param_origin: &dyn Fn(usize, usize) -> Option<u16>,
4473 exact_param: &dyn Fn(usize, usize) -> bool,
4474 capture_kinds: &[Vec<Option<Kind>>],
4475 capture_shapes: &[Vec<Option<ParamShape>>],
4476 capture_closures: &[Vec<Option<u16>>],
4477 strict: bool,
4478 linked: bool,
4479) -> R<Plan> {
4480 let f = &program.functions[fi];
4481 let (start, end) = layout.func_region[fi];
4482 if start >= end || end > program.code.len() {
4483 return Err(WasmLowerError::Unsupported("malformed function bounds"));
4484 }
4485 let holes = child_holes(&layout.closure_ranges, start, end);
4486 let ops = extract_region(&program.code, start, end, &holes)?;
4487
4488 let cap_n = f.captures.len() as u32;
4496 let num_params = f.param_count as u32 + 2 * cap_n;
4497 let mut seeds: Vec<Option<Kind>> = if cap_n > 0 {
4498 let mut s = vec![Some(Kind::Int); num_params as usize];
4499 for i in 0..f.param_count as usize {
4503 if let Some(Some(bt)) = f.param_types.get(i) {
4504 if let Some(k) = kind::boundary_to_kind(bt) {
4505 s[i] = Some(k);
4506 }
4507 }
4508 }
4509 let caps = capture_kinds.get(fi).map(|v| v.as_slice()).unwrap_or(&[]);
4510 for k in 0..f.captures.len() {
4511 if let Some(kind) = caps.get(k).copied().flatten() {
4512 s[f.param_count as usize + k] = Some(kind);
4513 }
4514 }
4515 s
4516 } else {
4517 kind::function_param_seeds(f)
4518 };
4519 for (i, seed) in seeds.iter_mut().enumerate().take(f.param_count as usize) {
4522 if exact_param(fi, i) && seed.map_or(true, Kind::lands_in_tower) {
4523 *seed = Some(Kind::Tower);
4524 }
4525 }
4526 let num_regs = f.register_count as u32;
4527 let (mut ops, num_regs, placed) =
4531 regsplit::split_registers(&ops, num_regs, num_params, &program.functions);
4532 let mut param_layouts = if cap_n == 0 {
4536 param_seeds(f, program)
4537 } else {
4538 Vec::new()
4539 };
4540 if let Some(k) = f.return_type.as_ref().and_then(kind::boundary_to_kind) {
4544 for op in &ops {
4545 if let Op::Return { src } = *op {
4546 if seeds.len() <= src as usize {
4547 seeds.resize(src as usize + 1, None);
4548 }
4549 seeds[src as usize].get_or_insert(k);
4550 }
4551 }
4552 }
4553 let body_declared = seed_declarations(
4556 program,
4557 &ops,
4558 ®ion_declarations(program, start, end, &holes, &placed),
4559 &mut seeds,
4560 &mut param_layouts,
4561 );
4562 let local_shapes = capture_shapes.get(fi).map(|v| v.as_slice()).unwrap_or(&[]);
4567 for (k, (_sym, global)) in f.captures.iter().enumerate() {
4568 let shape = if let Some(gidx) = global {
4569 program
4571 .global_types
4572 .get(*gidx as usize)
4573 .and_then(|t| t.as_ref())
4574 .and_then(|bt| boundary_to_param_shape(bt, program))
4575 } else {
4576 local_shapes.get(k).cloned().flatten()
4578 };
4579 if let Some(shape) = shape {
4580 param_layouts.push((f.param_count + k as u16, shape));
4581 }
4582 }
4583 let mut param_closures: Vec<(u16, u16)> = (0..f.param_count)
4588 .filter_map(|i| param_origin(fi, i as usize).map(|c| (i, c)))
4589 .collect();
4590 if let Some(caps) = capture_closures.get(fi) {
4593 for (k, c) in caps.iter().enumerate() {
4594 if let Some(c) = c {
4595 param_closures.push((f.param_count + k as u16, *c));
4596 }
4597 }
4598 }
4599 for &(reg, _) in ¶m_closures {
4603 if let Some(slot) = seeds.get_mut(reg as usize) {
4604 *slot = Some(Kind::Closure);
4605 }
4606 }
4607 for reg in channel_param_regs(&ops, f.param_count) {
4615 if let Some(slot) = seeds.get_mut(reg as usize) {
4616 let seq = f
4617 .param_types
4618 .get(reg as usize)
4619 .and_then(|t| t.as_ref())
4620 .and_then(chan_param_seq_kind);
4621 if let Some(seq) = seq {
4622 *slot = Some(seq);
4623 }
4624 }
4625 }
4626 let fn_rt = fn_return_types(program);
4627 let (kinds, pc_reach, reachable_blocks) = infer_with_reachability(
4628 &ops,
4629 &program.constants,
4630 &program.struct_types,
4631 &program.enum_types,
4632 &fn_rt,
4633 num_regs as usize,
4634 &seeds,
4635 ret_of,
4636 global_of,
4637 closure_ret,
4638 ret_layout,
4639 fn_return_closure,
4640 ¶m_layouts,
4641 ¶m_closures,
4642 global_layout,
4643 global_declared,
4644 linked,
4645 &program.functions,
4646 &f.mutable_param_regs,
4647 )?;
4648
4649 let inferred = infer_result(&ops, &kinds, &pc_reach, strict)?;
4653 let result = match (f.ret_kind.map(Kind::from_slot), inferred) {
4654 (Some(d), Some(i)) if d.wasm_valtype() != i.wasm_valtype() => Some(i),
4655 (Some(d), _) => Some(d),
4656 (None, i) => i,
4657 };
4658 let structs = kind::struct_layout(
4659 &ops,
4660 &program.constants,
4661 &program.struct_types,
4662 &program.enum_types,
4663 &fn_rt,
4664 ret_layout,
4665 fn_return_closure,
4666 ¶m_layouts,
4667 ¶m_closures,
4668 global_layout,
4669 global_declared,
4670 &body_declared,
4671 );
4672 let cow_inserts = cow_struct_inserts(&ops, &kinds, num_regs, &program.functions);
4673 let reg_shape = complete_reg_shape(&structs, &kinds, program);
4674 let return_closure = infer_return_closure(&ops, &kinds, &structs, &pc_reach);
4675 let iter_iterable = kind::iter_pairing(&ops);
4676 let place = PlaceSites::of(&ops, &program.constants, &program.functions);
4677 let transient = transient_reads(&ops, num_regs, &program.functions);
4678 let declared = declared_registers(&structs, body_declared, &f.param_types);
4679 let range_loops = range_loop_registers(&ops, &program.functions);
4680 let inout: Vec<u16> = f
4681 .mutable_param_regs
4682 .iter()
4683 .copied()
4684 .filter(|p| u32::from(*p) < num_params as u32)
4685 .collect();
4686 if !inout.is_empty() && !f.captures.is_empty() {
4687 return Err(WasmLowerError::Unsupported(
4688 "a function value's body with a `mutable` parameter",
4689 ));
4690 }
4691 if linked {
4692 accumulate_as_add(&mut ops, &kinds);
4693 }
4694 let mut plan = Plan {
4695 range_loops,
4696 ops,
4697 kinds,
4698 num_params,
4699 num_regs,
4700 result,
4701 reachable_blocks,
4702 structs,
4703 cow_inserts,
4704 reg_shape,
4705 return_closure,
4706 iter_iterable,
4707 place,
4708 transient,
4709 declared,
4710 inout,
4711 exact: Vec::new(),
4712 params_tagged: Vec::new(),
4713 ret_tagged: false,
4714 absence: false,
4715 absence_regs: Vec::new(),
4716 absence_globals: Vec::new(),
4717 tower: tower::Towers::default(),
4718 stub: false,
4719 };
4720 tower::settle(&mut plan, program, linked)?;
4721 Ok(plan)
4722}
4723
4724fn channel_param_regs(ops: &[Op], num_params: u16) -> Vec<u16> {
4729 let mut regs = Vec::new();
4730 let mut note = |chan: u16| {
4731 if chan < num_params && !regs.contains(&chan) {
4732 regs.push(chan);
4733 }
4734 };
4735 for op in ops {
4736 match op {
4737 Op::ChanSend { chan, .. }
4738 | Op::ChanRecv { chan, .. }
4739 | Op::ChanTrySend { chan, .. }
4740 | Op::ChanTryRecv { chan, .. }
4741 | Op::ChanClose { chan }
4742 | Op::SelectArmRecv { chan, .. } => note(*chan),
4743 _ => {}
4744 }
4745 }
4746 regs
4747}
4748
4749fn chan_param_seq_kind(bt: &BoundaryType) -> Option<Kind> {
4753 Some(match bt {
4754 BoundaryType::Int | BoundaryType::Bool => Kind::SeqInt,
4755 BoundaryType::Float => Kind::SeqFloat,
4756 BoundaryType::Text => Kind::SeqText,
4757 _ => return None,
4758 })
4759}
4760
4761fn infer_return_closure(
4767 ops: &[Op],
4768 kinds: &KindTable,
4769 structs: &kind::StructLayout,
4770 pc_reach: &[bool],
4771) -> Option<u16> {
4772 let mut found: Option<u16> = None;
4773 for (pc, op) in ops.iter().enumerate() {
4774 if !pc_reach.get(pc).copied().unwrap_or(true) {
4775 continue;
4776 }
4777 if let Op::Return { src } = *op {
4778 if kinds.get(src as usize) != Some(Kind::Closure) {
4779 continue;
4780 }
4781 match structs.closure_of.get(&src) {
4782 Some(&c) if found.is_none() => found = Some(c),
4783 Some(&c) if found == Some(c) => {}
4784 _ => return None,
4785 }
4786 }
4787 }
4788 found
4789}
4790
4791fn exact_arguments(program: &CompiledProgram, plans: &[&Plan], exact: &mut [Vec<bool>]) -> bool {
4803 let mut grew = false;
4804 for plan in plans {
4805 for op in &plan.ops {
4806 let (func, args_start, arg_count) = match *op {
4807 Op::Call {
4808 func,
4809 args_start,
4810 arg_count,
4811 ..
4812 }
4813 | Op::Spawn {
4814 func,
4815 args_start,
4816 arg_count,
4817 }
4818 | Op::SpawnHandle {
4819 func,
4820 args_start,
4821 arg_count,
4822 ..
4823 } => (func as usize, args_start, arg_count),
4824 _ => continue,
4825 };
4826 let params = program.functions.get(func).map_or(0, |f| f.param_count);
4827 for i in 0..arg_count.min(params) {
4828 if plan.kinds.get((args_start + i) as usize) == Some(Kind::Tower) {
4829 if let Some(mark) = exact.get_mut(func).and_then(|v| v.get_mut(i as usize)) {
4830 grew |= !*mark;
4831 *mark = true;
4832 }
4833 }
4834 }
4835 }
4836 }
4837 grew
4838}
4839
4840fn compute_param_origins(program: &CompiledProgram, plans: &[&Plan]) -> Vec<Vec<Option<u16>>> {
4841 use std::collections::{HashMap, HashSet};
4842 let mut obs: HashMap<(usize, usize), HashSet<Option<u16>>> = HashMap::new();
4843 for plan in plans {
4844 for (pc, op) in plan.ops.iter().enumerate() {
4845 let (func, args_start, arg_count) = match *op {
4846 Op::Call {
4847 func,
4848 args_start,
4849 arg_count,
4850 ..
4851 } => (Some(func as usize), args_start, arg_count),
4852 Op::CallValue {
4853 args_start,
4854 arg_count,
4855 ..
4856 } => (
4857 plan.structs
4858 .callee_func
4859 .get(pc)
4860 .copied()
4861 .flatten()
4862 .map(|f| f as usize),
4863 args_start,
4864 arg_count,
4865 ),
4866 _ => continue,
4867 };
4868 let Some(func) = func else { continue };
4869 for i in 0..arg_count {
4870 let origin = plan.structs.closure_of.get(&(args_start + i)).copied();
4871 obs.entry((func, i as usize)).or_default().insert(origin);
4872 }
4873 }
4874 }
4875 (0..program.functions.len())
4876 .map(|fi| {
4877 let pc = program.functions[fi].param_count as usize;
4878 (0..pc)
4879 .map(|i| match obs.get(&(fi, i)) {
4880 Some(set) if set.len() == 1 => set.iter().next().copied().flatten(),
4881 _ => None,
4882 })
4883 .collect()
4884 })
4885 .collect()
4886}
4887
4888fn boundary_to_param_shape(bt: &BoundaryType, program: &CompiledProgram) -> Option<ParamShape> {
4893 match bt {
4894 BoundaryType::Struct(name) => {
4895 kind::resolve_named_layout(name, &program.struct_types, &program.constants)
4896 .map(ParamShape::Struct)
4897 }
4898 BoundaryType::Map(key, value) => kind::boundary_to_kind(value).map(|vk| {
4901 let layout = match value.as_ref() {
4902 BoundaryType::Struct(name) => {
4903 kind::resolve_named_layout(name, &program.struct_types, &program.constants)
4904 }
4905 _ => None,
4906 };
4907 ParamShape::Map {
4908 key: kind::boundary_to_kind(key),
4909 value: vk,
4910 layout,
4911 }
4912 }),
4913 BoundaryType::Enum(_) | BoundaryType::Result(_, _) => {
4916 kind::enum_shape_of(bt, &program.enum_types).map(ParamShape::Enum)
4917 }
4918 BoundaryType::Tuple(elems) => elems
4919 .iter()
4920 .map(kind::boundary_to_kind)
4921 .collect::<Option<Vec<Kind>>>()
4922 .map(ParamShape::Tuple),
4923 BoundaryType::Seq(elem) => match elem.as_ref() {
4928 BoundaryType::Struct(name) => {
4929 kind::resolve_named_layout(name, &program.struct_types, &program.constants)
4930 .map(ParamShape::SeqOfStruct)
4931 }
4932 _ => None,
4933 },
4934 _ => None,
4935 }
4936}
4937
4938fn param_seeds(f: &CompiledFunction, program: &CompiledProgram) -> Vec<(u16, ParamShape)> {
4943 f.param_types
4944 .iter()
4945 .enumerate()
4946 .filter_map(|(i, pt)| {
4947 pt.as_ref()
4948 .and_then(|bt| boundary_to_param_shape(bt, program))
4949 .map(|shape| (i as u16, shape))
4950 })
4951 .collect()
4952}
4953
4954fn region_declarations<'p>(
4959 program: &'p CompiledProgram,
4960 start: usize,
4961 end: usize,
4962 holes: &[(usize, usize)],
4963 placed: &[usize],
4964) -> Vec<(usize, &'p BoundaryType)> {
4965 let first = program
4966 .declared_types
4967 .partition_point(|(pc, _)| (*pc as usize) < start);
4968 program.declared_types[first..]
4969 .iter()
4970 .take_while(|(pc, _)| (*pc as usize) < end)
4971 .filter(|(pc, _)| {
4972 !holes
4973 .iter()
4974 .any(|&(s, e)| (*pc as usize) >= s && (*pc as usize) < e)
4975 })
4976 .filter_map(|(pc, bt)| {
4977 let pc = *pc as usize;
4978 let excised: usize = holes
4979 .iter()
4980 .filter(|&&(s, _)| s < pc)
4981 .map(|&(s, e)| e.min(pc) - s.max(start))
4982 .sum();
4983 Some((*placed.get(pc - start - excised)?, bt))
4984 })
4985 .collect()
4986}
4987
4988fn seed_declarations(
4992 program: &CompiledProgram,
4993 ops: &[Op],
4994 declared: &[(usize, &BoundaryType)],
4995 kinds: &mut Vec<Option<Kind>>,
4996 shapes: &mut Vec<(u16, ParamShape)>,
4997) -> Vec<(usize, u16, BoundaryType)> {
4998 let mut seeded = Vec::new();
4999 for &(at, bt) in declared {
5000 let Some(op) = ops.get(at) else { continue };
5001 let defs = crate::vm::instruction::op_def_uses(op, &program.functions).0;
5002 let [dst] = defs[..] else { continue };
5003 if let Some(k) = kind::boundary_to_kind(bt) {
5004 if kinds.len() <= dst as usize {
5005 kinds.resize(dst as usize + 1, None);
5006 }
5007 kinds[dst as usize].get_or_insert(k);
5008 }
5009 if let Some(shape) = boundary_to_param_shape(bt, program) {
5010 shapes.push((dst, shape));
5011 }
5012 seeded.push((at, dst, bt.clone()));
5013 }
5014 seeded
5015}
5016
5017fn infer_result(ops: &[Op], kinds: &KindTable, pc_reach: &[bool], strict: bool) -> R<Option<Kind>> {
5023 let mut result = None;
5024 for (pc, op) in ops.iter().enumerate() {
5025 if !pc_reach.get(pc).copied().unwrap_or(true) {
5029 continue;
5030 }
5031 if let Op::Return { src } = *op {
5032 let k = match kinds.get(src as usize) {
5033 Some(k) => k,
5034 None if !strict => continue,
5035 None => {
5036 return Err(WasmLowerError::Unsupported(
5037 "return of an unknown-kind value",
5038 ))
5039 }
5040 };
5041 match result {
5042 None => result = Some(k),
5043 Some(prev) if prev == k => {}
5044 Some(Kind::SeqAny) if k.is_seq() => result = Some(k),
5050 Some(prev) if prev.is_seq() && k == Kind::SeqAny => {}
5051 Some(Kind::Tower) if k.lands_in_tower() => {}
5053 Some(prev) if k == Kind::Tower && prev.lands_in_tower() => result = Some(Kind::Tower),
5054 Some(_) => return Err(WasmLowerError::Unsupported("function returns mixed kinds")),
5055 }
5056 }
5057 }
5058 Ok(result)
5059}
5060
5061fn global_struct_layout(
5070 plan: &Plan,
5071 src: u16,
5072 struct_types: &[StructTypeDef],
5073 constants: &[Constant],
5074) -> Option<FieldLayout> {
5075 if let Some(name) = plan.structs.struct_name_of.get(&src) {
5076 if let Some(layout) = kind::resolve_named_layout(name, struct_types, constants) {
5077 return Some(layout);
5078 }
5079 }
5080 if let Some(layout) = plan.structs.reg_layout.get(&src) {
5083 return local_field_layout(plan, layout);
5084 }
5085 plan.structs.call_result.get(&src).cloned()
5086}
5087
5088fn local_field_layout(plan: &Plan, layout: &kind::LocalLayout) -> Option<FieldLayout> {
5095 layout
5096 .iter()
5097 .map(|&(f, vr)| {
5098 let vr = vr?;
5099 let k = plan.kinds.get(vr as usize)?;
5100 let nested = match (
5101 k,
5102 plan.declared.get(&vr),
5103 plan.structs.struct_name_of.get(&vr),
5104 ) {
5105 (_, Some(t), _) => kind::nested_of(t),
5106 (Kind::Struct, None, Some(name)) => FieldNested::Struct(name.clone()),
5107 _ => FieldNested::None,
5108 };
5109 Some((f, k, nested))
5110 })
5111 .collect()
5112}
5113
5114fn fn_return_struct_layout(
5115 plan: &Plan,
5116 struct_types: &[StructTypeDef],
5117 constants: &[Constant],
5118) -> Option<FieldLayout> {
5119 for op in &plan.ops {
5120 if let Op::Return { src } = *op {
5121 if plan.kinds.get(src as usize) == Some(Kind::Struct) {
5122 if let Some(name) = plan.structs.struct_name_of.get(&src) {
5129 if let Some(layout) = kind::resolve_named_layout(name, struct_types, constants)
5130 {
5131 return Some(layout);
5132 }
5133 }
5134 if let Some(layout) = plan.structs.reg_layout.get(&src) {
5137 return local_field_layout(plan, layout);
5138 }
5139 if let Some(resolved) = plan.structs.call_result.get(&src) {
5144 return Some(resolved.clone());
5145 }
5146 }
5147 }
5148 }
5149 None
5150}
5151
5152fn result_valtypes(result: Option<Kind>) -> Vec<u8> {
5154 match result {
5155 Some(k) => vec![k.wasm_valtype()],
5156 None => vec![],
5157 }
5158}
5159
5160fn plan_results(p: &Plan) -> Vec<u8> {
5162 let mut results = result_valtypes(p.result);
5163 results.extend(p.inout.iter().map(|r| p.kinds.valtype(*r as usize)));
5164 results
5165}
5166
5167fn push_inout_results(code: &mut Vec<u8>, plan: &Plan) {
5169 for p in &plan.inout {
5170 local_get(code, *p as u32);
5171 }
5172}
5173
5174struct Ctx<'a> {
5178 absence_base: Option<u32>,
5179 constants: &'a [Constant],
5180 shown: &'a display::ShownTable,
5182 host_index: &'a dyn Fn(HostFn) -> Option<u32>,
5183 fn_base: u32,
5184 heap_global: u32,
5187 iter_global: u32,
5191 replica_global: Option<u32>,
5193 uses_iter: bool,
5195 fn_type: &'a [u32],
5198 fn_param_valtypes: &'a [Vec<u8>],
5202 fn_param_kinds: &'a [Vec<Option<Kind>>],
5205 fn_stubbed: &'a [bool],
5209 fn_results: &'a [Option<Kind>],
5212 fn_inout: &'a [Vec<u16>],
5214 exact: &'a exact::Signatures,
5216 functions: &'a [crate::vm::instruction::CompiledFunction],
5219 capture_kinds: &'a [Vec<Option<Kind>>],
5223 enum_types: &'a [EnumTypeDef],
5226 struct_types: &'a [StructTypeDef],
5229 policies: &'a PolicyRegistry,
5232 interner: &'a Interner,
5235 text_pool: Option<&'a std::cell::RefCell<TextPool>>,
5238 runtime: Option<&'a Runtime>,
5242 global_valtypes: &'a [u8],
5247 global_kinds: &'a [Option<Kind>],
5250 shared_maps: bool,
5253 linked: bool,
5257 rt_alloc: Option<u32>,
5261 retain_base: Option<u32>,
5266 hot: std::cell::Cell<bool>,
5273 batch_reclaim: bool,
5275 may_safepoint: &'a [bool],
5277}
5278
5279impl<'a> Ctx<'a> {
5280 fn heap_counting(&self) -> bool {
5284 self.retain_base.is_some()
5285 }
5286}
5287
5288#[derive(PartialEq, Eq)]
5290enum Flow {
5291 Straight,
5292 Terminated,
5293}
5294
5295fn may_safepoint(fns: &[Plan]) -> Vec<bool> {
5300 let direct = |plan: &Plan| {
5301 plan.ops.iter().enumerate().any(|(pc, op)| match *op {
5302 Op::Jump { target }
5303 | Op::JumpIfFalse { target, .. }
5304 | Op::JumpIfTrue { target, .. } => target <= pc,
5305 Op::CallValue { .. } => true,
5306 Op::CallBuiltin {
5307 builtin: BuiltinId::TextFromBytes,
5308 ..
5309 } => true,
5310 Op::CallBuiltin {
5311 args_start,
5312 arg_count,
5313 ..
5314 } => (0..arg_count)
5315 .any(|a| plan.kinds.get((args_start + a) as usize) == Some(Kind::Closure)),
5316 _ => false,
5317 })
5318 };
5319 let mut may: Vec<bool> = fns.iter().map(|p| !p.stub && direct(p)).collect();
5320 loop {
5321 let reaches: Vec<usize> = (0..fns.len())
5322 .filter(|&fi| {
5323 !may[fi]
5324 && fns[fi].ops.iter().any(|op| {
5325 matches!(*op, Op::Call { func, .. } | Op::Spawn { func, .. }
5326 | Op::SpawnHandle { func, .. }
5327 if may.get(func as usize).copied().unwrap_or(true))
5328 })
5329 })
5330 .collect();
5331 if reaches.is_empty() {
5332 break;
5333 }
5334 for fi in reaches {
5335 may[fi] = true;
5336 }
5337 }
5338 may
5339}
5340
5341fn emit_body(plan: &Plan, _ctx: &Ctx) -> R<Vec<u8>> {
5344 if plan.stub {
5348 return Ok(vec![
5349 0x00, 0x00, 0x0B, ]);
5353 }
5354 let ctx = _ctx;
5355 let blocks = Blocks::new(&plan.ops).ok_or(WasmLowerError::Unsupported(
5356 "jump target escapes the function",
5357 ))?;
5358 let pc_local = plan.num_regs;
5359 let in_loop = loop_pcs(&plan.ops);
5360 let roots = ctx
5361 .batch_reclaim
5362 .then(|| roots::Frame::new(plan, ctx.functions, ctx.may_safepoint));
5363
5364 let mut blocks_code: Vec<Vec<u8>> = Vec::with_capacity(blocks.num_blocks());
5365 for k in 0..blocks.num_blocks() {
5366 if !plan.reachable_blocks.get(k).copied().unwrap_or(true) {
5370 blocks_code.push(vec![0x00]); continue;
5372 }
5373 let mut code = Vec::new();
5374 let mut terminated = false;
5375 for pc in blocks.start(k)..blocks.end(k) {
5376 ctx.hot
5380 .set(in_loop[pc] && !ctx.exact.sequence_ints() && !ctx.exact.map_ints);
5381 if let Some(roots) = &roots {
5382 roots.before(&mut code, plan, ctx, pc);
5383 }
5384 let flow = tower::lower(pc, plan, ctx, &blocks, k, &mut code).inspect_err(|e| {
5385 if std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some() {
5386 let (defs, uses) = crate::vm::instruction::op_def_uses(&plan.ops[pc], ctx.functions);
5387 let kinds: Vec<String> = defs
5388 .iter()
5389 .chain(&uses)
5390 .map(|r| format!("R{r} {:?}", plan.kinds.get(*r as usize)))
5391 .collect();
5392 eprintln!("[wasm] op {pc} `{:?}` refused: {e} ({})", plan.ops[pc], kinds.join(", "));
5393 }
5394 })?;
5395 if flow == Flow::Terminated {
5396 terminated = true;
5397 break;
5398 }
5399 }
5400 if !terminated {
5401 let end = blocks.end(k);
5402 if end >= plan.ops.len() {
5403 match plan.result {
5405 None => {
5406 if let Some(roots) = &roots {
5407 roots.leave(&mut code, ctx, end - 1);
5408 }
5409 emit_leave_loops(&mut code, plan, ctx);
5410 exact::leave(&mut code, plan, ctx)?;
5411 code.push(0x0F); }
5413 Some(_) => code.push(0x00), }
5415 } else {
5416 goto_block(&mut code, pc_local, &blocks, k, blocks.block_of(end));
5417 }
5418 }
5419 blocks_code.push(code);
5420 }
5421 ctx.hot.set(false);
5422
5423 let mut body = Vec::new();
5424 if runs_loops(plan) {
5425 global_get(&mut body, ctx.iter_global);
5428 local_set(&mut body, loop_base_local(plan));
5429 }
5430 exact::prologue(&mut body, plan, ctx)?;
5431 body.extend(assemble_dispatch_loop(pc_local, &blocks_code));
5432 if !plan_results(plan).is_empty() {
5433 body.push(0x00); }
5435 body.push(0x0B); let mut entry = encode_locals(plan, roots.as_ref().map_or(0, roots::Frame::len));
5438 entry.extend(body);
5439 Ok(super::stackify::stackify(entry))
5440}
5441
5442fn loop_pcs(ops: &[Op]) -> Vec<bool> {
5447 let mut depth = vec![0i32; ops.len() + 1];
5448 for (pc, op) in ops.iter().enumerate() {
5449 if let Op::Jump { target }
5450 | Op::JumpIfFalse { target, .. }
5451 | Op::JumpIfTrue { target, .. } = *op
5452 {
5453 if target <= pc {
5454 depth[target] += 1;
5455 depth[pc + 1] -= 1;
5456 }
5457 }
5458 }
5459 let mut open = 0;
5460 depth[..ops.len()]
5461 .iter()
5462 .map(|d| {
5463 open += d;
5464 open > 0
5465 })
5466 .collect()
5467}
5468
5469fn lower_op(
5471 pc: usize,
5472 plan: &Plan,
5473 ctx: &Ctx,
5474 blocks: &Blocks,
5475 k: usize,
5476 code: &mut Vec<u8>,
5477) -> R<Flow> {
5478 let kinds = &plan.kinds;
5479 match plan.ops[pc] {
5480 Op::LoadConst { dst, idx } => {
5481 let dst_float = kinds.get(dst as usize) == Some(Kind::Float);
5485 match ctx
5486 .constants
5487 .get(idx as usize)
5488 .ok_or(WasmLowerError::Unsupported("constant index out of range"))?
5489 {
5490 Constant::Int(v) if dst_float => {
5491 code.push(0x44); code.extend_from_slice(&(*v as f64).to_le_bytes());
5493 }
5494 Constant::Int(v) => {
5495 code.push(0x42); leb_i64(code, *v);
5497 }
5498 Constant::Bool(b) if dst_float => {
5499 code.push(0x44); code.extend_from_slice(&(if *b { 1.0f64 } else { 0.0f64 }).to_le_bytes());
5501 }
5502 Constant::Bool(b) => {
5503 code.push(0x42); leb_i64(code, i64::from(*b));
5505 }
5506 Constant::Char(c) => {
5507 code.push(0x42); leb_i64(code, i64::from(*c as u32));
5509 }
5510 Constant::Nothing => {
5511 match kinds.valtype(dst as usize) {
5515 F64 => {
5516 code.push(0x44);
5517 code.extend_from_slice(&0.0f64.to_le_bytes());
5518 }
5519 I32 => i32_const(code, 0),
5520 _ => {
5521 code.push(0x42);
5522 leb_i64(code, 0);
5523 }
5524 }
5525 }
5526 Constant::Float(f) => {
5527 code.push(0x44); code.extend_from_slice(&f.to_le_bytes());
5529 }
5530 Constant::Duration(v) | Constant::Moment(v) | Constant::Time(v) => {
5535 code.push(0x42); leb_i64(code, *v);
5537 }
5538 Constant::Date(v) => {
5539 i32_const(code, *v);
5544 }
5545 Constant::Span { months, days } => {
5548 let packed = ((*months as i64) << 32) | ((*days as u32) as i64);
5549 code.push(0x42); leb_i64(code, packed);
5551 }
5552 Constant::Text(s) => {
5553 lower_text_literal(code, ctx, plan.num_regs, s.as_bytes());
5556 }
5557 }
5558 local_set(code, dst as u32);
5559 Ok(Flow::Straight)
5560 }
5561 Op::EnsureOwned { .. } => Ok(Flow::Straight),
5567 Op::Move { dst, src } => {
5568 if kinds.get(dst as usize) == Some(Kind::Float)
5574 && kinds.get(src as usize) != Some(Kind::Float)
5575 {
5576 push_as_f64(code, src, kinds.get(src as usize))?;
5577 } else if kinds.valtype(dst as usize) != kinds.valtype(src as usize) {
5578 return Err(WasmLowerError::Unsupported(
5579 "move between differently-typed registers",
5580 ));
5581 } else {
5582 local_get(code, src as u32);
5583 }
5584 local_set(code, dst as u32);
5585 if counts_aliases(kinds.get(dst as usize)) {
5588 emit_retain(code, ctx, dst);
5589 }
5590 Ok(Flow::Straight)
5591 }
5592 Op::RevSwap { a, b } => {
5599 if kinds.valtype(a as usize) != kinds.valtype(b as usize) {
5600 return Err(WasmLowerError::Unsupported(
5601 "swap of two differently-typed registers",
5602 ));
5603 }
5604 local_get(code, b as u32);
5605 local_get(code, a as u32);
5606 local_set(code, b as u32);
5607 local_set(code, a as u32);
5608 Ok(Flow::Straight)
5609 }
5610 Op::RevAdd { place, delta } => {
5619 arith(code, 0x7C, place, place, delta); Ok(Flow::Straight)
5621 }
5622 Op::RevSub { place, delta } => {
5623 arith(code, 0x7D, place, place, delta); Ok(Flow::Straight)
5625 }
5626 Op::RevXor { place, delta } => {
5627 arith(code, 0x85, place, place, delta); Ok(Flow::Straight)
5629 }
5630 Op::RevNeg { place } => {
5631 code.push(0x42); leb_i64(code, 0);
5634 local_get(code, place as u32);
5635 code.push(0x7D); local_set(code, place as u32);
5637 Ok(Flow::Straight)
5638 }
5639 Op::Add { dst, lhs, rhs }
5645 if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5646 {
5647 lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintAdd)
5648 }
5649 Op::Sub { dst, lhs, rhs }
5650 if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5651 {
5652 lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintSub)
5653 }
5654 Op::Mul { dst, lhs, rhs }
5655 if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5656 {
5657 lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintMul)
5658 }
5659 Op::Div { dst, lhs, rhs }
5660 if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5661 {
5662 lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintDiv)
5663 }
5664 Op::Mod { dst, lhs, rhs }
5665 if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5666 {
5667 lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintMod)
5668 }
5669 Op::Add { dst, lhs, rhs }
5670 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Complex) =>
5671 {
5672 lower_complex_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ComplexAdd)
5673 }
5674 Op::Sub { dst, lhs, rhs }
5675 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Complex) =>
5676 {
5677 lower_complex_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ComplexSub)
5678 }
5679 Op::Mul { dst, lhs, rhs }
5680 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Complex) =>
5681 {
5682 lower_complex_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ComplexMul)
5683 }
5684 Op::Add { dst, lhs, rhs }
5685 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5686 {
5687 lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularAdd)
5688 }
5689 Op::Sub { dst, lhs, rhs }
5690 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5691 {
5692 lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularSub)
5693 }
5694 Op::Mul { dst, lhs, rhs }
5695 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5696 {
5697 lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularMul)
5698 }
5699 Op::Div { dst, lhs, rhs } | Op::ExactDiv { dst, lhs, rhs }
5700 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5701 {
5702 lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularDiv)
5703 }
5704 Op::Add { dst, lhs, rhs }
5705 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Decimal) =>
5706 {
5707 lower_decimal_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::DecimalAdd)
5708 }
5709 Op::Sub { dst, lhs, rhs }
5710 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Decimal) =>
5711 {
5712 lower_decimal_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::DecimalSub)
5713 }
5714 Op::Mul { dst, lhs, rhs }
5715 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Decimal) =>
5716 {
5717 lower_decimal_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::DecimalMul)
5718 }
5719 Op::Add { dst, lhs, rhs } if ctx.linked && kinds.get(dst as usize) == Some(Kind::Money) => {
5720 lower_money_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::MoneyAdd)
5721 }
5722 Op::Sub { dst, lhs, rhs } if ctx.linked && kinds.get(dst as usize) == Some(Kind::Money) => {
5723 lower_money_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::MoneySub)
5724 }
5725 Op::Add { dst, lhs, rhs }
5726 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5727 {
5728 lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantityAdd)
5729 }
5730 Op::Sub { dst, lhs, rhs }
5731 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5732 {
5733 lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantitySub)
5734 }
5735 Op::Mul { dst, lhs, rhs }
5736 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5737 {
5738 lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantityMul)
5739 }
5740 Op::Div { dst, lhs, rhs }
5741 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5742 {
5743 lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantityDiv)
5744 }
5745 Op::Add { dst, lhs, rhs }
5749 if ctx.linked
5750 && (kinds.get(lhs as usize) == Some(Kind::Span)
5751 || kinds.get(rhs as usize) == Some(Kind::Span)) =>
5752 {
5753 let (base, span) = if kinds.get(lhs as usize) == Some(Kind::Span) {
5754 (rhs, lhs)
5755 } else {
5756 (lhs, rhs)
5757 };
5758 let is_date = kinds.get(base as usize) == Some(Kind::Date);
5759 return lower_span_add(code, ctx, plan.num_regs, dst, base, span, is_date, false);
5760 }
5761 Op::Sub { dst, lhs, rhs } if ctx.linked && kinds.get(rhs as usize) == Some(Kind::Span) => {
5763 let is_date = kinds.get(lhs as usize) == Some(Kind::Date);
5764 return lower_span_add(code, ctx, plan.num_regs, dst, lhs, rhs, is_date, true);
5765 }
5766 Op::Add { dst, lhs, rhs } if ctx.linked && kinds.get(dst as usize) == Some(Kind::Lanes) => {
5768 let idx = (ctx.host_index)(HostFn::Lanes4Add)
5769 .ok_or(WasmLowerError::Unsupported("lanes4_add not imported"))?;
5770 local_get(code, lhs as u32);
5771 local_get(code, rhs as u32);
5772 code.push(0x10);
5773 leb_u32(code, idx);
5774 local_set(code, dst as u32);
5775 Ok(Flow::Straight)
5776 }
5777 Op::Add { dst, lhs, rhs }
5778 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5779 {
5780 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalAdd)
5781 }
5782 Op::Sub { dst, lhs, rhs }
5783 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5784 {
5785 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalSub)
5786 }
5787 Op::Mul { dst, lhs, rhs }
5788 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5789 {
5790 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalMul)
5791 }
5792 Op::Div { dst, lhs, rhs }
5793 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5794 {
5795 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalQuotient)
5796 }
5797 Op::Mod { dst, lhs, rhs }
5798 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5799 {
5800 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalRemainder)
5801 }
5802 Op::FloorDiv { dst, lhs, rhs }
5803 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5804 {
5805 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalFloorQuotient)
5806 }
5807 Op::Pow { dst, lhs, rhs }
5808 if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5809 {
5810 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalPower)
5811 }
5812 Op::BitXor { dst, lhs, rhs } | Op::BitAnd { dst, lhs, rhs } | Op::BitOr { dst, lhs, rhs }
5813 if ctx.linked
5814 && (kinds.get(lhs as usize) == Some(Kind::Rational)
5815 || kinds.get(rhs as usize) == Some(Kind::Rational)) =>
5816 {
5817 let which = match plan.ops[pc] {
5818 Op::BitAnd { .. } => 0,
5819 Op::BitOr { .. } => 1,
5820 _ => 2,
5821 };
5822 let idx = (ctx.host_index)(HostFn::RationalBitwise)
5823 .ok_or(WasmLowerError::Unsupported("rational_bitwise not imported"))?;
5824 push_rational_operand(code, kinds, ctx, lhs)?;
5825 push_rational_operand(code, kinds, ctx, rhs)?;
5826 i32_const(code, which);
5827 code.push(0x10);
5828 leb_u32(code, idx);
5829 local_set(code, dst as u32);
5830 Ok(Flow::Straight)
5831 }
5832 Op::Add { dst, lhs, rhs } => {
5833 if kinds.get(dst as usize) == Some(Kind::Text) {
5834 lower_concat(code, plan, ctx, dst, lhs, rhs)?;
5835 Ok(Flow::Straight)
5836 } else {
5837 lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Add)
5838 }
5839 }
5840 Op::Sub { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Sub),
5841 Op::Mul { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Mul),
5842 Op::Div { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Div),
5843 Op::FloorDiv { dst, lhs, rhs } => {
5844 lower_floordiv_regs(code, kinds, plan.num_regs, dst, lhs, rhs)
5845 }
5846 Op::Mod { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Mod),
5847 Op::Pow { dst, lhs, rhs } => lower_pow_regs(code, kinds, ctx, plan.num_regs, dst, lhs, rhs),
5851 Op::DivPow2 { dst, lhs, k } => {
5855 local_get(code, lhs as u32);
5856 code.push(0x42); leb_i64(code, 1i64 << k);
5858 code.push(0x7F); local_set(code, dst as u32);
5860 Ok(Flow::Straight)
5861 }
5862 Op::MagicDivU {
5865 dst,
5866 lhs,
5867 magic,
5868 more,
5869 mul_back,
5870 divisor: _,
5871 wrap: _,
5872 } => {
5873 lower_magic_div(code, plan.num_regs, dst, lhs, magic, more, mul_back);
5874 Ok(Flow::Straight)
5875 }
5876 Op::ExactDiv { dst, lhs, rhs } if ctx.linked => {
5880 lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalDiv)
5881 }
5882 Op::ExactDiv { dst, lhs, rhs } => {
5883 lower_exact_div(code, ctx, plan.num_regs, dst, lhs, rhs);
5884 Ok(Flow::Straight)
5885 }
5886 Op::RegionBoundsGuard { .. } => Ok(Flow::Straight),
5889 Op::AddAssign { dst, src } => {
5890 if kinds.get(dst as usize) == Some(Kind::Text) {
5891 let (a, b) = (plan.num_regs + 8, plan.num_regs + 9);
5892 local_get(code, dst as u32);
5893 local_set(code, a);
5894 display::emit_display_of(code, plan, ctx, src, b)?;
5895 emit_text_append(code, ctx, plan.num_regs, a, b, dst as u32);
5896 Ok(Flow::Straight)
5897 } else if ctx.linked && kinds.get(dst as usize) == Some(Kind::Lanes) {
5898 let idx = (ctx.host_index)(HostFn::Lanes4Add)
5900 .ok_or(WasmLowerError::Unsupported("lanes4_add not imported"))?;
5901 local_get(code, dst as u32);
5902 local_get(code, src as u32);
5903 code.push(0x10);
5904 leb_u32(code, idx);
5905 local_set(code, dst as u32);
5906 Ok(Flow::Straight)
5907 } else {
5908 lower_arith(code, ctx, kinds, dst, dst, src, ArithOp::Add)
5909 }
5910 }
5911 Op::BitXor { dst, lhs, rhs } => match kinds.get(lhs as usize) {
5916 Some(Kind::Int) | Some(Kind::Word64) => {
5917 arith(code, 0x85, dst, lhs, rhs); Ok(Flow::Straight)
5919 }
5920 Some(Kind::Word32) => {
5921 arith(code, 0x73, dst, lhs, rhs); Ok(Flow::Straight)
5923 }
5924 Some(Kind::Lanes) if ctx.linked => {
5926 let idx = (ctx.host_index)(HostFn::Lanes4Xor)
5927 .ok_or(WasmLowerError::Unsupported("lanes4_xor not imported"))?;
5928 local_get(code, lhs as u32);
5929 local_get(code, rhs as u32);
5930 code.push(0x10);
5931 leb_u32(code, idx);
5932 local_set(code, dst as u32);
5933 Ok(Flow::Straight)
5934 }
5935 _ => Err(WasmLowerError::Unsupported("`^` of a non-Int/Word value")),
5936 },
5937 Op::BitAnd { dst, lhs, rhs } => match kinds.get(lhs as usize) {
5938 Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Word64) => {
5939 arith(code, 0x83, dst, lhs, rhs); Ok(Flow::Straight)
5941 }
5942 Some(Kind::Word32) => {
5943 arith(code, 0x71, dst, lhs, rhs); Ok(Flow::Straight)
5945 }
5946 _ => Err(WasmLowerError::Unsupported(
5947 "`&` of a non-Int/Bool/Word value",
5948 )),
5949 },
5950 Op::BitOr { dst, lhs, rhs } => match kinds.get(lhs as usize) {
5951 Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Word64) => {
5952 arith(code, 0x84, dst, lhs, rhs); Ok(Flow::Straight)
5954 }
5955 Some(Kind::Word32) => {
5956 arith(code, 0x72, dst, lhs, rhs); Ok(Flow::Straight)
5958 }
5959 _ => Err(WasmLowerError::Unsupported(
5960 "`|` of a non-Int/Bool/Word value",
5961 )),
5962 },
5963 Op::Shl { dst, lhs, rhs } => {
5964 arith(code, 0x86, dst, lhs, rhs); Ok(Flow::Straight)
5966 }
5967 Op::Shr { dst, lhs, rhs } => {
5968 arith(code, 0x87, dst, lhs, rhs); Ok(Flow::Straight)
5970 }
5971 Op::Not { dst, src } => {
5972 match kinds.get(src as usize) {
5976 Some(Kind::Bool) | Some(Kind::Int) => {
5977 local_get(code, src as u32);
5978 code.push(0x50); code.push(0xAD); local_set(code, dst as u32);
5981 }
5982 _ => return Err(WasmLowerError::Unsupported("Not of a non-Int/Bool value")),
5983 }
5984 Ok(Flow::Straight)
5985 }
5986 Op::Lt { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Lt),
5987 Op::Gt { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Gt),
5988 Op::LtEq { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Le),
5989 Op::GtEq { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Ge),
5990 Op::ApproxEq { dst, lhs, rhs } => lower_approx_eq(code, kinds, dst, lhs, rhs),
5991 Op::Eq { dst, lhs, rhs } => {
5992 if kinds.get(lhs as usize) == Some(Kind::Text)
5993 && kinds.get(rhs as usize) == Some(Kind::Text)
5994 {
5995 lower_text_eq(code, ctx, plan.num_regs, dst, lhs, rhs, false);
5996 Ok(Flow::Straight)
5997 } else if ctx.linked
5998 && kinds.get(lhs as usize) == Some(Kind::Uuid)
5999 && kinds.get(rhs as usize) == Some(Kind::Uuid)
6000 {
6001 lower_uuid_eq(code, ctx, dst, lhs, rhs, false)
6002 } else {
6003 lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Eq)
6004 }
6005 }
6006 Op::NotEq { dst, lhs, rhs } => {
6007 if kinds.get(lhs as usize) == Some(Kind::Text)
6008 && kinds.get(rhs as usize) == Some(Kind::Text)
6009 {
6010 lower_text_eq(code, ctx, plan.num_regs, dst, lhs, rhs, true);
6011 Ok(Flow::Straight)
6012 } else if ctx.linked
6013 && kinds.get(lhs as usize) == Some(Kind::Uuid)
6014 && kinds.get(rhs as usize) == Some(Kind::Uuid)
6015 {
6016 lower_uuid_eq(code, ctx, dst, lhs, rhs, true)
6017 } else {
6018 lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Ne)
6019 }
6020 }
6021 Op::Jump { target } => {
6022 goto_block(code, plan.num_regs, blocks, k, blocks.block_of(target));
6023 Ok(Flow::Terminated)
6024 }
6025 Op::JumpIfFalse { cond, target } => {
6026 emit_cond_jump(
6027 code,
6028 cond,
6029 true,
6030 blocks.block_of(target),
6031 blocks.block_of(pc + 1),
6032 plan.num_regs,
6033 blocks.br_loop(k),
6034 );
6035 Ok(Flow::Terminated)
6036 }
6037 Op::JumpIfTrue { cond, target } => {
6038 emit_cond_jump(
6039 code,
6040 cond,
6041 false,
6042 blocks.block_of(target),
6043 blocks.block_of(pc + 1),
6044 plan.num_regs,
6045 blocks.br_loop(k),
6046 );
6047 Ok(Flow::Terminated)
6048 }
6049 Op::GlobalGet { dst, idx } => {
6050 code.push(0x23); leb_u32(code, idx as u32);
6052 local_set(code, dst as u32);
6053 let aliases = !plan.place.take.get(pc).copied().unwrap_or(false)
6057 && !plan.transient.get(dst as usize).copied().unwrap_or(false);
6058 if counts_aliases(kinds.get(dst as usize)) && aliases {
6059 emit_retain(code, ctx, dst);
6060 }
6061 Ok(Flow::Straight)
6062 }
6063 Op::LoadToday { dst } => {
6064 let idx = (ctx.host_index)(HostFn::Today)
6065 .ok_or(WasmLowerError::Unsupported("today not imported"))?;
6066 code.push(0x10); leb_u32(code, idx);
6068 local_set(code, dst as u32);
6069 Ok(Flow::Straight)
6070 }
6071 Op::NewEmptyListFixed { dst, capacity } => {
6077 emit_fixed_header(
6078 code,
6079 ctx,
6080 plan.num_regs,
6081 dst as u32,
6082 empty_collection_class(kinds.get(dst as usize)),
6083 capacity as u32,
6084 );
6085 Ok(Flow::Straight)
6086 }
6087 Op::NewEmptyListWithCapacity { dst, capacity } => {
6088 emit_capacity_header(
6089 code,
6090 ctx,
6091 plan.num_regs,
6092 dst as u32,
6093 capacity as u32,
6094 empty_collection_class(kinds.get(dst as usize)),
6095 8,
6096 );
6097 Ok(Flow::Straight)
6098 }
6099 Op::NewEmptyMapWithCapacity { dst, capacity } => {
6100 emit_capacity_header(
6101 code,
6102 ctx,
6103 plan.num_regs,
6104 dst as u32,
6105 capacity as u32,
6106 empty_collection_class(kinds.get(dst as usize)),
6107 16,
6108 );
6109 Ok(Flow::Straight)
6110 }
6111 Op::NewEmptyList { dst }
6112 | Op::NewEmptyListI32 { dst }
6113 | Op::NewEmptyMap { dst }
6114 | Op::NewEmptySet { dst } => {
6115 emit_empty_header(
6116 code,
6117 ctx,
6118 plan.num_regs,
6119 dst as u32,
6120 empty_collection_class(kinds.get(dst as usize)),
6121 );
6122 Ok(Flow::Straight)
6123 }
6124 Op::Length { dst, collection } => {
6126 local_get(code, collection as u32);
6127 i32_load(code, 0); code.push(0xAD); local_set(code, dst as u32);
6130 Ok(Flow::Straight)
6131 }
6132 Op::ListPush { list, value } => {
6133 emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, list)?;
6134 lower_list_push(code, kinds, ctx, plan.num_regs, list, value)?;
6135 if counts_aliases(kinds.get(value as usize)) {
6138 emit_retain(code, ctx, value);
6139 }
6140 if counted_kind(kinds.get(value as usize)) {
6145 emit_true_retain(code, ctx, value);
6146 }
6147 Ok(Flow::Straight)
6148 }
6149 Op::ListPushField { obj, field, src } => {
6150 let cow = plan.cow_inserts.get(pc).copied().unwrap_or(true);
6151 lower_list_push_field(code, plan, kinds, ctx, cow, obj, field, src)?;
6152 if counts_aliases(kinds.get(src as usize)) {
6153 emit_retain(code, ctx, src);
6154 }
6155 if counted_kind(kinds.get(src as usize)) {
6156 emit_true_retain(code, ctx, src);
6157 }
6158 Ok(Flow::Straight)
6159 }
6160 Op::ListPop { list, dst } => {
6161 emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, list)?;
6162 lower_list_pop(code, kinds, dst, list)?;
6163 if counted_kind(kinds.get(list as usize).and_then(Kind::seq_elem)) {
6166 emit_true_release(code, ctx, |c| local_get(c, dst as u32));
6167 }
6168 if counts_aliases(kinds.get(dst as usize)) {
6172 emit_retain(code, ctx, dst);
6173 }
6174 Ok(Flow::Straight)
6175 }
6176 Op::Index {
6180 dst,
6181 collection,
6182 index,
6183 }
6184 | Op::IndexUnchecked {
6185 dst,
6186 collection,
6187 index,
6188 } => {
6189 match kinds.get(collection as usize) {
6190 Some(Kind::Map) => {
6191 lower_map_get(code, kinds, ctx, plan.num_regs, dst, collection, index)?
6192 }
6193 Some(Kind::Text) => {
6194 lower_text_index(code, ctx, plan.num_regs, dst, collection, index)?
6195 }
6196 _ => lower_index(code, ctx, kinds, dst, collection, index)?,
6197 }
6198 let aliases = !plan.place.take.get(pc).copied().unwrap_or(false)
6202 && !plan.transient.get(dst as usize).copied().unwrap_or(false);
6203 if counts_aliases(kinds.get(dst as usize)) && aliases {
6204 emit_retain(code, ctx, dst);
6205 }
6206 Ok(Flow::Straight)
6207 }
6208 Op::SetIndex {
6211 collection,
6212 index,
6213 value,
6214 }
6215 | Op::SetIndexUnchecked {
6216 collection,
6217 index,
6218 value,
6219 } => {
6220 emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, collection)?;
6221 if kinds.get(collection as usize) == Some(Kind::Struct) {
6222 let cow = plan.cow_inserts.get(pc).copied().unwrap_or(true);
6223 lower_record_field_set(code, plan, kinds, ctx, pc, cow, collection, value)?;
6224 } else if plan.place.clear.get(pc).copied().unwrap_or(false) {
6225 return Ok(Flow::Straight);
6227 } else if kinds.get(collection as usize) == Some(Kind::Map) {
6228 lower_map_insert(code, kinds, ctx, plan.num_regs, collection, index, value)?;
6229 } else {
6230 lower_set_index(code, ctx, kinds, plan.num_regs, collection, index, value)?;
6231 }
6232 if plan.place.clear.get(pc).copied().unwrap_or(false) {
6234 return Ok(Flow::Straight);
6235 }
6236 if counts_aliases(kinds.get(value as usize))
6240 && !plan.place.put_back.get(pc).copied().unwrap_or(false)
6241 {
6242 emit_retain(code, ctx, value);
6243 }
6244 if counted_kind(kinds.get(value as usize)) {
6248 emit_true_retain(code, ctx, value);
6249 }
6250 Ok(Flow::Straight)
6251 }
6252 Op::NewRange { dst, start, end } => {
6253 if ctx.linked || !plan.range_loops.contains_key(&dst) {
6254 lower_new_range(code, ctx, plan.num_regs, dst, start, end);
6255 } else {
6256 lower_range_iter_prepare(code, ctx, plan.num_regs, start, end);
6260 }
6261 Ok(Flow::Straight)
6262 }
6263 Op::NewList { dst, start, count } => {
6267 lower_new_list(code, kinds, ctx, plan.num_regs, dst, start, count)?;
6268 Ok(Flow::Straight)
6269 }
6270 Op::NewTuple { dst, start, count } => {
6271 if kinds.get(dst as usize) == Some(Kind::Tuple) {
6272 lower_new_tuple_het(code, kinds, ctx, plan.num_regs, dst, start, count)?;
6273 for i in 0..count {
6275 if counted_kind(kinds.get((start + i) as usize)) {
6276 emit_true_retain(code, ctx, start + i);
6277 }
6278 }
6279 } else {
6280 lower_new_list(code, kinds, ctx, plan.num_regs, dst, start, count)?;
6281 }
6282 Ok(Flow::Straight)
6283 }
6284 Op::DestructureTuple { src, start, count } => {
6285 lower_destructure_tuple(code, kinds, src, start, count)?;
6286 Ok(Flow::Straight)
6287 }
6288 Op::IterPrepare { iterable } => {
6289 if ctx.linked || !plan.range_loops.contains_key(&iterable) {
6290 lower_iter_prepare(code, kinds, ctx, plan.num_regs, iterable)?;
6291 }
6292 Ok(Flow::Straight)
6293 }
6294 Op::IterNext { dst, exit } => {
6295 lower_iter_next(code, plan, ctx, blocks, k, dst, exit, pc)?;
6296 Ok(Flow::Terminated)
6297 }
6298 Op::SetAdd { set, value } => {
6299 emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, set)?;
6300 lower_set_add(code, kinds, ctx, plan.num_regs, set, value)?;
6301 Ok(Flow::Straight)
6302 }
6303 Op::RemoveFrom { collection, value } => {
6304 emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, collection)?;
6305 lower_remove_from(code, kinds, ctx, plan.num_regs, collection, value)?;
6306 Ok(Flow::Straight)
6307 }
6308 Op::UnionOp { dst, lhs, rhs } => {
6309 lower_union(code, kinds, ctx, plan.num_regs, dst, lhs, rhs)?;
6310 Ok(Flow::Straight)
6311 }
6312 Op::IntersectOp { dst, lhs, rhs } => {
6313 lower_intersect(code, kinds, ctx, plan.num_regs, dst, lhs, rhs)?;
6314 Ok(Flow::Straight)
6315 }
6316 Op::Contains {
6317 dst,
6318 collection,
6319 value,
6320 } => {
6321 if kinds.get(collection as usize) == Some(Kind::Map) {
6322 lower_map_contains(code, kinds, ctx, plan.num_regs, dst, collection, value)?;
6323 } else {
6324 lower_contains(code, kinds, ctx, plan.num_regs, dst, collection, value)?;
6325 }
6326 Ok(Flow::Straight)
6327 }
6328 Op::SliceOp {
6329 dst,
6330 collection,
6331 start,
6332 end,
6333 } => {
6334 lower_slice(code, kinds, ctx, plan.num_regs, dst, collection, start, end)?;
6335 Ok(Flow::Straight)
6336 }
6337 Op::SeqConcat { dst, lhs, rhs } => {
6338 lower_seq_concat(code, kinds, ctx, plan.num_regs, dst, lhs, rhs)?;
6339 Ok(Flow::Straight)
6340 }
6341 Op::Concat { dst, lhs, rhs } => {
6342 let folds = pc > 0
6359 && !blocks.is_leader(pc)
6360 && matches!(
6361 plan.ops.get(pc - 1),
6362 Some(Op::LoadConst { dst: d, idx })
6363 if *d == lhs
6364 && matches!(
6365 ctx.constants.get(*idx as usize),
6366 Some(Constant::Text(t)) if t.is_empty()
6367 )
6368 );
6369 if folds {
6370 display::emit_display_of(code, plan, ctx, rhs, dst as u32)?;
6371 return Ok(Flow::Straight);
6372 }
6373 lower_concat(code, plan, ctx, dst, lhs, rhs)?;
6374 Ok(Flow::Straight)
6375 }
6376 Op::FormatValue {
6377 dst,
6378 src,
6379 spec,
6380 debug_prefix,
6381 } => {
6382 lower_format_value(code, plan, ctx, dst, src, spec, debug_prefix)?;
6383 Ok(Flow::Straight)
6384 }
6385 Op::DeepClone { dst, src } => {
6386 lower_deep_clone(code, kinds, &plan.structs, ctx, plan.num_regs, dst, src)?;
6387 Ok(Flow::Straight)
6388 }
6389 Op::CallBuiltin {
6392 dst,
6393 builtin: BuiltinId::Copy,
6394 args_start,
6395 ..
6396 } => {
6397 lower_deep_clone(
6398 code,
6399 kinds,
6400 &plan.structs,
6401 ctx,
6402 plan.num_regs,
6403 dst,
6404 args_start,
6405 )?;
6406 Ok(Flow::Straight)
6407 }
6408 Op::NewStruct { dst, .. } => {
6409 let count = plan.structs.count.get(pc).copied().flatten().unwrap_or(0);
6410 lower_new_struct(code, ctx, plan.num_regs, count, dst);
6411 Ok(Flow::Straight)
6412 }
6413 Op::StructInsert { obj, value, .. } => {
6414 let slot =
6415 plan.structs
6416 .slot
6417 .get(pc)
6418 .copied()
6419 .flatten()
6420 .ok_or(WasmLowerError::Unsupported(
6421 "struct insert with no static slot",
6422 ))?;
6423 let cow = plan.cow_inserts.get(pc).copied().unwrap_or(true);
6424 let held = tower::field_value(code, plan, ctx, obj, usize::from(slot), value)?;
6425 lower_struct_insert(
6426 code,
6427 kinds,
6428 &plan.structs,
6429 ctx,
6430 plan.num_regs,
6431 slot,
6432 obj,
6433 value,
6434 cow,
6435 held,
6436 )?;
6437 if counts_aliases(kinds.get(value as usize)) {
6440 emit_retain(code, ctx, value);
6441 }
6442 if counted_kind(kinds.get(value as usize)) {
6445 emit_true_retain(code, ctx, value);
6446 }
6447 Ok(Flow::Straight)
6448 }
6449 Op::GetField { dst, obj, field } => {
6450 if plan.structs.slot.get(pc).copied().flatten().is_none()
6453 && std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some()
6454 {
6455 let name = match ctx.constants.get(field as usize) {
6456 Some(Constant::Text(t)) => t.clone(),
6457 other => format!("{other:?}"),
6458 };
6459 eprintln!(
6460 "[wasm] unresolved field access: '{name}' (pc {pc}, obj reg {obj}, kind {:?})",
6461 kinds.get(obj as usize)
6462 );
6463 }
6464 let slot =
6465 plan.structs
6466 .slot
6467 .get(pc)
6468 .copied()
6469 .flatten()
6470 .ok_or(WasmLowerError::Unsupported(
6471 "field access with no static slot",
6472 ))?;
6473 let is_counter = plan
6476 .structs
6477 .field_value
6478 .get(pc)
6479 .copied()
6480 .flatten()
6481 .map_or(false, |vr| {
6482 kinds.get(vr as usize) == Some(Kind::CrdtCounter)
6483 });
6484 if is_counter {
6485 lower_get_counter_total(code, plan, slot, dst, obj)?;
6486 } else {
6487 lower_get_field(code, kinds, slot, dst, obj)?;
6488 let aliases = !plan.place.take.get(pc).copied().unwrap_or(false)
6492 && !plan.transient.get(dst as usize).copied().unwrap_or(false);
6493 if counts_aliases(kinds.get(dst as usize)) && aliases {
6494 emit_retain(code, ctx, dst);
6495 }
6496 }
6497 Ok(Flow::Straight)
6498 }
6499 Op::CheckPolicy {
6500 subject,
6501 predicate,
6502 is_capability,
6503 object,
6504 ..
6505 } => {
6506 lower_check_policy(code, plan, ctx, subject, predicate, is_capability, object)?;
6507 Ok(Flow::Straight)
6508 }
6509 Op::CrdtBump {
6510 obj,
6511 field,
6512 amount,
6513 negate,
6514 } => {
6515 lower_crdt_bump(code, plan, ctx, obj, field, amount, negate)?;
6516 Ok(Flow::Straight)
6517 }
6518 Op::CrdtMerge { target, source } | Op::CrdtJoin { target, source } => {
6523 lower_crdt_merge(code, plan, ctx, target, source)?;
6524 Ok(Flow::Straight)
6525 }
6526 Op::NewCrdt { dst, kind } => {
6527 match kind {
6532 0 | 1 | 3 => emit_empty_header(
6533 code,
6534 ctx,
6535 plan.num_regs,
6536 dst as u32,
6537 empty_collection_class(kinds.get(dst as usize)),
6538 ),
6539 2 => {
6540 lower_text_literal(code, ctx, plan.num_regs, b"");
6541 local_set(code, dst as u32);
6542 }
6543 4 | 5 => emit_new_counter(code, ctx, plan.num_regs, dst as u32),
6547 6 => {
6548 emit_empty_header(
6551 code,
6552 ctx,
6553 plan.num_regs,
6554 dst as u32,
6555 AllocClass::MapScalarScalar,
6556 );
6557 local_get(code, dst as u32);
6558 i32_const(
6559 code,
6560 SHARED_MAP_MARK | i32::from(AllocClass::MapScalarScalar.code()),
6561 );
6562 i32_store(code, 12);
6563 }
6564 _ => {
6565 return Err(WasmLowerError::Unsupported(
6566 "a CRDT kind this backend does not know",
6567 ))
6568 }
6569 }
6570 Ok(Flow::Straight)
6571 }
6572 Op::CrdtResolve { obj, field, value } => {
6573 lower_crdt_resolve(code, plan, kinds, obj, field, value)?;
6574 Ok(Flow::Straight)
6575 }
6576 Op::CrdtAppend { seq, value } => {
6577 lower_crdt_append(code, plan, kinds, ctx, seq, value)?;
6578 Ok(Flow::Straight)
6579 }
6580 Op::ChanNew { dst, .. } => {
6585 emit_empty_header(
6586 code,
6587 ctx,
6588 plan.num_regs,
6589 dst as u32,
6590 empty_collection_class(kinds.get(dst as usize)),
6591 );
6592 Ok(Flow::Straight)
6593 }
6594 Op::ChanSend { chan, val } => {
6595 lower_list_push(code, kinds, ctx, plan.num_regs, chan, val)?;
6596 if counted_kind(kinds.get(val as usize)) {
6598 emit_true_retain(code, ctx, val);
6599 }
6600 Ok(Flow::Straight)
6601 }
6602 Op::ChanRecv { dst, chan } => {
6603 lower_chan_recv(code, kinds, plan.num_regs, dst, chan)?;
6604 if counted_kind(kinds.get(chan as usize).and_then(Kind::seq_elem)) {
6606 emit_true_release(code, ctx, |c| local_get(c, dst as u32));
6607 }
6608 Ok(Flow::Straight)
6609 }
6610 Op::ChanTryRecv { dst, chan } => {
6614 lower_chan_try_recv(code, kinds, ctx, plan.num_regs, dst, chan)?;
6615 Ok(Flow::Straight)
6616 }
6617 Op::ChanTrySend { dst, chan, val } => {
6621 lower_list_push(code, kinds, ctx, plan.num_regs, chan, val)?;
6622 if counted_kind(kinds.get(val as usize)) {
6623 emit_true_retain(code, ctx, val);
6624 }
6625 code.push(0x42); leb_i64(code, 1);
6627 local_set(code, dst as u32);
6628 Ok(Flow::Straight)
6629 }
6630 Op::ChanClose { .. } => Ok(Flow::Straight),
6634 Op::Spawn {
6638 func,
6639 args_start,
6640 arg_count,
6641 } => {
6642 if emit_sync_call(code, plan, ctx, func, args_start, arg_count)? {
6643 code.push(0x1A); }
6645 Ok(Flow::Straight)
6646 }
6647 Op::SpawnHandle {
6648 dst,
6649 func,
6650 args_start,
6651 arg_count,
6652 } => {
6653 if emit_sync_call(code, plan, ctx, func, args_start, arg_count)? {
6654 code.push(0x1A); }
6656 code.push(0x42); leb_i64(code, 0);
6658 local_set(code, dst as u32);
6659 Ok(Flow::Straight)
6660 }
6661 Op::TaskAbort { .. } => Ok(Flow::Straight),
6663 Op::TaskAwait { dst, handle } => {
6668 local_get(code, handle as u32);
6669 local_set(code, dst as u32);
6670 Ok(Flow::Straight)
6671 }
6672 Op::Sleep { .. } => Ok(Flow::Straight),
6676 Op::SelectArmRecv { .. } | Op::SelectArmTimeout { .. } => Ok(Flow::Straight),
6683 Op::SelectWait { dst_arm } => {
6684 lower_select_wait(code, plan, kinds, blocks, k, pc, dst_arm)?;
6685 Ok(Flow::Straight)
6686 }
6687 Op::NetConnect { .. } | Op::NetSync { .. } => Ok(Flow::Straight),
6694 Op::NetListen { .. } => {
6695 emit_empty_header(code, ctx, plan.num_regs, plan.num_regs + 8, AllocClass::Raw);
6699 i32_const(code, NET_INBOX_ADDR);
6700 local_get(code, plan.num_regs + 8);
6701 i32_store(code, 0);
6702 Ok(Flow::Straight)
6703 }
6704 Op::NetSend { msg, .. } => {
6705 let elem = kinds.get(msg as usize).ok_or(WasmLowerError::Unsupported(
6706 "Send of an unknown-kind message",
6707 ))?;
6708 i32_const(code, NET_INBOX_ADDR);
6709 i32_load(code, 0);
6710 local_set(code, plan.num_regs + 8);
6711 lower_list_push_at(code, elem, ctx, plan.num_regs, plan.num_regs + 8, msg)?;
6712 if counts_aliases(kinds.get(msg as usize)) {
6713 emit_retain(code, ctx, msg);
6714 }
6715 if counted_kind(kinds.get(msg as usize)) {
6717 emit_true_retain(code, ctx, msg);
6718 }
6719 Ok(Flow::Straight)
6720 }
6721 Op::NetStream { values, .. } => {
6722 let elem = kinds
6725 .get(values as usize)
6726 .ok_or(WasmLowerError::Unsupported(
6727 "Stream of an unknown-kind list",
6728 ))?;
6729 i32_const(code, NET_INBOX_ADDR);
6730 i32_load(code, 0);
6731 local_set(code, plan.num_regs + 8);
6732 lower_list_push_at(code, elem, ctx, plan.num_regs, plan.num_regs + 8, values)?;
6733 if counts_aliases(kinds.get(values as usize)) {
6734 emit_retain(code, ctx, values);
6735 }
6736 if counted_kind(kinds.get(values as usize)) {
6737 emit_true_retain(code, ctx, values);
6738 }
6739 Ok(Flow::Straight)
6740 }
6741 Op::NetAwait { dst, .. } => {
6742 let elem = kinds.get(dst as usize).ok_or(WasmLowerError::Unsupported(
6743 "Await of an unknown-kind message",
6744 ))?;
6745 i32_const(code, NET_INBOX_ADDR);
6746 i32_load(code, 0);
6747 local_set(code, plan.num_regs + 8);
6748 emit_pop_front(code, elem, plan.num_regs + 8, plan.num_regs + 5, dst as u32)?;
6749 if counts_aliases(kinds.get(dst as usize)) {
6750 emit_retain(code, ctx, dst);
6751 }
6752 Ok(Flow::Straight)
6753 }
6754 Op::NetMakePeer { dst, addr } => {
6755 local_get(code, addr as u32);
6756 local_set(code, dst as u32);
6757 Ok(Flow::Straight)
6758 }
6759 Op::NewInductive {
6760 dst,
6761 ctor,
6762 args_start,
6763 count,
6764 ..
6765 } => {
6766 lower_new_inductive(
6767 code,
6768 kinds,
6769 ctx,
6770 plan.num_regs,
6771 dst,
6772 ctor,
6773 args_start,
6774 count,
6775 )?;
6776 for i in 0..count {
6778 if counted_kind(kinds.get((args_start + i) as usize)) {
6779 emit_true_retain(code, ctx, args_start + i);
6780 }
6781 }
6782 Ok(Flow::Straight)
6783 }
6784 Op::TestArm {
6785 dst,
6786 target,
6787 variant,
6788 } => {
6789 lower_test_arm(code, kinds, ctx, dst, target, variant)?;
6790 Ok(Flow::Straight)
6791 }
6792 Op::BindArm {
6793 dst, target, index, ..
6794 } => {
6795 lower_bind_arm(code, kinds, ctx, dst, target, index)?;
6796 Ok(Flow::Straight)
6797 }
6798 Op::MakeClosure {
6799 dst,
6800 func,
6801 locals_start,
6802 } => {
6803 lower_make_closure(code, ctx, plan.num_regs, dst, func, locals_start)?;
6804 Ok(Flow::Straight)
6805 }
6806 Op::CallValue {
6807 dst,
6808 callee,
6809 args_start,
6810 arg_count,
6811 ..
6812 } => {
6813 for a in 0..arg_count {
6816 let arg = args_start + a;
6817 if counts_aliases(kinds.get(arg as usize)) {
6818 emit_retain(code, ctx, arg);
6819 }
6820 }
6821 lower_call_value(code, plan, ctx, pc, dst, callee, args_start, arg_count)?;
6822 Ok(Flow::Straight)
6823 }
6824 Op::IterPop => {
6825 global_get(code, ctx.iter_global);
6827 i32_load(code, FRAME_PREV);
6828 if let Some(unwind) = ctx.runtime.and_then(|r| r.index(RuntimeFn::IterUnwind)) {
6829 code.push(0x10);
6830 leb_u32(code, unwind);
6831 } else {
6832 global_set(code, ctx.iter_global);
6833 }
6834 Ok(Flow::Straight)
6835 }
6836 Op::LoadNow { dst } => {
6837 let idx = (ctx.host_index)(HostFn::Now)
6838 .ok_or(WasmLowerError::Unsupported("now not imported"))?;
6839 code.push(0x10); leb_u32(code, idx);
6841 local_set(code, dst as u32);
6842 Ok(Flow::Straight)
6843 }
6844 Op::GlobalSet { idx, src } => {
6845 let want = ctx
6854 .global_valtypes
6855 .get(idx as usize)
6856 .copied()
6857 .unwrap_or(I64);
6858 if kinds.valtype(src as usize) != want {
6859 if want == I32 {
6860 if !plan.place.clear.get(pc).copied().unwrap_or(false) {
6861 code.push(0x23); leb_u32(code, idx as u32);
6865 i32_const(code, 0);
6866 code.push(0x47); code.push(0x04); code.push(0x40); code.push(0x23);
6870 leb_u32(code, idx as u32);
6871 code.push(0x23);
6872 leb_u32(code, idx as u32);
6873 i32_load(code, 12);
6874 i32_const(code, 0x100); code.push(0x6B); i32_store(code, 12);
6877 code.push(0x0B); }
6879 emit_true_release(code, ctx, |c| {
6880 c.push(0x23); leb_u32(c, idx as u32);
6882 });
6883 i32_const(code, 0);
6884 } else if want == F64 {
6885 code.push(0x44);
6886 code.extend_from_slice(&0f64.to_le_bytes());
6887 } else {
6888 code.push(0x42); code.push(0x00);
6890 }
6891 code.push(0x24); leb_u32(code, idx as u32);
6893 return Ok(Flow::Straight);
6894 }
6895 if counts_aliases(kinds.get(src as usize))
6899 && !plan.place.put_back.get(pc).copied().unwrap_or(false)
6900 {
6901 emit_retain(code, ctx, src);
6902 }
6903 if want == I32 && counted_kind(kinds.get(src as usize)) {
6908 emit_true_release(code, ctx, |c| {
6909 c.push(0x23);
6910 leb_u32(c, idx as u32);
6911 });
6912 }
6913 local_get(code, src as u32);
6914 code.push(0x24); leb_u32(code, idx as u32);
6916 if counted_kind(kinds.get(src as usize)) {
6917 emit_true_retain(code, ctx, src);
6918 }
6919 Ok(Flow::Straight)
6920 }
6921 Op::Call {
6922 dst,
6923 func,
6924 args_start,
6925 arg_count,
6926 } => {
6927 if ctx.fn_stubbed.get(func as usize).copied().unwrap_or(false) {
6928 code.push(0x00); return Ok(Flow::Straight);
6930 }
6931 let inout = ctx.fn_inout.get(func as usize).cloned().unwrap_or_default();
6936 for a in 0..arg_count {
6937 let arg = args_start + a;
6938 if shares_argument(plan, ctx, func, a, arg) && !inout.contains(&a) {
6939 emit_retain(code, ctx, arg);
6940 }
6941 }
6942 let pvts = ctx
6943 .fn_param_valtypes
6944 .get(func as usize)
6945 .ok_or(WasmLowerError::Unsupported("call of unknown function"))?;
6946 for a in 0..arg_count {
6947 push_call_argument(code, plan, ctx, func, a, args_start + a)?;
6948 }
6949 code.push(0x10); leb_u32(code, ctx.fn_base + func as u32);
6951 for p in inout.iter().rev() {
6954 let arg = args_start + p;
6955 if kinds.valtype(arg as usize) != pvts.get(*p as usize).copied().unwrap_or(I64) {
6956 return Err(WasmLowerError::Unsupported(
6957 "a `mutable` argument of another type than its parameter",
6958 ));
6959 }
6960 local_set(code, arg as u32);
6961 }
6962 if ctx
6964 .fn_results
6965 .get(func as usize)
6966 .copied()
6967 .flatten()
6968 .is_some()
6969 {
6970 local_set(code, dst as u32);
6971 }
6972 Ok(Flow::Straight)
6973 }
6974 Op::CallBuiltin {
6975 dst,
6976 builtin: BuiltinId::Pow,
6977 args_start,
6978 arg_count,
6979 } => lower_pow(code, kinds, ctx, plan.num_regs, dst, args_start, arg_count),
6980 Op::CallBuiltin {
6982 dst,
6983 builtin: BuiltinId::ParseInt,
6984 args_start,
6985 ..
6986 } => {
6987 let idx = (ctx.host_index)(HostFn::ParseInt)
6988 .ok_or(WasmLowerError::Unsupported("parse_int host not imported"))?;
6989 local_get(code, args_start as u32);
6990 code.push(0x10); leb_u32(code, idx);
6992 local_set(code, dst as u32);
6993 Ok(Flow::Straight)
6994 }
6995 Op::CallBuiltin {
6997 dst,
6998 builtin: BuiltinId::Contains,
6999 args_start,
7000 ..
7001 } => lower_dom_call(code, ctx, dst, HostFn::TextContains, args_start, 2, true),
7002 Op::CallBuiltin {
7006 dst,
7007 builtin: BuiltinId::DomBody,
7008 ..
7009 } => lower_dom_call(code, ctx, dst, HostFn::DomBody, 0, 0, true),
7010 Op::CallBuiltin {
7011 dst,
7012 builtin: BuiltinId::DomCreateElement,
7013 args_start,
7014 ..
7015 } => lower_dom_call(
7016 code,
7017 ctx,
7018 dst,
7019 HostFn::DomCreateElement,
7020 args_start,
7021 1,
7022 true,
7023 ),
7024 Op::CallBuiltin {
7025 dst,
7026 builtin: BuiltinId::DomCreateTextNode,
7027 args_start,
7028 ..
7029 } => lower_dom_call(
7030 code,
7031 ctx,
7032 dst,
7033 HostFn::DomCreateTextNode,
7034 args_start,
7035 1,
7036 true,
7037 ),
7038 Op::CallBuiltin {
7039 dst,
7040 builtin: BuiltinId::DomQuerySelector,
7041 args_start,
7042 ..
7043 } => lower_dom_call(
7044 code,
7045 ctx,
7046 dst,
7047 HostFn::DomQuerySelector,
7048 args_start,
7049 1,
7050 true,
7051 ),
7052 Op::CallBuiltin {
7053 dst,
7054 builtin: BuiltinId::DomGetText,
7055 args_start,
7056 ..
7057 } => lower_dom_call(code, ctx, dst, HostFn::DomGetText, args_start, 1, true),
7058 Op::CallBuiltin {
7059 dst,
7060 builtin: BuiltinId::DomGetValue,
7061 args_start,
7062 ..
7063 } => lower_dom_call(code, ctx, dst, HostFn::DomGetValue, args_start, 1, true),
7064 Op::CallBuiltin {
7065 dst,
7066 builtin: BuiltinId::DomSetText,
7067 args_start,
7068 ..
7069 } => lower_dom_call(code, ctx, dst, HostFn::DomSetText, args_start, 2, false),
7070 Op::CallBuiltin {
7071 dst,
7072 builtin: BuiltinId::DomSetHtml,
7073 args_start,
7074 ..
7075 } => lower_dom_call(code, ctx, dst, HostFn::DomSetHtml, args_start, 2, false),
7076 Op::CallBuiltin {
7077 dst,
7078 builtin: BuiltinId::DomClearChildren,
7079 args_start,
7080 ..
7081 } => lower_dom_call(
7082 code,
7083 ctx,
7084 dst,
7085 HostFn::DomClearChildren,
7086 args_start,
7087 1,
7088 false,
7089 ),
7090 Op::CallBuiltin {
7091 dst,
7092 builtin: BuiltinId::DomOnMessage,
7093 args_start,
7094 ..
7095 } => lower_dom_call(code, ctx, dst, HostFn::DomOnMessage, args_start, 2, false),
7096 Op::CallBuiltin {
7099 builtin: BuiltinId::DomBeginPaint,
7100 ..
7101 } => Err(WasmLowerError::Unsupported("beginPaint is retired")),
7102 Op::CallBuiltin {
7103 builtin: BuiltinId::DomMoveChildren,
7104 ..
7105 } => Err(WasmLowerError::Unsupported("moveChildren is retired")),
7106 Op::CallBuiltin {
7107 dst,
7108 builtin: BuiltinId::DomAppendChild,
7109 args_start,
7110 ..
7111 } => lower_dom_call(code, ctx, dst, HostFn::DomAppendChild, args_start, 2, false),
7112 Op::CallBuiltin {
7113 dst,
7114 builtin: BuiltinId::DomSetValue,
7115 args_start,
7116 ..
7117 } => lower_dom_call(code, ctx, dst, HostFn::DomSetValue, args_start, 2, false),
7118 Op::CallBuiltin {
7119 dst,
7120 builtin: BuiltinId::DomSetChecked,
7121 args_start,
7122 ..
7123 } => lower_dom_call(code, ctx, dst, HostFn::DomSetChecked, args_start, 2, false),
7124 Op::CallBuiltin {
7125 dst,
7126 builtin: BuiltinId::DomPreventDefault,
7127 args_start,
7128 ..
7129 } => lower_dom_call(
7130 code,
7131 ctx,
7132 dst,
7133 HostFn::DomPreventDefault,
7134 args_start,
7135 2,
7136 false,
7137 ),
7138 Op::CallBuiltin {
7139 dst,
7140 builtin: BuiltinId::StorageSet,
7141 args_start,
7142 ..
7143 } => lower_dom_call(code, ctx, dst, HostFn::StorageSet, args_start, 3, false),
7144 Op::CallBuiltin {
7145 dst,
7146 builtin: BuiltinId::StorageRemove,
7147 args_start,
7148 ..
7149 } => lower_dom_call(code, ctx, dst, HostFn::StorageRemove, args_start, 2, false),
7150 Op::CallBuiltin {
7151 dst,
7152 builtin: BuiltinId::StorageGet,
7153 args_start,
7154 ..
7155 } => lower_storage_get(code, ctx, plan.num_regs, dst, args_start),
7156 Op::CallBuiltin {
7157 dst,
7158 builtin: BuiltinId::StorageGetOr,
7159 args_start,
7160 ..
7161 } => lower_storage_get_or(code, ctx, plan.num_regs, dst, args_start),
7162 Op::CallBuiltin {
7163 dst,
7164 builtin: BuiltinId::DomApplyPatches,
7165 args_start,
7166 ..
7167 } => lower_dom_call(code, ctx, dst, HostFn::DomApply, args_start, 1, false),
7168 Op::CallBuiltin {
7169 dst,
7170 builtin: BuiltinId::DomApplyWords,
7171 args_start,
7172 ..
7173 } => lower_dom_call(code, ctx, dst, HostFn::DomApplyWords, args_start, 4, true),
7174 Op::CallBuiltin {
7175 dst,
7176 builtin: BuiltinId::DomSetAttribute,
7177 args_start,
7178 ..
7179 } => {
7180 let host = if kinds.get(args_start as usize + 2) == Some(Kind::Bool) {
7185 HostFn::DomSetBoolAttribute
7186 } else {
7187 HostFn::DomSetAttribute
7188 };
7189 lower_dom_call(code, ctx, dst, host, args_start, 3, false)
7190 }
7191 Op::CallBuiltin {
7192 dst,
7193 builtin: BuiltinId::DomAddEventListener,
7194 args_start,
7195 ..
7196 } => lower_dom_call(
7197 code,
7198 ctx,
7199 dst,
7200 HostFn::DomAddEventListener,
7201 args_start,
7202 3,
7203 false,
7204 ),
7205 Op::CallBuiltin {
7206 dst,
7207 builtin: BuiltinId::DomListenFlags,
7208 args_start,
7209 ..
7210 } => lower_dom_call(code, ctx, dst, HostFn::DomListenFlags, args_start, 3, false),
7211 Op::CallBuiltin {
7212 dst,
7213 builtin: BuiltinId::DomEnterValue,
7214 args_start,
7215 ..
7216 } => lower_dom_call(code, ctx, dst, HostFn::DomEnterValue, args_start, 3, true),
7217 Op::CallBuiltin {
7218 dst,
7219 builtin: BuiltinId::DomDispatchEntry,
7220 args_start,
7221 ..
7222 } => lower_dispatch_entry(code, ctx, plan.num_regs, dst, args_start),
7223 Op::CallBuiltin {
7224 dst,
7225 builtin: BuiltinId::DomEventValue,
7226 args_start,
7227 ..
7228 } => lower_dom_call(code, ctx, dst, HostFn::DomEventValue, args_start, 1, true),
7229 Op::CallBuiltin {
7230 dst,
7231 builtin: BuiltinId::DomEventKey,
7232 args_start,
7233 ..
7234 } => lower_dom_call(code, ctx, dst, HostFn::DomEventKey, args_start, 1, true),
7235 Op::CallBuiltin {
7236 dst,
7237 builtin: BuiltinId::DomEventTarget,
7238 args_start,
7239 ..
7240 } => lower_dom_call(code, ctx, dst, HostFn::DomEventTarget, args_start, 1, true),
7241 Op::CallBuiltin {
7242 dst,
7243 builtin: BuiltinId::DomFetchText,
7244 args_start,
7245 ..
7246 } => lower_dom_call(code, ctx, dst, HostFn::DomFetchStart, args_start, 2, false),
7247 Op::CallBuiltin {
7248 dst,
7249 builtin: BuiltinId::DomResponseText,
7250 ..
7251 } => lower_dom_call(code, ctx, dst, HostFn::DomResponseText, 0, 0, true),
7252 Op::CallBuiltin {
7254 dst,
7255 builtin: BuiltinId::DomFetchSend,
7256 args_start,
7257 ..
7258 } => lower_dom_call(code, ctx, dst, HostFn::DomFetchSend, args_start, 5, true),
7259 Op::CallBuiltin {
7260 dst,
7261 builtin: BuiltinId::DomResponseStatus,
7262 args_start,
7263 ..
7264 } => lower_dom_call(
7265 code,
7266 ctx,
7267 dst,
7268 HostFn::DomResponseStatus,
7269 args_start,
7270 1,
7271 true,
7272 ),
7273 Op::CallBuiltin {
7274 dst,
7275 builtin: BuiltinId::DomResponseBody,
7276 args_start,
7277 ..
7278 } => lower_dom_call(code, ctx, dst, HostFn::DomResponseBody, args_start, 1, true),
7279 Op::CallBuiltin {
7280 dst,
7281 builtin: BuiltinId::DomResponseHeader,
7282 args_start,
7283 ..
7284 } => lower_dom_call(
7285 code,
7286 ctx,
7287 dst,
7288 HostFn::DomResponseHeader,
7289 args_start,
7290 2,
7291 true,
7292 ),
7293 Op::CallBuiltin {
7294 dst,
7295 builtin: BuiltinId::DomResponseError,
7296 args_start,
7297 ..
7298 } => lower_dom_call(
7299 code,
7300 ctx,
7301 dst,
7302 HostFn::DomResponseError,
7303 args_start,
7304 1,
7305 true,
7306 ),
7307 Op::CallBuiltin {
7308 dst,
7309 builtin: BuiltinId::DomFetchAbort,
7310 args_start,
7311 ..
7312 } => lower_dom_call(code, ctx, dst, HostFn::DomFetchAbort, args_start, 1, false),
7313 Op::CallBuiltin {
7314 dst,
7315 builtin: BuiltinId::DomFetchSetTimeout,
7316 args_start,
7317 ..
7318 } => lower_dom_call(
7319 code,
7320 ctx,
7321 dst,
7322 HostFn::DomFetchSetTimeout,
7323 args_start,
7324 2,
7325 false,
7326 ),
7327 Op::CallBuiltin {
7330 dst,
7331 builtin: BuiltinId::DomRoutePath,
7332 ..
7333 } => lower_dom_call(code, ctx, dst, HostFn::DomRoutePath, 0, 0, true),
7334 Op::CallBuiltin {
7335 dst,
7336 builtin: BuiltinId::DomRouteQuery,
7337 args_start,
7338 ..
7339 } => lower_dom_call(code, ctx, dst, HostFn::DomRouteQuery, args_start, 1, true),
7340 Op::CallBuiltin {
7341 dst,
7342 builtin: BuiltinId::DomNavigate,
7343 args_start,
7344 ..
7345 } => lower_dom_call(code, ctx, dst, HostFn::DomNavigate, args_start, 1, false),
7346 Op::CallBuiltin {
7347 dst,
7348 builtin: BuiltinId::DomAssignLocation,
7349 args_start,
7350 ..
7351 } => lower_dom_call(
7352 code,
7353 ctx,
7354 dst,
7355 HostFn::DomAssignLocation,
7356 args_start,
7357 1,
7358 false,
7359 ),
7360 Op::CallBuiltin {
7363 dst,
7364 builtin: BuiltinId::DomSetTitle,
7365 args_start,
7366 ..
7367 } => lower_dom_call(code, ctx, dst, HostFn::DomSetTitle, args_start, 1, false),
7368 Op::CallBuiltin {
7369 dst,
7370 builtin: BuiltinId::DomSetHeadHtml,
7371 args_start,
7372 ..
7373 } => lower_dom_call(code, ctx, dst, HostFn::DomSetHeadHtml, args_start, 1, false),
7374 Op::CallBuiltin {
7375 dst,
7376 builtin: BuiltinId::DomReload,
7377 args_start,
7378 ..
7379 } => lower_dom_call(code, ctx, dst, HostFn::DomReload, args_start, 0, false),
7380 Op::CallBuiltin {
7381 dst,
7382 builtin: BuiltinId::DomGoBack,
7383 args_start,
7384 ..
7385 } => lower_dom_call(code, ctx, dst, HostFn::DomGoBack, args_start, 0, false),
7386 Op::CallBuiltin {
7389 dst,
7390 builtin: BuiltinId::DomGetAttribute,
7391 args_start,
7392 ..
7393 } => lower_dom_call(code, ctx, dst, HostFn::DomGetAttribute, args_start, 2, true),
7394 Op::CallBuiltin {
7395 dst,
7396 builtin: BuiltinId::DomOnWindowEvent,
7397 args_start,
7398 ..
7399 } => lower_dom_call(
7400 code,
7401 ctx,
7402 dst,
7403 HostFn::DomOnWindowEvent,
7404 args_start,
7405 2,
7406 false,
7407 ),
7408 Op::CallBuiltin {
7409 dst,
7410 builtin: BuiltinId::DomScrollGap,
7411 args_start,
7412 ..
7413 } => lower_dom_call(code, ctx, dst, HostFn::DomScrollGap, args_start, 1, true),
7414 Op::CallBuiltin {
7415 dst,
7416 builtin: BuiltinId::DomSetInterval,
7417 args_start,
7418 ..
7419 } => lower_dom_call(code, ctx, dst, HostFn::DomSetInterval, args_start, 2, false),
7420 Op::CallBuiltin {
7421 dst,
7422 builtin: BuiltinId::DomEventFileName,
7423 args_start,
7424 ..
7425 } => lower_dom_call(
7426 code,
7427 ctx,
7428 dst,
7429 HostFn::DomEventFileName,
7430 args_start,
7431 1,
7432 true,
7433 ),
7434 Op::CallBuiltin {
7435 dst,
7436 builtin: BuiltinId::DomEventFileSize,
7437 args_start,
7438 ..
7439 } => lower_dom_call(
7440 code,
7441 ctx,
7442 dst,
7443 HostFn::DomEventFileSize,
7444 args_start,
7445 1,
7446 true,
7447 ),
7448 Op::CallBuiltin {
7449 dst,
7450 builtin: BuiltinId::DomEventFileType,
7451 args_start,
7452 ..
7453 } => lower_dom_call(
7454 code,
7455 ctx,
7456 dst,
7457 HostFn::DomEventFileType,
7458 args_start,
7459 1,
7460 true,
7461 ),
7462 Op::CallBuiltin {
7463 dst,
7464 builtin: BuiltinId::DomEventFileBytes,
7465 args_start,
7466 ..
7467 } => lower_dom_call(
7468 code,
7469 ctx,
7470 dst,
7471 HostFn::DomEventFileBytes,
7472 args_start,
7473 1,
7474 true,
7475 ),
7476 Op::CallBuiltin {
7477 dst,
7478 builtin: BuiltinId::DomElementCommand,
7479 args_start,
7480 ..
7481 } => lower_dom_call(
7482 code,
7483 ctx,
7484 dst,
7485 HostFn::DomElementCommand,
7486 args_start,
7487 2,
7488 false,
7489 ),
7490 Op::CallBuiltin {
7491 dst,
7492 builtin: BuiltinId::DomClipboardWrite,
7493 args_start,
7494 ..
7495 } => lower_dom_call(
7496 code,
7497 ctx,
7498 dst,
7499 HostFn::DomClipboardWrite,
7500 args_start,
7501 1,
7502 false,
7503 ),
7504 Op::CallBuiltin {
7505 dst,
7506 builtin: BuiltinId::DomDownloadFile,
7507 args_start,
7508 ..
7509 } => lower_dom_call(
7510 code,
7511 ctx,
7512 dst,
7513 HostFn::DomDownloadFile,
7514 args_start,
7515 2,
7516 false,
7517 ),
7518 Op::CallBuiltin {
7519 dst,
7520 builtin: BuiltinId::DomNotify,
7521 args_start,
7522 ..
7523 } => lower_dom_call(code, ctx, dst, HostFn::DomNotify, args_start, 2, false),
7524 Op::CallBuiltin {
7525 dst,
7526 builtin: BuiltinId::DomPublish,
7527 args_start,
7528 ..
7529 } => lower_dom_call(code, ctx, dst, HostFn::DomPublish, args_start, 2, false),
7530 Op::CallBuiltin {
7531 dst,
7532 builtin: BuiltinId::NoteTurn,
7533 args_start,
7534 ..
7535 } => lower_dom_call(code, ctx, dst, HostFn::DomNoteTurn, args_start, 4, false),
7536 Op::CallBuiltin {
7537 dst,
7538 builtin: BuiltinId::DomJournalDetail,
7539 args_start,
7540 ..
7541 } => lower_dom_call(
7542 code,
7543 ctx,
7544 dst,
7545 HostFn::DomJournalDetail,
7546 args_start,
7547 0,
7548 true,
7549 ),
7550 Op::CallBuiltin {
7551 dst,
7552 builtin: BuiltinId::DomWakeAfter,
7553 args_start,
7554 ..
7555 } => lower_dom_call(code, ctx, dst, HostFn::DomWakeAfter, args_start, 1, false),
7556 Op::CallBuiltin {
7557 dst,
7558 builtin: BuiltinId::RandomInt,
7559 args_start,
7560 ..
7561 } => lower_dom_call(code, ctx, dst, HostFn::RandomInt, args_start, 2, true),
7562 Op::CallBuiltin {
7563 dst,
7564 builtin: BuiltinId::EnvHas,
7565 args_start,
7566 ..
7567 } => lower_env_has(code, ctx, dst, args_start),
7568 Op::CallBuiltin {
7569 dst,
7570 builtin: BuiltinId::EnvValue,
7571 args_start,
7572 ..
7573 } => lower_env_value(code, ctx, plan.num_regs, dst, args_start),
7574 Op::CallBuiltin {
7575 dst,
7576 builtin: BuiltinId::TimeNow,
7577 args_start,
7578 ..
7579 } => lower_dom_call(code, ctx, dst, HostFn::TimeNow, args_start, 0, true),
7580 Op::CallBuiltin {
7581 dst,
7582 builtin: BuiltinId::DomReplaceRoute,
7583 args_start,
7584 ..
7585 } => lower_dom_call(
7586 code,
7587 ctx,
7588 dst,
7589 HostFn::DomReplaceRoute,
7590 args_start,
7591 1,
7592 false,
7593 ),
7594 Op::CallBuiltin {
7595 dst,
7596 builtin: BuiltinId::DomOnRoute,
7597 args_start,
7598 ..
7599 } => lower_dom_call(code, ctx, dst, HostFn::DomOnRoute, args_start, 1, false),
7600 Op::CallBuiltin {
7605 builtin:
7606 BuiltinId::SignalNew
7607 | BuiltinId::SignalSet
7608 | BuiltinId::SignalGetInt
7609 | BuiltinId::SignalGetText
7610 | BuiltinId::SignalBeginRender
7611 | BuiltinId::SignalNewText
7612 | BuiltinId::SignalSetText
7613 | BuiltinId::SignalEnterComponent
7614 | BuiltinId::SignalExitComponent
7615 | BuiltinId::SignalNewSeq
7616 | BuiltinId::SignalGetSeq
7617 | BuiltinId::SignalSetSeq
7618 | BuiltinId::SignalNewFloat
7619 | BuiltinId::SignalGetFloat
7620 | BuiltinId::SignalSetFloat,
7621 ..
7622 } => Err(WasmLowerError::Unsupported(
7623 "the reactive-signal dialect is retired",
7624 )),
7625 Op::CallBuiltin {
7628 dst,
7629 builtin: BuiltinId::ParseFloat,
7630 args_start,
7631 ..
7632 } => {
7633 let idx = (ctx.host_index)(HostFn::ParseFloat)
7634 .ok_or(WasmLowerError::Unsupported("parse_float host not imported"))?;
7635 local_get(code, args_start as u32);
7636 code.push(0x10); leb_u32(code, idx);
7638 local_set(code, dst as u32);
7639 Ok(Flow::Straight)
7640 }
7641 Op::CallBuiltin {
7643 dst,
7644 builtin: BuiltinId::ReadReals,
7645 args_start,
7646 ..
7647 } => {
7648 let idx = (ctx.host_index)(HostFn::ReadReals)
7649 .ok_or(WasmLowerError::Unsupported("read_reals host not imported"))?;
7650 local_get(code, args_start as u32);
7651 code.push(0x10); leb_u32(code, idx);
7653 local_set(code, dst as u32);
7654 Ok(Flow::Straight)
7655 }
7656 Op::CallBuiltin {
7659 dst,
7660 builtin: BuiltinId::Chr,
7661 args_start,
7662 ..
7663 } => {
7664 lower_chr(code, ctx, plan.num_regs, dst, args_start);
7665 Ok(Flow::Straight)
7666 }
7667 Op::CallBuiltin {
7669 dst,
7670 builtin: BuiltinId::ParseTimestamp,
7671 args_start,
7672 ..
7673 } => {
7674 let idx = (ctx.host_index)(HostFn::ParseTimestamp).ok_or(
7675 WasmLowerError::Unsupported("parse_timestamp host not imported"),
7676 )?;
7677 local_get(code, args_start as u32);
7678 code.push(0x10); leb_u32(code, idx);
7680 local_set(code, dst as u32);
7681 Ok(Flow::Straight)
7682 }
7683 Op::CallBuiltin {
7688 dst,
7689 builtin: BuiltinId::WriteWireResidual,
7690 args_start,
7691 ..
7692 } => {
7693 if kinds.get(args_start as usize) != Some(Kind::Text) {
7694 return Err(WasmLowerError::Unsupported(
7695 "writeWireResidual requires a Text argument",
7696 ));
7697 }
7698 let idx = (ctx.host_index)(HostFn::WriteWireResidual).ok_or(
7699 WasmLowerError::Unsupported("write_wire_residual host not imported"),
7700 )?;
7701 local_get(code, args_start as u32);
7702 i32_load(code, 8); local_get(code, args_start as u32);
7704 i32_load(code, 0); code.push(0x10); leb_u32(code, idx);
7707 local_set(code, dst as u32);
7708 Ok(Flow::Straight)
7709 }
7710 Op::CallBuiltin {
7716 dst,
7717 builtin:
7718 b @ (BuiltinId::YearOf
7719 | BuiltinId::MonthOf
7720 | BuiltinId::DayOf
7721 | BuiltinId::WeekdayOf
7722 | BuiltinId::HourOf
7723 | BuiltinId::MinuteOf
7724 | BuiltinId::SecondOf
7725 | BuiltinId::WeekOf
7726 | BuiltinId::QuarterOf),
7727 args_start,
7728 ..
7729 } => {
7730 let which: i32 = match b {
7731 BuiltinId::YearOf => 0,
7732 BuiltinId::MonthOf => 1,
7733 BuiltinId::DayOf => 2,
7734 BuiltinId::HourOf => 3,
7735 BuiltinId::MinuteOf => 4,
7736 BuiltinId::SecondOf => 5,
7737 BuiltinId::WeekdayOf => 6,
7738 BuiltinId::WeekOf => 7,
7739 BuiltinId::QuarterOf => 8,
7740 _ => unreachable!(),
7741 };
7742 match kinds.get(args_start as usize) {
7743 Some(Kind::Moment) => {
7744 let idx = (ctx.host_index)(HostFn::TemporalComponent).ok_or(
7745 WasmLowerError::Unsupported("temporal_component host not imported"),
7746 )?;
7747 local_get(code, args_start as u32); i32_const(code, which);
7749 code.push(0x10); leb_u32(code, idx);
7751 local_set(code, dst as u32);
7752 }
7753 Some(Kind::Date) => {
7757 if matches!(
7758 b,
7759 BuiltinId::HourOf | BuiltinId::MinuteOf | BuiltinId::SecondOf
7760 ) {
7761 return Err(WasmLowerError::Unsupported("clock component (hour/minute/second) of a Date — a Date has no time-of-day"));
7762 }
7763 let idx = (ctx.host_index)(HostFn::TemporalComponentDate).ok_or(
7764 WasmLowerError::Unsupported("temporal_component_date host not imported"),
7765 )?;
7766 local_get(code, args_start as u32); i32_const(code, which);
7768 code.push(0x10); leb_u32(code, idx);
7770 local_set(code, dst as u32);
7771 }
7772 _ => {
7773 return Err(WasmLowerError::Unsupported(
7774 "temporal component of a non-temporal value",
7775 ));
7776 }
7777 }
7778 Ok(Flow::Straight)
7779 }
7780 Op::CallBuiltin {
7790 dst,
7791 builtin:
7792 b @ (BuiltinId::SecondsBetween
7793 | BuiltinId::AddSeconds
7794 | BuiltinId::DateOf
7795 | BuiltinId::TimeOf),
7796 args_start,
7797 ..
7798 } => {
7799 const NANOS_PER_DAY: i64 = 86_400_000_000_000;
7800 const NANOS_PER_SEC: i64 = 1_000_000_000;
7801 if kinds.get(args_start as usize) != Some(Kind::Moment) {
7802 return Err(WasmLowerError::Unsupported(
7803 "temporal arithmetic requires a Moment argument",
7804 ));
7805 }
7806 let i64c = |code: &mut Vec<u8>, v: i64| {
7807 code.push(0x42); leb_i64(code, v);
7809 };
7810 match b {
7811 BuiltinId::SecondsBetween => {
7812 local_get(code, (args_start + 1) as u32); local_get(code, args_start as u32); code.push(0x7D); i64c(code, NANOS_PER_SEC);
7816 code.push(0x7F); }
7818 BuiltinId::AddSeconds => {
7819 local_get(code, args_start as u32); local_get(code, (args_start + 1) as u32); i64c(code, NANOS_PER_SEC);
7822 code.push(0x7E); code.push(0x7C); }
7825 BuiltinId::DateOf => {
7826 local_get(code, args_start as u32);
7827 i64c(code, NANOS_PER_DAY);
7828 code.push(0x7F); local_get(code, args_start as u32);
7830 i64c(code, NANOS_PER_DAY);
7831 code.push(0x81); i64c(code, 0);
7833 code.push(0x53); code.push(0xAD); code.push(0x7D); code.push(0xA7); }
7838 BuiltinId::TimeOf => {
7839 local_get(code, args_start as u32);
7840 i64c(code, NANOS_PER_DAY);
7841 code.push(0x81); local_get(code, args_start as u32);
7843 i64c(code, NANOS_PER_DAY);
7844 code.push(0x81); i64c(code, 0);
7846 code.push(0x53); code.push(0xAD); i64c(code, NANOS_PER_DAY);
7849 code.push(0x7E); code.push(0x7C); }
7852 _ => unreachable!(),
7853 }
7854 local_set(code, dst as u32);
7855 Ok(Flow::Straight)
7856 }
7857 Op::CallBuiltin {
7862 dst,
7863 builtin:
7864 b @ (BuiltinId::FormatTimestamp
7865 | BuiltinId::MonthsBetween
7866 | BuiltinId::YearsBetween
7867 | BuiltinId::InZone
7868 | BuiltinId::LocalInstant),
7869 args_start,
7870 ..
7871 } => {
7872 if !ctx.linked {
7873 return Err(WasmLowerError::Unsupported("format_timestamp/months_between/years_between/in_zone/local_instant need the linked runtime (base::temporal)"));
7874 }
7875 if kinds.get(args_start as usize) != Some(Kind::Moment) {
7876 return Err(WasmLowerError::Unsupported(
7877 "extended temporal requires a Moment argument",
7878 ));
7879 }
7880 let (rt, two_args) = match b {
7881 BuiltinId::FormatTimestamp => (HostFn::FormatTimestampRt, false),
7882 BuiltinId::MonthsBetween => (HostFn::MonthsBetweenRt, true),
7883 BuiltinId::YearsBetween => (HostFn::YearsBetweenRt, true),
7884 BuiltinId::InZone => (HostFn::InZoneRt, true),
7887 BuiltinId::LocalInstant => (HostFn::LocalInstantRt, true),
7888 _ => unreachable!(),
7889 };
7890 if matches!(b, BuiltinId::InZone | BuiltinId::LocalInstant)
7891 && kinds.get((args_start + 1) as usize) != Some(Kind::Text)
7892 {
7893 return Err(WasmLowerError::Unsupported(
7894 "in_zone/local_instant require a Text zone name",
7895 ));
7896 }
7897 let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
7898 "extended temporal runtime fn not imported",
7899 ))?;
7900 local_get(code, args_start as u32);
7901 if two_args {
7902 local_get(code, (args_start + 1) as u32);
7903 }
7904 code.push(0x10); leb_u32(code, idx);
7906 local_set(code, dst as u32);
7907 Ok(Flow::Straight)
7908 }
7909 Op::CallBuiltin {
7914 dst,
7915 builtin: b @ (BuiltinId::MakeDate | BuiltinId::MakeMoment),
7916 args_start,
7917 ..
7918 } => {
7919 if !ctx.linked {
7920 return Err(WasmLowerError::Unsupported(
7921 "makeDate/makeMoment need the linked runtime (base::temporal)",
7922 ));
7923 }
7924 let (rt, argc) = match b {
7925 BuiltinId::MakeDate => (HostFn::MakeDateRt, 3u32),
7926 BuiltinId::MakeMoment => (HostFn::MakeMomentRt, 6u32),
7927 _ => unreachable!(),
7928 };
7929 let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
7930 "date constructor runtime fn not imported",
7931 ))?;
7932 for i in 0..argc {
7933 local_get(code, args_start as u32 + i);
7934 }
7935 code.push(0x10); leb_u32(code, idx);
7937 local_set(code, dst as u32);
7938 Ok(Flow::Straight)
7939 }
7940 Op::CallBuiltin {
7946 dst,
7947 builtin: b,
7948 args_start,
7949 ..
7950 } if ctx.linked && lanes_v_host_fn(b).is_some() => {
7951 let rt = lanes_v_host_fn(b).expect("guarded by lanes_v_host_fn(b).is_some()");
7952 let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
7953 "lane-vector runtime fn not imported",
7954 ))?;
7955 let two = matches!(
7956 b,
7957 BuiltinId::Shuffle16
7958 | BuiltinId::InterleaveLo16
7959 | BuiltinId::InterleaveHi16
7960 | BuiltinId::ByteAdd16
7961 | BuiltinId::Maddubs16
7962 | BuiltinId::Packus16
7963 | BuiltinId::ShrBytes16
7964 );
7965 local_get(code, args_start as u32);
7966 if two {
7967 local_get(code, (args_start + 1) as u32);
7968 }
7969 code.push(0x10); leb_u32(code, idx);
7971 local_set(code, dst as u32);
7972 Ok(Flow::Straight)
7973 }
7974 Op::CallBuiltin {
7978 dst,
7979 builtin: BuiltinId::SetRate,
7980 args_start,
7981 ..
7982 } if ctx.linked => {
7983 let set_idx = (ctx.host_index)(HostFn::MoneySetRate).ok_or(
7984 WasmLowerError::Unsupported("set_rate runtime fn not imported"),
7985 )?;
7986 local_get(code, args_start as u32); match kinds.get((args_start + 1) as usize) {
7988 Some(Kind::Rational) => local_get(code, (args_start + 1) as u32),
7989 Some(Kind::Int) => {
7990 let c = (ctx.host_index)(HostFn::RationalFromI64).ok_or(
7991 WasmLowerError::Unsupported("rational_from_i64 not imported"),
7992 )?;
7993 local_get(code, (args_start + 1) as u32);
7994 code.push(0x10);
7995 leb_u32(code, c);
7996 }
7997 Some(Kind::Decimal) => {
7998 let c = (ctx.host_index)(HostFn::DecimalToRational).ok_or(
7999 WasmLowerError::Unsupported("decimal_to_rational not imported"),
8000 )?;
8001 local_get(code, (args_start + 1) as u32);
8002 code.push(0x10);
8003 leb_u32(code, c);
8004 }
8005 _ => {
8006 return Err(WasmLowerError::Unsupported(
8007 "set_rate rate must be an Int, Decimal, or Rational",
8008 ))
8009 }
8010 }
8011 code.push(0x10); leb_u32(code, set_idx);
8013 local_set(code, dst as u32);
8014 Ok(Flow::Straight)
8015 }
8016 Op::CallBuiltin {
8018 dst,
8019 builtin: BuiltinId::ToCurrency,
8020 args_start,
8021 ..
8022 } if ctx.linked => {
8023 let idx = (ctx.host_index)(HostFn::MoneyToCurrency).ok_or(
8024 WasmLowerError::Unsupported("to_currency runtime fn not imported"),
8025 )?;
8026 local_get(code, args_start as u32); local_get(code, (args_start + 1) as u32); code.push(0x10);
8029 leb_u32(code, idx);
8030 local_set(code, dst as u32);
8031 Ok(Flow::Straight)
8032 }
8033 Op::CallBuiltin {
8036 dst,
8037 builtin: BuiltinId::SetRates,
8038 args_start,
8039 ..
8040 } if ctx.linked => {
8041 let vk = set_rates_value_kind(&plan.ops, args_start, kinds);
8042 let rt = match vk {
8043 Some(Kind::Int) => HostFn::MoneySetRatesInt,
8044 Some(Kind::Rational) => HostFn::MoneySetRatesRational,
8045 Some(Kind::Decimal) => HostFn::MoneySetRatesDecimal,
8046 _ => return Err(WasmLowerError::Unsupported("set_rates needs a Map of currency code to an Int/Decimal/Rational rate whose value kind is statically known")),
8047 };
8048 let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
8049 "set_rates runtime fn not imported",
8050 ))?;
8051 local_get(code, args_start as u32); code.push(0x10);
8053 leb_u32(code, idx);
8054 local_set(code, dst as u32);
8055 Ok(Flow::Straight)
8056 }
8057 Op::CallBuiltin {
8063 dst,
8064 builtin: BuiltinId::WireBytes,
8065 args_start,
8066 ..
8067 } if ctx.linked => {
8068 let h = wire_bytes_host_fn(kinds.get(args_start as usize)).ok_or(
8069 WasmLowerError::Unsupported(
8070 "wireBytes of this value kind is not yet reconstructed for the wire codec",
8071 ),
8072 )?;
8073 let idx = (ctx.host_index)(h).ok_or(WasmLowerError::Unsupported(
8074 "wire_bytes runtime fn not imported",
8075 ))?;
8076 local_get(code, args_start as u32); code.push(0x10);
8078 leb_u32(code, idx);
8079 local_set(code, dst as u32);
8080 Ok(Flow::Straight)
8081 }
8082 Op::CallBuiltin {
8087 dst,
8088 builtin: BuiltinId::ReadWireProgram,
8089 ..
8090 } if ctx.linked => {
8091 const WIRE_BUF: i32 = 1 << 16;
8092 let frame = (ctx.host_index)(HostFn::ReadWireFrame).ok_or(
8093 WasmLowerError::Unsupported("read_wire_frame host not imported"),
8094 )?;
8095 let decode = (ctx.host_index)(HostFn::ReadWireProgramRt).ok_or(
8096 WasmLowerError::Unsupported("read_wire_program runtime fn not imported"),
8097 )?;
8098 let buf = plan.num_regs + 8; i32_const(code, WIRE_BUF);
8100 emit_alloc(code, ctx, buf, AllocClass::Raw); local_get(code, buf); local_get(code, buf);
8103 i32_const(code, WIRE_BUF);
8104 code.push(0x10); leb_u32(code, frame);
8106 code.push(0x10); leb_u32(code, decode);
8108 local_set(code, dst as u32);
8109 Ok(Flow::Straight)
8110 }
8111 Op::CallBuiltin {
8116 dst,
8117 builtin: BuiltinId::RunAccepted,
8118 args_start,
8119 ..
8120 } if ctx.linked => {
8121 if kinds.get(args_start as usize) != Some(Kind::Dynamic) {
8122 return Err(WasmLowerError::Unsupported(
8123 "run_accepted requires a wire-received (dynamic) shipped function",
8124 ));
8125 }
8126 let idx = (ctx.host_index)(HostFn::RunAccepted).ok_or(WasmLowerError::Unsupported(
8127 "run_accepted runtime fn not imported",
8128 ))?;
8129 local_get(code, args_start as u32); local_get(code, (args_start + 1) as u32); local_get(code, (args_start + 2) as u32); local_get(code, (args_start + 3) as u32); code.push(0x10); leb_u32(code, idx);
8135 local_set(code, dst as u32);
8136 Ok(Flow::Straight)
8137 }
8138 Op::CallBuiltin {
8141 dst,
8142 builtin: BuiltinId::Format,
8143 args_start,
8144 arg_count,
8145 } => {
8146 if arg_count == 0 {
8147 lower_text_literal(code, ctx, plan.num_regs, b""); local_set(code, dst as u32);
8149 } else {
8150 display::emit_display_of(code, plan, ctx, args_start, dst as u32)?;
8152 }
8153 Ok(Flow::Straight)
8154 }
8155 Op::CallBuiltin {
8160 builtin: b @ (BuiltinId::Fail | BuiltinId::FailReason),
8161 args_start,
8162 ..
8163 } => {
8164 let fail = (ctx.host_index)(HostFn::LogosRtFail).ok_or(WasmLowerError::Unsupported(
8165 "logos_rt_fail host not imported",
8166 ))?;
8167 let kind = kinds.get(args_start as usize);
8168 if kind == Some(Kind::Text) {
8169 local_get(code, args_start as u32);
8170 } else if b == BuiltinId::Fail {
8171 let text = plan.num_regs + 8;
8174 display::emit_display_of(code, plan, ctx, args_start, text)?;
8175 local_get(code, text);
8176 } else {
8177 let type_name = match kind {
8178 Some(Kind::Int) => "Int",
8179 Some(Kind::Float) => "Real",
8180 Some(Kind::Bool) => "Bool",
8181 _ => {
8182 return Err(WasmLowerError::Unsupported(
8183 "a contract reason of this kind",
8184 ))
8185 }
8186 };
8187 let refusal =
8188 format!("The reason after `otherwise` must be Text, but it was {type_name}.");
8189 lower_text_literal(code, ctx, plan.num_regs, refusal.as_bytes());
8190 }
8191 code.push(0x10); leb_u32(code, fail);
8193 code.push(0x00); Ok(Flow::Terminated)
8195 }
8196 Op::CallBuiltin {
8200 builtin: BuiltinId::VfsMount | BuiltinId::VfsWriteFile,
8201 ..
8202 } => {
8203 let fail = (ctx.host_index)(HostFn::LogosRtFail).ok_or(WasmLowerError::Unsupported(
8204 "logos_rt_fail host not imported",
8205 ))?;
8206 lower_text_literal(code, ctx, plan.num_regs, VFS_IN_THE_BROWSER.as_bytes());
8207 code.push(0x10); leb_u32(code, fail);
8209 code.push(0x00); Ok(Flow::Terminated)
8211 }
8212 Op::CallBuiltin {
8214 dst,
8215 builtin: BuiltinId::RepeatSeq,
8216 args_start,
8217 arg_count,
8218 } => {
8219 if arg_count != 2 {
8220 return Err(WasmLowerError::Unsupported("repeatSeq arity"));
8221 }
8222 lower_repeat_seq(code, kinds, ctx, plan.num_regs, dst, args_start)?;
8223 Ok(Flow::Straight)
8224 }
8225 Op::CallBuiltin {
8228 dst,
8229 builtin: BuiltinId::Money,
8230 args_start,
8231 arg_count,
8232 } if ctx.linked && arg_count == 2 => {
8233 if kinds.get((args_start + 1) as usize) != Some(Kind::Text) {
8234 return Err(WasmLowerError::Unsupported(
8235 "money(amount, currency) with a non-Text currency",
8236 ));
8237 }
8238 let host = match kinds.get(args_start as usize) {
8239 Some(Kind::Decimal) => HostFn::MoneyFromDecimal,
8240 Some(Kind::Int) => HostFn::MoneyFromI64,
8241 _ => {
8242 return Err(WasmLowerError::Unsupported(
8243 "money amount must be an Int or Decimal",
8244 ))
8245 }
8246 };
8247 let make = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported(
8248 "money constructor not imported",
8249 ))?;
8250 local_get(code, args_start as u32);
8251 local_get(code, (args_start + 1) as u32);
8252 code.push(0x10);
8253 leb_u32(code, make);
8254 local_set(code, dst as u32);
8255 return Ok(Flow::Straight);
8256 }
8257 Op::CallBuiltin {
8260 dst,
8261 builtin: BuiltinId::Quantity,
8262 args_start,
8263 arg_count,
8264 } if ctx.linked && arg_count == 2 => {
8265 if kinds.get((args_start + 1) as usize) != Some(Kind::Text) {
8266 return Err(WasmLowerError::Unsupported(
8267 "quantity(value, unit) with a non-Text unit",
8268 ));
8269 }
8270 if kinds.get(args_start as usize) != Some(Kind::Int) {
8271 return Err(WasmLowerError::Unsupported(
8272 "quantity magnitude must be an Int",
8273 ));
8274 }
8275 let make = (ctx.host_index)(HostFn::QuantityOfI64).ok_or(
8276 WasmLowerError::Unsupported("quantity constructor not imported"),
8277 )?;
8278 local_get(code, args_start as u32);
8279 local_get(code, (args_start + 1) as u32);
8280 code.push(0x10);
8281 leb_u32(code, make);
8282 local_set(code, dst as u32);
8283 return Ok(Flow::Straight);
8284 }
8285 Op::CallBuiltin {
8288 dst,
8289 builtin: BuiltinId::Convert,
8290 args_start,
8291 arg_count,
8292 } if ctx.linked && arg_count == 2 => {
8293 if kinds.get(args_start as usize) != Some(Kind::Quantity) {
8294 return Err(WasmLowerError::Unsupported("convert() requires a Quantity"));
8295 }
8296 if kinds.get((args_start + 1) as usize) != Some(Kind::Text) {
8297 return Err(WasmLowerError::Unsupported(
8298 "convert(q, unit) with a non-Text unit",
8299 ));
8300 }
8301 let make = (ctx.host_index)(HostFn::QuantityConvert)
8302 .ok_or(WasmLowerError::Unsupported("quantity convert not imported"))?;
8303 local_get(code, args_start as u32);
8304 local_get(code, (args_start + 1) as u32);
8305 code.push(0x10);
8306 leb_u32(code, make);
8307 local_set(code, dst as u32);
8308 return Ok(Flow::Straight);
8309 }
8310 Op::CallBuiltin {
8312 dst,
8313 builtin: BuiltinId::Decimal,
8314 args_start,
8315 arg_count,
8316 } if ctx.linked && arg_count == 1 => {
8317 if kinds.get(args_start as usize) != Some(Kind::Text) {
8318 return Err(WasmLowerError::Unsupported(
8319 "decimal(x) with a non-Text argument",
8320 ));
8321 }
8322 let from = (ctx.host_index)(HostFn::DecimalFromText).ok_or(
8323 WasmLowerError::Unsupported("decimal_from_text not imported"),
8324 )?;
8325 local_get(code, args_start as u32);
8326 code.push(0x10);
8327 leb_u32(code, from);
8328 local_set(code, dst as u32);
8329 return Ok(Flow::Straight);
8330 }
8331 Op::CallBuiltin {
8333 dst,
8334 builtin: BuiltinId::Modular,
8335 args_start,
8336 arg_count,
8337 } if ctx.linked && arg_count == 2 => {
8338 if kinds.get(args_start as usize) != Some(Kind::Int)
8339 || kinds.get((args_start + 1) as usize) != Some(Kind::Int)
8340 {
8341 return Err(WasmLowerError::Unsupported(
8342 "modular(v, n) with non-Int components",
8343 ));
8344 }
8345 let from = (ctx.host_index)(HostFn::ModularFromI64)
8346 .ok_or(WasmLowerError::Unsupported("modular_from_i64 not imported"))?;
8347 local_get(code, args_start as u32);
8348 local_get(code, (args_start + 1) as u32);
8349 code.push(0x10);
8350 leb_u32(code, from);
8351 local_set(code, dst as u32);
8352 return Ok(Flow::Straight);
8353 }
8354 Op::CallBuiltin {
8355 dst,
8356 builtin: BuiltinId::Complex,
8357 args_start,
8358 arg_count,
8359 } if ctx.linked && arg_count == 2 => {
8360 let re_k = kinds.get(args_start as usize);
8361 let im_k = kinds.get((args_start + 1) as usize);
8362 if re_k == Some(Kind::Int) && im_k == Some(Kind::Int) {
8363 let from = (ctx.host_index)(HostFn::ComplexFromI64)
8364 .ok_or(WasmLowerError::Unsupported("complex_from_i64 not imported"))?;
8365 local_get(code, args_start as u32);
8366 local_get(code, (args_start + 1) as u32);
8367 code.push(0x10); leb_u32(code, from);
8369 local_set(code, dst as u32);
8370 return Ok(Flow::Straight);
8371 }
8372 if !matches!(re_k, Some(Kind::Int) | Some(Kind::Float))
8375 || !matches!(im_k, Some(Kind::Int) | Some(Kind::Float))
8376 {
8377 return Err(WasmLowerError::Unsupported(
8378 "complex(re, im) with non-numeric components",
8379 ));
8380 }
8381 let from = (ctx.host_index)(HostFn::ComplexFromF64)
8382 .ok_or(WasmLowerError::Unsupported("complex_from_f64 not imported"))?;
8383 local_get(code, args_start as u32);
8384 if re_k == Some(Kind::Int) {
8385 code.push(0xB9);
8386 } local_get(code, (args_start + 1) as u32);
8388 if im_k == Some(Kind::Int) {
8389 code.push(0xB9);
8390 } code.push(0x10); leb_u32(code, from);
8393 local_set(code, dst as u32);
8394 Ok(Flow::Straight)
8395 }
8396 Op::CallBuiltin {
8399 dst,
8400 builtin: BuiltinId::Abs,
8401 args_start,
8402 ..
8403 } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Complex) => {
8404 let host = (ctx.host_index)(HostFn::ComplexAbs)
8405 .ok_or(WasmLowerError::Unsupported("complex_abs not imported"))?;
8406 local_get(code, args_start as u32);
8407 code.push(0x10); leb_u32(code, host);
8409 local_set(code, dst as u32);
8410 Ok(Flow::Straight)
8411 }
8412 Op::CallBuiltin {
8415 dst,
8416 builtin: BuiltinId::RealPart,
8417 args_start,
8418 ..
8419 } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Complex) => {
8420 let host = (ctx.host_index)(HostFn::ComplexReF64)
8421 .ok_or(WasmLowerError::Unsupported("complex_re_f64 not imported"))?;
8422 local_get(code, args_start as u32);
8423 code.push(0x10); leb_u32(code, host);
8425 local_set(code, dst as u32);
8426 Ok(Flow::Straight)
8427 }
8428 Op::CallBuiltin {
8429 dst,
8430 builtin: BuiltinId::ImagPart,
8431 args_start,
8432 ..
8433 } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Complex) => {
8434 let host = (ctx.host_index)(HostFn::ComplexImF64)
8435 .ok_or(WasmLowerError::Unsupported("complex_im_f64 not imported"))?;
8436 local_get(code, args_start as u32);
8437 code.push(0x10); leb_u32(code, host);
8439 local_set(code, dst as u32);
8440 Ok(Flow::Straight)
8441 }
8442 Op::CallBuiltin {
8446 dst,
8447 builtin: b @ (BuiltinId::Floor | BuiltinId::Ceil | BuiltinId::Round | BuiltinId::Abs),
8448 args_start,
8449 ..
8450 } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Rational) => {
8451 let host = match b {
8452 BuiltinId::Floor => HostFn::RationalFloor,
8453 BuiltinId::Ceil => HostFn::RationalCeil,
8454 BuiltinId::Round => HostFn::RationalRound,
8455 _ => HostFn::RationalAbs,
8456 };
8457 lower_rational_unary(code, ctx, dst, args_start, host)
8458 }
8459 Op::CallBuiltin {
8462 dst,
8463 builtin:
8464 b @ (BuiltinId::Uuid
8465 | BuiltinId::UuidNil
8466 | BuiltinId::UuidMax
8467 | BuiltinId::UuidDns
8468 | BuiltinId::UuidUrl
8469 | BuiltinId::UuidOid
8470 | BuiltinId::UuidX500
8471 | BuiltinId::UuidVersion),
8472 args_start,
8473 ..
8474 } if ctx.linked => {
8475 let host = match b {
8476 BuiltinId::Uuid => HostFn::UuidParse,
8477 BuiltinId::UuidNil => HostFn::UuidNil,
8478 BuiltinId::UuidMax => HostFn::UuidMax,
8479 BuiltinId::UuidDns => HostFn::UuidDns,
8480 BuiltinId::UuidUrl => HostFn::UuidUrl,
8481 BuiltinId::UuidOid => HostFn::UuidOid,
8482 BuiltinId::UuidX500 => HostFn::UuidX500,
8483 _ => HostFn::UuidVersion,
8484 };
8485 let idx = (ctx.host_index)(host)
8486 .ok_or(WasmLowerError::Unsupported("uuid builtin not imported"))?;
8487 if matches!(b, BuiltinId::Uuid | BuiltinId::UuidVersion) {
8489 local_get(code, args_start as u32);
8490 }
8491 code.push(0x10);
8492 leb_u32(code, idx);
8493 local_set(code, dst as u32);
8494 return Ok(Flow::Straight);
8495 }
8496 Op::CallBuiltin {
8500 dst,
8501 builtin: BuiltinId::TextBytes,
8502 args_start,
8503 ..
8504 } => {
8505 lower_text_bytes(code, ctx, plan.num_regs, dst, args_start);
8506 return Ok(Flow::Straight);
8507 }
8508 Op::CallBuiltin {
8509 dst,
8510 builtin: BuiltinId::UuidBytes,
8511 args_start,
8512 ..
8513 } if ctx.linked => {
8514 lower_uuid_bytes(code, ctx, plan.num_regs, dst, args_start);
8515 return Ok(Flow::Straight);
8516 }
8517 Op::CallBuiltin {
8518 dst,
8519 builtin: BuiltinId::TextFromBytes,
8520 args_start,
8521 ..
8522 } => {
8523 lower_text_from_bytes(code, ctx, plan.num_regs, dst, args_start)?;
8524 return Ok(Flow::Straight);
8525 }
8526 Op::CallBuiltin {
8527 dst,
8528 builtin: BuiltinId::UuidFromBytes,
8529 args_start,
8530 ..
8531 } if ctx.linked => {
8532 return lower_uuid_from_bytes(code, ctx, plan.num_regs, dst, args_start);
8533 }
8534 Op::CallBuiltin {
8537 dst,
8538 builtin: BuiltinId::Lanes4Of,
8539 args_start,
8540 ..
8541 } if ctx.linked => {
8542 lower_lanes4_of(
8543 code,
8544 ctx,
8545 plan.num_regs,
8546 dst,
8547 [args_start, args_start + 1, args_start + 2, args_start + 3],
8548 );
8549 return Ok(Flow::Straight);
8550 }
8551 Op::CallBuiltin {
8552 dst,
8553 builtin: BuiltinId::Lanes4Word32Make,
8554 args_start,
8555 ..
8556 } if ctx.linked => {
8557 lower_lanes4_word32(code, ctx, plan.num_regs, dst, args_start);
8558 return Ok(Flow::Straight);
8559 }
8560 Op::CallBuiltin {
8561 dst,
8562 builtin: BuiltinId::SeqOfLanes4W32,
8563 args_start,
8564 ..
8565 } if ctx.linked => {
8566 lower_seq_of_lanes4(code, ctx, plan.num_regs, dst, args_start);
8567 return Ok(Flow::Straight);
8568 }
8569 Op::CallBuiltin {
8570 dst,
8571 builtin:
8572 b @ (BuiltinId::Sha1Rnds4
8573 | BuiltinId::Sha1Msg1
8574 | BuiltinId::Sha1Msg2
8575 | BuiltinId::Sha1Nexte),
8576 args_start,
8577 ..
8578 } if ctx.linked => {
8579 let (host, ternary) = match b {
8580 BuiltinId::Sha1Rnds4 => (HostFn::Sha1Rnds4, true),
8581 BuiltinId::Sha1Msg1 => (HostFn::Sha1Msg1, false),
8582 BuiltinId::Sha1Msg2 => (HostFn::Sha1Msg2, false),
8583 _ => (HostFn::Sha1Nexte, false),
8584 };
8585 return lower_sha1_op(code, ctx, dst, args_start, host, ternary);
8586 }
8587 Op::CallBuiltin {
8588 dst,
8589 builtin,
8590 args_start,
8591 arg_count,
8592 } => lower_builtin(code, kinds, dst, builtin, args_start, arg_count),
8593 Op::Args { dst } => {
8595 let idx = (ctx.host_index)(HostFn::Args)
8596 .ok_or(WasmLowerError::Unsupported("args host not imported"))?;
8597 code.push(0x10); leb_u32(code, idx);
8599 local_set(code, dst as u32);
8600 Ok(Flow::Straight)
8601 }
8602 Op::Show { src } => {
8603 if plan.structs.tuple_layouts.contains_key(&src) {
8610 lower_show_tuple(code, plan, ctx, src)?;
8611 return Ok(Flow::Straight);
8612 }
8613 let kind = kinds
8614 .get(src as usize)
8615 .ok_or(WasmLowerError::Unsupported("Show of an unknown-kind value"))?;
8616 if kind == Kind::Enum {
8619 lower_show_enum(code, plan, ctx, src)?;
8620 return Ok(Flow::Straight);
8621 }
8622 if kind == Kind::Struct {
8625 lower_show_struct(code, plan, ctx, src)?;
8626 return Ok(Flow::Straight);
8627 }
8628 if kind == Kind::SeqStruct {
8631 lower_show_seqstruct(code, plan, ctx, src)?;
8632 return Ok(Flow::Straight);
8633 }
8634 if kind == Kind::SeqSeqInt {
8641 lower_show_seqseq(code, ctx, plan.num_regs, src)?;
8642 return Ok(Flow::Straight);
8643 }
8644 if kind == Kind::SeqEnum {
8647 lower_show_seqenum(code, plan, ctx, src)?;
8648 return Ok(Flow::Straight);
8649 }
8650 if kind == Kind::Map {
8651 lower_show_map(code, plan, kinds, ctx, src)?;
8652 return Ok(Flow::Straight);
8653 }
8654 if kind == Kind::Rational {
8659 if ctx.linked {
8660 let to_text = (ctx.host_index)(HostFn::RationalToText)
8661 .ok_or(WasmLowerError::Unsupported("rational_to_text not imported"))?;
8662 let print_text = (ctx.host_index)(HostFn::PrintText)
8663 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8664 local_get(code, src as u32);
8665 code.push(0x10);
8666 leb_u32(code, to_text);
8667 code.push(0x10);
8668 leb_u32(code, print_text);
8669 return Ok(Flow::Straight);
8670 }
8671 let idx = (ctx.host_index)(HostFn::PrintRational)
8672 .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8673 local_get(code, src as u32);
8674 i32_load(code, 8);
8675 i64_load(code, 0);
8676 local_get(code, src as u32);
8677 i32_load(code, 8);
8678 i64_load(code, 8);
8679 code.push(0x10); leb_u32(code, idx);
8681 return Ok(Flow::Straight);
8682 }
8683 if kind == Kind::BigInt {
8687 let to_text = (ctx.host_index)(HostFn::BigintToText)
8688 .ok_or(WasmLowerError::Unsupported("bigint_to_text not imported"))?;
8689 let print_text = (ctx.host_index)(HostFn::PrintText)
8690 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8691 local_get(code, src as u32); code.push(0x10);
8693 leb_u32(code, to_text); code.push(0x10);
8695 leb_u32(code, print_text); return Ok(Flow::Straight);
8697 }
8698 if kind == Kind::Complex {
8700 let to_text = (ctx.host_index)(HostFn::ComplexToText)
8701 .ok_or(WasmLowerError::Unsupported("complex_to_text not imported"))?;
8702 let print_text = (ctx.host_index)(HostFn::PrintText)
8703 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8704 local_get(code, src as u32); code.push(0x10);
8706 leb_u32(code, to_text); code.push(0x10);
8708 leb_u32(code, print_text);
8709 return Ok(Flow::Straight);
8710 }
8711 if kind == Kind::Modular {
8713 let to_text = (ctx.host_index)(HostFn::ModularToText)
8714 .ok_or(WasmLowerError::Unsupported("modular_to_text not imported"))?;
8715 let print_text = (ctx.host_index)(HostFn::PrintText)
8716 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8717 local_get(code, src as u32);
8718 code.push(0x10);
8719 leb_u32(code, to_text);
8720 code.push(0x10);
8721 leb_u32(code, print_text);
8722 return Ok(Flow::Straight);
8723 }
8724 if kind == Kind::Decimal {
8725 let to_text = (ctx.host_index)(HostFn::DecimalToText)
8726 .ok_or(WasmLowerError::Unsupported("decimal_to_text not imported"))?;
8727 let print_text = (ctx.host_index)(HostFn::PrintText)
8728 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8729 local_get(code, src as u32);
8730 code.push(0x10);
8731 leb_u32(code, to_text);
8732 code.push(0x10);
8733 leb_u32(code, print_text);
8734 return Ok(Flow::Straight);
8735 }
8736 if kind == Kind::Money {
8737 let to_text = (ctx.host_index)(HostFn::MoneyToText)
8738 .ok_or(WasmLowerError::Unsupported("money_to_text not imported"))?;
8739 let print_text = (ctx.host_index)(HostFn::PrintText)
8740 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8741 local_get(code, src as u32);
8742 code.push(0x10);
8743 leb_u32(code, to_text);
8744 code.push(0x10);
8745 leb_u32(code, print_text);
8746 return Ok(Flow::Straight);
8747 }
8748 if kind == Kind::Quantity {
8751 let to_text = (ctx.host_index)(HostFn::QuantityToText)
8752 .ok_or(WasmLowerError::Unsupported("quantity_to_text not imported"))?;
8753 let print_text = (ctx.host_index)(HostFn::PrintText)
8754 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8755 local_get(code, src as u32);
8756 code.push(0x10);
8757 leb_u32(code, to_text);
8758 code.push(0x10);
8759 leb_u32(code, print_text);
8760 return Ok(Flow::Straight);
8761 }
8762 if kind == Kind::Uuid {
8764 let to_text = (ctx.host_index)(HostFn::UuidToText)
8765 .ok_or(WasmLowerError::Unsupported("uuid_to_text not imported"))?;
8766 let print_text = (ctx.host_index)(HostFn::PrintText)
8767 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8768 local_get(code, src as u32);
8769 code.push(0x10);
8770 leb_u32(code, to_text);
8771 code.push(0x10);
8772 leb_u32(code, print_text);
8773 return Ok(Flow::Straight);
8774 }
8775 if kind == Kind::Dynamic {
8777 let to_text = (ctx.host_index)(HostFn::DynamicToText)
8778 .ok_or(WasmLowerError::Unsupported("dynamic_to_text not imported"))?;
8779 let print_text = (ctx.host_index)(HostFn::PrintText)
8780 .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8781 local_get(code, src as u32);
8782 code.push(0x10);
8783 leb_u32(code, to_text);
8784 code.push(0x10);
8785 leb_u32(code, print_text);
8786 return Ok(Flow::Straight);
8787 }
8788 if kind == Kind::Optional {
8792 let nothing = (ctx.host_index)(HostFn::PrintNothing)
8793 .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8794 let inner = plan
8795 .structs
8796 .opt_inner
8797 .get(&src)
8798 .copied()
8799 .unwrap_or(Kind::Int);
8800 let some_host = HostFn::for_show(inner).ok_or(WasmLowerError::Unsupported(
8801 "Show of an optional with a non-scalar inner",
8802 ))?;
8803 let some_idx = (ctx.host_index)(some_host)
8804 .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8805 local_get(code, src as u32);
8806 code.push(0x45); code.push(0x04);
8808 code.push(0x40); code.push(0x10); leb_u32(code, nothing);
8811 code.push(0x05); local_get(code, src as u32);
8813 emit_slot_load(code, Some(inner), 0)?; if inner == Kind::Bool {
8815 code.push(0xA7); }
8817 code.push(0x10); leb_u32(code, some_idx);
8819 code.push(0x0B); return Ok(Flow::Straight);
8821 }
8822 if kind == Kind::Word32 || kind == Kind::Word64 {
8825 let idx = (ctx.host_index)(HostFn::PrintWord)
8826 .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8827 local_get(code, src as u32);
8828 if kind == Kind::Word32 {
8829 code.push(0xAD); }
8831 code.push(0x10); leb_u32(code, idx);
8833 return Ok(Flow::Straight);
8834 }
8835 let host = HostFn::for_show(kind)
8836 .ok_or(WasmLowerError::Unsupported("Show of a non-scalar value"))?;
8837 let idx = (ctx.host_index)(host)
8838 .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8839 if kind != Kind::Nothing {
8840 local_get(code, src as u32);
8841 }
8842 if kind == Kind::Bool {
8843 code.push(0xA7); }
8845 code.push(0x10); leb_u32(code, idx);
8847 Ok(Flow::Straight)
8848 }
8849 Op::Return { src } => {
8850 if plan.result.is_none() {
8851 return Err(WasmLowerError::Unsupported(
8852 "value return from a void function",
8853 ));
8854 }
8855 emit_leave_loops(code, plan, ctx);
8856 local_get(code, src as u32);
8857 push_inout_results(code, plan);
8858 code.push(0x0F); Ok(Flow::Terminated)
8860 }
8861 Op::ReturnNothing => {
8862 match plan.result {
8863 None => {
8864 emit_leave_loops(code, plan, ctx);
8865 push_inout_results(code, plan);
8866 code.push(0x0F); }
8868 Some(_) => code.push(0x00), }
8870 Ok(Flow::Terminated)
8871 }
8872 Op::Halt => {
8873 emit_leave_loops(code, plan, ctx);
8874 if ctx.batch_reclaim {
8875 code.push(0x10);
8876 leb_u32(
8877 code,
8878 ctx.runtime
8879 .and_then(|r| r.index(RuntimeFn::Safepoint))
8880 .expect("batch safepoint"),
8881 );
8882 }
8883 code.push(0x0F); Ok(Flow::Terminated)
8885 }
8886 Op::FailWith { msg } => {
8901 if let Some(Constant::Text(text)) = ctx.constants.get(msg as usize) {
8902 let idx = (ctx.host_index)(HostFn::LogosRtFail).ok_or(
8903 WasmLowerError::Unsupported("logos_rt_fail host not imported"),
8904 )?;
8905 lower_text_literal(code, ctx, plan.num_regs, text.as_bytes());
8906 code.push(0x10); leb_u32(code, idx);
8908 }
8909 code.push(0x00); Ok(Flow::Terminated)
8911 }
8912 Op::Obs {
8920 site,
8921 args_start,
8922 args_count,
8923 } => {
8924 let idx = (ctx.host_index)(HostFn::Obs)
8925 .ok_or(WasmLowerError::Unsupported("obs host import not present"))?;
8926 i32_const(
8927 code,
8928 i32::try_from(site).expect("an observation site index fits an i32"),
8929 );
8930 for slot in 0..3usize {
8931 let reg = args_start as usize + slot;
8932 if slot < args_count as usize && kinds.get(reg) == Some(Kind::Int) {
8933 local_get(code, reg as u32); } else {
8935 code.push(0x42); code.push(0x00);
8937 }
8938 }
8939 code.push(0x10); leb_u32(code, idx);
8941 Ok(Flow::Straight)
8942 }
8943 other => Err(unsupported_op(&other)),
8944 }
8945}
8946
8947#[derive(Clone, Copy)]
8948enum ArithOp {
8949 Add,
8950 Sub,
8951 Mul,
8952 Div,
8953 Mod,
8954}
8955
8956fn lower_arith(
8960 code: &mut Vec<u8>,
8961 ctx: &Ctx,
8962 kinds: &KindTable,
8963 dst: u16,
8964 lhs: u16,
8965 rhs: u16,
8966 op: ArithOp,
8967) -> R<Flow> {
8968 match kinds.get(dst as usize) {
8969 Some(Kind::Int) => {
8970 if kinds.valtype(lhs as usize) != I64 || kinds.valtype(rhs as usize) != I64 {
8973 return Err(WasmLowerError::Unsupported(
8974 "integer arithmetic with a non-integer operand",
8975 ));
8976 }
8977 let helper = match op {
8978 ArithOp::Add => Some(RuntimeFn::AddChecked),
8979 ArithOp::Sub => Some(RuntimeFn::SubChecked),
8980 ArithOp::Mul => Some(RuntimeFn::MulChecked),
8981 ArithOp::Div | ArithOp::Mod => None,
8982 };
8983 let call = helper
8986 .filter(|_| !ctx.hot.get())
8987 .and_then(|f| ctx.runtime.and_then(|r| r.index(f)));
8988 if let Some(f) = call {
8989 local_get(code, lhs as u32);
8990 local_get(code, rhs as u32);
8991 code.push(0x10);
8992 leb_u32(code, f);
8993 local_set(code, dst as u32);
8994 return Ok(Flow::Straight);
8995 }
8996 match op {
8997 ArithOp::Add => emit_checked_addsub(code, false, dst, lhs, rhs),
8998 ArithOp::Sub => emit_checked_addsub(code, true, dst, lhs, rhs),
8999 ArithOp::Mul => emit_checked_mul(code, dst, lhs, rhs),
9000 ArithOp::Div | ArithOp::Mod => {
9007 if let Some(fail_at) = (ctx.host_index)(HostFn::LogosRtFailAt) {
9008 local_get(code, rhs as u32);
9009 code.push(0x50); code.push(0x04);
9011 code.push(0x40); i32_const(
9013 code,
9014 crate::semantics::failcode::FailCode::DivisionByZero.code(),
9015 );
9016 code.push(0x42); leb_i64(code, 0);
9018 code.push(0x10); leb_u32(code, fail_at);
9020 code.push(0x00); code.push(0x0B); }
9023 let opcode = if matches!(op, ArithOp::Div) {
9024 0x7F
9025 } else {
9026 0x81
9027 };
9028 arith(code, opcode, dst, lhs, rhs)
9029 }
9030 }
9031 }
9032 Some(Kind::Word32) => {
9035 let opcode = match op {
9036 ArithOp::Add => 0x6A, ArithOp::Sub => 0x6B, ArithOp::Mul => 0x6C, ArithOp::Div => 0x6E, ArithOp::Mod => 0x70, };
9042 arith(code, opcode, dst, lhs, rhs);
9043 }
9044 Some(Kind::Word64) => {
9045 let opcode = match op {
9046 ArithOp::Add => 0x7C, ArithOp::Sub => 0x7D, ArithOp::Mul => 0x7E, ArithOp::Div => 0x80, ArithOp::Mod => 0x82, };
9052 arith(code, opcode, dst, lhs, rhs);
9053 }
9054 Some(Kind::Float) => {
9055 let opcode = match op {
9056 ArithOp::Add => 0xA0,
9057 ArithOp::Sub => 0xA1,
9058 ArithOp::Mul => 0xA2,
9059 ArithOp::Div => 0xA3,
9060 ArithOp::Mod => return Err(WasmLowerError::Unsupported("float modulo")),
9061 };
9062 push_number_as_f64(code, ctx, lhs, kinds.get(lhs as usize))?;
9066 push_number_as_f64(code, ctx, rhs, kinds.get(rhs as usize))?;
9067 code.push(opcode);
9068 local_set(code, dst as u32);
9069 }
9070 Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Moment) => {
9074 let opcode = match op {
9075 ArithOp::Add => 0x7C, ArithOp::Sub => 0x7D, _ => {
9078 return Err(WasmLowerError::Unsupported(
9079 "only + and - on temporal values",
9080 ))
9081 }
9082 };
9083 arith(code, opcode, dst, lhs, rhs);
9084 }
9085 _ => {
9086 return Err(WasmLowerError::Unsupported(
9087 "arithmetic on a non-numeric value",
9088 ))
9089 }
9090 }
9091 Ok(Flow::Straight)
9092}
9093
9094#[derive(Clone, Copy)]
9095enum Cmp {
9096 Lt,
9097 Gt,
9098 Le,
9099 Ge,
9100 Eq,
9101 Ne,
9102}
9103
9104fn lower_compare(
9107 code: &mut Vec<u8>,
9108 ctx: &Ctx,
9109 kinds: &KindTable,
9110 dst: u16,
9111 lhs: u16,
9112 rhs: u16,
9113 cmp: Cmp,
9114) -> R<Flow> {
9115 let (lk, rk) = (kinds.get(lhs as usize), kinds.get(rhs as usize));
9116 if ctx.linked && (lk == Some(Kind::Rational) || rk == Some(Kind::Rational)) {
9117 return lower_rational_compare(code, kinds, ctx, dst, lhs, rhs, cmp);
9118 }
9119 if lk == Some(Kind::Nothing) || rk == Some(Kind::Nothing) {
9120 if !matches!(cmp, Cmp::Eq | Cmp::Ne) {
9121 return Err(WasmLowerError::Unsupported(
9122 "ordering comparison with nothing",
9123 ));
9124 }
9125 let other = if lk == Some(Kind::Nothing) { rhs } else { lhs };
9126 let other_kind = kinds
9127 .get(other as usize)
9128 .ok_or(WasmLowerError::Unsupported(
9129 "comparison of unknown-kind values",
9130 ))?;
9131 if other_kind == Kind::Optional {
9132 local_get(code, other as u32);
9133 code.push(0x45); } else {
9135 i32_const(code, i32::from(other_kind == Kind::Nothing));
9136 }
9137 if matches!(cmp, Cmp::Ne) {
9138 code.push(0x45); }
9140 code.push(0xAD); local_set(code, dst as u32);
9142 return Ok(Flow::Straight);
9143 }
9144 let lf = kinds.valtype(lhs as usize) == F64;
9145 let rf = kinds.valtype(rhs as usize) == F64;
9146 if lf || rf {
9147 if lf != rf {
9154 if matches!(cmp, Cmp::Eq | Cmp::Ne) {
9155 let (int_reg, float_reg) = if lf { (rhs, lhs) } else { (lhs, rhs) };
9156 local_get(code, int_reg as u32);
9158 code.push(0xB9); local_get(code, float_reg as u32);
9160 code.push(0x61); local_get(code, int_reg as u32);
9163 local_get(code, float_reg as u32);
9164 code.push(0xFC); code.push(0x06); code.push(0x51); code.push(0x71); local_get(code, float_reg as u32);
9170 code.push(0x44); code.extend_from_slice(&9223372036854775808.0f64.to_le_bytes());
9172 code.push(0x63); code.push(0x71); if matches!(cmp, Cmp::Ne) {
9175 code.push(0x45); }
9177 code.push(0xAD); local_set(code, dst as u32);
9179 return Ok(Flow::Straight);
9180 }
9181 }
9182 let opcode = match cmp {
9183 Cmp::Lt => 0x63, Cmp::Gt => 0x64, Cmp::Le => 0x65, Cmp::Ge => 0x66, Cmp::Eq => 0x61, Cmp::Ne => 0x62, };
9190 push_as_f64(code, lhs, kinds.get(lhs as usize))?;
9191 push_as_f64(code, rhs, kinds.get(rhs as usize))?;
9192 code.push(opcode);
9193 code.push(0xAD); local_set(code, dst as u32);
9195 return Ok(Flow::Straight);
9196 }
9197 if lk == Some(Kind::Optional) || rk == Some(Kind::Optional) {
9198 return Err(WasmLowerError::Unsupported(
9199 "comparison of present optional payloads requires their inner value kinds",
9200 ));
9201 }
9202 let operand = kinds.get(lhs as usize).or_else(|| kinds.get(rhs as usize));
9203 match operand {
9204 Some(Kind::Nothing) => unreachable!("absence comparisons handled above"),
9205 Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Char) | Some(Kind::Duration)
9208 | Some(Kind::Time) | Some(Kind::Span) => {
9209 let opcode = match cmp {
9210 Cmp::Lt => 0x53, Cmp::Gt => 0x55, Cmp::Le => 0x57, Cmp::Ge => 0x59, Cmp::Eq => 0x51, Cmp::Ne => 0x52, };
9217 compare(code, opcode, dst, lhs, rhs);
9218 }
9219 Some(Kind::Word32) => {
9222 let opcode = match cmp {
9223 Cmp::Lt => 0x49, Cmp::Gt => 0x4B, Cmp::Le => 0x4D, Cmp::Ge => 0x4F, Cmp::Eq => 0x46, Cmp::Ne => 0x47, };
9230 compare(code, opcode, dst, lhs, rhs);
9231 }
9232 Some(Kind::Word64) => {
9233 let opcode = match cmp {
9234 Cmp::Lt => 0x54, Cmp::Gt => 0x56, Cmp::Le => 0x58, Cmp::Ge => 0x5A, Cmp::Eq => 0x51, Cmp::Ne => 0x52, };
9241 compare(code, opcode, dst, lhs, rhs);
9242 }
9243 Some(Kind::Float) => unreachable!("float comparison handled by the f64 promotion path"),
9245 Some(Kind::Date) | Some(Kind::Moment) => {
9246 return Err(WasmLowerError::Unsupported("comparison of temporal values"))
9247 }
9248 Some(Kind::SeqInt)
9249 | Some(Kind::SeqBool)
9250 | Some(Kind::SeqFloat)
9251 | Some(Kind::SeqText)
9252 | Some(Kind::SeqStruct)
9253 | Some(Kind::SeqEnum)
9254 | Some(Kind::SeqSeqInt)
9255 | Some(Kind::SeqHandle)
9256 | Some(Kind::SeqAny)
9257 | Some(Kind::SeqWord32)
9258 | Some(Kind::SeqWord64) => {
9259 return Err(WasmLowerError::Unsupported("comparison of sequences"))
9260 }
9261 Some(Kind::Text) => return Err(WasmLowerError::Unsupported("comparison of text values")),
9262 Some(Kind::Tower) => {
9263 return Err(WasmLowerError::Unsupported(
9264 "comparison of an exact value outside the value runtime",
9265 ))
9266 }
9267 Some(Kind::Struct) => {
9268 return Err(WasmLowerError::Unsupported("comparison of struct values"))
9269 }
9270 Some(Kind::Map) => return Err(WasmLowerError::Unsupported("comparison of map values")),
9271 Some(Kind::Set) | Some(Kind::SetText) | Some(Kind::CrdtSetText) => {
9272 return Err(WasmLowerError::Unsupported("comparison of set values"))
9273 }
9274 Some(Kind::CrdtCounter) => {
9279 return Err(WasmLowerError::Unsupported(
9280 "comparison of counter CRDT values",
9281 ))
9282 }
9283 Some(Kind::Enum) => return Err(WasmLowerError::Unsupported("comparison of enum values")),
9284 Some(Kind::Closure) => {
9285 return Err(WasmLowerError::Unsupported("comparison of closure values"))
9286 }
9287 Some(Kind::Tuple) => return Err(WasmLowerError::Unsupported("comparison of tuple values")),
9288 Some(Kind::Rational) => {
9289 return Err(WasmLowerError::Unsupported("comparison of rational values"))
9290 }
9291 Some(Kind::BigInt) => {
9292 return Err(WasmLowerError::Unsupported("comparison of bigint values"))
9293 }
9294 Some(Kind::Complex) => {
9295 return Err(WasmLowerError::Unsupported("comparison of complex values"))
9296 }
9297 Some(Kind::Modular) => {
9298 return Err(WasmLowerError::Unsupported("comparison of modular values"))
9299 }
9300 Some(Kind::Decimal) => {
9301 return Err(WasmLowerError::Unsupported("comparison of decimal values"))
9302 }
9303 Some(Kind::Money) => return Err(WasmLowerError::Unsupported("comparison of money values")),
9304 Some(Kind::Quantity) => {
9305 return Err(WasmLowerError::Unsupported("comparison of quantity values"))
9306 }
9307 Some(Kind::Uuid) => {
9308 return Err(WasmLowerError::Unsupported(
9309 "ordering comparison of uuid values",
9310 ))
9311 }
9312 Some(Kind::LanesV) => {
9313 return Err(WasmLowerError::Unsupported(
9314 "comparison of lane-vector values",
9315 ))
9316 }
9317 Some(Kind::Dynamic) => {
9318 return Err(WasmLowerError::Unsupported(
9319 "comparison of dynamic wire values",
9320 ))
9321 }
9322 Some(Kind::Lanes) => return Err(WasmLowerError::Unsupported("comparison of lane vectors")),
9323 Some(Kind::Optional) => {
9325 unreachable!("optional comparisons handled by the is-nothing path above")
9326 }
9327 None => {
9328 return Err(WasmLowerError::Unsupported(
9329 "comparison of unknown-kind values",
9330 ))
9331 }
9332 }
9333 Ok(Flow::Straight)
9334}
9335
9336fn lower_rational_compare(
9345 code: &mut Vec<u8>,
9346 kinds: &KindTable,
9347 ctx: &Ctx,
9348 dst: u16,
9349 lhs: u16,
9350 rhs: u16,
9351 cmp: Cmp,
9352) -> R<Flow> {
9353 let real = |r: u16| kinds.get(r as usize) == Some(Kind::Float);
9354 if real(lhs) || real(rhs) {
9355 let (rational, f, flipped) = if real(rhs) { (lhs, rhs, false) } else { (rhs, lhs, true) };
9358 let idx = (ctx.host_index)(HostFn::RationalCmpF64)
9359 .ok_or(WasmLowerError::Unsupported("rational_cmp_f64 not imported"))?;
9360 local_get(code, rational as u32);
9361 local_get(code, f as u32);
9362 code.push(0x10);
9363 leb_u32(code, idx);
9364 let cmp = match (cmp, flipped) {
9365 (Cmp::Lt, true) => Cmp::Gt,
9366 (Cmp::Gt, true) => Cmp::Lt,
9367 (Cmp::Le, true) => Cmp::Ge,
9368 (Cmp::Ge, true) => Cmp::Le,
9369 (c, _) => c,
9370 };
9371 match cmp {
9372 Cmp::Eq => code.push(0x45), Cmp::Ne => code.extend([0x45, 0x45]),
9374 Cmp::Lt => {
9375 i32_const(code, 0);
9376 code.push(0x48); }
9378 Cmp::Gt => {
9379 i32_const(code, 1);
9380 code.push(0x46); }
9382 Cmp::Le => {
9383 i32_const(code, 1);
9384 code.push(0x48); }
9386 Cmp::Ge => {
9387 i32_const(code, 2);
9388 code.push(0x49); }
9390 }
9391 code.push(0xAD); local_set(code, dst as u32);
9393 return Ok(Flow::Straight);
9394 }
9395 push_rational_operand(code, kinds, ctx, lhs)?;
9396 push_rational_operand(code, kinds, ctx, rhs)?;
9397 let order = (ctx.host_index)(HostFn::RationalCmp)
9398 .ok_or(WasmLowerError::Unsupported("rational_cmp not imported"))?;
9399 code.push(0x10);
9400 leb_u32(code, order);
9401 match cmp {
9402 Cmp::Eq => code.push(0x45), Cmp::Ne => code.extend([0x45, 0x45]),
9404 Cmp::Lt | Cmp::Gt | Cmp::Le | Cmp::Ge => {
9405 i32_const(code, 0);
9406 code.push(match cmp {
9407 Cmp::Lt => 0x48, Cmp::Gt => 0x4A, Cmp::Le => 0x4C, _ => 0x4E, });
9412 }
9413 }
9414 code.push(0xAD); local_set(code, dst as u32);
9416 Ok(Flow::Straight)
9417}
9418
9419fn lower_approx_eq(code: &mut Vec<u8>, kinds: &KindTable, dst: u16, lhs: u16, rhs: u16) -> R<Flow> {
9420 let lk = kinds.get(lhs as usize);
9421 let rk = kinds.get(rhs as usize);
9422 push_as_f64(code, lhs, lk)?;
9424 push_as_f64(code, rhs, rk)?;
9425 code.push(0x61); push_as_f64(code, lhs, lk)?;
9428 push_as_f64(code, rhs, rk)?;
9429 code.push(0xA1); code.push(0x99); push_as_f64(code, lhs, lk)?;
9433 code.push(0x99); push_as_f64(code, rhs, rk)?;
9435 code.push(0x99); code.push(0xA5); code.push(0x44); code.extend_from_slice(&1e-9f64.to_le_bytes());
9439 code.push(0xA2); code.push(0x44); code.extend_from_slice(&1e-12f64.to_le_bytes());
9442 code.push(0xA5); code.push(0x65); code.push(0x72); code.push(0xAD); local_set(code, dst as u32);
9448 Ok(Flow::Straight)
9449}
9450
9451fn push_number_as_f64(code: &mut Vec<u8>, ctx: &Ctx, reg: u16, kind: Option<Kind>) -> R<()> {
9453 if kind == Some(Kind::Rational) {
9454 let idx = (ctx.host_index)(HostFn::RationalToF64)
9455 .ok_or(WasmLowerError::Unsupported("rational_to_f64 not imported"))?;
9456 local_get(code, reg as u32);
9457 code.push(0x10);
9458 leb_u32(code, idx);
9459 return Ok(());
9460 }
9461 push_as_f64(code, reg, kind)
9462}
9463
9464fn push_as_f64(code: &mut Vec<u8>, reg: u16, kind: Option<Kind>) -> R<()> {
9465 local_get(code, reg as u32);
9466 match kind {
9467 Some(Kind::Float) => {}
9468 Some(Kind::Int) => code.push(0xB9), _ => {
9470 return Err(WasmLowerError::Unsupported(
9471 "numeric builtin on a non-number",
9472 ))
9473 }
9474 }
9475 Ok(())
9476}
9477
9478fn lower_builtin(
9480 code: &mut Vec<u8>,
9481 kinds: &KindTable,
9482 dst: u16,
9483 builtin: BuiltinId,
9484 args_start: u16,
9485 arg_count: u16,
9486) -> R<Flow> {
9487 let arg = args_start;
9488 let ak = kinds.get(arg as usize);
9489 match builtin {
9490 BuiltinId::Sqrt => {
9492 push_as_f64(code, arg, ak)?;
9493 code.push(0x9F); local_set(code, dst as u32);
9495 Ok(Flow::Straight)
9496 }
9497 BuiltinId::Floor => lower_floor_ceil(code, ak, dst, arg, 0x9C), BuiltinId::Ceil => lower_floor_ceil(code, ak, dst, arg, 0x9B), BuiltinId::Round => match ak {
9505 Some(Kind::Float) => {
9506 local_get(code, arg as u32);
9507 code.push(0x44); code.extend_from_slice(&0.5f64.to_le_bytes());
9509 local_get(code, arg as u32);
9510 code.push(0xA6); code.push(0xA0); code.push(0x9D); code.push(0xFC); leb_u32(code, 6); local_set(code, dst as u32);
9516 Ok(Flow::Straight)
9517 }
9518 Some(Kind::Int) => {
9519 local_get(code, arg as u32);
9520 local_set(code, dst as u32);
9521 Ok(Flow::Straight)
9522 }
9523 _ => Err(WasmLowerError::Unsupported("round of a non-number")),
9524 },
9525 BuiltinId::Abs => match ak {
9529 Some(Kind::Float) => {
9530 local_get(code, arg as u32);
9531 code.push(0x99); local_set(code, dst as u32);
9533 Ok(Flow::Straight)
9534 }
9535 Some(Kind::Int) => {
9536 local_get(code, arg as u32);
9538 code.push(0x42); leb_i64(code, i64::MIN);
9540 code.push(0x51); code.push(0x04);
9542 code.push(0x40); code.push(0x00); code.push(0x0B); code.push(0x42);
9547 leb_i64(code, 0); local_get(code, arg as u32);
9549 code.push(0x7D); local_get(code, arg as u32); local_get(code, arg as u32);
9552 code.push(0x42);
9553 leb_i64(code, 0);
9554 code.push(0x53); code.push(0x1B); local_set(code, dst as u32);
9557 Ok(Flow::Straight)
9558 }
9559 _ => Err(WasmLowerError::Unsupported("abs of a non-number")),
9560 },
9561 BuiltinId::Min => lower_minmax(code, kinds, dst, args_start, arg_count, false),
9562 BuiltinId::Max => lower_minmax(code, kinds, dst, args_start, arg_count, true),
9563 BuiltinId::CountOnes => {
9566 local_get(code, arg as u32);
9567 code.push(0x7B); local_set(code, dst as u32);
9569 Ok(Flow::Straight)
9570 }
9571 BuiltinId::LeadingZeros => {
9574 local_get(code, arg as u32);
9575 code.push(0x79); local_set(code, dst as u32);
9577 Ok(Flow::Straight)
9578 }
9579 BuiltinId::TrailingZeros => {
9580 local_get(code, arg as u32);
9581 code.push(0x7A); local_set(code, dst as u32);
9583 Ok(Flow::Straight)
9584 }
9585 BuiltinId::Word32 => {
9589 local_get(code, arg as u32);
9590 code.push(0xA7); local_set(code, dst as u32);
9592 Ok(Flow::Straight)
9593 }
9594 BuiltinId::Word64 => {
9595 local_get(code, arg as u32);
9596 local_set(code, dst as u32);
9597 Ok(Flow::Straight)
9598 }
9599 BuiltinId::IntOfWord32 => {
9602 local_get(code, arg as u32);
9603 code.push(0xAD); local_set(code, dst as u32);
9605 Ok(Flow::Straight)
9606 }
9607 BuiltinId::IntOfWord64 => {
9608 local_get(code, arg as u32);
9609 local_set(code, dst as u32);
9610 Ok(Flow::Straight)
9611 }
9612 BuiltinId::Rotl | BuiltinId::Rotr => {
9615 let is_l = matches!(builtin, BuiltinId::Rotl);
9616 match kinds.get(args_start as usize) {
9617 Some(Kind::Word32) => {
9618 local_get(code, args_start as u32);
9619 local_get(code, (args_start + 1) as u32);
9620 code.push(0xA7); code.push(if is_l { 0x77 } else { 0x78 }); }
9623 Some(Kind::Word64) => {
9624 local_get(code, args_start as u32);
9625 local_get(code, (args_start + 1) as u32);
9626 code.push(if is_l { 0x89 } else { 0x8A }); }
9628 _ => return Err(WasmLowerError::Unsupported("rotate of a non-Word value")),
9629 }
9630 local_set(code, dst as u32);
9631 Ok(Flow::Straight)
9632 }
9633 BuiltinId::Wand | BuiltinId::Wor => {
9635 let is_and = matches!(builtin, BuiltinId::Wand);
9636 let op32 = if is_and { 0x71 } else { 0x72 }; let op64 = if is_and { 0x83 } else { 0x84 }; match kinds.get(args_start as usize) {
9639 Some(Kind::Word32) => {
9640 local_get(code, args_start as u32);
9641 local_get(code, (args_start + 1) as u32);
9642 code.push(op32);
9643 }
9644 Some(Kind::Word64) => {
9645 local_get(code, args_start as u32);
9646 local_get(code, (args_start + 1) as u32);
9647 code.push(op64);
9648 }
9649 _ => {
9650 return Err(WasmLowerError::Unsupported(
9651 "word_and/or of a non-Word value",
9652 ))
9653 }
9654 }
9655 local_set(code, dst as u32);
9656 Ok(Flow::Straight)
9657 }
9658 BuiltinId::Wnot => {
9660 match kinds.get(arg as usize) {
9661 Some(Kind::Word32) => {
9662 local_get(code, arg as u32);
9663 i32_const(code, -1);
9664 code.push(0x73); }
9666 Some(Kind::Word64) => {
9667 local_get(code, arg as u32);
9668 i64c(code, -1);
9669 code.push(0x85); }
9671 _ => return Err(WasmLowerError::Unsupported("word_not of a non-Word value")),
9672 }
9673 local_set(code, dst as u32);
9674 Ok(Flow::Straight)
9675 }
9676 BuiltinId::Word64Shl | BuiltinId::Word64Shr | BuiltinId::Word64And => {
9678 local_get(code, args_start as u32);
9679 local_get(code, (args_start + 1) as u32);
9680 code.push(match builtin {
9681 BuiltinId::Word64Shl => 0x86, BuiltinId::Word64Shr => 0x88, _ => 0x83, });
9685 local_set(code, dst as u32);
9686 Ok(Flow::Straight)
9687 }
9688 BuiltinId::Word32Shr => {
9691 local_get(code, args_start as u32);
9692 local_get(code, (args_start + 1) as u32);
9693 code.push(0xA7); code.push(0x76); local_set(code, dst as u32);
9696 Ok(Flow::Straight)
9697 }
9698 other => {
9699 if std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some() {
9702 eprintln!("[wasm] builtin not yet lowered: {other:?}");
9703 }
9704 Err(WasmLowerError::Unsupported("builtin not yet lowered"))
9705 }
9706 }
9707}
9708
9709fn lower_floor_ceil(
9712 code: &mut Vec<u8>,
9713 arg_kind: Option<Kind>,
9714 dst: u16,
9715 arg: u16,
9716 fop: u8,
9717) -> R<Flow> {
9718 match arg_kind {
9719 Some(Kind::Float) => {
9720 local_get(code, arg as u32);
9721 code.push(fop); code.push(0xFC); leb_u32(code, 6); local_set(code, dst as u32);
9725 }
9726 Some(Kind::Int) => {
9727 local_get(code, arg as u32);
9728 local_set(code, dst as u32);
9729 }
9730 _ => return Err(WasmLowerError::Unsupported("floor/ceil of a non-number")),
9731 }
9732 Ok(Flow::Straight)
9733}
9734
9735fn lower_minmax(
9740 code: &mut Vec<u8>,
9741 kinds: &KindTable,
9742 dst: u16,
9743 args_start: u16,
9744 arg_count: u16,
9745 is_max: bool,
9746) -> R<Flow> {
9747 if arg_count != 2 {
9748 return Err(WasmLowerError::Unsupported("min/max arity"));
9749 }
9750 let (a, b) = (args_start, args_start + 1);
9751 let (ak, bk) = (kinds.get(a as usize), kinds.get(b as usize));
9752 match (ak, bk) {
9753 (Some(Kind::Int), Some(Kind::Int)) => {
9754 local_get(code, a as u32); local_get(code, b as u32); local_get(code, a as u32);
9757 local_get(code, b as u32);
9758 code.push(if is_max { 0x55 } else { 0x53 }); code.push(0x1B); local_set(code, dst as u32);
9761 Ok(Flow::Straight)
9762 }
9763 (a_some, b_some) if a_some.is_some() && b_some.is_some() => {
9764 let fop = if is_max { 0xA5 } else { 0xA4 }; push_as_f64(code, b, bk)?; push_as_f64(code, a, ak)?; push_as_f64(code, a, ak)?;
9769 push_as_f64(code, b, bk)?;
9770 code.push(fop); push_as_f64(code, b, bk)?;
9772 push_as_f64(code, b, bk)?;
9773 code.push(0x62); code.push(0x1B); push_as_f64(code, a, ak)?;
9776 push_as_f64(code, a, ak)?;
9777 code.push(0x62); code.push(0x1B); local_set(code, dst as u32);
9780 Ok(Flow::Straight)
9781 }
9782 _ => Err(WasmLowerError::Unsupported("min/max of non-numbers")),
9783 }
9784}
9785
9786fn pow_host_for(base: Option<Kind>, exp: Option<Kind>) -> Option<HostFn> {
9790 match (base, exp) {
9791 (_, Some(Kind::Float)) => Some(HostFn::PowFf),
9792 (Some(Kind::Float), Some(Kind::Int)) => Some(HostFn::PowFi),
9793 (Some(Kind::Modular), Some(Kind::Int)) => Some(HostFn::ModularPow),
9795 _ => None,
9796 }
9797}
9798
9799fn lower_pow(
9804 code: &mut Vec<u8>,
9805 kinds: &KindTable,
9806 ctx: &Ctx,
9807 num_regs: u32,
9808 dst: u16,
9809 args_start: u16,
9810 arg_count: u16,
9811) -> R<Flow> {
9812 if arg_count != 2 {
9813 return Err(WasmLowerError::Unsupported("pow arity"));
9814 }
9815 lower_pow_regs(code, kinds, ctx, num_regs, dst, args_start, args_start + 1)
9816}
9817
9818fn push_bigint_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
9825 match kinds.get(reg as usize) {
9826 Some(Kind::BigInt) => local_get(code, reg as u32),
9827 Some(Kind::Int) => {
9828 let from_i64 = (ctx.host_index)(HostFn::BigintFromI64)
9829 .ok_or(WasmLowerError::Unsupported("bigint_from_i64 not imported"))?;
9830 local_get(code, reg as u32);
9831 code.push(0x10);
9832 leb_u32(code, from_i64);
9833 }
9834 _ => {
9835 return Err(WasmLowerError::Unsupported(
9836 "bigint arithmetic operand must be a BigInt or an Int",
9837 ))
9838 }
9839 }
9840 Ok(())
9841}
9842
9843fn lower_bigint_binop(
9847 code: &mut Vec<u8>,
9848 kinds: &KindTable,
9849 ctx: &Ctx,
9850 dst: u16,
9851 lhs: u16,
9852 rhs: u16,
9853 host: HostFn,
9854) -> R<Flow> {
9855 let op = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("bigint op not imported"))?;
9856 push_bigint_operand(code, kinds, ctx, lhs)?;
9857 push_bigint_operand(code, kinds, ctx, rhs)?;
9858 code.push(0x10);
9859 leb_u32(code, op);
9860 local_set(code, dst as u32);
9861 Ok(Flow::Straight)
9862}
9863
9864fn push_complex_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
9867 match kinds.get(reg as usize) {
9868 Some(Kind::Complex) => local_get(code, reg as u32),
9869 Some(Kind::Int) => {
9870 let from = (ctx.host_index)(HostFn::ComplexFromI64)
9871 .ok_or(WasmLowerError::Unsupported("complex_from_i64 not imported"))?;
9872 local_get(code, reg as u32);
9873 code.push(0x42); leb_i64(code, 0);
9875 code.push(0x10);
9876 leb_u32(code, from);
9877 }
9878 _ => {
9879 return Err(WasmLowerError::Unsupported(
9880 "complex arithmetic operand must be a Complex or an Int",
9881 ))
9882 }
9883 }
9884 Ok(())
9885}
9886
9887fn lower_complex_binop(
9890 code: &mut Vec<u8>,
9891 kinds: &KindTable,
9892 ctx: &Ctx,
9893 dst: u16,
9894 lhs: u16,
9895 rhs: u16,
9896 host: HostFn,
9897) -> R<Flow> {
9898 let op =
9899 (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("complex op not imported"))?;
9900 push_complex_operand(code, kinds, ctx, lhs)?;
9901 push_complex_operand(code, kinds, ctx, rhs)?;
9902 code.push(0x10);
9903 leb_u32(code, op);
9904 local_set(code, dst as u32);
9905 Ok(Flow::Straight)
9906}
9907
9908fn push_modular_operand(code: &mut Vec<u8>, kinds: &KindTable, reg: u16) -> R<()> {
9911 match kinds.get(reg as usize) {
9912 Some(Kind::Modular) => local_get(code, reg as u32),
9913 _ => {
9914 return Err(WasmLowerError::Unsupported(
9915 "modular arithmetic operand must be a Modular",
9916 ))
9917 }
9918 }
9919 Ok(())
9920}
9921
9922fn lower_modular_binop(
9924 code: &mut Vec<u8>,
9925 kinds: &KindTable,
9926 ctx: &Ctx,
9927 dst: u16,
9928 lhs: u16,
9929 rhs: u16,
9930 host: HostFn,
9931) -> R<Flow> {
9932 let op =
9933 (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("modular op not imported"))?;
9934 push_modular_operand(code, kinds, lhs)?;
9935 push_modular_operand(code, kinds, rhs)?;
9936 code.push(0x10);
9937 leb_u32(code, op);
9938 local_set(code, dst as u32);
9939 Ok(Flow::Straight)
9940}
9941
9942fn push_decimal_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
9945 match kinds.get(reg as usize) {
9946 Some(Kind::Decimal) => local_get(code, reg as u32),
9947 Some(Kind::Int) => {
9948 let from = (ctx.host_index)(HostFn::DecimalFromI64)
9949 .ok_or(WasmLowerError::Unsupported("decimal_from_i64 not imported"))?;
9950 local_get(code, reg as u32);
9951 code.push(0x10);
9952 leb_u32(code, from);
9953 }
9954 _ => {
9955 return Err(WasmLowerError::Unsupported(
9956 "decimal arithmetic operand must be a Decimal or an Int",
9957 ))
9958 }
9959 }
9960 Ok(())
9961}
9962
9963fn lower_decimal_binop(
9965 code: &mut Vec<u8>,
9966 kinds: &KindTable,
9967 ctx: &Ctx,
9968 dst: u16,
9969 lhs: u16,
9970 rhs: u16,
9971 host: HostFn,
9972) -> R<Flow> {
9973 let op =
9974 (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("decimal op not imported"))?;
9975 push_decimal_operand(code, kinds, ctx, lhs)?;
9976 push_decimal_operand(code, kinds, ctx, rhs)?;
9977 code.push(0x10);
9978 leb_u32(code, op);
9979 local_set(code, dst as u32);
9980 Ok(Flow::Straight)
9981}
9982
9983fn push_money_operand(code: &mut Vec<u8>, kinds: &KindTable, _ctx: &Ctx, reg: u16) -> R<()> {
9984 match kinds.get(reg as usize) {
9985 Some(Kind::Money) => local_get(code, reg as u32),
9986 _ => {
9987 return Err(WasmLowerError::Unsupported(
9988 "money arithmetic operand must be a Money value",
9989 ))
9990 }
9991 }
9992 Ok(())
9993}
9994
9995fn lower_money_binop(
9997 code: &mut Vec<u8>,
9998 kinds: &KindTable,
9999 ctx: &Ctx,
10000 dst: u16,
10001 lhs: u16,
10002 rhs: u16,
10003 host: HostFn,
10004) -> R<Flow> {
10005 let op = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("money op not imported"))?;
10006 push_money_operand(code, kinds, ctx, lhs)?;
10007 push_money_operand(code, kinds, ctx, rhs)?;
10008 code.push(0x10);
10009 leb_u32(code, op);
10010 local_set(code, dst as u32);
10011 Ok(Flow::Straight)
10012}
10013
10014fn push_quantity_operand(code: &mut Vec<u8>, kinds: &KindTable, _ctx: &Ctx, reg: u16) -> R<()> {
10015 match kinds.get(reg as usize) {
10016 Some(Kind::Quantity) => local_get(code, reg as u32),
10017 _ => {
10020 return Err(WasmLowerError::Unsupported(
10021 "quantity arithmetic operand must be a Quantity value",
10022 ))
10023 }
10024 }
10025 Ok(())
10026}
10027
10028fn lower_quantity_binop(
10031 code: &mut Vec<u8>,
10032 kinds: &KindTable,
10033 ctx: &Ctx,
10034 dst: u16,
10035 lhs: u16,
10036 rhs: u16,
10037 host: HostFn,
10038) -> R<Flow> {
10039 let op =
10040 (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("quantity op not imported"))?;
10041 push_quantity_operand(code, kinds, ctx, lhs)?;
10042 push_quantity_operand(code, kinds, ctx, rhs)?;
10043 code.push(0x10);
10044 leb_u32(code, op);
10045 local_set(code, dst as u32);
10046 Ok(Flow::Straight)
10047}
10048
10049fn push_rational_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
10053 match kinds.get(reg as usize) {
10054 Some(Kind::Rational) => local_get(code, reg as u32),
10055 Some(Kind::Int) => {
10056 let from = (ctx.host_index)(HostFn::RationalFromI64).ok_or(
10057 WasmLowerError::Unsupported("rational_from_i64 not imported"),
10058 )?;
10059 local_get(code, reg as u32);
10060 code.push(0x10);
10061 leb_u32(code, from);
10062 }
10063 Some(Kind::BigInt) => {
10064 let from = (ctx.host_index)(HostFn::RationalFromBigint).ok_or(
10065 WasmLowerError::Unsupported("rational_from_bigint not imported"),
10066 )?;
10067 local_get(code, reg as u32);
10068 code.push(0x10);
10069 leb_u32(code, from);
10070 }
10071 _ => {
10072 return Err(WasmLowerError::Unsupported(
10073 "rational arithmetic operand must be a Rational, Int, or BigInt",
10074 ))
10075 }
10076 }
10077 Ok(())
10078}
10079
10080fn lower_rational_binop(
10083 code: &mut Vec<u8>,
10084 kinds: &KindTable,
10085 ctx: &Ctx,
10086 dst: u16,
10087 lhs: u16,
10088 rhs: u16,
10089 host: HostFn,
10090) -> R<Flow> {
10091 let op =
10092 (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("rational op not imported"))?;
10093 push_rational_operand(code, kinds, ctx, lhs)?;
10094 push_rational_operand(code, kinds, ctx, rhs)?;
10095 code.push(0x10);
10096 leb_u32(code, op);
10097 local_set(code, dst as u32);
10098 Ok(Flow::Straight)
10099}
10100
10101fn lower_rational_unary(
10104 code: &mut Vec<u8>,
10105 ctx: &Ctx,
10106 dst: u16,
10107 arg: u16,
10108 host: HostFn,
10109) -> R<Flow> {
10110 let op = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported(
10111 "rational unary op not imported",
10112 ))?;
10113 local_get(code, arg as u32);
10114 code.push(0x10);
10115 leb_u32(code, op);
10116 local_set(code, dst as u32);
10117 Ok(Flow::Straight)
10118}
10119
10120fn lower_uuid_eq(
10124 code: &mut Vec<u8>,
10125 ctx: &Ctx,
10126 dst: u16,
10127 lhs: u16,
10128 rhs: u16,
10129 negate: bool,
10130) -> R<Flow> {
10131 let eq = (ctx.host_index)(HostFn::UuidEq)
10132 .ok_or(WasmLowerError::Unsupported("uuid_eq not imported"))?;
10133 local_get(code, lhs as u32);
10134 local_get(code, rhs as u32);
10135 code.push(0x10);
10136 leb_u32(code, eq); if negate {
10138 code.push(0x45); }
10140 code.push(0xAD); local_set(code, dst as u32);
10142 Ok(Flow::Straight)
10143}
10144
10145fn lower_span_add(
10149 code: &mut Vec<u8>,
10150 ctx: &Ctx,
10151 num_regs: u32,
10152 dst: u16,
10153 base: u16,
10154 span: u16,
10155 is_date: bool,
10156 negate: bool,
10157) -> R<Flow> {
10158 let host = if is_date {
10159 HostFn::DateAddSpan
10160 } else {
10161 HostFn::MomentAddSpan
10162 };
10163 let idx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("span add not imported"))?;
10164 let (months, days) = (num_regs + 5, num_regs + 6);
10165 local_get(code, span as u32);
10167 code.push(0x42);
10168 leb_i64(code, 32);
10169 code.push(0x87); code.push(0xA7); local_set(code, months);
10172 local_get(code, span as u32);
10174 code.push(0xA7); local_set(code, days);
10176 if negate {
10177 for r in [months, days] {
10178 i32_const(code, 0);
10179 local_get(code, r);
10180 code.push(0x6B); local_set(code, r);
10182 }
10183 }
10184 local_get(code, base as u32);
10186 local_get(code, months);
10187 local_get(code, days);
10188 code.push(0x10);
10189 leb_u32(code, idx);
10190 local_set(code, dst as u32);
10191 Ok(Flow::Straight)
10192}
10193
10194fn lower_pow_regs(
10195 code: &mut Vec<u8>,
10196 kinds: &KindTable,
10197 ctx: &Ctx,
10198 num_regs: u32,
10199 dst: u16,
10200 base: u16,
10201 exp: u16,
10202) -> R<Flow> {
10203 let (bk, ek) = (kinds.get(base as usize), kinds.get(exp as usize));
10204 match (bk, ek) {
10205 (_, Some(Kind::Float)) => {
10206 push_as_f64(code, base, bk)?;
10207 local_get(code, exp as u32); let idx = (ctx.host_index)(HostFn::PowFf)
10209 .ok_or(WasmLowerError::Unsupported("pow_ff not imported"))?;
10210 code.push(0x10);
10211 leb_u32(code, idx);
10212 local_set(code, dst as u32);
10213 Ok(Flow::Straight)
10214 }
10215 (Some(Kind::Float), Some(Kind::Int)) => {
10216 local_get(code, base as u32);
10217 local_get(code, exp as u32);
10218 let idx = (ctx.host_index)(HostFn::PowFi)
10219 .ok_or(WasmLowerError::Unsupported("pow_fi not imported"))?;
10220 code.push(0x10);
10221 leb_u32(code, idx);
10222 local_set(code, dst as u32);
10223 Ok(Flow::Straight)
10224 }
10225 (Some(Kind::Modular), Some(Kind::Int)) if ctx.linked => {
10226 let pow = (ctx.host_index)(HostFn::ModularPow)
10229 .ok_or(WasmLowerError::Unsupported("modular_pow not imported"))?;
10230 local_get(code, base as u32); local_get(code, exp as u32); code.push(0x10);
10233 leb_u32(code, pow);
10234 local_set(code, dst as u32);
10235 Ok(Flow::Straight)
10236 }
10237 (Some(Kind::Int), Some(Kind::Int)) if ctx.linked => {
10238 let from_i64 = (ctx.host_index)(HostFn::BigintFromI64)
10243 .ok_or(WasmLowerError::Unsupported("bigint_from_i64 not imported"))?;
10244 let pow = (ctx.host_index)(HostFn::BigintPow)
10245 .ok_or(WasmLowerError::Unsupported("bigint_pow not imported"))?;
10246 local_get(code, base as u32); code.push(0x10);
10248 leb_u32(code, from_i64); local_get(code, exp as u32); code.push(0x10);
10251 leb_u32(code, pow); local_set(code, dst as u32);
10253 Ok(Flow::Straight)
10254 }
10255 (Some(Kind::Int), Some(Kind::Int)) => {
10256 lower_int_pow(code, num_regs, dst, base, exp);
10257 Ok(Flow::Straight)
10258 }
10259 _ => Err(WasmLowerError::Unsupported("pow of non-numbers")),
10260 }
10261}
10262
10263fn lower_floordiv_regs(
10270 code: &mut Vec<u8>,
10271 kinds: &KindTable,
10272 num_regs: u32,
10273 dst: u16,
10274 lhs: u16,
10275 rhs: u16,
10276) -> R<Flow> {
10277 match kinds.get(dst as usize) {
10278 Some(Kind::Int) => {
10279 if kinds.valtype(lhs as usize) != I64 || kinds.valtype(rhs as usize) != I64 {
10280 return Err(WasmLowerError::Unsupported(
10281 "integer floor division with a non-integer operand",
10282 ));
10283 }
10284 let s_r = num_regs + 1; local_get(code, lhs as u32);
10287 local_get(code, rhs as u32);
10288 code.push(0x81); local_set(code, s_r);
10290 local_get(code, lhs as u32);
10292 local_get(code, rhs as u32);
10293 code.push(0x7F); local_get(code, s_r);
10296 code.push(0x42);
10297 leb_i64(code, 0); code.push(0x52); local_get(code, s_r);
10300 local_get(code, rhs as u32);
10301 code.push(0x85); code.push(0x42);
10303 leb_i64(code, 0); code.push(0x53); code.push(0x71); code.push(0xAD); code.push(0x7D); local_set(code, dst as u32);
10309 }
10310 Some(Kind::Word32) => arith(code, 0x6E, dst, lhs, rhs), Some(Kind::Word64) => arith(code, 0x80, dst, lhs, rhs), Some(Kind::Float) => {
10313 push_as_f64(code, lhs, kinds.get(lhs as usize))?;
10314 push_as_f64(code, rhs, kinds.get(rhs as usize))?;
10315 code.push(0xA3); code.push(0x9C); local_set(code, dst as u32);
10318 }
10319 _ => {
10320 return Err(WasmLowerError::Unsupported(
10321 "floor division on a non-numeric value",
10322 ))
10323 }
10324 }
10325 Ok(Flow::Straight)
10326}
10327
10328fn lower_int_pow(code: &mut Vec<u8>, num_regs: u32, dst: u16, base: u16, exp: u16) {
10332 let result = (num_regs + 1) as u16;
10333 let base_s = (num_regs + 2) as u16;
10334 let exp_s = (num_regs + 3) as u16;
10335 let tmp = (num_regs + 4) as u16;
10339 local_get(code, exp as u32);
10341 code.push(0x42);
10342 leb_i64(code, 0);
10343 code.push(0x53); code.push(0x04);
10345 code.push(0x40); code.push(0x00); code.push(0x0B); code.push(0x42);
10350 leb_i64(code, 1);
10351 local_set(code, result as u32);
10352 local_get(code, base as u32);
10353 local_set(code, base_s as u32);
10354 local_get(code, exp as u32);
10355 local_set(code, exp_s as u32);
10356 code.push(0x02);
10358 code.push(0x40);
10359 code.push(0x03);
10360 code.push(0x40);
10361 local_get(code, exp_s as u32);
10363 code.push(0x50); code.push(0x0D);
10365 leb_u32(code, 1); local_get(code, exp_s as u32);
10368 code.push(0x42);
10369 leb_i64(code, 1);
10370 code.push(0x83); code.push(0xA7); code.push(0x04);
10373 code.push(0x40); emit_checked_mul(code, tmp, result, base_s); local_get(code, tmp as u32);
10376 local_set(code, result as u32); code.push(0x0B); local_get(code, exp_s as u32);
10380 code.push(0x42);
10381 leb_i64(code, 1);
10382 code.push(0x87); local_set(code, exp_s as u32);
10384 local_get(code, exp_s as u32);
10386 code.push(0x50); code.push(0x45); code.push(0x04);
10389 code.push(0x40); emit_checked_mul(code, tmp, base_s, base_s); local_get(code, tmp as u32);
10392 local_set(code, base_s as u32); code.push(0x0B); code.push(0x0C);
10395 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, result as u32);
10400 local_set(code, dst as u32);
10401}
10402
10403#[derive(Clone, Copy, PartialEq, Eq, Debug)]
10405enum RuntimeFn {
10406 Alloc,
10408 Free,
10410 HeapAllocated,
10413 HeapUsed,
10416 IterUnwind,
10419 TextNew,
10423 SeqNew,
10429 SeqSlot,
10434 SeqPushSlot,
10438 SeqClone,
10444 SeqOwn,
10448 TextEq,
10450 TextConcat,
10453 MapClone,
10456 MapOwn,
10459 MapPut,
10462 MapFind,
10465 MapAt,
10468 AddChecked,
10472 SubChecked,
10474 MulChecked,
10477 ExactAdd,
10482 ExactSub,
10484 ExactMul,
10486 ExactAddW,
10490 ExactSubW,
10492 ExactMulW,
10494 ExactTag,
10497 ExactRelease,
10500 ExactNarrow,
10503 ExactClone,
10506 ExactSeqPromote,
10508 ExactCell,
10509 ExactCompare,
10510 ExactSeqAt,
10511 ExactSeqStore,
10512 ExactMapPromoteKey,
10513 ExactMapPromoteValue,
10514 NewHeader,
10519 Share,
10522 TurnRetain,
10528 Retain,
10534 RetainChildren,
10539 Release,
10545 Safepoint,
10550 FreeObject,
10557 Census,
10564 CensusVisit,
10566 ClosureRetain,
10569 ClosureRelease,
10573}
10574
10575impl RuntimeFn {
10576 fn signature(self) -> (Vec<u8>, Vec<u8>) {
10577 match self {
10578 RuntimeFn::Alloc
10579 | RuntimeFn::TextNew
10580 | RuntimeFn::SeqPushSlot
10581 | RuntimeFn::MapClone
10582 | RuntimeFn::MapOwn
10583 | RuntimeFn::ClosureRetain => (vec![I32], vec![I32]),
10584 RuntimeFn::SeqNew
10585 | RuntimeFn::SeqClone
10586 | RuntimeFn::SeqOwn
10587 | RuntimeFn::TextEq
10588 | RuntimeFn::TextConcat => (vec![I32, I32], vec![I32]),
10589 RuntimeFn::SeqSlot => (vec![I32, I64], vec![I32]),
10590 RuntimeFn::MapPut | RuntimeFn::MapFind | RuntimeFn::MapAt => {
10591 (vec![I32, I64, I32], vec![I32])
10592 }
10593 RuntimeFn::AddChecked
10594 | RuntimeFn::SubChecked
10595 | RuntimeFn::MulChecked
10596 | RuntimeFn::ExactAdd
10597 | RuntimeFn::ExactSub
10598 | RuntimeFn::ExactMul
10599 | RuntimeFn::ExactAddW
10600 | RuntimeFn::ExactSubW
10601 | RuntimeFn::ExactMulW => (vec![I64, I64], vec![I64]),
10602 RuntimeFn::ExactTag | RuntimeFn::ExactClone => (vec![I64], vec![I64]),
10603 RuntimeFn::ExactCell => (vec![I64], vec![I32]),
10604 RuntimeFn::ExactCompare => (vec![I64, I64], vec![I32]),
10605 RuntimeFn::ExactSeqAt => (vec![I32, I64], vec![I64]),
10606 RuntimeFn::ExactSeqStore => (vec![I32, I64], vec![]),
10607 RuntimeFn::ExactSeqPromote
10608 | RuntimeFn::ExactMapPromoteKey
10609 | RuntimeFn::ExactMapPromoteValue => (vec![I32], vec![]),
10610 RuntimeFn::ExactRelease => (vec![I64], vec![]),
10611 RuntimeFn::ExactNarrow => (vec![I64, I32], vec![I64]),
10612 RuntimeFn::NewHeader => (vec![I32], vec![I32]),
10613 RuntimeFn::Share => (vec![I32], vec![]),
10614 RuntimeFn::Free => (vec![I32, I32], vec![]),
10615 RuntimeFn::HeapAllocated | RuntimeFn::HeapUsed => (vec![], vec![I32]),
10616 RuntimeFn::IterUnwind => (vec![I32], vec![]),
10617 RuntimeFn::TurnRetain
10618 | RuntimeFn::Retain
10619 | RuntimeFn::RetainChildren
10620 | RuntimeFn::Release
10621 | RuntimeFn::FreeObject
10622 | RuntimeFn::ClosureRelease => (vec![I32], vec![]),
10623 RuntimeFn::Safepoint => (vec![], vec![]),
10624 RuntimeFn::Census => (vec![], vec![I32]),
10625 RuntimeFn::CensusVisit => (vec![I32, I32], vec![]),
10626 }
10627 }
10628
10629 fn export(self) -> Option<&'static str> {
10631 match self {
10632 RuntimeFn::Alloc
10633 | RuntimeFn::Free
10634 | RuntimeFn::IterUnwind
10635 | RuntimeFn::SeqSlot
10636 | RuntimeFn::SeqPushSlot
10637 | RuntimeFn::SeqClone
10638 | RuntimeFn::SeqOwn
10639 | RuntimeFn::TextEq
10640 | RuntimeFn::TextConcat
10641 | RuntimeFn::MapClone
10642 | RuntimeFn::MapOwn
10643 | RuntimeFn::MapPut
10644 | RuntimeFn::MapFind
10645 | RuntimeFn::MapAt
10646 | RuntimeFn::AddChecked
10647 | RuntimeFn::SubChecked
10648 | RuntimeFn::MulChecked
10649 | RuntimeFn::ExactAdd
10650 | RuntimeFn::ExactSub
10651 | RuntimeFn::ExactMul
10652 | RuntimeFn::ExactAddW
10653 | RuntimeFn::ExactSubW
10654 | RuntimeFn::ExactMulW
10655 | RuntimeFn::ExactTag
10656 | RuntimeFn::ExactRelease
10657 | RuntimeFn::ExactNarrow
10658 | RuntimeFn::ExactClone
10659 | RuntimeFn::ExactSeqPromote
10660 | RuntimeFn::ExactCell
10661 | RuntimeFn::ExactCompare
10662 | RuntimeFn::ExactSeqAt
10663 | RuntimeFn::ExactSeqStore
10664 | RuntimeFn::ExactMapPromoteKey
10665 | RuntimeFn::ExactMapPromoteValue
10666 | RuntimeFn::NewHeader
10667 | RuntimeFn::Share
10668 | RuntimeFn::TurnRetain
10669 | RuntimeFn::Retain
10670 | RuntimeFn::RetainChildren
10671 | RuntimeFn::Release
10672 | RuntimeFn::FreeObject
10673 | RuntimeFn::CensusVisit
10674 | RuntimeFn::ClosureRetain => None,
10675 RuntimeFn::HeapAllocated => Some("__logos_heap_allocated"),
10676 RuntimeFn::HeapUsed => Some("__logos_heap_used"),
10677 RuntimeFn::TextNew => Some("__logos_text_new"),
10678 RuntimeFn::SeqNew => Some("__logos_seq_new"),
10679 RuntimeFn::Safepoint => Some("__logos_safepoint"),
10680 RuntimeFn::Census => Some("__logos_heap_census"),
10681 RuntimeFn::ClosureRelease => Some("__logos_release"),
10690 }
10691 }
10692
10693 fn body(self, env: &RuntimeEnv) -> Vec<u8> {
10694 match self {
10695 RuntimeFn::Alloc => emit_alloc_helper(env.heap_global, env.fail_at),
10696 RuntimeFn::Free => emit_free_helper(),
10697 RuntimeFn::HeapAllocated => emit_heap_allocated_helper(env),
10698 RuntimeFn::HeapUsed => emit_heap_used_helper(env),
10699 RuntimeFn::IterUnwind => emit_iter_unwind_helper(env),
10700 RuntimeFn::TextNew => emit_text_new_helper(env),
10701 RuntimeFn::SeqNew => emit_seq_new_helper(env),
10702 RuntimeFn::SeqSlot => emit_seq_slot_helper(env),
10703 RuntimeFn::SeqPushSlot => emit_seq_push_slot_helper(env),
10704 RuntimeFn::SeqClone => emit_seq_clone_helper(env),
10705 RuntimeFn::SeqOwn => emit_seq_own_helper(env),
10706 RuntimeFn::TextEq => emit_text_eq_helper(),
10707 RuntimeFn::TextConcat => emit_text_concat_helper(env),
10708 RuntimeFn::MapClone => emit_map_clone_helper(env),
10709 RuntimeFn::MapOwn => emit_map_own_helper(env),
10710 RuntimeFn::MapPut => emit_map_put_helper(env),
10711 RuntimeFn::MapFind => emit_map_find_helper(env),
10712 RuntimeFn::MapAt => emit_map_at_helper(env),
10713 RuntimeFn::AddChecked => emit_checked_arith_helper(ArithOp::Add),
10714 RuntimeFn::SubChecked => emit_checked_arith_helper(ArithOp::Sub),
10715 RuntimeFn::MulChecked => emit_checked_arith_helper(ArithOp::Mul),
10716 RuntimeFn::ExactAdd => exact::emit_ring_helper(env, ArithOp::Add),
10717 RuntimeFn::ExactSub => exact::emit_ring_helper(env, ArithOp::Sub),
10718 RuntimeFn::ExactMul => exact::emit_ring_helper(env, ArithOp::Mul),
10719 RuntimeFn::ExactAddW => exact::emit_ring_word_helper(env, ArithOp::Add),
10720 RuntimeFn::ExactSubW => exact::emit_ring_word_helper(env, ArithOp::Sub),
10721 RuntimeFn::ExactMulW => exact::emit_ring_word_helper(env, ArithOp::Mul),
10722 RuntimeFn::ExactTag => exact::emit_tag_helper(env),
10723 RuntimeFn::ExactRelease => exact::emit_release_helper(env),
10724 RuntimeFn::ExactNarrow => exact::emit_narrow_helper(env),
10725 RuntimeFn::ExactClone => exact::emit_clone_helper(env),
10726 RuntimeFn::ExactSeqPromote => exact::emit_seq_promote_helper(env),
10727 RuntimeFn::ExactCell => exact::emit_cell_helper(env),
10728 RuntimeFn::ExactCompare => exact::emit_compare_helper(env),
10729 RuntimeFn::ExactSeqAt => exact::emit_seq_at_helper(env),
10730 RuntimeFn::ExactSeqStore => exact::emit_seq_store_helper(env),
10731 RuntimeFn::ExactMapPromoteKey => exact::emit_map_promote_helper(env, 0),
10732 RuntimeFn::ExactMapPromoteValue => exact::emit_map_promote_helper(env, 8),
10733 RuntimeFn::NewHeader => emit_new_header_helper(env),
10734 RuntimeFn::Share => emit_share_helper(),
10735 RuntimeFn::TurnRetain => emit_turn_retain_helper(env),
10736 RuntimeFn::Retain => emit_true_retain_helper(),
10737 RuntimeFn::RetainChildren => emit_retain_children_helper(env),
10738 RuntimeFn::Release => emit_true_release_helper(env),
10739 RuntimeFn::Safepoint => emit_safepoint_helper(env),
10740 RuntimeFn::FreeObject => emit_free_object_helper(env),
10741 RuntimeFn::Census => emit_heap_census_helper(env),
10742 RuntimeFn::CensusVisit => emit_heap_census_visit_helper(env),
10743 RuntimeFn::ClosureRetain => emit_closure_retain_helper(env),
10744 RuntimeFn::ClosureRelease => emit_closure_release_helper(env),
10745 }
10746 }
10747}
10748
10749struct RuntimeEnv<'r> {
10752 heap_global: u32,
10753 iter_global: u32,
10754 heap_base: i32,
10756 fail_at: u32,
10758 exact_drop: Option<u32>,
10760 exact_clone: Option<u32>,
10761 exact_cmp: Option<u32>,
10762 exact_host: Option<[u32; 6]>,
10765 retain_base: Option<u32>,
10768 global_kinds: Vec<Option<Kind>>,
10771 callback_base: Option<u32>,
10772 shared_maps: bool,
10774 runtime: &'r Runtime,
10775}
10776
10777impl RuntimeEnv<'_> {
10778 fn call(&self, f: RuntimeFn) -> u32 {
10781 self.runtime.index(f).unwrap_or_else(|| {
10782 panic!("a runtime body calls {f:?}, which this module's runtime does not lay out")
10783 })
10784 }
10785}
10786
10787struct Runtime {
10790 first: u32,
10792 fns: Vec<RuntimeFn>,
10793 types: Vec<u32>,
10795 called: std::cell::Cell<u64>,
10798}
10799
10800impl Runtime {
10801 fn layout(
10809 first: u32,
10810 interactive: bool,
10811 host_text: bool,
10812 host_seq: bool,
10813 loops: bool,
10814 exact: bool,
10815 reclaim: Reclaim,
10816 types: &mut TypeTable,
10817 ) -> Runtime {
10818 let mut fns = vec![
10819 RuntimeFn::Alloc,
10820 RuntimeFn::Free,
10821 RuntimeFn::SeqSlot,
10822 RuntimeFn::SeqPushSlot,
10823 RuntimeFn::SeqClone,
10824 RuntimeFn::SeqOwn,
10825 RuntimeFn::TextEq,
10826 RuntimeFn::TextConcat,
10827 RuntimeFn::MapClone,
10828 RuntimeFn::MapOwn,
10829 RuntimeFn::MapPut,
10830 RuntimeFn::MapFind,
10831 RuntimeFn::MapAt,
10832 RuntimeFn::AddChecked,
10833 RuntimeFn::SubChecked,
10834 RuntimeFn::MulChecked,
10835 RuntimeFn::NewHeader,
10836 RuntimeFn::Share,
10837 ];
10838 if !interactive && host_text {
10839 fns.push(RuntimeFn::TextNew);
10840 }
10841 if interactive {
10842 fns.extend([
10843 RuntimeFn::HeapAllocated,
10844 RuntimeFn::HeapUsed,
10845 RuntimeFn::TextNew,
10846 ]);
10847 }
10848 if reclaim != Reclaim::Off {
10849 fns.extend([
10850 RuntimeFn::TurnRetain,
10851 RuntimeFn::Retain,
10852 RuntimeFn::RetainChildren,
10853 RuntimeFn::Release,
10854 RuntimeFn::Safepoint,
10855 RuntimeFn::FreeObject,
10856 RuntimeFn::ClosureRetain,
10857 RuntimeFn::ClosureRelease,
10858 ]);
10859 }
10860 if reclaim == Reclaim::Checked {
10861 fns.extend([RuntimeFn::Census, RuntimeFn::CensusVisit]);
10862 }
10863 if host_seq {
10864 fns.push(RuntimeFn::SeqNew);
10865 }
10866 if loops {
10867 fns.push(RuntimeFn::IterUnwind);
10868 }
10869 if exact {
10870 fns.extend([
10871 RuntimeFn::ExactAdd,
10872 RuntimeFn::ExactSub,
10873 RuntimeFn::ExactMul,
10874 RuntimeFn::ExactAddW,
10875 RuntimeFn::ExactSubW,
10876 RuntimeFn::ExactMulW,
10877 RuntimeFn::ExactTag,
10878 RuntimeFn::ExactRelease,
10879 RuntimeFn::ExactNarrow,
10880 RuntimeFn::ExactClone,
10881 RuntimeFn::ExactSeqPromote,
10882 RuntimeFn::ExactCell,
10883 RuntimeFn::ExactCompare,
10884 RuntimeFn::ExactSeqAt,
10885 RuntimeFn::ExactSeqStore,
10886 RuntimeFn::ExactMapPromoteKey,
10887 RuntimeFn::ExactMapPromoteValue,
10888 ]);
10889 }
10890 let types = fns
10891 .iter()
10892 .map(|f| {
10893 let (p, r) = f.signature();
10894 types.intern(p, r)
10895 })
10896 .collect();
10897 Runtime {
10898 first,
10899 fns,
10900 types,
10901 called: std::cell::Cell::new(0),
10902 }
10903 }
10904
10905 fn index(&self, f: RuntimeFn) -> Option<u32> {
10908 let i = self.fns.iter().position(|x| *x == f)?;
10909 self.called.set(self.called.get() | 1 << i);
10910 Some(self.first + i as u32)
10911 }
10912
10913 fn bodies(&self, env: &RuntimeEnv<'_>) -> Vec<Vec<u8>> {
10917 let mut bodies: Vec<Option<Vec<u8>>> = vec![None; self.fns.len()];
10918 loop {
10919 let mut grew = false;
10920 for (i, f) in self.fns.iter().enumerate() {
10921 if bodies[i].is_none()
10922 && (f.export().is_some() || self.called.get() & (1 << i) != 0)
10923 {
10924 bodies[i] = Some(f.body(env));
10925 grew = true;
10926 }
10927 }
10928 if !grew {
10929 break;
10930 }
10931 }
10932 bodies
10933 .into_iter()
10934 .map(|b| b.unwrap_or_else(|| vec![0x00, 0x00, 0x0B]))
10935 .collect()
10936 }
10937}
10938
10939fn emit_heap_allocated_helper(env: &RuntimeEnv) -> Vec<u8> {
10941 let mut c = vec![0x00]; global_get(&mut c, env.heap_global);
10943 i32_const(&mut c, env.heap_base);
10944 c.push(0x6B); c.push(0x0B);
10946 c
10947}
10948
10949fn emit_heap_used_helper(env: &RuntimeEnv) -> Vec<u8> {
10952 let mut c = Vec::new();
10953 c.push(0x01);
10955 leb_u32(&mut c, 3);
10956 c.push(I32);
10957 global_get(&mut c, env.heap_global);
10958 i32_const(&mut c, env.heap_base);
10959 c.push(0x6B);
10960 local_set(&mut c, 2);
10961 c.push(0x02);
10962 c.push(0x40); c.push(0x03);
10964 c.push(0x40); local_get(&mut c, 0);
10966 i32_const(&mut c, FREE_CLASSES + POWER_CLASSES);
10967 c.push(0x4E); c.push(0x0D);
10969 leb_u32(&mut c, 1); local_get(&mut c, 0);
10972 i32_const(&mut c, 4);
10973 c.push(0x6C);
10974 i32_load(&mut c, FREE_TABLE_BASE as u32);
10975 local_set(&mut c, 1);
10976 c.push(0x02);
10977 c.push(0x40); c.push(0x03);
10979 c.push(0x40); local_get(&mut c, 1);
10981 c.push(0x45); c.push(0x0D);
10983 leb_u32(&mut c, 1); local_get(&mut c, 0);
10987 i32_const(&mut c, FREE_CLASSES);
10988 c.push(0x49); c.push(0x04);
10990 c.push(0x40); {
10992 local_get(&mut c, 2);
10993 local_get(&mut c, 0);
10994 i32_const(&mut c, 1);
10995 c.push(0x6A);
10996 i32_const(&mut c, 8);
10997 c.push(0x6C);
10998 c.push(0x6B);
10999 local_set(&mut c, 2);
11000 }
11001 c.push(0x05); {
11003 local_get(&mut c, 2);
11004 i32_const(&mut c, 1);
11005 i32_const(&mut c, POWER_MIN);
11006 local_get(&mut c, 0);
11007 i32_const(&mut c, FREE_CLASSES);
11008 c.push(0x6B); c.push(0x6A); c.push(0x74); c.push(0x6B);
11012 local_set(&mut c, 2);
11013 }
11014 c.push(0x0B); local_get(&mut c, 1);
11016 i32_load(&mut c, 0); local_set(&mut c, 1);
11018 c.push(0x0C);
11019 leb_u32(&mut c, 0); c.push(0x0B);
11021 c.push(0x0B);
11022 local_get(&mut c, 0);
11023 i32_const(&mut c, 1);
11024 c.push(0x6A);
11025 local_set(&mut c, 0);
11026 c.push(0x0C);
11027 leb_u32(&mut c, 0); c.push(0x0B);
11029 c.push(0x0B);
11030 local_get(&mut c, 2);
11031 c.push(0x0B);
11032 c
11033}
11034
11035fn emit_alloc_helper(heap_global: u32, fail_at: u32) -> Vec<u8> {
11044 let mut c = Vec::new();
11045 c.push(0x01); leb_u32(&mut c, 9);
11050 c.push(I32);
11051
11052 local_get(&mut c, 0);
11056 c.push(0x45); c.push(0x04);
11058 c.push(0x40);
11059 {
11060 i32_const(&mut c, 0);
11061 c.push(0x0F); }
11063 c.push(0x0B);
11064
11065 local_get(&mut c, 0);
11067 i32_const(&mut c, 7);
11068 c.push(0x6A); i32_const(&mut c, 3);
11070 c.push(0x76); local_set(&mut c, 1);
11072
11073 i32_const(&mut c, 0);
11074 local_set(&mut c, 4); local_get(&mut c, 1);
11077 i32_const(&mut c, FREE_CLASSES);
11078 c.push(0x4D); c.push(0x04);
11080 c.push(0x40); {
11082 local_get(&mut c, 1);
11084 i32_const(&mut c, 1);
11085 c.push(0x6B); i32_const(&mut c, 4);
11087 c.push(0x6C); i32_const(&mut c, FREE_TABLE_BASE);
11089 c.push(0x6A); local_set(&mut c, 2);
11091 local_get(&mut c, 1);
11092 i32_const(&mut c, 8);
11093 c.push(0x6C);
11094 local_set(&mut c, 5);
11095 i32_const(&mut c, 1);
11096 local_set(&mut c, 6);
11097 }
11098 c.push(0x05); {
11100 i32_const(&mut c, 32 - POWER_MIN);
11102 local_get(&mut c, 0);
11103 i32_const(&mut c, 1);
11104 c.push(0x6B); c.push(0x67); c.push(0x6B); local_set(&mut c, 1);
11108 local_get(&mut c, 1);
11109 i32_const(&mut c, POWER_CLASSES);
11110 c.push(0x49); local_set(&mut c, 6); local_get(&mut c, 6);
11113 c.push(0x04);
11114 c.push(0x40); {
11116 local_get(&mut c, 1);
11117 i32_const(&mut c, FREE_CLASSES);
11118 c.push(0x6A);
11119 i32_const(&mut c, 4);
11120 c.push(0x6C);
11121 i32_const(&mut c, FREE_TABLE_BASE);
11122 c.push(0x6A);
11123 local_set(&mut c, 2); i32_const(&mut c, 1);
11126 i32_const(&mut c, POWER_MIN);
11127 local_get(&mut c, 1);
11128 c.push(0x6A);
11129 c.push(0x74); local_set(&mut c, 5);
11131 }
11132 c.push(0x05); {
11134 local_get(&mut c, 0);
11135 i32_const(&mut c, 7);
11136 c.push(0x6A);
11137 i32_const(&mut c, -8);
11138 c.push(0x71);
11139 local_set(&mut c, 5);
11140 }
11141 c.push(0x0B); }
11143 c.push(0x0B); local_get(&mut c, 6);
11146 c.push(0x04);
11147 c.push(0x40); {
11149 local_get(&mut c, 2);
11150 i32_load(&mut c, 0);
11151 local_tee(&mut c, 3); c.push(0x04);
11153 c.push(0x40); {
11155 local_get(&mut c, 2);
11157 local_get(&mut c, 3);
11158 i32_load(&mut c, 0);
11159 i32_store(&mut c, 0);
11160 local_get(&mut c, 3);
11161 local_set(&mut c, 4);
11162 }
11163 c.push(0x0B); }
11165 c.push(0x0B); local_get(&mut c, 4);
11171 c.push(0x45); c.push(0x04);
11173 c.push(0x40); {
11175 global_get(&mut c, heap_global);
11176 i32_const(&mut c, 7);
11177 c.push(0x6A);
11178 i32_const(&mut c, -8);
11179 c.push(0x71); local_tee(&mut c, 4);
11181 local_get(&mut c, 5);
11182 c.push(0x6A); local_set(&mut c, 7); c.push(0x3F); c.push(0x00); local_tee(&mut c, 8); i32_const(&mut c, 16);
11190 c.push(0x74); local_get(&mut c, 7); c.push(0x49); c.push(0x04);
11194 c.push(0x40); {
11196 local_get(&mut c, 7);
11198 local_get(&mut c, 8);
11199 i32_const(&mut c, 16);
11200 c.push(0x74); c.push(0x6B); i32_const(&mut c, 65535);
11203 c.push(0x6A);
11204 i32_const(&mut c, 16);
11205 c.push(0x76); local_set(&mut c, 9); local_get(&mut c, 9);
11211 local_get(&mut c, 8);
11212 c.push(0x49); c.push(0x04);
11214 c.push(0x40); {
11216 local_get(&mut c, 8);
11217 local_set(&mut c, 9); }
11219 c.push(0x0B); local_get(&mut c, 9);
11222 c.push(0x40); c.push(0x00);
11224 i32_const(&mut c, -1);
11225 c.push(0x46); c.push(0x04);
11227 c.push(0x40); {
11229 i32_const(
11230 &mut c,
11231 crate::semantics::failcode::FailCode::OutOfMemory.code(),
11232 );
11233 c.push(0x42); leb_i64(&mut c, 0);
11235 c.push(0x10); leb_u32(&mut c, fail_at);
11237 c.push(0x00); }
11239 c.push(0x0B); }
11241 c.push(0x0B); local_get(&mut c, 7);
11244 global_set(&mut c, heap_global);
11245 }
11246 c.push(0x0B); local_get(&mut c, 4);
11249 c.push(0x0B); c
11251}
11252
11253fn emit_seq_new_helper(env: &RuntimeEnv) -> Vec<u8> {
11260 let mut c = Vec::new();
11261 c.push(0x01);
11263 leb_u32(&mut c, 3);
11264 c.push(I32);
11265
11266 local_get(&mut c, 0);
11267 i32_const(&mut c, 8);
11268 c.push(0x6C); c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11271 local_set(&mut c, 2);
11272
11273 i32_const(&mut c, 0);
11275 local_set(&mut c, 4);
11276 c.push(0x02);
11277 c.push(0x40); c.push(0x03);
11279 c.push(0x40); local_get(&mut c, 4);
11281 local_get(&mut c, 0);
11282 c.push(0x4E); c.push(0x0D);
11284 leb_u32(&mut c, 1); local_get(&mut c, 2);
11286 local_get(&mut c, 4);
11287 i32_const(&mut c, 8);
11288 c.push(0x6C);
11289 c.push(0x6A); c.push(0x42);
11291 leb_i64(&mut c, 0);
11292 i64_store(&mut c, 0);
11293 local_get(&mut c, 4);
11294 i32_const(&mut c, 1);
11295 c.push(0x6A);
11296 local_set(&mut c, 4);
11297 c.push(0x0C);
11298 leb_u32(&mut c, 0); c.push(0x0B); c.push(0x0B); let counted = env.retain_base.is_some();
11303 i32_const(&mut c, if counted { 20 } else { 16 });
11304 c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11306 local_set(&mut c, 3);
11307
11308 local_get(&mut c, 3);
11309 local_get(&mut c, 0);
11310 i32_store(&mut c, 0); local_get(&mut c, 3);
11312 local_get(&mut c, 0);
11313 i32_store(&mut c, 4); local_get(&mut c, 3);
11315 local_get(&mut c, 2);
11316 i32_store(&mut c, 8); local_get(&mut c, 3);
11318 i32_const(&mut c, AllocClass::HandleHeader.code() as i32);
11319 i32_const(&mut c, AllocClass::ScalarHeader.code() as i32);
11320 local_get(&mut c, 1);
11321 c.push(0x1B); i32_store(&mut c, 12);
11323 if counted {
11324 local_get(&mut c, 3);
11325 i32_const(&mut c, 1);
11326 i32_store(&mut c, 16); local_get(&mut c, 3);
11328 c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11330 }
11331
11332 local_get(&mut c, 3); c.push(0x0B); c
11335}
11336
11337fn emit_seq_slot_helper(env: &RuntimeEnv) -> Vec<u8> {
11342 let mut c = vec![0x00]; local_get(&mut c, 1);
11344 c.push(0x42);
11345 leb_i64(&mut c, 1);
11346 c.push(0x53); local_get(&mut c, 1);
11348 local_get(&mut c, 0);
11349 i32_load(&mut c, 0);
11350 c.push(0xAD); c.push(0x55); c.push(0x72); c.push(0x04);
11354 c.push(0x40);
11355 {
11356 i32_const(
11357 &mut c,
11358 crate::semantics::failcode::FailCode::IndexOutOfBounds.code(),
11359 );
11360 local_get(&mut c, 1);
11361 c.push(0x10);
11362 leb_u32(&mut c, env.fail_at);
11363 c.push(0x00); }
11365 c.push(0x0B);
11366 local_get(&mut c, 0);
11367 i32_load(&mut c, 8); local_get(&mut c, 1);
11369 c.push(0x42);
11370 leb_i64(&mut c, 1);
11371 c.push(0x7D); c.push(0xA7); i32_const(&mut c, 8);
11374 c.push(0x6C);
11375 c.push(0x6A);
11376 c.push(0x0B); c
11378}
11379
11380fn emit_seq_push_slot_helper(env: &RuntimeEnv) -> Vec<u8> {
11386 let mut c = Vec::new();
11387 c.push(0x01);
11389 leb_u32(&mut c, 4);
11390 c.push(I32);
11391 local_get(&mut c, 0);
11392 i32_load(&mut c, 0);
11393 local_tee(&mut c, 1);
11394 local_get(&mut c, 0);
11395 i32_load(&mut c, 4);
11396 local_tee(&mut c, 2);
11397 c.push(0x4E); c.push(0x04);
11399 c.push(0x40);
11400 {
11401 i32_const(&mut c, 4);
11402 local_get(&mut c, 2);
11403 i32_const(&mut c, 2);
11404 c.push(0x6C);
11405 local_get(&mut c, 2);
11406 c.push(0x45); c.push(0x1B); local_tee(&mut c, 4);
11409 i32_const(&mut c, 8);
11410 c.push(0x6C);
11411 c.push(0x10);
11412 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11413 local_tee(&mut c, 3);
11414 local_get(&mut c, 0);
11415 i32_load(&mut c, 8);
11416 local_get(&mut c, 1);
11417 i32_const(&mut c, 8);
11418 c.push(0x6C);
11419 memory_copy(&mut c); local_get(&mut c, 0);
11421 i32_load(&mut c, 8);
11422 local_get(&mut c, 2);
11423 i32_const(&mut c, 8);
11424 c.push(0x6C);
11425 c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::Free));
11427 local_get(&mut c, 0);
11428 local_get(&mut c, 3);
11429 i32_store(&mut c, 8);
11430 local_get(&mut c, 0);
11431 local_get(&mut c, 4);
11432 i32_store(&mut c, 4);
11433 }
11434 c.push(0x0B);
11435 local_get(&mut c, 0);
11436 local_get(&mut c, 1);
11437 i32_const(&mut c, 1);
11438 c.push(0x6A);
11439 i32_store(&mut c, 0); local_get(&mut c, 0);
11441 i32_load(&mut c, 8);
11442 local_get(&mut c, 1);
11443 i32_const(&mut c, 8);
11444 c.push(0x6C);
11445 c.push(0x6A); c.push(0x0B); c
11448}
11449
11450const CLONE_RETAINS: i32 = 0x100;
11453const CLONE_SHARES: i32 = 0x200;
11456
11457fn emit_seq_clone_helper(env: &RuntimeEnv) -> Vec<u8> {
11465 let mut c = Vec::new();
11466 c.push(0x01);
11468 leb_u32(&mut c, 5);
11469 c.push(I32);
11470 let counting = env.retain_base.is_some();
11471 local_get(&mut c, 0);
11473 i32_load(&mut c, 12);
11474 i32_const(&mut c, 0xff);
11475 c.push(0x71);
11476 i32_const(&mut c, AllocClass::ExactIntegerHeader.code() as i32);
11477 c.extend([0x46, 0x04, 0x40]);
11478 local_get(&mut c, 1);
11479 i32_const(&mut c, !0xff);
11480 c.push(0x71);
11481 i32_const(&mut c, AllocClass::ExactIntegerHeader.code() as i32);
11482 c.push(0x72);
11483 local_set(&mut c, 1);
11484 c.push(0x0b);
11485 if counting {
11486 local_get(&mut c, 1);
11487 emit_class_is_counted(&mut c, 4);
11488 local_set(&mut c, 6);
11489 }
11490 i32_const(&mut c, 16);
11491 if counting {
11492 local_get(&mut c, 6);
11493 i32_const(&mut c, 2);
11494 c.push(0x74); c.push(0x6A);
11496 }
11497 c.push(0x10);
11498 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11499 local_set(&mut c, 2);
11500 local_get(&mut c, 2);
11501 local_get(&mut c, 1);
11502 i32_const(&mut c, 0xFF);
11503 c.push(0x71);
11504 i32_store(&mut c, 12); if counting {
11506 local_get(&mut c, 6);
11507 c.push(0x04);
11508 c.push(0x40);
11509 {
11510 local_get(&mut c, 2);
11511 i32_const(&mut c, 1);
11512 i32_store(&mut c, 16);
11513 local_get(&mut c, 2);
11514 c.push(0x10);
11515 leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11516 }
11517 c.push(0x0B);
11518 }
11519 local_get(&mut c, 0);
11520 i32_load(&mut c, 0);
11521 local_tee(&mut c, 5);
11522 if counting {
11523 i32_const(&mut c, 9);
11525 i32_const(&mut c, 8);
11526 local_get(&mut c, 1);
11527 i32_const(&mut c, 0xFF);
11528 c.push(0x71);
11529 i32_const(&mut c, i32::from(AllocClass::RecordHeader.code()));
11530 c.push(0x46);
11531 c.push(0x1B);
11532 } else {
11533 i32_const(&mut c, 8);
11534 }
11535 c.push(0x6C);
11536 c.push(0x10);
11537 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11538 local_tee(&mut c, 3);
11539 local_get(&mut c, 0);
11540 i32_load(&mut c, 8);
11541 local_get(&mut c, 5);
11542 if counting {
11543 i32_const(&mut c, 9);
11545 i32_const(&mut c, 8);
11546 local_get(&mut c, 1);
11547 i32_const(&mut c, 0xFF);
11548 c.push(0x71);
11549 i32_const(&mut c, i32::from(AllocClass::RecordHeader.code()));
11550 c.push(0x46);
11551 c.push(0x1B);
11552 } else {
11553 i32_const(&mut c, 8);
11554 }
11555 c.push(0x6C);
11556 memory_copy(&mut c);
11557 for off in [0u32, 4] {
11558 local_get(&mut c, 2);
11559 local_get(&mut c, 5);
11560 i32_store(&mut c, off);
11561 }
11562 local_get(&mut c, 2);
11563 local_get(&mut c, 3);
11564 i32_store(&mut c, 8);
11565 if counting {
11566 local_get(&mut c, 1);
11567 i32_const(&mut c, CLONE_RETAINS);
11568 c.push(0x71);
11569 c.push(0x04);
11570 c.push(0x40);
11571 local_get(&mut c, 2);
11572 c.push(0x10);
11573 leb_u32(&mut c, env.call(RuntimeFn::RetainChildren));
11574 c.push(0x0B);
11575 }
11576 local_get(&mut c, 1);
11577 i32_const(&mut c, CLONE_SHARES);
11578 c.push(0x71);
11579 c.push(0x04);
11580 c.push(0x40);
11581 emit_cow_retain_each_element(&mut c, 2, 4);
11582 c.push(0x0B);
11583 if let Some(clone) = env.exact_clone {
11584 emit_exact_buffer_holds(&mut c, 2, 4, 6, clone, true);
11585 }
11586 local_get(&mut c, 2);
11587 c.push(0x0B); c
11589}
11590
11591fn emit_checked_arith_helper(op: ArithOp) -> Vec<u8> {
11595 let mut c = Vec::new();
11596 c.push(0x01);
11598 leb_u32(&mut c, 1);
11599 c.push(I64);
11600 match op {
11601 ArithOp::Add => emit_checked_addsub(&mut c, false, 2, 0, 1),
11602 ArithOp::Sub => emit_checked_addsub(&mut c, true, 2, 0, 1),
11603 ArithOp::Mul => emit_checked_mul(&mut c, 2, 0, 1),
11604 ArithOp::Div | ArithOp::Mod => {
11605 unreachable!("a division lowers inline; the runtime has no checked helper for it")
11606 }
11607 }
11608 local_get(&mut c, 2);
11609 c.push(0x0B); c
11611}
11612
11613fn emit_new_header_helper(env: &RuntimeEnv) -> Vec<u8> {
11616 let mut c = Vec::new();
11617 c.push(0x01);
11619 leb_u32(&mut c, 3);
11620 c.push(I32);
11621 let counting = env.retain_base.is_some();
11622 if counting {
11623 local_get(&mut c, 0);
11624 emit_class_is_counted(&mut c, 3);
11625 local_set(&mut c, 2);
11626 }
11627 i32_const(&mut c, 16);
11628 if counting {
11629 local_get(&mut c, 2);
11630 i32_const(&mut c, 2);
11631 c.push(0x74); c.push(0x6A);
11633 }
11634 c.push(0x10);
11635 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11636 local_set(&mut c, 1);
11637 for off in [0u32, 4, 8] {
11638 local_get(&mut c, 1);
11639 i32_const(&mut c, 0);
11640 i32_store(&mut c, off);
11641 }
11642 local_get(&mut c, 1);
11643 local_get(&mut c, 0);
11644 i32_store(&mut c, 12); if counting {
11646 local_get(&mut c, 2);
11647 c.push(0x04);
11648 c.push(0x40);
11649 {
11650 local_get(&mut c, 1);
11651 i32_const(&mut c, 1);
11652 i32_store(&mut c, 16);
11653 local_get(&mut c, 1);
11654 c.push(0x10);
11655 leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11656 }
11657 c.push(0x0B);
11658 }
11659 local_get(&mut c, 1);
11660 c.push(0x0B); c
11662}
11663
11664fn emit_share_helper() -> Vec<u8> {
11666 let mut c = vec![0x00]; emit_share_inline(&mut c, |c| local_get(c, 0));
11668 c.push(0x0B); c
11670}
11671
11672fn memory_copy(c: &mut Vec<u8>) {
11674 c.extend_from_slice(&[0xFC, 0x0A, 0x00, 0x00]);
11675}
11676
11677fn emit_text_eq_helper() -> Vec<u8> {
11680 let mut c = Vec::new();
11681 c.push(0x01);
11683 leb_u32(&mut c, 2);
11684 c.push(I32);
11685 local_get(&mut c, 0);
11686 local_get(&mut c, 1);
11687 c.push(0x46); c.push(0x04);
11689 c.push(0x40);
11690 i32_const(&mut c, 1);
11691 c.push(0x0F);
11692 c.push(0x0B);
11693 local_get(&mut c, 0);
11694 i32_load(&mut c, 0);
11695 local_tee(&mut c, 3);
11696 local_get(&mut c, 1);
11697 i32_load(&mut c, 0);
11698 c.push(0x47); c.push(0x04);
11700 c.push(0x40);
11701 i32_const(&mut c, 0);
11702 c.push(0x0F);
11703 c.push(0x0B);
11704 i32_const(&mut c, 0);
11705 local_set(&mut c, 2);
11706 c.push(0x02);
11707 c.push(0x40);
11708 c.push(0x03);
11709 c.push(0x40);
11710 local_get(&mut c, 2);
11711 local_get(&mut c, 3);
11712 c.push(0x4E); c.push(0x0D);
11714 leb_u32(&mut c, 1);
11715 for side in [0u32, 1] {
11716 local_get(&mut c, side);
11717 i32_load(&mut c, 8);
11718 local_get(&mut c, 2);
11719 c.push(0x6A);
11720 i32_load8_u(&mut c, 0);
11721 }
11722 c.push(0x47); c.push(0x04);
11724 c.push(0x40);
11725 i32_const(&mut c, 0);
11726 c.push(0x0F);
11727 c.push(0x0B);
11728 local_get(&mut c, 2);
11729 i32_const(&mut c, 1);
11730 c.push(0x6A);
11731 local_set(&mut c, 2);
11732 c.push(0x0C);
11733 leb_u32(&mut c, 0);
11734 c.push(0x0B);
11735 c.push(0x0B);
11736 i32_const(&mut c, 1);
11737 c.push(0x0B); c
11739}
11740
11741fn emit_text_concat_helper(env: &RuntimeEnv) -> Vec<u8> {
11745 let mut c = Vec::new();
11746 c.push(0x01);
11748 leb_u32(&mut c, 3);
11749 c.push(I32);
11750 let counting = env.retain_base.is_some();
11751 i32_const(&mut c, if counting { 20 } else { 16 });
11752 c.push(0x10);
11753 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11754 local_tee(&mut c, 2);
11755 i32_const(&mut c, i32::from(AllocClass::TextHeader.code()));
11756 i32_store(&mut c, 12);
11757 if counting {
11758 local_get(&mut c, 2);
11759 i32_const(&mut c, 1);
11760 i32_store(&mut c, 16);
11761 local_get(&mut c, 2);
11762 c.push(0x10);
11763 leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11764 }
11765 local_get(&mut c, 0);
11766 i32_load(&mut c, 0);
11767 local_tee(&mut c, 4);
11768 local_get(&mut c, 1);
11769 i32_load(&mut c, 0);
11770 c.push(0x6A);
11771 c.push(0x10);
11772 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11773 local_tee(&mut c, 3);
11774 local_get(&mut c, 0);
11775 i32_load(&mut c, 8);
11776 local_get(&mut c, 4);
11777 memory_copy(&mut c); local_get(&mut c, 3);
11779 local_get(&mut c, 4);
11780 c.push(0x6A);
11781 local_get(&mut c, 1);
11782 i32_load(&mut c, 8);
11783 local_get(&mut c, 1);
11784 i32_load(&mut c, 0);
11785 memory_copy(&mut c); for off in [0u32, 4] {
11787 local_get(&mut c, 2);
11788 local_get(&mut c, 4);
11789 local_get(&mut c, 1);
11790 i32_load(&mut c, 0);
11791 c.push(0x6A);
11792 i32_store(&mut c, off);
11793 }
11794 local_get(&mut c, 2);
11795 local_get(&mut c, 3);
11796 i32_store(&mut c, 8);
11797 local_get(&mut c, 2);
11798 c.push(0x0B); c
11800}
11801
11802fn emit_map_clone_helper(env: &RuntimeEnv) -> Vec<u8> {
11808 let mut c = Vec::new();
11809 c.push(0x01);
11811 leb_u32(&mut c, 2);
11812 c.push(I32);
11813 i32_const(&mut c, i32::from(AllocClass::MapScalarScalar.code()));
11814 c.push(0x10);
11815 leb_u32(&mut c, env.call(RuntimeFn::NewHeader));
11816 local_set(&mut c, 1);
11817 local_get(&mut c, 0);
11818 i32_load(&mut c, 0);
11819 i32_const(&mut c, 16);
11820 c.push(0x6C);
11821 c.push(0x10);
11822 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11823 local_tee(&mut c, 2);
11824 local_get(&mut c, 0);
11825 i32_load(&mut c, 8);
11826 local_get(&mut c, 0);
11827 i32_load(&mut c, 0);
11828 i32_const(&mut c, 16);
11829 c.push(0x6C);
11830 memory_copy(&mut c);
11831 for off in [0u32, 4] {
11832 local_get(&mut c, 1);
11833 local_get(&mut c, 0);
11834 i32_load(&mut c, 0);
11835 i32_store(&mut c, off);
11836 }
11837 local_get(&mut c, 1);
11838 local_get(&mut c, 2);
11839 i32_store(&mut c, 8);
11840 local_get(&mut c, 1);
11841 if env.shared_maps {
11842 i32_const(&mut c, SHARED_MAP_MARK);
11843 i32_const(&mut c, 0);
11844 local_get(&mut c, 0);
11845 i32_load(&mut c, 12);
11846 i32_const(&mut c, 0);
11847 c.push(0x48); c.push(0x1B); } else {
11850 i32_const(&mut c, 0);
11851 }
11852 local_get(&mut c, 0);
11853 i32_load(&mut c, 12);
11854 i32_const(&mut c, 0xFF);
11855 c.push(0x71);
11856 c.push(0x72); i32_store(&mut c, 12);
11858 if env.retain_base.is_some() {
11859 local_get(&mut c, 1);
11860 c.push(0x10);
11861 leb_u32(&mut c, env.call(RuntimeFn::RetainChildren));
11862 }
11863 local_get(&mut c, 1);
11864 c.push(0x0B); c
11866}
11867
11868fn emit_map_own_helper(env: &RuntimeEnv) -> Vec<u8> {
11871 let mut c = vec![0x00]; emit_should_clone(&mut c, 0);
11873 c.push(0x04);
11874 c.push(I32);
11875 local_get(&mut c, 0);
11876 c.push(0x10);
11877 leb_u32(&mut c, env.call(RuntimeFn::MapClone));
11878 c.push(0x05);
11879 local_get(&mut c, 0);
11880 c.push(0x0B);
11881 c.push(0x0B); c
11883}
11884
11885fn emit_map_find_helper(env: &RuntimeEnv) -> Vec<u8> {
11888 let mut c = Vec::new();
11889 c.push(0x01);
11891 leb_u32(&mut c, 2);
11892 c.push(I32);
11893 i32_const(&mut c, 0);
11894 local_set(&mut c, 3);
11895 c.push(0x02);
11896 c.push(0x40);
11897 c.push(0x03);
11898 c.push(0x40);
11899 local_get(&mut c, 3);
11900 local_get(&mut c, 0);
11901 i32_load(&mut c, 0);
11902 c.push(0x4E); c.push(0x0D);
11904 leb_u32(&mut c, 1);
11905 local_get(&mut c, 0);
11906 i32_load(&mut c, 8);
11907 local_get(&mut c, 3);
11908 i32_const(&mut c, 16);
11909 c.push(0x6C);
11910 c.push(0x6A);
11911 local_set(&mut c, 4);
11912 local_get(&mut c, 2);
11913 c.push(0x04);
11914 c.push(I32);
11915 {
11916 if let Some(cmp) = env.exact_cmp {
11917 local_get(&mut c, 1);
11918 c.push(0xa7);
11919 i32_load(&mut c, 12);
11920 i32_const(&mut c, 0xff);
11921 c.push(0x71);
11922 i32_const(&mut c, AllocClass::ExactIntegerHeader.code() as i32);
11923 c.extend([0x46, 0x04, I32]);
11924 local_get(&mut c, 4);
11925 i32_load(&mut c, 0);
11926 i32_load(&mut c, 8);
11927 i64_load(&mut c, 0);
11928 local_get(&mut c, 1);
11929 c.push(0xa7);
11930 i32_load(&mut c, 8);
11931 i64_load(&mut c, 0);
11932 c.push(0x10);
11933 leb_u32(&mut c, cmp);
11934 c.extend([0x45, 0x05]);
11935 }
11936 local_get(&mut c, 4);
11937 i32_load(&mut c, 0);
11938 local_get(&mut c, 1);
11939 c.push(0xA7); c.push(0x10);
11941 leb_u32(&mut c, env.call(RuntimeFn::TextEq));
11942 if env.exact_cmp.is_some() {
11943 c.push(0x0b);
11944 }
11945 }
11946 c.push(0x05);
11947 {
11948 local_get(&mut c, 4);
11949 i64_load(&mut c, 0);
11950 local_get(&mut c, 1);
11951 c.push(0x51); }
11953 c.push(0x0B);
11954 c.push(0x04);
11955 c.push(0x40);
11956 local_get(&mut c, 4);
11957 c.push(0x0F);
11958 c.push(0x0B);
11959 local_get(&mut c, 3);
11960 i32_const(&mut c, 1);
11961 c.push(0x6A);
11962 local_set(&mut c, 3);
11963 c.push(0x0C);
11964 leb_u32(&mut c, 0);
11965 c.push(0x0B);
11966 c.push(0x0B);
11967 i32_const(&mut c, 0);
11968 c.push(0x0B); c
11970}
11971
11972fn emit_map_at_helper(env: &RuntimeEnv) -> Vec<u8> {
11975 let mut c = Vec::new();
11976 c.push(0x01);
11978 leb_u32(&mut c, 1);
11979 c.push(I32);
11980 local_get(&mut c, 0);
11981 local_get(&mut c, 1);
11982 local_get(&mut c, 2);
11983 c.push(0x10);
11984 leb_u32(&mut c, env.call(RuntimeFn::MapFind));
11985 local_tee(&mut c, 3);
11986 c.push(0x45); c.push(0x04);
11988 c.push(0x40);
11989 c.push(0x00); c.push(0x0B);
11991 local_get(&mut c, 3);
11992 c.push(0x0B); c
11994}
11995
11996fn emit_map_put_helper(env: &RuntimeEnv) -> Vec<u8> {
12005 let mut c = Vec::new();
12006 c.push(0x01);
12008 leb_u32(&mut c, 4);
12009 c.push(I32);
12010 local_get(&mut c, 0);
12011 local_get(&mut c, 0);
12012 i32_load(&mut c, 12);
12013 i32_const(&mut c, !0xFFu32 as i32);
12014 c.push(0x71);
12015 local_get(&mut c, 2);
12016 c.push(0x72);
12017 i32_store(&mut c, 12);
12018 let key_handle: i32 = AllocClass::ALL
12019 .iter()
12020 .filter(|k| k.held_handles().0 && **k != AllocClass::HandleHeader)
12021 .map(|k| 1i32 << k.code())
12022 .sum();
12023 i32_const(&mut c, key_handle);
12024 local_get(&mut c, 2);
12025 c.push(0x76); i32_const(&mut c, 1);
12027 c.push(0x71);
12028 local_set(&mut c, 3);
12029 local_get(&mut c, 0);
12030 local_get(&mut c, 1);
12031 local_get(&mut c, 3);
12032 c.push(0x10);
12033 leb_u32(&mut c, env.call(RuntimeFn::MapFind));
12034 local_tee(&mut c, 4);
12035 c.push(0x04);
12036 c.push(0x40);
12037 local_get(&mut c, 4);
12038 c.push(0x0F); c.push(0x0B);
12040 local_get(&mut c, 0);
12041 i32_load(&mut c, 0);
12042 local_get(&mut c, 0);
12043 i32_load(&mut c, 4);
12044 c.push(0x4E); c.push(0x04);
12046 c.push(0x40);
12047 {
12048 i32_const(&mut c, 4);
12049 local_get(&mut c, 0);
12050 i32_load(&mut c, 4);
12051 i32_const(&mut c, 2);
12052 c.push(0x6C);
12053 local_get(&mut c, 0);
12054 i32_load(&mut c, 4);
12055 c.push(0x45);
12056 c.push(0x1B); local_tee(&mut c, 6);
12058 i32_const(&mut c, 16);
12059 c.push(0x6C);
12060 c.push(0x10);
12061 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12062 local_tee(&mut c, 5);
12063 local_get(&mut c, 0);
12064 i32_load(&mut c, 8);
12065 local_get(&mut c, 0);
12066 i32_load(&mut c, 0);
12067 i32_const(&mut c, 16);
12068 c.push(0x6C);
12069 memory_copy(&mut c);
12070 local_get(&mut c, 0);
12071 i32_load(&mut c, 8);
12072 local_get(&mut c, 0);
12073 i32_load(&mut c, 4);
12074 i32_const(&mut c, 16);
12075 c.push(0x6C);
12076 c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::Free));
12078 local_get(&mut c, 0);
12079 local_get(&mut c, 5);
12080 i32_store(&mut c, 8);
12081 local_get(&mut c, 0);
12082 local_get(&mut c, 6);
12083 i32_store(&mut c, 4);
12084 }
12085 c.push(0x0B);
12086 local_get(&mut c, 0);
12087 i32_load(&mut c, 8);
12088 local_get(&mut c, 0);
12089 i32_load(&mut c, 0);
12090 i32_const(&mut c, 16);
12091 c.push(0x6C);
12092 c.push(0x6A);
12093 local_set(&mut c, 4);
12094 local_get(&mut c, 3);
12095 c.push(0x04);
12096 c.push(0x40);
12097 {
12098 local_get(&mut c, 4);
12099 local_get(&mut c, 1);
12100 c.push(0xA7);
12101 i32_store(&mut c, 0);
12102 if env.retain_base.is_some() {
12103 local_get(&mut c, 1);
12104 c.push(0xA7);
12105 c.push(0x10);
12106 leb_u32(&mut c, env.call(RuntimeFn::Retain));
12107 }
12108 }
12109 c.push(0x05);
12110 {
12111 local_get(&mut c, 4);
12112 local_get(&mut c, 1);
12113 i64_store(&mut c, 0);
12114 }
12115 c.push(0x0B);
12116 local_get(&mut c, 4);
12117 c.push(0x42);
12118 leb_i64(&mut c, 0);
12119 i64_store(&mut c, 8); local_get(&mut c, 0);
12121 local_get(&mut c, 0);
12122 i32_load(&mut c, 0);
12123 i32_const(&mut c, 1);
12124 c.push(0x6A);
12125 i32_store(&mut c, 0);
12126 local_get(&mut c, 4);
12127 c.push(0x0B); c
12129}
12130
12131fn emit_seq_own_helper(env: &RuntimeEnv) -> Vec<u8> {
12136 let mut c = vec![0x00]; emit_should_clone(&mut c, 0);
12138 c.push(0x04);
12139 c.push(I32); local_get(&mut c, 0);
12141 local_get(&mut c, 1);
12142 c.push(0x10);
12143 leb_u32(&mut c, env.call(RuntimeFn::SeqClone));
12144 c.push(0x05); local_get(&mut c, 0);
12146 c.push(0x0B);
12147 c.push(0x0B); c
12149}
12150
12151fn emit_text_new_helper(env: &RuntimeEnv) -> Vec<u8> {
12156 let mut c = Vec::new();
12157 c.push(0x01);
12159 leb_u32(&mut c, 2);
12160 c.push(I32);
12161
12162 local_get(&mut c, 0); c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12165 local_set(&mut c, 1); let counted = env.retain_base.is_some();
12171 i32_const(&mut c, if counted { 20 } else { 16 });
12172 c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12174 local_set(&mut c, 2); local_get(&mut c, 2);
12177 local_get(&mut c, 0);
12178 i32_store(&mut c, 0); local_get(&mut c, 2);
12180 local_get(&mut c, 0);
12181 i32_store(&mut c, 4); local_get(&mut c, 2);
12183 local_get(&mut c, 1);
12184 i32_store(&mut c, 8); local_get(&mut c, 2);
12186 i32_const(&mut c, AllocClass::TextHeader.code() as i32);
12187 i32_store(&mut c, 12);
12188 if counted {
12189 local_get(&mut c, 2);
12190 i32_const(&mut c, 1);
12191 i32_store(&mut c, 16); local_get(&mut c, 2);
12193 c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
12195 }
12196
12197 local_get(&mut c, 2); c.push(0x0B); c
12200}
12201
12202fn emit_free_helper() -> Vec<u8> {
12210 let mut c = Vec::new();
12211 c.push(0x01);
12214 leb_u32(&mut c, 4);
12215 c.push(I32);
12216
12217 local_get(&mut c, 0); c.push(0x04);
12219 c.push(0x40);
12220 {
12221 local_get(&mut c, 1);
12222 i32_const(&mut c, 7);
12223 c.push(0x6A);
12224 i32_const(&mut c, 3);
12225 c.push(0x76);
12226 local_set(&mut c, 2); i32_const(&mut c, 0);
12228 local_set(&mut c, 4); local_get(&mut c, 2);
12232 i32_const(&mut c, 0);
12233 c.push(0x4B); local_get(&mut c, 2);
12235 i32_const(&mut c, FREE_CLASSES);
12236 c.push(0x4D); c.push(0x71); c.push(0x04);
12239 c.push(0x40); {
12241 local_get(&mut c, 2);
12242 i32_const(&mut c, 1);
12243 c.push(0x6B);
12244 i32_const(&mut c, 4);
12245 c.push(0x6C);
12246 i32_const(&mut c, FREE_TABLE_BASE);
12247 c.push(0x6A);
12248 local_set(&mut c, 3); i32_const(&mut c, 1);
12250 local_set(&mut c, 4); }
12252 c.push(0x05); {
12254 i32_const(&mut c, 32 - POWER_MIN);
12256 local_get(&mut c, 1);
12257 i32_const(&mut c, 1);
12258 c.push(0x6B); c.push(0x67); c.push(0x6B);
12261 local_tee(&mut c, 5); i32_const(&mut c, POWER_CLASSES);
12263 c.push(0x49); c.push(0x04);
12265 c.push(0x40); {
12267 local_get(&mut c, 5);
12268 i32_const(&mut c, FREE_CLASSES);
12269 c.push(0x6A);
12270 i32_const(&mut c, 4);
12271 c.push(0x6C);
12272 i32_const(&mut c, FREE_TABLE_BASE);
12273 c.push(0x6A);
12274 local_set(&mut c, 3); i32_const(&mut c, 1);
12276 local_set(&mut c, 4); }
12278 c.push(0x0B); }
12280 c.push(0x0B); local_get(&mut c, 4);
12283 c.push(0x04);
12284 c.push(0x40); {
12286 local_get(&mut c, 2);
12299 i32_const(&mut c, 2);
12300 c.push(0x4F); c.push(0x04);
12302 c.push(0x40); {
12304 local_get(&mut c, 0);
12305 i32_const(&mut c, 0);
12306 i32_store(&mut c, 12);
12307 }
12308 c.push(0x0B);
12309
12310 local_get(&mut c, 0);
12312 local_get(&mut c, 3);
12313 i32_load(&mut c, 0);
12314 i32_store(&mut c, 0);
12315 local_get(&mut c, 3);
12316 local_get(&mut c, 0);
12317 i32_store(&mut c, 0);
12318 }
12319 c.push(0x0B);
12320 }
12321 c.push(0x0B);
12322
12323 c.push(0x0B); c
12325}
12326
12327const HEAP_POISON: i32 = 0xDEAD_BEEFu32 as i32;
12332
12333fn emit_turn_retain_helper(env: &RuntimeEnv) -> Vec<u8> {
12339 let Some(base) = env.retain_base else {
12340 return vec![0x00, 0x0B];
12341 };
12342 let (ptr_g, len_g, cap_g) = (base, base + 1, base + 2);
12343 let mut c = Vec::new();
12344 c.push(0x01);
12345 leb_u32(&mut c, 3);
12346 c.push(I32); global_get(&mut c, len_g);
12348 global_get(&mut c, cap_g);
12349 c.push(0x48); c.push(0x04);
12351 c.push(0x40); {
12353 global_get(&mut c, ptr_g);
12354 global_get(&mut c, len_g);
12355 i32_const(&mut c, 4);
12356 c.push(0x6C);
12357 c.push(0x6A);
12358 local_get(&mut c, 0);
12359 i32_store(&mut c, 0);
12360 global_get(&mut c, len_g);
12361 i32_const(&mut c, 1);
12362 c.push(0x6A);
12363 global_set(&mut c, len_g);
12364 c.push(0x0F); }
12366 c.push(0x0B); i32_const(&mut c, 4);
12369 global_get(&mut c, cap_g);
12370 i32_const(&mut c, 2);
12371 c.push(0x6C);
12372 global_get(&mut c, cap_g);
12373 c.push(0x45); c.push(0x1B); local_set(&mut c, 1);
12376 local_get(&mut c, 1);
12378 i32_const(&mut c, 4);
12379 c.push(0x6C);
12380 c.push(0x10);
12381 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12382 local_set(&mut c, 2);
12383 i32_const(&mut c, 0);
12385 local_set(&mut c, 3);
12386 c.push(0x02);
12387 c.push(0x40); c.push(0x03);
12389 c.push(0x40); local_get(&mut c, 3);
12391 global_get(&mut c, len_g);
12392 c.push(0x4E); c.push(0x0D);
12394 leb_u32(&mut c, 1); local_get(&mut c, 2);
12396 local_get(&mut c, 3);
12397 i32_const(&mut c, 4);
12398 c.push(0x6C);
12399 c.push(0x6A);
12400 global_get(&mut c, ptr_g);
12401 local_get(&mut c, 3);
12402 i32_const(&mut c, 4);
12403 c.push(0x6C);
12404 c.push(0x6A);
12405 i32_load(&mut c, 0);
12406 i32_store(&mut c, 0);
12407 local_get(&mut c, 3);
12408 i32_const(&mut c, 1);
12409 c.push(0x6A);
12410 local_set(&mut c, 3);
12411 c.push(0x0C);
12412 leb_u32(&mut c, 0); c.push(0x0B); c.push(0x0B); global_get(&mut c, cap_g);
12417 c.push(0x04);
12418 c.push(0x40);
12419 {
12420 global_get(&mut c, ptr_g);
12421 global_get(&mut c, cap_g);
12422 i32_const(&mut c, 4);
12423 c.push(0x6C);
12424 c.push(0x10);
12425 leb_u32(&mut c, env.call(RuntimeFn::Free));
12426 }
12427 c.push(0x0B);
12428 local_get(&mut c, 2);
12429 global_set(&mut c, ptr_g);
12430 local_get(&mut c, 1);
12431 global_set(&mut c, cap_g);
12432 global_get(&mut c, ptr_g);
12434 global_get(&mut c, len_g);
12435 i32_const(&mut c, 4);
12436 c.push(0x6C);
12437 c.push(0x6A);
12438 local_get(&mut c, 0);
12439 i32_store(&mut c, 0);
12440 global_get(&mut c, len_g);
12441 i32_const(&mut c, 1);
12442 c.push(0x6A);
12443 global_set(&mut c, len_g);
12444 c.push(0x0B); c
12446}
12447
12448fn emit_true_retain_helper() -> Vec<u8> {
12455 let mut c = Vec::new();
12456 c.push(0x01);
12457 leb_u32(&mut c, 1);
12458 c.push(I32); local_get(&mut c, 0);
12460 c.push(0x04);
12461 c.push(0x40); {
12463 local_get(&mut c, 0);
12464 i32_load(&mut c, 12);
12465 emit_class_is_counted(&mut c, 1);
12466 c.push(0x04);
12467 c.push(0x40); {
12469 local_get(&mut c, 0);
12470 local_get(&mut c, 0);
12471 i32_load(&mut c, 16);
12472 i32_const(&mut c, 1);
12473 c.push(0x6A);
12474 i32_store(&mut c, 16);
12475 }
12476 c.push(0x0B);
12477 }
12478 c.push(0x0B);
12479 c.push(0x0B); c
12481}
12482
12483fn emit_class_has_field_kinds(c: &mut Vec<u8>, class: u32) {
12493 for (i, kind) in [
12494 AllocClass::RecordHeader,
12495 AllocClass::EnumHeader,
12496 AllocClass::ClosureHeader,
12497 ]
12498 .iter()
12499 .enumerate()
12500 {
12501 local_get(c, class);
12502 i32_const(c, i32::from(kind.code()));
12503 c.push(0x46);
12504 if i != 0 {
12505 c.push(0x72);
12506 }
12507 }
12508}
12509
12510fn emit_heap_child_count(c: &mut Vec<u8>, handle: u32, class: u32) {
12511 local_get(c, handle);
12512 i32_load(c, 4);
12513 local_get(c, handle);
12514 i32_load(c, 0);
12515 local_get(c, class);
12516 i32_const(c, i32::from(AllocClass::EnumHeader.code()));
12517 c.push(0x46);
12518 local_get(c, class);
12519 i32_const(c, i32::from(AllocClass::ClosureHeader.code()));
12520 c.push(0x46);
12521 c.push(0x72);
12522 c.push(0x1B); }
12524
12525fn emit_each_heap_child(
12526 c: &mut Vec<u8>,
12527 handle: u32,
12528 locals: [u32; 5],
12529 visit: impl Fn(&mut Vec<u8>),
12530) {
12531 let [class, stride, flags, index, slot] = locals;
12532 let mask = |second: bool| -> i32 {
12533 AllocClass::ALL
12534 .iter()
12535 .filter(|k| {
12536 let words = k.held_handles();
12537 if second {
12538 words.1
12539 } else {
12540 words.0
12541 }
12542 })
12543 .map(|k| 1i32 << k.code())
12544 .sum()
12545 };
12546 local_get(c, handle);
12547 i32_load(c, 12);
12548 i32_const(c, 0xFF);
12549 c.push(0x71);
12550 local_set(c, class);
12551 for (bit, m) in [(0, mask(false)), (1, mask(true))] {
12552 i32_const(c, m);
12553 local_get(c, class);
12554 c.push(0x76);
12555 i32_const(c, 1);
12556 c.push(0x71);
12557 if bit == 1 {
12558 i32_const(c, 1);
12559 c.push(0x74);
12560 c.push(0x72);
12561 }
12562 }
12563 local_set(c, flags);
12564 local_get(c, class);
12565 i32_const(c, AllocClass::ALL.len() as i32);
12566 c.push(0x49);
12567 c.push(0x04);
12568 c.push(0x40);
12569 local_get(c, flags);
12570 c.push(0x04);
12571 c.push(0x40);
12572 i32_const(c, 8);
12573 i32_const(c, 16);
12574 local_get(c, class);
12575 i32_const(c, i32::from(AllocClass::HandleHeader.code()));
12576 c.push(0x46);
12577 emit_class_has_field_kinds(c, class);
12578 c.push(0x72);
12579 c.push(0x1B);
12580 local_set(c, stride);
12581 i32_const(c, 0);
12582 local_set(c, index);
12583 c.push(0x02);
12584 c.push(0x40);
12585 c.push(0x03);
12586 c.push(0x40);
12587 local_get(c, index);
12588 emit_heap_child_count(c, handle, class);
12589 c.push(0x4F);
12590 c.push(0x0D);
12591 leb_u32(c, 1);
12592 local_get(c, handle);
12593 i32_load(c, 8);
12594 local_get(c, index);
12595 local_get(c, stride);
12596 c.push(0x6C);
12597 c.push(0x6A);
12598 local_set(c, slot);
12599 for (bit, off) in [(1, 0), (2, 8)] {
12600 local_get(c, flags);
12601 i32_const(c, bit);
12602 c.push(0x71);
12603 c.push(0x45);
12604 c.push(0x45); emit_class_has_field_kinds(c, class);
12606 c.push(0x04);
12607 c.push(I32);
12608 local_get(c, handle);
12609 i32_load(c, 8);
12610 emit_heap_child_count(c, handle, class);
12611 i32_const(c, 16);
12612 i32_const(c, 8);
12613 local_get(c, class);
12614 i32_const(c, i32::from(AllocClass::ClosureHeader.code()));
12615 c.push(0x46);
12616 c.push(0x1B); c.push(0x6C);
12618 c.push(0x6A);
12619 local_get(c, index);
12620 c.push(0x6A);
12621 i32_load8_u(c, 0);
12622 c.push(0x05);
12623 i32_const(c, 1);
12624 c.push(0x0B);
12625 c.push(0x71);
12626 c.push(0x04);
12627 c.push(0x40);
12628 local_get(c, slot);
12629 i32_load(c, off);
12630 visit(c);
12631 c.push(0x0B);
12632 }
12633 local_get(c, index);
12634 i32_const(c, 1);
12635 c.push(0x6A);
12636 local_set(c, index);
12637 c.push(0x0C);
12638 leb_u32(c, 0);
12639 c.push(0x0B);
12640 c.push(0x0B);
12641 c.push(0x0B);
12642 c.push(0x0B);
12643}
12644
12645fn emit_retain_children_helper(env: &RuntimeEnv) -> Vec<u8> {
12646 let mut c = vec![0x01];
12647 leb_u32(&mut c, 5);
12648 c.push(I32);
12649 local_get(&mut c, 0);
12650 c.push(0x04);
12651 c.push(0x40);
12652 emit_each_heap_child(&mut c, 0, [1, 2, 3, 4, 5], |c| {
12653 c.push(0x10);
12654 leb_u32(c, env.call(RuntimeFn::Retain));
12655 });
12656 c.push(0x0B);
12657 c.push(0x0B);
12658 c
12659}
12660
12661fn emit_closure_retain_helper(env: &RuntimeEnv) -> Vec<u8> {
12664 let Some(base) = env.callback_base else {
12665 return vec![0x00, 0x00, 0x0B];
12666 };
12667 let mut c = vec![0x01];
12668 leb_u32(&mut c, 1);
12669 c.push(I32); global_get(&mut c, base + 1);
12671 i32_const(&mut c, -1);
12672 c.push(0x46);
12673 c.extend([0x04, 0x40, 0x00, 0x0B]); i32_const(&mut c, 12);
12675 c.push(0x10);
12676 leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12677 local_set(&mut c, 1);
12678 global_get(&mut c, base + 1);
12679 i32_const(&mut c, 1);
12680 c.push(0x6A);
12681 global_set(&mut c, base + 1);
12682 local_get(&mut c, 1);
12683 global_get(&mut c, base + 1);
12684 i32_store(&mut c, 0);
12685 local_get(&mut c, 1);
12686 local_get(&mut c, 0);
12687 i32_store(&mut c, 4);
12688 local_get(&mut c, 1);
12689 global_get(&mut c, base);
12690 i32_store(&mut c, 8);
12691 local_get(&mut c, 1);
12692 global_set(&mut c, base);
12693 local_get(&mut c, 0);
12694 c.push(0x10);
12695 leb_u32(&mut c, env.call(RuntimeFn::Retain));
12696 global_get(&mut c, base + 1);
12697 c.push(0x0B);
12698 c
12699}
12700
12701fn emit_closure_release_helper(env: &RuntimeEnv) -> Vec<u8> {
12704 let Some(base) = env.callback_base else {
12705 return vec![0x00, 0x0B];
12706 };
12707 let mut c = vec![0x01];
12708 leb_u32(&mut c, 2);
12709 c.push(I32); global_get(&mut c, base);
12711 local_set(&mut c, 1);
12712 c.extend([0x02, 0x40, 0x03, 0x40]);
12713 local_get(&mut c, 1);
12714 c.push(0x45);
12715 c.push(0x0D);
12716 leb_u32(&mut c, 1);
12717 local_get(&mut c, 1);
12718 i32_load(&mut c, 0);
12719 local_get(&mut c, 0);
12720 c.push(0x46);
12721 c.extend([0x04, 0x40]);
12722 local_get(&mut c, 2);
12723 c.extend([0x04, 0x40]);
12724 local_get(&mut c, 2);
12725 local_get(&mut c, 1);
12726 i32_load(&mut c, 8);
12727 i32_store(&mut c, 8);
12728 c.push(0x05);
12729 local_get(&mut c, 1);
12730 i32_load(&mut c, 8);
12731 global_set(&mut c, base);
12732 c.push(0x0B);
12733 local_get(&mut c, 1);
12734 i32_load(&mut c, 4);
12735 c.push(0x10);
12736 leb_u32(&mut c, env.call(RuntimeFn::Release));
12737 local_get(&mut c, 1);
12738 i32_const(&mut c, 12);
12739 c.push(0x10);
12740 leb_u32(&mut c, env.call(RuntimeFn::Free));
12741 c.push(0x0F);
12742 c.push(0x0B);
12743 local_get(&mut c, 1);
12744 local_set(&mut c, 2);
12745 local_get(&mut c, 1);
12746 i32_load(&mut c, 8);
12747 local_set(&mut c, 1);
12748 c.push(0x0C);
12749 leb_u32(&mut c, 0);
12750 c.extend([0x0B, 0x0B, 0x0B]);
12751 c
12752}
12753
12754fn emit_true_release_helper(env: &RuntimeEnv) -> Vec<u8> {
12761 let mut c = Vec::new();
12762 c.push(0x01);
12763 leb_u32(&mut c, 1);
12764 c.push(I32); local_get(&mut c, 0);
12766 c.push(0x04);
12767 c.push(0x40); {
12769 local_get(&mut c, 0);
12770 i32_load(&mut c, 12);
12771 emit_class_is_counted(&mut c, 1);
12772 c.push(0x45); c.push(0x0D); leb_u32(&mut c, 0);
12775 local_get(&mut c, 0);
12776 i32_load(&mut c, 16);
12777 local_set(&mut c, 1);
12778 local_get(&mut c, 1);
12779 i32_const(&mut c, 1);
12780 c.push(0x4C); c.push(0x04);
12782 c.push(0x40); {
12784 local_get(&mut c, 0);
12785 c.push(0x10);
12786 leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
12787 }
12788 c.push(0x05); {
12790 local_get(&mut c, 0);
12791 local_get(&mut c, 1);
12792 i32_const(&mut c, 1);
12793 c.push(0x6B);
12794 i32_store(&mut c, 16);
12795 }
12796 c.push(0x0B); }
12798 c.push(0x0B); c.push(0x0B); c
12801}
12802
12803fn emit_class_is_counted(c: &mut Vec<u8>, class_local: u32) {
12827 let mask: u32 = AllocClass::ALL
12828 .iter()
12829 .filter(|k| k.is_counted())
12830 .map(|k| 1u32 << k.code())
12831 .sum();
12832 let classes = AllocClass::ALL.len() as i32;
12833 i32_const(c, 0xFF);
12834 c.push(0x71); local_tee(c, class_local);
12836 i32_const(c, classes);
12837 c.push(0x49); i32_const(c, mask as i32);
12839 local_get(c, class_local);
12840 c.push(0x76); i32_const(c, 1);
12842 c.push(0x71); c.push(0x71); }
12845
12846fn emit_exact_buffer_holds(
12847 code: &mut Vec<u8>,
12848 hdr: u32,
12849 i: u32,
12850 slot: u32,
12851 host: u32,
12852 cloning: bool,
12853) {
12854 local_get(code, hdr);
12855 i32_load(code, 12);
12856 i32_const(code, 0xff);
12857 code.push(0x71);
12858 i32_const(code, AllocClass::ExactIntegerHeader.code() as i32);
12859 code.extend([0x46, 0x04, 0x40]);
12860 i32_const(code, 0);
12861 local_set(code, i);
12862 code.extend([0x02, 0x40, 0x03, 0x40]);
12863 local_get(code, i);
12864 local_get(code, hdr);
12865 i32_load(code, 0);
12866 code.extend([0x4f, 0x0d]);
12867 leb_u32(code, 1);
12868 local_get(code, hdr);
12869 i32_load(code, 8);
12870 local_get(code, i);
12871 i32_const(code, 8);
12872 code.extend([0x6c, 0x6a]);
12873 local_tee(code, slot);
12874 i64_load(code, 0);
12875 code.push(0x42);
12876 leb_i64(code, 1);
12877 code.extend([0x83, 0xa7, 0x04, 0x40]);
12878 if cloning {
12879 local_get(code, slot);
12880 }
12881 local_get(code, slot);
12882 i64_load(code, 0);
12883 code.push(0x10);
12884 leb_u32(code, host);
12885 if cloning {
12886 i64_store(code, 0);
12887 }
12888 code.push(0x0b);
12889 local_get(code, i);
12890 i32_const(code, 1);
12891 code.push(0x6a);
12892 local_set(code, i);
12893 code.push(0x0c);
12894 leb_u32(code, 0);
12895 code.extend([0x0b, 0x0b, 0x0b]);
12896}
12897
12898fn emit_free_object_helper(env: &RuntimeEnv) -> Vec<u8> {
12899 let mut c = Vec::new();
12900 c.push(0x01);
12902 leb_u32(&mut c, 7);
12903 c.push(I32);
12904 local_get(&mut c, 0);
12905 c.push(0x04);
12906 c.push(0x40); {
12908 local_get(&mut c, 0);
12909 i32_load(&mut c, 12);
12910 i32_const(&mut c, 0xFF);
12911 c.push(0x71); local_set(&mut c, 1);
12913 emit_each_heap_child(&mut c, 0, [1, 2, 3, 4, 7], |c| {
12914 local_set(c, 5); local_get(c, 5);
12916 c.push(0x04);
12917 c.push(0x40); {
12919 local_get(c, 5);
12920 i32_load(c, 12);
12921 emit_class_is_counted(c, 6);
12922 c.push(0x04);
12923 c.push(0x40); {
12925 local_get(c, 5);
12926 local_get(c, 5);
12927 i32_load(c, 16);
12928 i32_const(c, 1);
12929 c.push(0x6B); local_tee(c, 6);
12931 i32_store(c, 16);
12932 local_get(c, 6);
12933 i32_const(c, 0);
12934 c.push(0x4C); c.push(0x04);
12936 c.push(0x40);
12937 {
12938 local_get(c, 5);
12939 c.push(0x10); leb_u32(c, env.call(RuntimeFn::FreeObject));
12941 }
12942 c.push(0x0B); }
12944 c.push(0x0B); }
12946 c.push(0x0B); });
12948 if let Some(drop) = env.exact_drop {
12949 emit_exact_buffer_holds(&mut c, 0, 4, 7, drop, false);
12950 }
12951 local_get(&mut c, 1);
12955 i32_const(&mut c, AllocClass::TextHeader.code() as i32);
12956 c.push(0x46); c.push(0x04);
12958 c.push(0x40); {
12960 local_get(&mut c, 0);
12961 i32_load(&mut c, 4);
12962 i32_const(&mut c, TEXT_GROWABLE);
12963 c.push(0x71);
12964 c.push(0x45); c.push(0x04);
12966 c.push(0x40);
12967 {
12968 local_get(&mut c, 0);
12969 i32_load(&mut c, 8);
12970 local_get(&mut c, 0);
12971 i32_load(&mut c, 4);
12972 c.push(0x10);
12973 leb_u32(&mut c, env.call(RuntimeFn::Free));
12974 }
12975 c.push(0x05); {
12977 local_get(&mut c, 0);
12978 i32_load(&mut c, 8);
12979 i32_const(&mut c, 8);
12980 c.push(0x6B);
12981 local_set(&mut c, 3); local_get(&mut c, 3);
12983 local_get(&mut c, 3);
12984 i32_load(&mut c, 0);
12985 i32_const(&mut c, 1);
12986 c.push(0x6B);
12987 local_tee(&mut c, 6);
12988 i32_store(&mut c, 0);
12989 local_get(&mut c, 6);
12990 i32_const(&mut c, 0);
12991 c.push(0x4C); c.push(0x04);
12993 c.push(0x40);
12994 {
12995 local_get(&mut c, 3);
12996 local_get(&mut c, 0);
12997 i32_load(&mut c, 4);
12998 i32_const(&mut c, i32::MAX);
12999 c.push(0x71); i32_const(&mut c, 8);
13001 c.push(0x6A); c.push(0x10);
13003 leb_u32(&mut c, env.call(RuntimeFn::Free));
13004 }
13005 c.push(0x0B);
13006 }
13007 c.push(0x0B);
13008 }
13009 c.push(0x05); {
13011 local_get(&mut c, 0);
13012 i32_load(&mut c, 8);
13013 local_get(&mut c, 0);
13014 i32_load(&mut c, 4);
13015 i32_const(&mut c, 17);
13016 i32_const(&mut c, CRDT_RECORD_BYTES);
13017 i32_const(&mut c, 16);
13018 i32_const(&mut c, 9);
13019 i32_const(&mut c, 8);
13020 emit_class_has_field_kinds(&mut c, 1);
13021 c.push(0x1B);
13022 local_get(&mut c, 1);
13023 i32_const(&mut c, i32::from(AllocClass::MapScalarScalar.code()));
13024 c.push(0x4F);
13025 local_get(&mut c, 1);
13026 i32_const(&mut c, i32::from(AllocClass::MapHandleHandle.code()));
13027 c.push(0x4D);
13028 c.push(0x71);
13029 c.push(0x1B); local_get(&mut c, 1);
13031 i32_const(&mut c, i32::from(AllocClass::CounterHeader.code()));
13032 c.push(0x46);
13033 c.push(0x1B); local_get(&mut c, 1);
13035 i32_const(&mut c, i32::from(AllocClass::ClosureHeader.code()));
13036 c.push(0x46);
13037 c.push(0x1B); c.push(0x6C);
13039 c.push(0x10);
13040 leb_u32(&mut c, env.call(RuntimeFn::Free));
13041 }
13042 c.push(0x0B);
13043 for off in [0u32, 4, 8, 16] {
13046 local_get(&mut c, 0);
13047 i32_const(&mut c, HEAP_POISON);
13048 i32_store(&mut c, off);
13049 }
13050 local_get(&mut c, 0);
13051 i32_const(&mut c, 20);
13052 c.push(0x10);
13053 leb_u32(&mut c, env.call(RuntimeFn::Free));
13054 }
13055 c.push(0x0B); c.push(0x0B); c
13058}
13059
13060fn emit_safepoint_helper(env: &RuntimeEnv) -> Vec<u8> {
13068 let Some(base) = env.retain_base else {
13069 return vec![0x00, 0x0B];
13070 };
13071 let (ptr_g, len_g, cap_g) = (base, base + 1, base + 2);
13072 let mut c = Vec::new();
13073 c.push(0x01);
13076 leb_u32(&mut c, 6);
13077 c.push(I32);
13078 global_get(&mut c, ptr_g);
13079 local_set(&mut c, 1);
13080 global_get(&mut c, len_g);
13081 local_set(&mut c, 2);
13082 global_get(&mut c, cap_g);
13083 local_set(&mut c, 0); i32_const(&mut c, 0);
13090 global_set(&mut c, ptr_g);
13091 i32_const(&mut c, 0);
13092 global_set(&mut c, len_g);
13093 i32_const(&mut c, 0);
13094 global_set(&mut c, cap_g);
13095 i32_const(&mut c, 0);
13096 local_set(&mut c, 3); c.push(0x02);
13098 c.push(0x40); c.push(0x03);
13100 c.push(0x40); local_get(&mut c, 3);
13102 local_get(&mut c, 2);
13103 c.push(0x4E); c.push(0x0D);
13105 leb_u32(&mut c, 1); local_get(&mut c, 1);
13107 local_get(&mut c, 3);
13108 i32_const(&mut c, 4);
13109 c.push(0x6C);
13110 c.push(0x6A);
13111 i32_load(&mut c, 0);
13112 local_set(&mut c, 4); local_get(&mut c, 4);
13114 c.push(0x04);
13115 c.push(0x40); {
13117 local_get(&mut c, 4);
13118 local_get(&mut c, 4);
13119 i32_load(&mut c, 16);
13120 i32_const(&mut c, 1);
13121 c.push(0x6B); local_tee(&mut c, 5);
13123 i32_store(&mut c, 16);
13124 local_get(&mut c, 5);
13125 i32_const(&mut c, 0);
13126 c.push(0x4C); c.push(0x04);
13128 c.push(0x40);
13129 {
13130 local_get(&mut c, 4);
13131 c.push(0x10);
13132 leb_u32(&mut c, env.call(RuntimeFn::FreeObject));
13133 }
13134 c.push(0x0B); }
13136 c.push(0x0B); local_get(&mut c, 3);
13138 i32_const(&mut c, 1);
13139 c.push(0x6A);
13140 local_set(&mut c, 3);
13141 c.push(0x0C);
13142 leb_u32(&mut c, 0); c.push(0x0B); c.push(0x0B); local_get(&mut c, 1);
13148 local_get(&mut c, 0);
13149 i32_const(&mut c, 4);
13150 c.push(0x6C);
13151 c.push(0x10);
13152 leb_u32(&mut c, env.call(RuntimeFn::Free));
13153 c.push(0x0B); c
13155}
13156
13157fn emit_heap_census_visit_helper(env: &RuntimeEnv) -> Vec<u8> {
13171 let mut c = vec![0x01];
13172 leb_u32(&mut c, 7);
13174 c.push(I32);
13175 local_get(&mut c, 0);
13176 c.push(0x45);
13177 c.push(0x04);
13178 c.push(0x40);
13179 c.push(0x0F);
13180 c.push(0x0B);
13181 local_get(&mut c, 0);
13182 i32_load(&mut c, 12);
13183 emit_class_is_counted(&mut c, 2);
13184 c.push(0x45);
13185 c.push(0x04);
13186 c.push(0x40);
13187 c.push(0x0F);
13188 c.push(0x0B);
13189 local_get(&mut c, 1);
13190 local_get(&mut c, 0);
13191 i32_const(&mut c, env.heap_base);
13192 c.push(0x6B);
13193 i32_const(&mut c, 3);
13194 c.push(0x76);
13195 i32_const(&mut c, 4);
13196 c.push(0x6C);
13197 c.push(0x6A);
13198 local_tee(&mut c, 7);
13199 i32_load(&mut c, 0);
13200 local_set(&mut c, 8);
13201 local_get(&mut c, 7);
13202 local_get(&mut c, 8);
13203 i32_const(&mut c, 1);
13204 c.push(0x6A);
13205 i32_store(&mut c, 0);
13206 local_get(&mut c, 8);
13207 c.push(0x04);
13208 c.push(0x40);
13209 c.push(0x0F); c.push(0x0B);
13211 emit_each_heap_child(&mut c, 0, [2, 3, 4, 5, 6], |c| {
13212 local_get(c, 1);
13213 c.push(0x10);
13214 leb_u32(c, env.call(RuntimeFn::CensusVisit));
13215 });
13216 c.push(0x0B);
13217 c
13218}
13219
13220fn emit_heap_census_helper(env: &RuntimeEnv) -> Vec<u8> {
13221 let mut c = Vec::new();
13222 c.push(0x01);
13225 leb_u32(&mut c, 11);
13226 c.push(I32);
13227 global_get(&mut c, env.heap_global);
13232 i32_const(&mut c, env.heap_base);
13233 c.push(0x6B);
13234 i32_const(&mut c, 3);
13235 c.push(0x76); i32_const(&mut c, 1);
13237 c.push(0x6A);
13238 local_set(&mut c, 1); global_get(&mut c, env.heap_global);
13240 i32_const(&mut c, 7);
13241 c.push(0x6A);
13242 i32_const(&mut c, -8);
13243 c.push(0x71); local_set(&mut c, 0); local_get(&mut c, 0);
13247 local_get(&mut c, 1);
13248 i32_const(&mut c, 4);
13249 c.push(0x6C);
13250 c.push(0x6A);
13251 local_set(&mut c, 10);
13252 c.push(0x3F); c.push(0x00);
13254 i32_const(&mut c, 16);
13255 c.push(0x74); local_get(&mut c, 10);
13257 c.push(0x49); c.push(0x04);
13259 c.push(0x40); {
13261 local_get(&mut c, 10);
13262 c.push(0x3F);
13263 c.push(0x00);
13264 i32_const(&mut c, 16);
13265 c.push(0x74);
13266 c.push(0x6B); i32_const(&mut c, 0xFFFF);
13268 c.push(0x6A);
13269 i32_const(&mut c, 16);
13270 c.push(0x76); c.push(0x40); c.push(0x00);
13273 i32_const(&mut c, -1);
13274 c.push(0x46); c.push(0x04);
13276 c.push(0x40); {
13278 i32_const(&mut c, 4);
13279 c.push(0x42);
13280 c.push(0x00); c.push(0x10);
13282 leb_u32(&mut c, env.fail_at);
13283 c.push(0x00); }
13285 c.push(0x0B);
13286 }
13287 c.push(0x0B);
13288 let zero_scratch = |c: &mut Vec<u8>| {
13291 i32_const(c, 0);
13292 local_set(c, 9); c.push(0x02);
13294 c.push(0x40);
13295 c.push(0x03);
13296 c.push(0x40);
13297 local_get(c, 9);
13298 local_get(c, 1);
13299 c.push(0x4E);
13300 c.push(0x0D);
13301 leb_u32(c, 1);
13302 local_get(c, 0);
13303 local_get(c, 9);
13304 i32_const(c, 4);
13305 c.push(0x6C);
13306 c.push(0x6A);
13307 i32_const(c, 0);
13308 i32_store(c, 0);
13309 local_get(c, 9);
13310 i32_const(c, 1);
13311 c.push(0x6A);
13312 local_set(c, 9);
13313 c.push(0x0C);
13314 leb_u32(c, 0);
13315 c.push(0x0B);
13316 c.push(0x0B);
13317 };
13318 zero_scratch(&mut c);
13319
13320 for (i, kind) in env.global_kinds.iter().enumerate() {
13321 if counted_kind(*kind) {
13322 global_get(&mut c, i as u32);
13323 local_get(&mut c, 0);
13324 c.push(0x10);
13325 leb_u32(&mut c, env.call(RuntimeFn::CensusVisit));
13326 }
13327 }
13328
13329 if let Some(base) = env.callback_base {
13330 global_get(&mut c, base);
13331 local_set(&mut c, 7);
13332 c.extend([0x02, 0x40, 0x03, 0x40]);
13333 local_get(&mut c, 7);
13334 c.push(0x45);
13335 c.push(0x0D);
13336 leb_u32(&mut c, 1);
13337 local_get(&mut c, 7);
13338 i32_load(&mut c, 4);
13339 local_get(&mut c, 0);
13340 c.push(0x10);
13341 leb_u32(&mut c, env.call(RuntimeFn::CensusVisit));
13342 local_get(&mut c, 7);
13343 i32_load(&mut c, 8);
13344 local_set(&mut c, 7);
13345 c.push(0x0C);
13346 leb_u32(&mut c, 0);
13347 c.extend([0x0B, 0x0B]);
13348 }
13349 i32_const(&mut c, 0);
13351 local_set(&mut c, 9);
13352 c.push(0x02);
13353 c.push(0x40);
13354 c.push(0x03);
13355 c.push(0x40);
13356 local_get(&mut c, 9);
13357 local_get(&mut c, 1);
13358 c.push(0x4F);
13359 c.push(0x0D);
13360 leb_u32(&mut c, 1);
13361 local_get(&mut c, 0);
13362 local_get(&mut c, 9);
13363 i32_const(&mut c, 4);
13364 c.push(0x6C);
13365 c.push(0x6A);
13366 i32_load(&mut c, 0);
13367 local_tee(&mut c, 10);
13368 c.push(0x04);
13369 c.push(0x40);
13370 local_get(&mut c, 9);
13371 i32_const(&mut c, 8);
13372 c.push(0x6C);
13373 i32_const(&mut c, env.heap_base);
13374 c.push(0x6A);
13375 local_tee(&mut c, 3);
13376 i32_load(&mut c, 16);
13377 local_get(&mut c, 10);
13378 c.push(0x47);
13379 c.push(0x04);
13380 c.push(0x40);
13381 local_get(&mut c, 3);
13382 local_set(&mut c, 2);
13383 c.push(0x0C);
13384 leb_u32(&mut c, 3);
13385 c.push(0x0B);
13386 c.push(0x0B);
13387 local_get(&mut c, 9);
13388 i32_const(&mut c, 1);
13389 c.push(0x6A);
13390 local_set(&mut c, 9);
13391 c.push(0x0C);
13392 leb_u32(&mut c, 0);
13393 c.push(0x0B);
13394 c.push(0x0B);
13395 zero_scratch(&mut c);
13396 local_get(&mut c, 2);
13397 c.push(0x0B); c
13399}
13400
13401#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13413enum AllocClass {
13414 Raw,
13417 ScalarHeader,
13420 HandleHeader,
13423 MapScalarScalar,
13425 MapScalarHandle,
13427 MapHandleScalar,
13429 MapHandleHandle,
13431 TextHeader,
13435 RecordHeader,
13438 EnumHeader,
13440 CounterHeader,
13442 ClosureHeader,
13444 ExactIntegerHeader,
13446}
13447
13448impl AllocClass {
13449 const ALL: [AllocClass; 13] = [
13450 AllocClass::Raw,
13451 AllocClass::ScalarHeader,
13452 AllocClass::HandleHeader,
13453 AllocClass::MapScalarScalar,
13454 AllocClass::MapScalarHandle,
13455 AllocClass::MapHandleScalar,
13456 AllocClass::MapHandleHandle,
13457 AllocClass::TextHeader,
13458 AllocClass::RecordHeader,
13459 AllocClass::EnumHeader,
13460 AllocClass::CounterHeader,
13461 AllocClass::ClosureHeader,
13462 AllocClass::ExactIntegerHeader,
13463 ];
13464
13465 fn code(self) -> u8 {
13468 match self {
13469 AllocClass::Raw => 0,
13470 AllocClass::ScalarHeader => 1,
13471 AllocClass::HandleHeader => 2,
13472 AllocClass::MapScalarScalar => 3,
13473 AllocClass::MapScalarHandle => 4,
13474 AllocClass::MapHandleScalar => 5,
13475 AllocClass::MapHandleHandle => 6,
13476 AllocClass::TextHeader => 7,
13477 AllocClass::RecordHeader => 8,
13478 AllocClass::EnumHeader => 9,
13479 AllocClass::CounterHeader => 10,
13480 AllocClass::ClosureHeader => 11,
13481 AllocClass::ExactIntegerHeader => 12,
13482 }
13483 }
13484
13485 fn of_elements(elements_are_handles: bool) -> AllocClass {
13488 if elements_are_handles {
13489 AllocClass::HandleHeader
13490 } else {
13491 AllocClass::ScalarHeader
13492 }
13493 }
13494
13495 fn of_map(key_is_handle: bool, value_is_handle: bool) -> AllocClass {
13498 match (key_is_handle, value_is_handle) {
13499 (false, false) => AllocClass::MapScalarScalar,
13500 (false, true) => AllocClass::MapScalarHandle,
13501 (true, false) => AllocClass::MapHandleScalar,
13502 (true, true) => AllocClass::MapHandleHandle,
13503 }
13504 }
13505
13506 fn held_handles(self) -> (bool, bool) {
13510 match self {
13511 AllocClass::HandleHeader
13512 | AllocClass::MapHandleScalar
13513 | AllocClass::RecordHeader
13514 | AllocClass::EnumHeader
13515 | AllocClass::ClosureHeader => (true, false),
13516 AllocClass::MapScalarHandle => (false, true),
13517 AllocClass::MapHandleHandle => (true, true),
13518 AllocClass::Raw
13519 | AllocClass::ScalarHeader
13520 | AllocClass::MapScalarScalar
13521 | AllocClass::TextHeader
13522 | AllocClass::CounterHeader
13523 | AllocClass::ExactIntegerHeader => (false, false),
13524 }
13525 }
13526
13527 fn is_counted(self) -> bool {
13530 matches!(
13531 self,
13532 AllocClass::ScalarHeader
13533 | AllocClass::HandleHeader
13534 | AllocClass::TextHeader
13535 | AllocClass::MapScalarScalar
13536 | AllocClass::MapScalarHandle
13537 | AllocClass::MapHandleScalar
13538 | AllocClass::MapHandleHandle
13539 | AllocClass::RecordHeader
13540 | AllocClass::EnumHeader
13541 | AllocClass::CounterHeader
13542 | AllocClass::ClosureHeader
13543 | AllocClass::ExactIntegerHeader
13544 )
13545 }
13546}
13547
13548fn counted_kind(k: Option<Kind>) -> bool {
13553 matches!(
13554 k,
13555 Some(Kind::SeqInt)
13556 | Some(Kind::SeqBool)
13557 | Some(Kind::SeqFloat)
13558 | Some(Kind::SeqWord32)
13559 | Some(Kind::SeqWord64)
13560 | Some(Kind::SeqText)
13561 | Some(Kind::SeqStruct)
13562 | Some(Kind::SeqEnum)
13563 | Some(Kind::SeqSeqInt)
13564 | Some(Kind::SeqHandle)
13565 | Some(Kind::Set)
13566 | Some(Kind::SetText)
13567 | Some(Kind::CrdtSetText)
13568 | Some(Kind::Text)
13569 | Some(Kind::Map)
13570 | Some(Kind::Struct)
13571 | Some(Kind::Tuple)
13572 | Some(Kind::Enum)
13573 | Some(Kind::Rational)
13574 | Some(Kind::CrdtCounter)
13575 | Some(Kind::Closure)
13576 )
13577}
13578
13579fn kind_is_handle(k: Kind) -> bool {
13591 match k {
13592 Kind::Nothing
13593 | Kind::Int
13594 | Kind::Bool
13595 | Kind::Char
13596 | Kind::Float
13597 | Kind::Date
13598 | Kind::Moment
13599 | Kind::Duration
13600 | Kind::Time
13601 | Kind::Span
13602 | Kind::Word32
13603 | Kind::Word64 => false,
13604 Kind::SeqInt
13605 | Kind::SeqBool
13606 | Kind::SeqFloat
13607 | Kind::SeqText
13608 | Kind::SeqStruct
13609 | Kind::SeqEnum
13610 | Kind::SeqSeqInt
13611 | Kind::SeqHandle
13612 | Kind::SeqAny
13613 | Kind::SeqWord32
13614 | Kind::SeqWord64
13615 | Kind::Text
13616 | Kind::Struct
13617 | Kind::Map
13618 | Kind::Set
13619 | Kind::SetText
13620 | Kind::CrdtSetText
13621 | Kind::CrdtCounter
13622 | Kind::Enum
13623 | Kind::Closure
13624 | Kind::Tuple
13625 | Kind::Rational
13626 | Kind::Optional
13627 | Kind::Lanes
13628 | Kind::BigInt
13629 | Kind::Complex
13630 | Kind::Modular
13631 | Kind::Decimal
13632 | Kind::Money
13633 | Kind::Quantity
13634 | Kind::Uuid
13635 | Kind::LanesV
13636 | Kind::Dynamic
13637 | Kind::Tower => true,
13638 }
13639}
13640
13641fn empty_collection_class(kind: Option<Kind>) -> AllocClass {
13647 match kind {
13648 Some(Kind::Map) => AllocClass::MapScalarScalar,
13651 Some(Kind::SeqInt)
13652 | Some(Kind::SeqBool)
13653 | Some(Kind::SeqFloat)
13654 | Some(Kind::SeqWord32)
13655 | Some(Kind::SeqWord64)
13656 | Some(Kind::Set) => AllocClass::ScalarHeader,
13657 Some(Kind::SeqText)
13658 | Some(Kind::SeqStruct)
13659 | Some(Kind::SeqEnum)
13660 | Some(Kind::SeqSeqInt)
13661 | Some(Kind::SeqHandle)
13662 | Some(Kind::SetText)
13663 | Some(Kind::CrdtSetText) => AllocClass::HandleHeader,
13664 _ => AllocClass::Raw,
13665 }
13666}
13667
13668fn emit_alloc(code: &mut Vec<u8>, ctx: &Ctx, dst_scratch: u32, class: AllocClass) {
13671 if let Some(rt_alloc) = ctx.rt_alloc {
13673 code.push(0x10); leb_u32(code, rt_alloc);
13679 local_set(code, dst_scratch); } else if let Some(alloc) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Alloc)) {
13681 let counted = class.is_counted() && ctx.heap_counting();
13691 if counted {
13692 i32_const(code, 4);
13693 code.push(0x6A); }
13695 code.push(0x10); leb_u32(code, alloc);
13697 local_set(code, dst_scratch);
13698 if class != AllocClass::Raw {
13699 local_get(code, dst_scratch);
13700 i32_const(code, class.code() as i32);
13701 i32_store(code, 12);
13702 }
13703 if counted {
13704 local_get(code, dst_scratch);
13705 i32_const(code, 1);
13706 i32_store(code, 16);
13707 if let Some(push) = ctx.runtime.and_then(|r| r.index(RuntimeFn::TurnRetain)) {
13708 local_get(code, dst_scratch);
13709 code.push(0x10);
13710 leb_u32(code, push);
13711 }
13712 }
13713 } else {
13714 global_get(code, ctx.heap_global);
13716 i32_const(code, 7);
13717 code.push(0x6A);
13718 i32_const(code, -8);
13719 code.push(0x71);
13720 local_tee(code, dst_scratch);
13721 code.push(0x6A);
13722 global_set(code, ctx.heap_global);
13723 }
13724}
13725
13726fn emit_free(
13729 code: &mut Vec<u8>,
13730 ctx: &Ctx,
13731 push_ptr: impl Fn(&mut Vec<u8>),
13732 push_size: impl Fn(&mut Vec<u8>),
13733) {
13734 let Some(free) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Free)) else {
13735 return;
13736 };
13737 push_ptr(code);
13738 push_size(code);
13739 code.push(0x10); leb_u32(code, free);
13741}
13742
13743fn lower_list_push(
13752 code: &mut Vec<u8>,
13753 kinds: &KindTable,
13754 ctx: &Ctx,
13755 num_regs: u32,
13756 list: u16,
13757 value: u16,
13758) -> R<()> {
13759 let elem =
13760 kinds
13761 .get(list as usize)
13762 .and_then(Kind::seq_elem)
13763 .ok_or(WasmLowerError::Unsupported(
13764 "push to a sequence of unknown element kind",
13765 ))?;
13766 lower_list_push_at(code, elem, ctx, num_regs, list as u32, value)
13767}
13768
13769fn lower_list_push_at(
13773 code: &mut Vec<u8>,
13774 elem: Kind,
13775 ctx: &Ctx,
13776 num_regs: u32,
13777 lst: u32,
13778 value: u16,
13779) -> R<()> {
13780 let elem_load = seq_elem_load(elem)?;
13782 let elem_store = seq_elem_store(elem)?;
13783 if let Some(push_slot) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqPushSlot)) {
13784 if ctx.hot.get() {
13785 let len = num_regs + 5;
13788 local_get(code, lst);
13789 i32_load(code, 0);
13790 local_tee(code, len);
13791 local_get(code, lst);
13792 i32_load(code, 4);
13793 code.push(0x48); code.push(0x04);
13795 code.push(I32);
13796 local_get(code, lst);
13797 local_get(code, len);
13798 i32_const(code, 1);
13799 code.push(0x6A);
13800 i32_store(code, 0); local_get(code, lst);
13802 i32_load(code, 8);
13803 local_get(code, len);
13804 i32_const(code, 3);
13805 code.push(0x74); code.push(0x6A);
13807 code.push(0x05);
13808 local_get(code, lst);
13809 code.push(0x10);
13810 leb_u32(code, push_slot);
13811 code.push(0x0B);
13812 } else {
13813 local_get(code, lst);
13814 code.push(0x10);
13815 leb_u32(code, push_slot);
13816 }
13817 local_get(code, value as u32);
13818 elem_store(code, 0);
13819 return Ok(());
13820 }
13821 let (hs_new, hs_i, hs_cap) = (num_regs + 5, num_regs + 6, num_regs + 7);
13823 local_get(code, lst);
13831 i32_load(code, 0); local_get(code, lst);
13833 i32_load(code, 4); code.push(0x48); code.push(0x04);
13836 code.push(0x40); {
13838 local_get(code, lst);
13840 i32_load(code, 8); local_get(code, lst);
13842 i32_load(code, 0); i32_const(code, 8);
13844 code.push(0x6C);
13845 code.push(0x6A); local_get(code, value as u32);
13847 elem_store(code, 0);
13848 }
13849 code.push(0x05); {
13851 i32_const(code, 4);
13853 local_get(code, lst);
13854 i32_load(code, 4);
13855 i32_const(code, 2);
13856 code.push(0x6C); local_get(code, lst);
13858 i32_load(code, 4);
13859 code.push(0x45); code.push(0x1B); local_set(code, hs_cap);
13862 local_get(code, hs_cap);
13864 i32_const(code, 8);
13865 code.push(0x6C);
13866 emit_alloc(code, ctx, hs_new, AllocClass::Raw);
13867 i32_const(code, 0);
13869 local_set(code, hs_i);
13870 code.push(0x02);
13871 code.push(0x40); code.push(0x03);
13873 code.push(0x40); local_get(code, hs_i);
13875 local_get(code, lst);
13876 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
13879 leb_u32(code, 1); local_get(code, hs_new);
13881 local_get(code, hs_i);
13882 i32_const(code, 8);
13883 code.push(0x6C);
13884 code.push(0x6A); local_get(code, lst);
13886 i32_load(code, 8); local_get(code, hs_i);
13888 i32_const(code, 8);
13889 code.push(0x6C);
13890 code.push(0x6A); elem_load(code, 0);
13892 elem_store(code, 0); local_get(code, hs_i);
13894 i32_const(code, 1);
13895 code.push(0x6A);
13896 local_set(code, hs_i);
13897 code.push(0x0C);
13898 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, hs_new);
13903 local_get(code, lst);
13904 i32_load(code, 0); i32_const(code, 8);
13906 code.push(0x6C);
13907 code.push(0x6A);
13908 local_get(code, value as u32);
13909 elem_store(code, 0);
13910 emit_free(
13919 code,
13920 ctx,
13921 |c| {
13922 local_get(c, lst);
13923 i32_load(c, 8); },
13925 |c| {
13926 local_get(c, lst);
13927 i32_load(c, 4); i32_const(c, 8);
13929 c.push(0x6C); },
13931 );
13932 local_get(code, lst);
13934 local_get(code, hs_new);
13935 i32_store(code, 8);
13936 local_get(code, lst);
13938 local_get(code, hs_cap);
13939 i32_store(code, 4);
13940 }
13941 code.push(0x0B); local_get(code, lst);
13944 local_get(code, lst);
13945 i32_load(code, 0);
13946 i32_const(code, 1);
13947 code.push(0x6A);
13948 i32_store(code, 0);
13949 Ok(())
13950}
13951
13952fn lower_list_pop(code: &mut Vec<u8>, kinds: &KindTable, dst: u16, list: u16) -> R<()> {
13959 let elem =
13960 kinds
13961 .get(list as usize)
13962 .and_then(Kind::seq_elem)
13963 .ok_or(WasmLowerError::Unsupported(
13964 "pop from a sequence of unknown element kind",
13965 ))?;
13966 let elem_load = seq_elem_load(elem)?;
13967 let vt = elem.wasm_valtype();
13968 let lst = list as u32;
13969 local_get(code, lst);
13971 i32_load(code, 0); i32_const(code, 0);
13973 code.push(0x4A); code.push(0x04);
13975 code.push(vt); {
13977 local_get(code, lst);
13979 i32_load(code, 8); local_get(code, lst);
13981 i32_load(code, 0); i32_const(code, 1);
13983 code.push(0x6B); i32_const(code, 8);
13985 code.push(0x6C); code.push(0x6A); elem_load(code, 0);
13988 local_get(code, lst);
13990 local_get(code, lst);
13991 i32_load(code, 0);
13992 i32_const(code, 1);
13993 code.push(0x6B); i32_store(code, 0);
13995 }
13996 code.push(0x05); match vt {
13998 F64 => {
13999 code.push(0x44);
14000 code.extend_from_slice(&0.0f64.to_le_bytes());
14001 }
14002 I64 => {
14003 code.push(0x42);
14004 leb_i64(code, 0);
14005 }
14006 _ => i32_const(code, 0),
14007 }
14008 code.push(0x0B); local_set(code, dst as u32);
14010 Ok(())
14011}
14012
14013fn emit_seq_elem_addr(
14017 code: &mut Vec<u8>,
14018 ctx: &Ctx,
14019 kinds: &KindTable,
14020 collection: u16,
14021 index: u16,
14022) -> R<()> {
14023 match kinds.get(collection as usize) {
14027 Some(Kind::Tuple) => {}
14028 other if other.and_then(Kind::seq_elem).is_some() => {}
14029 _ => {
14030 return Err(WasmLowerError::Unsupported(
14031 "index of a non-scalar sequence",
14032 ))
14033 }
14034 }
14035 let col = collection as u32;
14036 let slot = if ctx.hot.get() {
14037 None
14038 } else {
14039 ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqSlot))
14040 };
14041 if let Some(slot) = slot {
14042 local_get(code, col);
14043 local_get(code, index as u32);
14044 code.push(0x10);
14045 leb_u32(code, slot);
14046 return Ok(());
14047 }
14048 local_get(code, index as u32);
14052 code.push(0x42);
14053 leb_i64(code, 1);
14054 code.push(0x53); local_get(code, index as u32);
14056 local_get(code, col);
14057 i32_load(code, 0);
14058 code.push(0xAD); code.push(0x55); code.push(0x72); code.push(0x04);
14062 code.push(0x40); if let Some(fail_at) = (ctx.host_index)(HostFn::LogosRtFailAt) {
14068 i32_const(
14069 code,
14070 crate::semantics::failcode::FailCode::IndexOutOfBounds.code(),
14071 );
14072 local_get(code, index as u32);
14073 code.push(0x10); leb_u32(code, fail_at);
14075 }
14076 code.push(0x00); code.push(0x0B); local_get(code, col);
14080 i32_load(code, 8); local_get(code, index as u32);
14082 code.push(0x42);
14083 leb_i64(code, 1);
14084 code.push(0x7D); code.push(0xA7); i32_const(code, 8);
14087 code.push(0x6C); code.push(0x6A); Ok(())
14090}
14091
14092fn seq_elem_kind(kinds: &KindTable, collection: u16) -> R<Kind> {
14094 kinds
14095 .get(collection as usize)
14096 .and_then(Kind::seq_elem)
14097 .ok_or(WasmLowerError::Unsupported(
14098 "sequence of unknown element kind",
14099 ))
14100}
14101
14102fn seq_elem_load(elem: Kind) -> R<fn(&mut Vec<u8>, u32)> {
14106 Ok(match elem.wasm_valtype() {
14107 F64 => f64_load,
14108 I64 => i64_load,
14109 _ => i32_load,
14110 })
14111}
14112
14113fn seq_elem_store(elem: Kind) -> R<fn(&mut Vec<u8>, u32)> {
14115 Ok(match elem.wasm_valtype() {
14116 F64 => f64_store,
14117 I64 => i64_store,
14118 _ => i32_store,
14119 })
14120}
14121
14122fn lower_index(
14126 code: &mut Vec<u8>,
14127 ctx: &Ctx,
14128 kinds: &KindTable,
14129 dst: u16,
14130 collection: u16,
14131 index: u16,
14132) -> R<()> {
14133 let elem = if kinds.get(collection as usize) == Some(Kind::Tuple) {
14134 kinds
14135 .get(dst as usize)
14136 .ok_or(WasmLowerError::Unsupported("tuple element of unknown kind"))?
14137 } else {
14138 seq_elem_kind(kinds, collection)?
14139 };
14140 let load = seq_elem_load(elem)?;
14141 emit_seq_elem_addr(code, ctx, kinds, collection, index)?;
14142 load(code, 0);
14143 local_set(code, dst as u32);
14144 Ok(())
14145}
14146
14147fn lower_text_index(
14154 code: &mut Vec<u8>,
14155 ctx: &Ctx,
14156 num_regs: u32,
14157 dst: u16,
14158 collection: u16,
14159 index: u16,
14160) -> R<()> {
14161 let (hdr, data) = (num_regs + 5, num_regs + 6);
14162 let col = collection as u32;
14163 local_get(code, index as u32);
14165 code.push(0x42);
14166 leb_i64(code, 1);
14167 code.push(0x53); local_get(code, index as u32);
14169 local_get(code, col);
14170 i32_load(code, 0); code.push(0xAD); code.push(0x55); code.push(0x72); code.push(0x04);
14175 code.push(0x40); code.push(0x00); code.push(0x0B); i32_const(code, 16);
14180 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
14181 i32_const(code, 1);
14182 emit_alloc(code, ctx, data, AllocClass::Raw);
14183 local_get(code, data); local_get(code, col);
14186 i32_load(code, 8); local_get(code, index as u32);
14188 code.push(0x42);
14189 leb_i64(code, 1);
14190 code.push(0x7D); code.push(0xA7); code.push(0x6A); i32_load8_u(code, 0);
14194 i32_store8(code, 0);
14195 local_get(code, hdr);
14197 i32_const(code, 1);
14198 i32_store(code, 0);
14199 local_get(code, hdr);
14200 i32_const(code, 1);
14201 i32_store(code, 4);
14202 local_get(code, hdr);
14203 local_get(code, data);
14204 i32_store(code, 8);
14205 local_get(code, hdr);
14206 local_set(code, dst as u32);
14207 Ok(())
14208}
14209
14210fn emit_bytes_to_seq(
14214 code: &mut Vec<u8>,
14215 ctx: &Ctx,
14216 num_regs: u32,
14217 dst: u16,
14218 base_reg: u32,
14219 len_reg: u32,
14220) {
14221 let (hdr, data, i) = (num_regs + 7, num_regs + 8, num_regs + 9);
14222 i32_const(code, 16);
14223 emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); local_get(code, len_reg);
14226 i32_const(code, 8);
14227 code.push(0x6C); emit_alloc(code, ctx, data, AllocClass::Raw);
14229 local_get(code, hdr);
14231 local_get(code, len_reg);
14232 i32_store(code, 0);
14233 local_get(code, hdr);
14234 local_get(code, len_reg);
14235 i32_store(code, 4);
14236 local_get(code, hdr);
14237 local_get(code, data);
14238 i32_store(code, 8);
14239 i32_const(code, 0);
14241 local_set(code, i);
14242 code.push(0x02);
14243 code.push(0x40); code.push(0x03);
14245 code.push(0x40); local_get(code, i);
14247 local_get(code, len_reg);
14248 code.push(0x4E); code.push(0x0D);
14250 leb_u32(code, 1); local_get(code, data);
14253 local_get(code, i);
14254 i32_const(code, 8);
14255 code.push(0x6C); code.push(0x6A); local_get(code, base_reg);
14259 local_get(code, i);
14260 code.push(0x6A); i32_load8_u(code, 0);
14262 code.push(0xAD); i64_store(code, 0);
14264 local_get(code, i);
14265 i32_const(code, 1);
14266 code.push(0x6A); local_set(code, i);
14268 code.push(0x0C);
14269 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, hdr);
14273 local_set(code, dst as u32);
14274}
14275
14276fn lower_text_bytes(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, text: u16) {
14278 let (base, len) = (num_regs + 5, num_regs + 6);
14279 local_get(code, text as u32);
14280 i32_load(code, 8); local_set(code, base);
14282 local_get(code, text as u32);
14283 i32_load(code, 0); local_set(code, len);
14285 emit_bytes_to_seq(code, ctx, num_regs, dst, base, len);
14286}
14287
14288fn lower_uuid_bytes(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, uuid: u16) {
14290 let (base, len) = (num_regs + 5, num_regs + 6);
14291 local_get(code, uuid as u32);
14292 local_set(code, base);
14293 i32_const(code, 16);
14294 local_set(code, len);
14295 emit_bytes_to_seq(code, ctx, num_regs, dst, base, len);
14296}
14297
14298fn compiled_fn_by_name(ctx: &Ctx, name: &str, params: &[u8], result_valtype: u8) -> Option<u32> {
14308 let idx = ctx
14309 .functions
14310 .iter()
14311 .position(|f| ctx.interner.resolve(f.name) == name)?;
14312 if ctx.fn_param_valtypes.get(idx).map(Vec::as_slice) != Some(params) {
14313 return None;
14314 }
14315 if ctx.fn_inout.get(idx).is_some_and(|ps| !ps.is_empty()) {
14316 return None;
14317 }
14318 if ctx
14319 .fn_results
14320 .get(idx)
14321 .copied()
14322 .flatten()
14323 .map(Kind::wasm_valtype)
14324 != Some(result_valtype)
14325 {
14326 return None;
14327 }
14328 Some(ctx.fn_base + idx as u32)
14329}
14330
14331fn lower_text_from_bytes(
14332 code: &mut Vec<u8>,
14333 ctx: &Ctx,
14334 num_regs: u32,
14335 dst: u16,
14336 seq: u16,
14337) -> R<()> {
14338 let check = compiled_fn_by_name(ctx, crate::vm::reach::UTF8_VALIDATOR, &[I32], I64)
14351 .ok_or(WasmLowerError::Unsupported(
14352 "text_from_bytes cannot validate: `validUtf8 (data: Seq of Int) -> Bool` was not loaded. \
14353 The loader demands it whenever `text_from_bytes` is reachable (see `loader.rs`); if a \
14354 program declares its own `validUtf8` with another shape, that one wins and this refuses \
14355 rather than calling it.",
14356 ))?;
14357 emit_retain(code, ctx, seq);
14361 local_get(code, seq as u32);
14362 code.push(0x10); leb_u32(code, check);
14364 code.push(0x50); code.push(0x04);
14366 code.push(0x40); if let Some(fail_at) = (ctx.host_index)(HostFn::LogosRtFailAt) {
14368 i32_const(
14369 code,
14370 crate::semantics::failcode::FailCode::InvalidUtf8.code(),
14371 );
14372 code.push(0x42);
14373 leb_i64(code, 0); code.push(0x10); leb_u32(code, fail_at);
14376 }
14377 code.push(0x00); code.push(0x0B); let (hdr, data, i, len, src) = (
14380 num_regs + 7,
14381 num_regs + 8,
14382 num_regs + 9,
14383 num_regs + 6,
14384 num_regs + 5,
14385 );
14386 local_get(code, seq as u32);
14387 i32_load(code, 0); local_set(code, len);
14389 local_get(code, seq as u32);
14390 i32_load(code, 8); local_set(code, src);
14392 i32_const(code, 16);
14393 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
14394 local_get(code, len); emit_alloc(code, ctx, data, AllocClass::Raw);
14396 local_get(code, hdr);
14397 local_get(code, len);
14398 i32_store(code, 0);
14399 local_get(code, hdr);
14400 local_get(code, len);
14401 i32_store(code, 4);
14402 local_get(code, hdr);
14403 local_get(code, data);
14404 i32_store(code, 8);
14405 i32_const(code, 0);
14407 local_set(code, i);
14408 code.push(0x02);
14409 code.push(0x40);
14410 code.push(0x03);
14411 code.push(0x40);
14412 local_get(code, i);
14413 local_get(code, len);
14414 code.push(0x4E);
14415 code.push(0x0D);
14416 leb_u32(code, 1);
14417 local_get(code, data);
14418 local_get(code, i);
14419 code.push(0x6A); local_get(code, src);
14421 local_get(code, i);
14422 i32_const(code, 8);
14423 code.push(0x6C);
14424 code.push(0x6A); if ctx.exact.sequence_ints() {
14426 i64_load(code, 0);
14427 exact::narrow_sequence_slot(code, ctx, num_regs, seq as u32)?;
14428 code.push(0xa7);
14429 } else {
14430 i32_load8_u(code, 0);
14431 }
14432 i32_store8(code, 0);
14433 local_get(code, i);
14434 i32_const(code, 1);
14435 code.push(0x6A);
14436 local_set(code, i);
14437 code.push(0x0C);
14438 leb_u32(code, 0);
14439 code.push(0x0B);
14440 code.push(0x0B);
14441 local_get(code, hdr);
14442 local_set(code, dst as u32);
14443 Ok(())
14444}
14445
14446fn lower_uuid_from_bytes(
14449 code: &mut Vec<u8>,
14450 ctx: &Ctx,
14451 num_regs: u32,
14452 dst: u16,
14453 seq: u16,
14454) -> R<Flow> {
14455 let from_ptr = (ctx.host_index)(HostFn::UuidFromPtr)
14456 .ok_or(WasmLowerError::Unsupported("uuid_from_ptr not imported"))?;
14457 let (block, i, src) = (num_regs + 7, num_regs + 9, num_regs + 5);
14458 local_get(code, seq as u32);
14459 i32_load(code, 8); local_set(code, src);
14461 i32_const(code, 16);
14462 emit_alloc(code, ctx, block, AllocClass::Raw);
14463 i32_const(code, 0);
14465 local_set(code, i);
14466 code.push(0x02);
14467 code.push(0x40);
14468 code.push(0x03);
14469 code.push(0x40);
14470 local_get(code, i);
14471 i32_const(code, 16);
14472 code.push(0x4E);
14473 code.push(0x0D);
14474 leb_u32(code, 1);
14475 local_get(code, block);
14476 local_get(code, i);
14477 code.push(0x6A);
14478 local_get(code, src);
14479 local_get(code, i);
14480 i32_const(code, 8);
14481 code.push(0x6C);
14482 code.push(0x6A);
14483 i32_load8_u(code, 0);
14484 i32_store8(code, 0);
14485 local_get(code, i);
14486 i32_const(code, 1);
14487 code.push(0x6A);
14488 local_set(code, i);
14489 code.push(0x0C);
14490 leb_u32(code, 0);
14491 code.push(0x0B);
14492 code.push(0x0B);
14493 local_get(code, block);
14495 code.push(0x10);
14496 leb_u32(code, from_ptr);
14497 local_set(code, dst as u32);
14498 Ok(Flow::Straight)
14499}
14500
14501fn lower_lanes4_of(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, words: [u16; 4]) {
14504 let block = num_regs + 7;
14505 i32_const(code, 16);
14506 emit_alloc(code, ctx, block, AllocClass::Raw);
14507 for (i, w) in words.iter().enumerate() {
14508 local_get(code, block);
14509 local_get(code, *w as u32);
14510 i32_store(code, (i * 4) as u32);
14511 }
14512 local_get(code, block);
14513 local_set(code, dst as u32);
14514}
14515
14516fn lower_lanes4_word32(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, seq: u16) {
14519 let block = num_regs + 7;
14520 i32_const(code, 16);
14521 emit_alloc(code, ctx, block, AllocClass::Raw);
14522 for i in 0..4u32 {
14523 local_get(code, block);
14524 local_get(code, seq as u32);
14526 i32_load(code, 8);
14527 i32_const(code, (i * 8) as i32);
14528 code.push(0x6A); i32_load(code, 0);
14530 i32_store(code, i * 4);
14531 }
14532 local_get(code, block);
14533 local_set(code, dst as u32);
14534}
14535
14536fn lower_seq_of_lanes4(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, lanes: u16) {
14539 let (hdr, data) = (num_regs + 7, num_regs + 8);
14540 i32_const(code, 16);
14541 emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); i32_const(code, 32); emit_alloc(code, ctx, data, AllocClass::Raw);
14544 local_get(code, hdr);
14545 i32_const(code, 4);
14546 i32_store(code, 0);
14547 local_get(code, hdr);
14548 i32_const(code, 4);
14549 i32_store(code, 4);
14550 local_get(code, hdr);
14551 local_get(code, data);
14552 i32_store(code, 8);
14553 for i in 0..4u32 {
14554 local_get(code, data);
14555 local_get(code, lanes as u32);
14556 i32_load(code, i * 4); i32_store(code, i * 8); }
14559 local_get(code, hdr);
14560 local_set(code, dst as u32);
14561}
14562
14563fn lower_sha1_op(
14566 code: &mut Vec<u8>,
14567 ctx: &Ctx,
14568 dst: u16,
14569 args_start: u16,
14570 host: HostFn,
14571 ternary: bool,
14572) -> R<Flow> {
14573 let idx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("sha1 op not imported"))?;
14574 local_get(code, args_start as u32);
14575 local_get(code, (args_start + 1) as u32);
14576 if ternary {
14577 local_get(code, (args_start + 2) as u32); }
14579 code.push(0x10);
14580 leb_u32(code, idx);
14581 local_set(code, dst as u32);
14582 Ok(Flow::Straight)
14583}
14584
14585fn lower_set_index(
14587 code: &mut Vec<u8>,
14588 ctx: &Ctx,
14589 kinds: &KindTable,
14590 num_regs: u32,
14591 collection: u16,
14592 index: u16,
14593 value: u16,
14594) -> R<()> {
14595 let elem = seq_elem_kind(kinds, collection)?;
14596 let store = seq_elem_store(elem)?;
14597 let elem_is_counted = counted_kind(Some(elem));
14598 let addr_local = num_regs + 5;
14599 emit_seq_elem_addr(code, ctx, kinds, collection, index)?; if ctx.heap_counting() && elem_is_counted {
14601 local_tee(code, addr_local); i32_load(code, 0);
14606 emit_true_release(code, ctx, |_| {});
14607 local_get(code, addr_local);
14608 }
14609 local_get(code, value as u32); store(code, 0);
14611 Ok(())
14612}
14613
14614fn lower_new_range(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, start: u16, end: u16) {
14617 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7); let cnt = num_regs + 1; local_get(code, end as u32);
14621 local_get(code, start as u32);
14622 code.push(0x7D); code.push(0x42);
14624 leb_i64(code, 1);
14625 code.push(0x7C); local_set(code, cnt);
14627 local_get(code, cnt);
14628 code.push(0x42);
14629 leb_i64(code, 0);
14630 code.push(0x53); code.push(0x04);
14632 code.push(0x40); code.push(0x42);
14634 leb_i64(code, 0);
14635 local_set(code, cnt); code.push(0x0B);
14637 i32_const(code, 16);
14639 emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); local_get(code, cnt);
14641 code.push(0xA7); i32_const(code, 8);
14643 code.push(0x6C); emit_alloc(code, ctx, data, AllocClass::Raw);
14645 local_get(code, hdr);
14647 local_get(code, cnt);
14648 code.push(0xA7);
14649 i32_store(code, 0);
14650 local_get(code, hdr);
14651 local_get(code, cnt);
14652 code.push(0xA7);
14653 i32_store(code, 4);
14654 local_get(code, hdr);
14655 local_get(code, data);
14656 i32_store(code, 8);
14657 i32_const(code, 0);
14659 local_set(code, idx);
14660 code.push(0x02);
14661 code.push(0x40); code.push(0x03);
14663 code.push(0x40); local_get(code, idx);
14665 local_get(code, cnt);
14666 code.push(0xA7);
14667 code.push(0x4E); code.push(0x0D);
14669 leb_u32(code, 1); local_get(code, data);
14671 local_get(code, idx);
14672 i32_const(code, 8);
14673 code.push(0x6C);
14674 code.push(0x6A); local_get(code, start as u32);
14676 local_get(code, idx);
14677 code.push(0xAC); code.push(0x7C); i64_store(code, 0);
14680 local_get(code, idx);
14681 i32_const(code, 1);
14682 code.push(0x6A);
14683 local_set(code, idx); code.push(0x0C);
14685 leb_u32(code, 0); code.push(0x0B);
14687 code.push(0x0B); local_get(code, hdr);
14689 local_set(code, dst as u32);
14690}
14691
14692fn lower_repeat_seq(
14697 code: &mut Vec<u8>,
14698 kinds: &KindTable,
14699 ctx: &Ctx,
14700 num_regs: u32,
14701 dst: u16,
14702 args_start: u16,
14703) -> R<()> {
14704 let value = args_start; let n = args_start + 1; let is_float = matches!(kinds.get(value as usize), Some(Kind::Float));
14707 if !matches!(
14708 kinds.get(value as usize),
14709 Some(Kind::Int) | Some(Kind::Float)
14710 ) {
14711 return Err(WasmLowerError::Unsupported(
14712 "repeatSeq of a non-scalar element (deep-copy)",
14713 ));
14714 }
14715 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7); let cnt = num_regs + 1; local_get(code, n as u32);
14719 local_set(code, cnt);
14720 local_get(code, cnt);
14721 code.push(0x42);
14722 leb_i64(code, 0);
14723 code.push(0x53); code.push(0x04);
14725 code.push(0x40); code.push(0x42);
14727 leb_i64(code, 0);
14728 local_set(code, cnt); code.push(0x0B);
14730 i32_const(code, 16);
14732 emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); local_get(code, cnt);
14734 code.push(0xA7); i32_const(code, 8);
14736 code.push(0x6C); emit_alloc(code, ctx, data, AllocClass::Raw);
14738 local_get(code, hdr);
14740 local_get(code, cnt);
14741 code.push(0xA7);
14742 i32_store(code, 0);
14743 local_get(code, hdr);
14744 local_get(code, cnt);
14745 code.push(0xA7);
14746 i32_store(code, 4);
14747 local_get(code, hdr);
14748 local_get(code, data);
14749 i32_store(code, 8);
14750 i32_const(code, 0);
14752 local_set(code, idx);
14753 code.push(0x02);
14754 code.push(0x40); code.push(0x03);
14756 code.push(0x40); local_get(code, idx);
14758 local_get(code, cnt);
14759 code.push(0xA7);
14760 code.push(0x4E); code.push(0x0D);
14762 leb_u32(code, 1); local_get(code, data);
14764 local_get(code, idx);
14765 i32_const(code, 8);
14766 code.push(0x6C);
14767 code.push(0x6A); local_get(code, value as u32);
14769 if is_float {
14770 f64_store(code, 0);
14771 } else {
14772 i64_store(code, 0);
14773 }
14774 local_get(code, idx);
14775 i32_const(code, 1);
14776 code.push(0x6A);
14777 local_set(code, idx); code.push(0x0C);
14779 leb_u32(code, 0); code.push(0x0B);
14781 code.push(0x0B); local_get(code, hdr);
14783 local_set(code, dst as u32);
14784 Ok(())
14785}
14786
14787fn lower_new_list(
14791 code: &mut Vec<u8>,
14792 kinds: &KindTable,
14793 ctx: &Ctx,
14794 num_regs: u32,
14795 dst: u16,
14796 start: u16,
14797 count: u16,
14798) -> R<()> {
14799 let want = if count > 0 {
14800 kinds
14801 .get(start as usize)
14802 .ok_or(WasmLowerError::Unsupported(
14803 "list literal of unknown element kind",
14804 ))?
14805 } else {
14806 Kind::Int
14807 };
14808 let elem_store = seq_elem_store(want)?;
14809 for j in 0..count {
14810 if kinds.get((start + j) as usize) != Some(want) {
14811 return Err(WasmLowerError::Unsupported(
14812 "list literal with mixed element kinds",
14813 ));
14814 }
14815 }
14816 let (hdr, data) = (num_regs + 5, num_regs + 6);
14817 i32_const(code, 16);
14818 emit_alloc(
14819 code,
14820 ctx,
14821 hdr,
14822 AllocClass::of_elements(kind_is_handle(want)),
14823 );
14824 i32_const(code, i32::from(count) * 8);
14825 emit_alloc(code, ctx, data, AllocClass::Raw);
14826 local_get(code, hdr);
14828 i32_const(code, i32::from(count));
14829 i32_store(code, 0);
14830 local_get(code, hdr);
14831 i32_const(code, i32::from(count));
14832 i32_store(code, 4);
14833 local_get(code, hdr);
14834 local_get(code, data);
14835 i32_store(code, 8);
14836 for j in 0..count {
14838 local_get(code, data);
14839 local_get(code, (start + j) as u32);
14840 elem_store(code, u32::from(j) * 8);
14841 }
14842 if count > 0 && counted_kind(Some(want)) {
14847 emit_retain_children(code, ctx, hdr);
14848 }
14849 local_get(code, hdr);
14850 local_set(code, dst as u32);
14851 Ok(())
14852}
14853
14854fn lower_destructure_tuple(
14859 code: &mut Vec<u8>,
14860 kinds: &KindTable,
14861 src: u16,
14862 start: u16,
14863 count: u16,
14864) -> R<()> {
14865 for i in 0..count {
14866 let dst = start + i;
14867 local_get(code, src as u32);
14868 i32_load(code, 8); emit_slot_load(code, kinds.get(dst as usize), u32::from(i) * 8)?;
14870 local_set(code, dst as u32);
14871 }
14872 Ok(())
14873}
14874
14875fn lower_new_tuple_het(
14879 code: &mut Vec<u8>,
14880 kinds: &KindTable,
14881 ctx: &Ctx,
14882 num_regs: u32,
14883 dst: u16,
14884 start: u16,
14885 count: u16,
14886) -> R<()> {
14887 let (hdr, data) = (num_regs + 5, num_regs + 6);
14888 i32_const(code, 16);
14889 emit_alloc(code, ctx, hdr, AllocClass::RecordHeader);
14890 i32_const(
14891 code,
14892 i32::from(count) * if ctx.heap_counting() { 9 } else { 8 },
14893 );
14894 emit_alloc(code, ctx, data, AllocClass::Raw);
14895 for (off, v) in [(0u32, i32::from(count)), (4, i32::from(count))] {
14896 local_get(code, hdr);
14897 i32_const(code, v);
14898 i32_store(code, off);
14899 }
14900 local_get(code, hdr);
14901 local_get(code, data);
14902 i32_store(code, 8);
14903 for j in 0..count {
14904 local_get(code, data);
14905 local_get(code, (start + j) as u32);
14906 emit_slot_store(code, kinds.get((start + j) as usize), u32::from(j) * 8)?;
14907 if ctx.heap_counting() {
14908 local_get(code, data);
14909 i32_const(
14910 code,
14911 i32::from(kinds.get((start + j) as usize).is_some_and(kind_is_handle)),
14912 );
14913 i32_store8(code, u32::from(count) * 8 + u32::from(j));
14914 }
14915 }
14916 local_get(code, hdr);
14917 local_set(code, dst as u32);
14918 Ok(())
14919}
14920
14921fn emit_enum_payload_base(code: &mut Vec<u8>, ctx: &Ctx) {
14925 if !ctx.linked {
14926 i32_load(code, 8);
14927 }
14928}
14929
14930fn enum_payload_offset(ctx: &Ctx, index: u32) -> u32 {
14932 8 * (index + u32::from(ctx.linked))
14933}
14934
14935fn lower_new_inductive(
14939 code: &mut Vec<u8>,
14940 kinds: &KindTable,
14941 ctx: &Ctx,
14942 num_regs: u32,
14943 dst: u16,
14944 ctor: u32,
14945 args_start: u16,
14946 count: u16,
14947) -> R<()> {
14948 let (hdr, data) = (num_regs + 5, num_regs + 6);
14949 if ctx.linked {
14950 i32_const(code, 8 * (1 + i32::from(count)));
14952 emit_alloc(code, ctx, hdr, AllocClass::Raw);
14953 local_get(code, hdr);
14954 i32_const(code, ctor as i32);
14955 i32_store(code, 0);
14956 for k in 0..count {
14957 let arg = args_start + k;
14958 local_get(code, hdr);
14959 local_get(code, arg as u32);
14960 emit_slot_store(code, kinds.get(arg as usize), 8 * (1 + u32::from(k)))?;
14961 }
14962 } else {
14963 i32_const(code, 16);
14966 emit_alloc(code, ctx, hdr, AllocClass::EnumHeader);
14967 if count == 0 {
14968 i32_const(code, 0);
14969 local_set(code, data);
14970 } else {
14971 i32_const(
14972 code,
14973 i32::from(count) * if ctx.heap_counting() { 9 } else { 8 },
14974 );
14975 emit_alloc(code, ctx, data, AllocClass::Raw);
14976 }
14977 local_get(code, hdr);
14978 i32_const(code, ctor as i32);
14979 i32_store(code, 0);
14980 local_get(code, hdr);
14981 i32_const(code, i32::from(count));
14982 i32_store(code, 4);
14983 local_get(code, hdr);
14984 local_get(code, data);
14985 i32_store(code, 8);
14986 for k in 0..count {
14987 let arg = args_start + k;
14988 let kind = kinds.get(arg as usize);
14989 local_get(code, data);
14990 local_get(code, arg as u32);
14991 emit_slot_store(code, kind, u32::from(k) * 8)?;
14992 if ctx.heap_counting() {
14993 local_get(code, data);
14994 i32_const(code, i32::from(kind.is_some_and(kind_is_handle)));
14995 i32_store8(code, u32::from(count) * 8 + u32::from(k));
14996 }
14997 }
14998 }
14999 local_get(code, hdr);
15000 local_set(code, dst as u32);
15001 Ok(())
15002}
15003
15004fn lower_bind_arm(
15008 code: &mut Vec<u8>,
15009 kinds: &KindTable,
15010 ctx: &Ctx,
15011 dst: u16,
15012 target: u16,
15013 index: u16,
15014) -> R<()> {
15015 let target_kind = kinds.get(target as usize);
15035 if target_kind != Some(Kind::Enum) {
15036 if index == 0
15040 && kinds.valtype(target as usize) == I32
15041 && kinds.valtype(target as usize) == kinds.valtype(dst as usize)
15042 {
15043 local_get(code, target as u32);
15044 local_set(code, dst as u32);
15045 return Ok(());
15046 }
15047 return Err(WasmLowerError::Unsupported(
15048 "payload binding on a non-enum target",
15049 ));
15050 }
15051 let kind = kinds.get(dst as usize).or(Some(Kind::Int));
15058 local_get(code, target as u32);
15059 emit_enum_payload_base(code, ctx);
15060 emit_slot_load(code, kind, enum_payload_offset(ctx, u32::from(index)))?;
15061 local_set(code, dst as u32);
15062 Ok(())
15063}
15064
15065fn capture_valtype(ctx: &Ctx, func: u16, k: usize) -> u8 {
15075 ctx.capture_kinds
15076 .get(func as usize)
15077 .and_then(|v| v.get(k))
15078 .copied()
15079 .flatten()
15080 .map(Kind::wasm_valtype)
15081 .unwrap_or(I64)
15082}
15083
15084fn lower_make_closure(
15085 code: &mut Vec<u8>,
15086 ctx: &Ctx,
15087 num_regs: u32,
15088 dst: u16,
15089 func: u16,
15090 locals_start: u16,
15091) -> R<()> {
15092 let caps = ctx
15093 .functions
15094 .get(func as usize)
15095 .map(|f| f.captures.as_slice())
15096 .ok_or(WasmLowerError::Unsupported("closure of unknown function"))?;
15097 let cap_n = caps.len() as u32;
15098 let hs = num_regs + 5;
15099 let data = num_regs + 6;
15100 i32_const(
15101 code,
15102 if ctx.linked {
15103 8 * (1 + 2 * cap_n) as i32
15104 } else {
15105 16
15106 },
15107 );
15108 emit_alloc(
15109 code,
15110 ctx,
15111 hs,
15112 if ctx.linked {
15113 AllocClass::Raw
15114 } else {
15115 AllocClass::ClosureHeader
15116 },
15117 );
15118 local_get(code, hs);
15119 i32_const(code, i32::from(func));
15120 i32_store(code, 0);
15121 if ctx.linked {
15122 local_get(code, hs);
15123 i32_const(code, 8);
15124 code.push(0x6A);
15125 local_set(code, data);
15126 } else {
15127 local_get(code, hs);
15128 i32_const(code, cap_n as i32);
15129 i32_store(code, 4);
15130 if cap_n != 0 {
15131 i32_const(code, (17 * cap_n) as i32);
15132 emit_alloc(code, ctx, data, AllocClass::Raw);
15133 } else {
15134 i32_const(code, 0);
15135 local_set(code, data);
15136 }
15137 local_get(code, hs);
15138 local_get(code, data);
15139 i32_store(code, 8);
15140 }
15141 let mut local_k = 0_u16;
15142 for (k, (_sym, global)) in caps.iter().enumerate() {
15143 local_get(code, data);
15144 match global {
15145 Some(gidx) => global_get(code, u32::from(*gidx)),
15146 None => {
15147 local_get(code, u32::from(locals_start + local_k));
15148 local_k += 1;
15149 }
15150 }
15151 let off = 8 * k as u32;
15152 match capture_valtype(ctx, func, k) {
15153 I32 => i32_store(code, off),
15154 F64 => f64_store(code, off),
15155 _ => i64_store(code, off),
15156 }
15157 local_get(code, data);
15158 i64c(code, 1);
15159 i64_store(code, 8 * cap_n + off);
15160 let kind = ctx
15161 .capture_kinds
15162 .get(func as usize)
15163 .and_then(|v| v.get(k))
15164 .copied()
15165 .flatten();
15166 if !ctx.linked {
15167 local_get(code, data);
15168 i32_const(code, i32::from(counted_kind(kind)));
15169 i32_store8(code, 16 * cap_n + k as u32);
15170 }
15171 if counted_kind(kind) {
15172 if let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Retain)) {
15173 match global {
15174 Some(gidx) => global_get(code, u32::from(*gidx)),
15175 None => local_get(code, u32::from(locals_start + local_k - 1)),
15176 }
15177 code.push(0x10);
15178 leb_u32(code, f);
15179 }
15180 }
15181 }
15182 local_get(code, hs);
15183 local_set(code, u32::from(dst));
15184 Ok(())
15185}
15186
15187fn lower_call_value(
15193 code: &mut Vec<u8>,
15194 plan: &Plan,
15195 ctx: &Ctx,
15196 pc: usize,
15197 dst: u16,
15198 callee: u16,
15199 args_start: u16,
15200 arg_count: u16,
15201) -> R<()> {
15202 let func =
15203 plan.structs
15204 .callee_func
15205 .get(pc)
15206 .copied()
15207 .flatten()
15208 .ok_or(WasmLowerError::Unsupported(
15209 "indirect call to a closure of unknown origin",
15210 ))?;
15211 let type_idx = *ctx
15212 .fn_type
15213 .get(func as usize)
15214 .ok_or(WasmLowerError::Unsupported(
15215 "closure call: unknown callee type",
15216 ))?;
15217 let cap_n = ctx
15218 .functions
15219 .get(func as usize)
15220 .map(|f| f.captures.len() as u32)
15221 .unwrap_or(0);
15222 for k in 0..arg_count {
15223 exact::push_closure_argument(code, plan, ctx, func, k, args_start + k)?;
15224 }
15225 for k in 0..cap_n {
15227 local_get(code, callee as u32);
15228 if !ctx.linked {
15229 i32_load(code, 8);
15230 }
15231 let off = u32::from(ctx.linked) * 8 + 8 * k;
15232 match capture_valtype(ctx, func, k as usize) {
15233 I32 => i32_load(code, off),
15234 F64 => f64_load(code, off),
15235 _ => i64_load(code, off),
15236 }
15237 }
15238 for k in 0..cap_n {
15239 local_get(code, callee as u32);
15240 if !ctx.linked {
15241 i32_load(code, 8);
15242 }
15243 i64_load(code, u32::from(ctx.linked) * 8 + 8 * cap_n + 8 * k);
15244 }
15245 if ctx.linked {
15250 code.push(0x10); leb_u32(code, ctx.fn_base + func as u32);
15252 } else {
15253 local_get(code, callee as u32);
15254 i32_load(code, 0); code.push(0x11); leb_u32(code, type_idx);
15257 leb_u32(code, 0); }
15259 if ctx
15261 .fn_results
15262 .get(func as usize)
15263 .copied()
15264 .flatten()
15265 .is_some()
15266 {
15267 exact::take_closure_result(code, plan, ctx, func, dst)?;
15268 }
15269 Ok(())
15270}
15271
15272fn emit_closure_trampoline(
15278 fns: &[Plan],
15279 program: &CompiledProgram,
15280 fn_types: &[u32],
15281 ctx: &Ctx,
15282 callback_base: Option<u32>,
15283) -> R<Vec<u8>> {
15284 let n = fns.len();
15285 let mut body = Vec::new();
15286 let registration = if fns.iter().any(exact::on) {
15288 body.extend_from_slice(&[0x02, 0x02, I64, 0x01, I32]);
15289 4
15290 } else {
15291 body.extend_from_slice(&[0x01, 0x01, I32]);
15292 2
15293 };
15294 if let Some(base) = callback_base {
15295 global_get(&mut body, base);
15296 local_set(&mut body, registration);
15297 body.extend([0x02, 0x40, 0x03, 0x40]);
15298 local_get(&mut body, registration);
15299 body.push(0x45);
15300 body.extend([0x04, 0x40, 0x00, 0x0B]); local_get(&mut body, registration);
15302 i32_load(&mut body, 0);
15303 local_get(&mut body, 0);
15304 body.push(0x46);
15305 body.push(0x0D);
15306 leb_u32(&mut body, 1);
15307 local_get(&mut body, registration);
15308 i32_load(&mut body, 8);
15309 local_set(&mut body, registration);
15310 body.push(0x0C);
15311 leb_u32(&mut body, 0);
15312 body.extend([0x0B, 0x0B]);
15313 local_get(&mut body, registration);
15314 i32_load(&mut body, 4);
15315 local_set(&mut body, 0);
15316 }
15317 for _ in 0..=n {
15318 body.extend([0x02, 0x40]);
15319 }
15320 local_get(&mut body, 0);
15321 i32_load(&mut body, 0);
15322 body.push(0x0E);
15323 leb_u32(&mut body, n as u32);
15324 for i in 0..n as u32 {
15325 leb_u32(&mut body, i);
15326 }
15327 leb_u32(&mut body, n as u32);
15328 for fi in 0..n {
15329 body.push(0x0B); emit_trampoline_arm(&mut body, fi, fns, program, fn_types, ctx)?;
15331 }
15332 body.push(0x0B); body.push(0x00); body.push(0x0B); Ok(body)
15336}
15337
15338fn emit_trampoline_arm(
15341 body: &mut Vec<u8>,
15342 fi: usize,
15343 fns: &[Plan],
15344 program: &CompiledProgram,
15345 fn_types: &[u32],
15346 ctx: &Ctx,
15347) -> R<()> {
15348 let f = &program.functions[fi];
15349 let plan = &fns[fi];
15350 let param_count = f.param_count as usize;
15351 let cap_n = f.captures.len();
15352 if param_count != 1 || plan.kinds.valtype(0) != I64 {
15355 body.push(0x00); return Ok(());
15357 }
15358 local_get(body, 1);
15360 exact::trampoline_argument(body, ctx, fi, 2)?;
15361 for k in 0..cap_n {
15364 local_get(body, 0);
15365 i32_load(body, 8);
15366 let off = 8 * k as u32;
15367 match plan.kinds.valtype(param_count + k) {
15368 v if v == I32 => i32_load(body, off),
15369 v if v == F64 => f64_load(body, off),
15370 _ => i64_load(body, off),
15371 }
15372 }
15373 for k in 0..cap_n {
15374 local_get(body, 0);
15375 i32_load(body, 8);
15376 i64_load(body, 8 * cap_n as u32 + 8 * k as u32);
15377 }
15378 local_get(body, 0);
15380 i32_load(body, 0); body.push(0x11); leb_u32(body, fn_types[fi]);
15383 leb_u32(body, 0); match result_valtypes(plan.result).first().copied() {
15386 None => {
15387 body.push(0x42); leb_i64(body, 0);
15389 }
15390 Some(v) if v == I64 => exact::trampoline_result(body, ctx, fi, 2, 3)?,
15391 Some(v) if v == I32 => body.push(0xAD), Some(v) if v == F64 => body.push(0xBD), Some(_) => {}
15394 }
15395 body.push(0x0F); Ok(())
15397}
15398
15399fn lower_dom_call(
15404 code: &mut Vec<u8>,
15405 ctx: &Ctx,
15406 dst: u16,
15407 host: HostFn,
15408 args_start: u16,
15409 arg_count: u16,
15410 returns_value: bool,
15411) -> R<Flow> {
15412 let idx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("dom host not imported"))?;
15413 for i in 0..arg_count {
15414 local_get(code, args_start as u32 + i as u32);
15415 if host
15416 .retained_params()
15417 .into_iter()
15418 .any(|kept| kept == usize::from(i))
15419 {
15420 if let Some(retain) = ctx.runtime.and_then(|r| r.index(RuntimeFn::ClosureRetain)) {
15421 code.push(0x10);
15422 leb_u32(code, retain);
15423 }
15424 }
15425 }
15426 code.push(0x10);
15428 leb_u32(code, idx);
15429 if !returns_value {
15430 i32_const(code, 0);
15431 }
15432 local_set(code, dst as u32);
15433 Ok(Flow::Straight)
15434}
15435
15436fn lower_dispatch_entry(
15442 code: &mut Vec<u8>,
15443 ctx: &Ctx,
15444 num_regs: u32,
15445 dst: u16,
15446 args_start: u16,
15447) -> R<Flow> {
15448 let idx = (ctx.host_index)(HostFn::DomPageEntry)
15449 .ok_or(WasmLowerError::Unsupported("dom host not imported"))?;
15450 let saved = num_regs + 5;
15451 if ctx.uses_iter {
15452 global_get(code, ctx.iter_global);
15453 local_set(code, saved);
15454 }
15455 for k in 3..6 {
15456 local_get(code, u32::from(args_start) + k);
15457 }
15458 code.push(0x10); leb_u32(code, idx);
15460 local_set(code, u32::from(dst));
15461 if ctx.uses_iter {
15462 local_get(code, saved);
15463 global_set(code, ctx.iter_global);
15464 }
15465 Ok(Flow::Straight)
15466}
15467
15468fn lower_storage_get(
15477 code: &mut Vec<u8>,
15478 ctx: &Ctx,
15479 num_regs: u32,
15480 dst: u16,
15481 args_start: u16,
15482) -> R<Flow> {
15483 let idx = (ctx.host_index)(HostFn::StorageGet)
15484 .ok_or(WasmLowerError::Unsupported("storage_get host not imported"))?;
15485 let boxp = num_regs + 6; let val = num_regs + 7; local_get(code, args_start as u32);
15488 local_get(code, args_start as u32 + 1);
15489 code.push(0x10); leb_u32(code, idx);
15491 local_set(code, val);
15492 local_get(code, val);
15493 code.push(0x45); code.push(0x04);
15495 code.push(0x40); i32_const(code, 0);
15497 local_set(code, dst as u32); code.push(0x05); i32_const(code, 8);
15500 emit_alloc(code, ctx, boxp, AllocClass::Raw);
15501 local_get(code, boxp);
15502 local_get(code, val);
15503 emit_slot_store(code, Some(Kind::Text), 0)?;
15504 local_get(code, boxp);
15505 local_set(code, dst as u32);
15506 code.push(0x0B); Ok(Flow::Straight)
15508}
15509
15510fn lower_env_has(code: &mut Vec<u8>, ctx: &Ctx, dst: u16, args_start: u16) -> R<Flow> {
15513 let idx = (ctx.host_index)(HostFn::EnvLen)
15514 .ok_or(WasmLowerError::Unsupported("env_len host not imported"))?;
15515 local_get(code, args_start as u32);
15516 code.push(0x10); leb_u32(code, idx);
15518 i32_const(code, 0);
15519 code.push(0x4E); code.push(0xAD); local_set(code, dst as u32);
15522 Ok(Flow::Straight)
15523}
15524
15525fn lower_env_value(
15529 code: &mut Vec<u8>,
15530 ctx: &Ctx,
15531 num_regs: u32,
15532 dst: u16,
15533 args_start: u16,
15534) -> R<Flow> {
15535 let len_idx = (ctx.host_index)(HostFn::EnvLen)
15536 .ok_or(WasmLowerError::Unsupported("env_len host not imported"))?;
15537 let into_idx = (ctx.host_index)(HostFn::EnvInto)
15538 .ok_or(WasmLowerError::Unsupported("env_into host not imported"))?;
15539 let (hdr, data, len) = (num_regs + 5, num_regs + 6, num_regs + 7);
15540 local_get(code, args_start as u32);
15542 code.push(0x10); leb_u32(code, len_idx);
15544 local_set(code, len);
15545 local_get(code, len);
15546 i32_const(code, 0);
15547 local_get(code, len);
15548 i32_const(code, 0);
15549 code.push(0x4A); code.push(0x1B); local_set(code, len);
15552 local_get(code, len);
15554 emit_alloc(code, ctx, data, AllocClass::Raw);
15555 local_get(code, data);
15556 local_get(code, args_start as u32);
15557 code.push(0x10); leb_u32(code, into_idx);
15559 code.push(0x1A); i32_const(code, 16);
15562 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
15563 local_get(code, hdr);
15564 local_get(code, len);
15565 i32_store(code, 0);
15566 local_get(code, hdr);
15567 local_get(code, len);
15568 i32_store(code, 4);
15569 local_get(code, hdr);
15570 local_get(code, data);
15571 i32_store(code, 8);
15572 local_get(code, hdr);
15573 local_set(code, dst as u32);
15574 Ok(Flow::Straight)
15575}
15576
15577fn lower_storage_get_or(
15584 code: &mut Vec<u8>,
15585 ctx: &Ctx,
15586 num_regs: u32,
15587 dst: u16,
15588 args_start: u16,
15589) -> R<Flow> {
15590 let idx = (ctx.host_index)(HostFn::StorageGet)
15591 .ok_or(WasmLowerError::Unsupported("storage_get host not imported"))?;
15592 let val = num_regs + 7; local_get(code, args_start as u32);
15594 local_get(code, args_start as u32 + 1);
15595 code.push(0x10); leb_u32(code, idx);
15597 local_set(code, val);
15598 local_get(code, val);
15599 code.push(0x45); code.push(0x04);
15601 code.push(0x7F); local_get(code, args_start as u32 + 2); code.push(0x05); local_get(code, val);
15605 code.push(0x0B); local_set(code, dst as u32);
15607 Ok(Flow::Straight)
15608}
15609
15610fn lower_test_arm(
15614 code: &mut Vec<u8>,
15615 kinds: &KindTable,
15616 ctx: &Ctx,
15617 dst: u16,
15618 target: u16,
15619 variant: u32,
15620) -> R<()> {
15621 let target_kind = kinds.get(target as usize);
15632 if target_kind != Some(Kind::Enum) {
15633 let name = match ctx.constants.get(variant as usize) {
15634 Some(Constant::Text(t)) => t.as_str(),
15635 _ => {
15636 return Err(WasmLowerError::Unsupported(
15637 "an arm's variant name is not a Text constant",
15638 ))
15639 }
15640 };
15641 if kinds.valtype(target as usize) != I32 {
15652 return Err(WasmLowerError::Unsupported(
15653 "`Inspect` over an `Option` of a scalar (Int/Bool/Float): `nothing` and `some 0` are \
15654 the same bits in a compiled module, so the arms cannot be told apart. Inspect an \
15655 `Option` of a record, of Text, or of a sequence — or use a `Result`, which carries a \
15656 real tag.",
15657 ));
15658 }
15659 match name {
15660 "Some" | "None" => {
15661 local_get(code, target as u32);
15662 i32_const(code, 0);
15663 code.push(if name == "None" { 0x46 } else { 0x47 }); code.push(0xAD); local_set(code, dst as u32);
15666 return Ok(());
15667 }
15668 _ => return Err(WasmLowerError::Unsupported(
15669 "a variant arm on a value that carries no variant tag — only `Some` and `None` \
15670 match a transparent `Option`",
15671 )),
15672 }
15673 }
15674 local_get(code, target as u32);
15675 i32_load(code, 0); i32_const(code, variant as i32);
15677 code.push(0x46); code.push(0xAD); local_set(code, dst as u32);
15680 Ok(())
15681}
15682
15683fn emit_empty_header(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u32, class: AllocClass) {
15689 if let Some(f) = ctx
15690 .rt_alloc
15691 .is_none()
15692 .then(|| ctx.runtime.and_then(|r| r.index(RuntimeFn::NewHeader)))
15693 .flatten()
15694 {
15695 i32_const(code, class.code() as i32);
15696 code.push(0x10);
15697 leb_u32(code, f);
15698 local_set(code, dst);
15699 return;
15700 }
15701 let hs = num_regs + 5;
15702 i32_const(code, 16);
15703 emit_alloc(code, ctx, hs, class);
15704 for off in [0u32, 4, 8] {
15705 local_get(code, hs);
15706 i32_const(code, 0);
15707 i32_store(code, off);
15708 }
15709 local_get(code, hs);
15710 local_set(code, dst);
15711}
15712
15713fn emit_fixed_header(
15717 code: &mut Vec<u8>,
15718 ctx: &Ctx,
15719 num_regs: u32,
15720 dst: u32,
15721 class: AllocClass,
15722 capacity: u32,
15723) {
15724 let header = num_regs + 5;
15725 let data = num_regs + 6;
15726 i32_const(code, 16);
15727 emit_alloc(code, ctx, header, class);
15728 i32_const(code, (capacity as i64 * 8) as i32);
15729 emit_alloc(code, ctx, data, AllocClass::Raw);
15730 local_get(code, header);
15731 i32_const(code, 0);
15732 i32_store(code, 0);
15733 local_get(code, header);
15734 i32_const(code, capacity as i32);
15735 i32_store(code, 4);
15736 local_get(code, header);
15737 local_get(code, data);
15738 i32_store(code, 8);
15739 local_get(code, header);
15740 local_set(code, dst);
15741}
15742
15743fn emit_capacity_header(
15747 code: &mut Vec<u8>,
15748 ctx: &Ctx,
15749 num_regs: u32,
15750 dst: u32,
15751 capacity: u32,
15752 class: AllocClass,
15753 stride: i32,
15754) {
15755 let header = num_regs + 5;
15756 let data = num_regs + 6;
15757 let cap = num_regs + 7;
15758 let limit = i32::MAX / stride;
15759
15760 local_get(code, capacity);
15761 code.push(0x42); leb_i64(code, 0);
15763 code.push(0x55); code.push(0x04); code.push(I32);
15766 local_get(code, capacity);
15767 code.push(0x42); leb_i64(code, limit as i64);
15769 code.push(0x53); code.push(0x04); code.push(I32);
15772 local_get(code, capacity);
15773 code.push(0xA7); code.push(0x05); i32_const(code, limit);
15776 code.push(0x0B); code.push(0x05); i32_const(code, 0);
15779 code.push(0x0B); local_set(code, cap);
15781
15782 i32_const(code, 16);
15783 emit_alloc(code, ctx, header, class);
15784 local_get(code, cap);
15785 i32_const(code, stride);
15786 code.push(0x6C); emit_alloc(code, ctx, data, AllocClass::Raw);
15788 local_get(code, header);
15789 i32_const(code, 0);
15790 i32_store(code, 0);
15791 local_get(code, header);
15792 local_get(code, cap);
15793 i32_store(code, 4);
15794 local_get(code, header);
15795 local_get(code, data);
15796 i32_store(code, 8);
15797 local_get(code, header);
15798 local_set(code, dst);
15799}
15800
15801fn emit_retain(code: &mut Vec<u8>, ctx: &Ctx, reg: u16) {
15811 if let Some(f) = (!ctx.hot.get())
15812 .then(|| ctx.runtime.and_then(|r| r.index(RuntimeFn::Share)))
15813 .flatten()
15814 {
15815 local_get(code, reg as u32);
15816 code.push(0x10);
15817 leb_u32(code, f);
15818 return;
15819 }
15820 emit_share_inline(code, |c| local_get(c, reg as u32));
15821}
15822
15823fn emit_share_inline(code: &mut Vec<u8>, push: impl Fn(&mut Vec<u8>)) {
15825 push(code);
15826 push(code);
15827 i32_load(code, 12);
15828 i32_const(code, 0x100); code.push(0x6A); i32_store(code, 12);
15831}
15832
15833fn emit_true_retain(code: &mut Vec<u8>, ctx: &Ctx, reg: u16) {
15839 emit_true_retain_of(code, ctx, |c| local_get(c, reg as u32));
15840}
15841
15842fn emit_true_retain_of(code: &mut Vec<u8>, ctx: &Ctx, push_handle: impl Fn(&mut Vec<u8>)) {
15844 let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Retain)) else {
15845 return;
15846 };
15847 push_handle(code);
15848 code.push(0x10);
15849 leb_u32(code, f);
15850}
15851
15852fn emit_cow_retain_each_element(code: &mut Vec<u8>, hdr: u32, counter: u32) {
15856 i32_const(code, 0);
15857 local_set(code, counter);
15858 code.push(0x02);
15859 code.push(0x40); code.push(0x03);
15861 code.push(0x40); local_get(code, counter);
15863 local_get(code, hdr);
15864 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
15867 leb_u32(code, 1); for _ in 0..2 {
15869 local_get(code, hdr);
15870 i32_load(code, 8); local_get(code, counter);
15872 i32_const(code, 8);
15873 code.push(0x6C);
15874 code.push(0x6A);
15875 i32_load(code, 0); }
15877 i32_load(code, 12);
15878 i32_const(code, 0x100);
15879 code.push(0x6A);
15880 i32_store(code, 12);
15881 local_get(code, counter);
15882 i32_const(code, 1);
15883 code.push(0x6A);
15884 local_set(code, counter);
15885 code.push(0x0C);
15886 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); }
15890
15891fn emit_retain_children(code: &mut Vec<u8>, ctx: &Ctx, hdr: u32) {
15896 let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::RetainChildren)) else {
15897 return;
15898 };
15899 local_get(code, hdr);
15900 code.push(0x10);
15901 leb_u32(code, f);
15902}
15903
15904fn emit_true_release(code: &mut Vec<u8>, ctx: &Ctx, push_handle: impl Fn(&mut Vec<u8>)) {
15909 let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Release)) else {
15910 return;
15911 };
15912 push_handle(code);
15913 code.push(0x10);
15914 leb_u32(code, f);
15915}
15916
15917fn counts_aliases(k: Option<Kind>) -> bool {
15920 cow_clonable(k) || k == Some(Kind::Struct)
15921}
15922
15923fn cow_clonable(k: Option<Kind>) -> bool {
15927 matches!(
15928 k,
15929 Some(Kind::SeqInt)
15930 | Some(Kind::SeqBool)
15931 | Some(Kind::SeqFloat)
15932 | Some(Kind::SeqWord32)
15933 | Some(Kind::SeqWord64)
15934 | Some(Kind::SeqAny)
15935 | Some(Kind::Set)
15936 | Some(Kind::SetText)
15937 | Some(Kind::SeqSeqInt)
15938 | Some(Kind::Map)
15939 | Some(Kind::SeqText)
15940 | Some(Kind::SeqStruct)
15941 | Some(Kind::SeqEnum)
15942 | Some(Kind::SeqHandle)
15943 )
15944}
15945
15946fn seq_clone_mode(k: Kind) -> Option<i32> {
15951 let handles = i32::from(AllocClass::HandleHeader.code()) | CLONE_RETAINS;
15952 Some(match k {
15953 Kind::SeqInt
15954 | Kind::SeqBool
15955 | Kind::SeqFloat
15956 | Kind::SeqWord32
15957 | Kind::SeqWord64
15958 | Kind::Set => i32::from(AllocClass::ScalarHeader.code()),
15959 Kind::SeqAny | Kind::SetText | Kind::SeqText | Kind::SeqEnum => handles,
15960 Kind::SeqStruct | Kind::SeqHandle => handles | CLONE_SHARES,
15961 _ => return None,
15962 })
15963}
15964
15965fn emit_cow(
15970 code: &mut Vec<u8>,
15971 kinds: &KindTable,
15972 structs: &kind::StructLayout,
15973 ctx: &Ctx,
15974 num_regs: u32,
15975 reg: u16,
15976) -> R<()> {
15977 if !cow_clonable(kinds.get(reg as usize)) {
15978 return Ok(());
15979 }
15980 if let Some(mode) = kinds.get(reg as usize).and_then(seq_clone_mode) {
15981 if ctx.hot.get() {
15982 if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqClone)) {
15984 emit_should_clone(code, reg as u32);
15985 code.push(0x04);
15986 code.push(0x40);
15987 local_get(code, reg as u32);
15988 i32_const(code, mode);
15989 code.push(0x10);
15990 leb_u32(code, clone);
15991 local_set(code, reg as u32);
15992 code.push(0x0B);
15993 return Ok(());
15994 }
15995 } else if let Some(own) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqOwn)) {
15996 local_get(code, reg as u32);
15997 i32_const(code, mode);
15998 code.push(0x10);
15999 leb_u32(code, own);
16000 local_set(code, reg as u32);
16001 return Ok(());
16002 }
16003 }
16004 if kinds.get(reg as usize) == Some(Kind::Map) {
16005 if let Some(own) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapOwn)) {
16006 local_get(code, reg as u32);
16007 code.push(0x10);
16008 leb_u32(code, own);
16009 local_set(code, reg as u32);
16010 return Ok(());
16011 }
16012 }
16013 emit_should_clone(code, reg as u32);
16014 code.push(0x04);
16015 code.push(0x40); lower_deep_clone(code, kinds, structs, ctx, num_regs, reg, reg)?;
16017 code.push(0x0B); Ok(())
16019}
16020
16021fn emit_should_clone(code: &mut Vec<u8>, local: u32) {
16028 local_get(code, local);
16029 i32_load(code, 12);
16030 i32_const(code, 0x100);
16031 code.push(0x4E); }
16033
16034fn emit_record_copy(
16041 code: &mut Vec<u8>,
16042 ctx: &Ctx,
16043 kinds: &KindTable,
16044 structs: &kind::StructLayout,
16045 num_regs: u32,
16046 obj: u16,
16047 overwritten: Option<usize>,
16048) -> R<()> {
16049 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
16050 emit_should_clone(code, obj as u32);
16051 code.push(0x04);
16052 code.push(0x40); emit_buffer_clone(
16055 code,
16056 ctx,
16057 hdr,
16058 data,
16059 idx,
16060 obj as u32,
16061 false,
16062 AllocClass::RecordHeader,
16063 );
16064 local_get(code, hdr);
16065 local_set(code, obj as u32);
16066 if ctx.heap_counting() {
16067 emit_retain_children(code, ctx, obj as u32);
16068 }
16069 if let Some(slot_kinds) = record_slot_kinds(kinds, structs, obj) {
16070 for (slot, k) in slot_kinds.iter().enumerate() {
16071 if *k == Some(Kind::Tower) && overwritten != Some(slot) {
16074 tower::own_field(code, ctx, obj, slot as u32)?;
16075 continue;
16076 }
16077 let cow_hold = counts_aliases(*k) && overwritten != Some(slot);
16080 if !cow_hold {
16081 continue;
16082 }
16083 local_get(code, obj as u32);
16084 i32_load(code, 8); i32_load(code, slot as u32 * 8);
16086 local_tee(code, idx);
16087 code.push(0x04);
16088 code.push(0x40); if cow_hold {
16090 local_get(code, idx);
16091 local_get(code, idx);
16092 i32_load(code, 12);
16093 i32_const(code, 0x100); code.push(0x6A);
16095 i32_store(code, 12);
16096 }
16097 code.push(0x0B);
16098 }
16099 }
16100 code.push(0x0B); Ok(())
16102}
16103
16104const SHARED_MAP_MARK: i32 = -(1 << 30);
16111
16112fn map_key_text(kinds: &KindTable, key: u16) -> R<bool> {
16114 match kinds.get(key as usize) {
16115 Some(Kind::Int) => Ok(false),
16116 Some(Kind::Text) => Ok(true),
16117 _ => Err(WasmLowerError::Unsupported("map key must be Int or Text")),
16118 }
16119}
16120
16121fn emit_map_key_compare(
16125 code: &mut Vec<u8>,
16126 ctx: &Ctx,
16127 num_regs: u32,
16128 key_text: bool,
16129 m: u32,
16130 idx_local: u32,
16131 key: u16,
16132) {
16133 if key_text {
16134 let entry_key = num_regs + 8;
16135 emit_map_entry_addr(code, m, idx_local);
16136 i32_load(code, 0); local_set(code, entry_key);
16138 emit_text_eq(code, ctx, num_regs, key as u32, entry_key);
16139 } else {
16140 emit_map_entry_addr(code, m, idx_local);
16141 i64_load(code, 0); local_get(code, key as u32);
16143 code.push(0x51); }
16145}
16146
16147fn map_value_store(k: Option<Kind>) -> R<fn(&mut Vec<u8>, u32)> {
16150 match k {
16151 Some(Kind::Float) => Ok(f64_store),
16152 Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Moment) | Some(Kind::Duration)
16153 | Some(Kind::Time) | Some(Kind::Span) => Ok(i64_store),
16154 Some(vk) if vk.wasm_valtype() == I32 => Ok(i32_store),
16157 _ => Err(WasmLowerError::Unsupported(
16158 "map value of an unsupported kind",
16159 )),
16160 }
16161}
16162
16163fn map_value_load(k: Option<Kind>) -> R<fn(&mut Vec<u8>, u32)> {
16165 match k {
16166 Some(Kind::Float) => Ok(f64_load),
16167 Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Moment) | Some(Kind::Duration)
16168 | Some(Kind::Time) | Some(Kind::Span) => Ok(i64_load),
16169 Some(vk) if vk.wasm_valtype() == I32 => Ok(i32_load),
16170 _ => Err(WasmLowerError::Unsupported(
16171 "map value of unknown/unsupported kind",
16172 )),
16173 }
16174}
16175
16176fn emit_map_key_i64(code: &mut Vec<u8>, key: u16, key_text: bool) {
16179 local_get(code, key as u32);
16180 if key_text {
16181 code.push(0xAD); }
16183}
16184
16185fn emit_map_entry_addr(code: &mut Vec<u8>, m: u32, idx: u32) {
16188 local_get(code, m);
16189 i32_load(code, 8); local_get(code, idx);
16191 i32_const(code, 16);
16192 code.push(0x6C); code.push(0x6A); }
16195
16196fn lower_map_insert(
16200 code: &mut Vec<u8>,
16201 kinds: &KindTable,
16202 ctx: &Ctx,
16203 num_regs: u32,
16204 map: u16,
16205 key: u16,
16206 value: u16,
16207) -> R<()> {
16208 let key_text = map_key_text(kinds, key)?;
16209 let val_store = map_value_store(kinds.get(value as usize))?;
16210 let m = map as u32;
16211 let value_is_handle = kinds
16218 .get(value as usize)
16219 .map(|k| kind_is_handle(k))
16220 .unwrap_or(false);
16221 let class = AllocClass::of_map(key_text, value_is_handle);
16222 let put = if ctx.shared_maps {
16223 None
16224 } else {
16225 ctx.runtime.and_then(|r| r.index(RuntimeFn::MapPut))
16226 };
16227 if let Some(put) = put {
16228 local_get(code, m);
16229 emit_map_key_i64(code, key, key_text);
16230 i32_const(code, i32::from(class.code()));
16231 code.push(0x10);
16232 leb_u32(code, put);
16233 if ctx.heap_counting() && counted_kind(kinds.get(value as usize)) {
16234 let entry = num_regs + 5;
16237 local_tee(code, entry);
16238 emit_true_release(code, ctx, |c| {
16239 local_get(c, entry);
16240 i32_load(c, 8);
16241 });
16242 }
16243 local_get(code, value as u32);
16244 val_store(code, 8);
16245 return Ok(());
16246 }
16247 local_get(code, m);
16249 local_get(code, m);
16250 i32_load(code, 12);
16251 i32_const(code, !0xFFu32 as i32); code.push(0x71); i32_const(code, class.code() as i32);
16254 code.push(0x72); i32_store(code, 12);
16256 let (idx, found, new) = (num_regs + 5, num_regs + 6, num_regs + 7);
16257 i32_const(code, 0);
16259 local_set(code, idx);
16260 i32_const(code, 0);
16261 local_set(code, found);
16262 code.push(0x02);
16263 code.push(0x40); code.push(0x03);
16265 code.push(0x40); local_get(code, idx);
16267 local_get(code, m);
16268 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
16271 leb_u32(code, 1); emit_map_key_compare(code, ctx, num_regs, key_text, m, idx, key);
16273 code.push(0x04);
16274 code.push(0x40); if ctx.heap_counting() && counted_kind(kinds.get(value as usize)) {
16276 emit_true_release(code, ctx, |c| {
16279 emit_map_entry_addr(c, m, idx);
16280 i32_load(c, 8);
16281 });
16282 }
16283 emit_map_entry_addr(code, m, idx);
16284 local_get(code, value as u32);
16285 val_store(code, 8); i32_const(code, 1);
16287 local_set(code, found);
16288 code.push(0x0C);
16289 leb_u32(code, 2); code.push(0x0B); local_get(code, idx);
16292 i32_const(code, 1);
16293 code.push(0x6A);
16294 local_set(code, idx);
16295 code.push(0x0C);
16296 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); let new_cap = num_regs + 23; local_get(code, found);
16304 code.push(0x45); code.push(0x04);
16306 code.push(0x40); local_get(code, m);
16308 i32_load(code, 0); local_get(code, m);
16310 i32_load(code, 4); code.push(0x4E); code.push(0x04);
16313 code.push(0x40); {
16315 i32_const(code, 4);
16317 local_get(code, m);
16318 i32_load(code, 4);
16319 i32_const(code, 2);
16320 code.push(0x6C);
16321 local_get(code, m);
16322 i32_load(code, 4);
16323 code.push(0x45); code.push(0x1B); local_set(code, new_cap);
16326 local_get(code, new_cap);
16328 i32_const(code, 16);
16329 code.push(0x6C);
16330 emit_alloc(code, ctx, new, AllocClass::Raw);
16331 i32_const(code, 0);
16333 local_set(code, idx);
16334 code.push(0x02);
16335 code.push(0x40);
16336 code.push(0x03);
16337 code.push(0x40);
16338 local_get(code, idx);
16339 local_get(code, m);
16340 i32_load(code, 0);
16341 code.push(0x4E);
16342 code.push(0x0D);
16343 leb_u32(code, 1);
16344 for field in [0u32, 8] {
16345 local_get(code, new);
16347 local_get(code, idx);
16348 i32_const(code, 16);
16349 code.push(0x6C);
16350 code.push(0x6A); emit_map_entry_addr(code, m, idx); i64_load(code, field);
16353 i64_store(code, field);
16354 }
16355 local_get(code, idx);
16356 i32_const(code, 1);
16357 code.push(0x6A);
16358 local_set(code, idx);
16359 code.push(0x0C);
16360 leb_u32(code, 0);
16361 code.push(0x0B);
16362 code.push(0x0B);
16363 emit_free(
16366 code,
16367 ctx,
16368 |c| {
16369 local_get(c, m);
16370 i32_load(c, 8); },
16372 |c| {
16373 local_get(c, m);
16374 i32_load(c, 4); i32_const(c, 16);
16376 c.push(0x6C);
16377 },
16378 );
16379 local_get(code, m);
16381 local_get(code, new);
16382 i32_store(code, 8);
16383 local_get(code, m);
16384 local_get(code, new_cap);
16385 i32_store(code, 4);
16386 }
16387 code.push(0x0B); local_get(code, m);
16391 i32_load(code, 8);
16392 local_get(code, m);
16393 i32_load(code, 0);
16394 i32_const(code, 16);
16395 code.push(0x6C);
16396 code.push(0x6A); local_get(code, key as u32);
16398 if key_text {
16399 i32_store(code, 0);
16400 if ctx.heap_counting() {
16403 emit_true_retain(code, ctx, key);
16404 }
16405 } else {
16406 i64_store(code, 0);
16407 }
16408 local_get(code, m);
16409 i32_load(code, 8);
16410 local_get(code, m);
16411 i32_load(code, 0);
16412 i32_const(code, 16);
16413 code.push(0x6C);
16414 code.push(0x6A);
16415 local_get(code, value as u32);
16416 val_store(code, 8);
16417 local_get(code, m);
16419 local_get(code, m);
16420 i32_load(code, 0);
16421 i32_const(code, 1);
16422 code.push(0x6A);
16423 i32_store(code, 0);
16424 if ctx.shared_maps {
16425 local_get(code, m);
16427 i32_load(code, 12);
16428 i32_const(code, 0);
16429 code.push(0x48); code.push(0x04);
16431 code.push(0x40); emit_sink_last_entry_to_sorted_place(code, num_regs, m, key as u32, key_text, None);
16433 code.push(0x0B); }
16435 code.push(0x0B); Ok(())
16437}
16438
16439fn emit_sink_last_entry_to_sorted_place(
16445 code: &mut Vec<u8>,
16446 num_regs: u32,
16447 m: u32,
16448 key: u32,
16449 key_text: bool,
16450 exact_cmp: Option<u32>,
16451) {
16452 let at = num_regs + 11;
16453 let prev_key = if key_text || exact_cmp.is_some() {
16454 num_regs + 8
16455 } else {
16456 num_regs + 16
16457 };
16458 let new_value = num_regs + 15;
16459 let entry_at = |code: &mut Vec<u8>, minus_one: bool| {
16460 local_get(code, m);
16461 i32_load(code, 8);
16462 local_get(code, at);
16463 if minus_one {
16464 i32_const(code, 1);
16465 code.push(0x6B);
16466 }
16467 i32_const(code, 16);
16468 code.push(0x6C);
16469 code.push(0x6A);
16470 };
16471 local_get(code, m);
16473 i32_load(code, 0);
16474 i32_const(code, 1);
16475 code.push(0x6B);
16476 local_set(code, at);
16477 entry_at(code, false);
16478 i64_load(code, 8);
16479 local_set(code, new_value);
16480 code.push(0x02);
16481 code.push(0x40); code.push(0x03);
16483 code.push(0x40); local_get(code, at);
16485 code.push(0x45); code.push(0x0D);
16487 leb_u32(code, 1); entry_at(code, true);
16489 if let Some(cmp) = exact_cmp {
16490 i32_load(code, 0);
16491 i32_load(code, 8);
16492 i64_load(code, 0);
16493 local_get(code, key);
16494 i32_load(code, 8);
16495 i64_load(code, 0);
16496 code.push(0x10);
16497 leb_u32(code, cmp);
16498 i32_const(code, 0);
16499 code.push(0x48);
16500 } else if key_text {
16501 i32_load(code, 0);
16502 local_set(code, prev_key);
16503 emit_text_handles_lt(code, num_regs, prev_key, key as u32);
16504 } else {
16505 i64_load(code, 0);
16506 local_set(code, prev_key);
16507 local_get(code, prev_key);
16508 local_get(code, key as u32);
16509 code.push(0x53); }
16511 code.push(0x0D);
16512 leb_u32(code, 1); for off in [0u32, 8] {
16514 entry_at(code, false);
16515 entry_at(code, true);
16516 i64_load(code, off);
16517 i64_store(code, off);
16518 }
16519 local_get(code, at);
16520 i32_const(code, 1);
16521 code.push(0x6B);
16522 local_set(code, at);
16523 code.push(0x0C);
16524 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); entry_at(code, false);
16529 local_get(code, key as u32);
16530 if key_text || exact_cmp.is_some() {
16531 i32_store(code, 0);
16532 } else {
16533 i64_store(code, 0);
16534 }
16535 entry_at(code, false);
16536 local_get(code, new_value);
16537 i64_store(code, 8);
16538}
16539
16540fn lower_map_get(
16543 code: &mut Vec<u8>,
16544 kinds: &KindTable,
16545 ctx: &Ctx,
16546 num_regs: u32,
16547 dst: u16,
16548 map: u16,
16549 key: u16,
16550) -> R<()> {
16551 let key_text = map_key_text(kinds, key)?;
16552 let val_load = map_value_load(kinds.get(dst as usize))?;
16553 let m = map as u32;
16554 if let Some(at) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapAt)) {
16555 local_get(code, m);
16556 emit_map_key_i64(code, key, key_text);
16557 i32_const(code, i32::from(key_text));
16558 code.push(0x10);
16559 leb_u32(code, at);
16560 val_load(code, 8);
16561 local_set(code, dst as u32);
16562 return Ok(());
16563 }
16564 let (idx, found) = (num_regs + 5, num_regs + 6);
16566 i32_const(code, 0);
16567 local_set(code, idx);
16568 i32_const(code, 0);
16569 local_set(code, found);
16570 code.push(0x02);
16571 code.push(0x40);
16572 code.push(0x03);
16573 code.push(0x40);
16574 local_get(code, idx);
16575 local_get(code, m);
16576 i32_load(code, 0);
16577 code.push(0x4E);
16578 code.push(0x0D);
16579 leb_u32(code, 1);
16580 emit_map_key_compare(code, ctx, num_regs, key_text, m, idx, key);
16581 code.push(0x04);
16582 code.push(0x40); emit_map_entry_addr(code, m, idx);
16584 val_load(code, 8); local_set(code, dst as u32);
16586 i32_const(code, 1);
16587 local_set(code, found);
16588 code.push(0x0C);
16589 leb_u32(code, 2);
16590 code.push(0x0B); local_get(code, idx);
16592 i32_const(code, 1);
16593 code.push(0x6A);
16594 local_set(code, idx);
16595 code.push(0x0C);
16596 leb_u32(code, 0);
16597 code.push(0x0B);
16598 code.push(0x0B);
16599 local_get(code, found);
16601 code.push(0x45); code.push(0x04);
16603 code.push(0x40);
16604 code.push(0x00); code.push(0x0B);
16606 Ok(())
16607}
16608
16609fn lower_map_contains(
16611 code: &mut Vec<u8>,
16612 kinds: &KindTable,
16613 ctx: &Ctx,
16614 num_regs: u32,
16615 dst: u16,
16616 map: u16,
16617 key: u16,
16618) -> R<()> {
16619 let key_text = map_key_text(kinds, key)?;
16620 let m = map as u32;
16621 if let Some(find) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapFind)) {
16622 local_get(code, m);
16623 emit_map_key_i64(code, key, key_text);
16624 i32_const(code, i32::from(key_text));
16625 code.push(0x10);
16626 leb_u32(code, find);
16627 i32_const(code, 0);
16628 code.push(0x47); code.push(0xAD); local_set(code, dst as u32);
16631 return Ok(());
16632 }
16633 let idx = num_regs + 5;
16635 code.push(0x42);
16636 leb_i64(code, 0);
16637 local_set(code, dst as u32); i32_const(code, 0);
16639 local_set(code, idx);
16640 code.push(0x02);
16641 code.push(0x40);
16642 code.push(0x03);
16643 code.push(0x40);
16644 local_get(code, idx);
16645 local_get(code, m);
16646 i32_load(code, 0);
16647 code.push(0x4E);
16648 code.push(0x0D);
16649 leb_u32(code, 1);
16650 emit_map_key_compare(code, ctx, num_regs, key_text, m, idx, key);
16651 code.push(0x04);
16652 code.push(0x40); code.push(0x42);
16654 leb_i64(code, 1);
16655 local_set(code, dst as u32); code.push(0x0C);
16657 leb_u32(code, 2); code.push(0x0B);
16659 local_get(code, idx);
16660 i32_const(code, 1);
16661 code.push(0x6A);
16662 local_set(code, idx);
16663 code.push(0x0C);
16664 leb_u32(code, 0);
16665 code.push(0x0B);
16666 code.push(0x0B);
16667 Ok(())
16668}
16669
16670fn emit_text_eq(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, a: u32, b: u32) {
16676 if let Some(eq) = ctx.runtime.and_then(|r| r.index(RuntimeFn::TextEq)) {
16677 local_get(code, a);
16678 local_get(code, b);
16679 code.push(0x10);
16680 leb_u32(code, eq);
16681 return;
16682 }
16683 let (idx, res) = (num_regs + 9, num_regs + 10);
16684 i32_const(code, 1);
16685 local_set(code, res); local_get(code, a);
16688 i32_load(code, 0);
16689 local_get(code, b);
16690 i32_load(code, 0);
16691 code.push(0x47); code.push(0x04);
16693 code.push(0x40); i32_const(code, 0);
16695 local_set(code, res);
16696 code.push(0x05); i32_const(code, 0);
16698 local_set(code, idx);
16699 code.push(0x02);
16700 code.push(0x40); code.push(0x03);
16702 code.push(0x40); local_get(code, idx);
16704 local_get(code, a);
16705 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
16708 leb_u32(code, 1); local_get(code, a);
16711 i32_load(code, 8);
16712 local_get(code, idx);
16713 code.push(0x6A);
16714 i32_load8_u(code, 0);
16715 local_get(code, b);
16716 i32_load(code, 8);
16717 local_get(code, idx);
16718 code.push(0x6A);
16719 i32_load8_u(code, 0);
16720 code.push(0x47); code.push(0x04);
16722 code.push(0x40); i32_const(code, 0);
16724 local_set(code, res);
16725 code.push(0x0C);
16726 leb_u32(code, 2); code.push(0x0B); local_get(code, idx);
16729 i32_const(code, 1);
16730 code.push(0x6A);
16731 local_set(code, idx);
16732 code.push(0x0C);
16733 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); code.push(0x0B); local_get(code, res); }
16739
16740fn emit_set_elem_eq(
16745 code: &mut Vec<u8>,
16746 ctx: &Ctx,
16747 num_regs: u32,
16748 set: u32,
16749 idx: u32,
16750 value: u32,
16751 is_text: bool,
16752) {
16753 local_get(code, set);
16754 i32_load(code, 8); local_get(code, idx);
16756 i32_const(code, 8);
16757 code.push(0x6C);
16758 code.push(0x6A); if is_text {
16760 i32_load(code, 0); local_set(code, num_regs + 8);
16762 emit_text_eq(code, ctx, num_regs, num_regs + 8, value);
16763 } else {
16764 i64_load(code, 0); local_get(code, value);
16766 code.push(0x51); }
16768}
16769
16770fn lower_remove_from(
16776 code: &mut Vec<u8>,
16777 kinds: &KindTable,
16778 ctx: &Ctx,
16779 num_regs: u32,
16780 collection: u16,
16781 value: u16,
16782) -> R<()> {
16783 let set_text = matches!(
16784 kinds.get(collection as usize),
16785 Some(Kind::SetText) | Some(Kind::CrdtSetText)
16786 );
16787 let map_text_key = kinds.get(collection as usize) == Some(Kind::Map)
16788 && kinds.get(value as usize) == Some(Kind::Text);
16789 if !set_text && !map_text_key && kinds.get(value as usize) != Some(Kind::Int) {
16790 return Err(WasmLowerError::Unsupported("remove of a non-Int value"));
16791 }
16792 let stride: i32 = match kinds.get(collection as usize) {
16793 Some(Kind::Set) | Some(Kind::SetText) | Some(Kind::CrdtSetText) => 8,
16794 Some(Kind::Map) => 16,
16795 _ => {
16796 return Err(WasmLowerError::Unsupported(
16797 "remove from a non-set/map collection",
16798 ))
16799 }
16800 };
16801 let c = collection as u32;
16802 let (idx, found) = (num_regs + 5, num_regs + 6);
16803 i32_const(code, 0);
16804 local_set(code, idx);
16805 i32_const(code, 0);
16806 local_set(code, found);
16807 code.push(0x02);
16808 code.push(0x40);
16809 code.push(0x03);
16810 code.push(0x40);
16811 local_get(code, idx);
16812 local_get(code, c);
16813 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
16816 leb_u32(code, 1); if set_text {
16820 emit_set_elem_eq(code, ctx, num_regs, c, idx, value as u32, true);
16821 } else if map_text_key {
16822 emit_map_key_compare(code, ctx, num_regs, true, c, idx, value);
16823 } else {
16824 local_get(code, c);
16825 i32_load(code, 8);
16826 local_get(code, idx);
16827 i32_const(code, stride);
16828 code.push(0x6C);
16829 code.push(0x6A);
16830 i64_load(code, 0);
16831 local_get(code, value as u32);
16832 code.push(0x51); }
16834 code.push(0x04);
16835 code.push(0x40); if ctx.heap_counting() {
16839 for off in (0..stride as u32).step_by(8) {
16840 let mask: i32 = AllocClass::ALL
16841 .iter()
16842 .filter(|class| {
16843 let (first, second) = class.held_handles();
16844 if off == 0 {
16845 first
16846 } else {
16847 second
16848 }
16849 })
16850 .map(|class| 1i32 << class.code())
16851 .sum();
16852 i32_const(code, mask);
16853 local_get(code, c);
16854 i32_load(code, 12);
16855 i32_const(code, 0xFF);
16856 code.push(0x71);
16857 code.push(0x76); i32_const(code, 1);
16859 code.push(0x71);
16860 code.push(0x04);
16861 code.push(0x40);
16862 emit_true_release(code, ctx, |code| {
16863 local_get(code, c);
16864 i32_load(code, 8);
16865 local_get(code, idx);
16866 i32_const(code, stride);
16867 code.push(0x6C);
16868 code.push(0x6A);
16869 i32_load(code, off);
16870 });
16871 code.push(0x0B);
16872 }
16873 }
16874 code.push(0x02);
16877 code.push(0x40); code.push(0x03);
16879 code.push(0x40); local_get(code, idx);
16881 i32_const(code, 1);
16882 code.push(0x6A);
16883 local_get(code, c);
16884 i32_load(code, 0);
16885 code.push(0x4E); code.push(0x0D);
16887 leb_u32(code, 1); let offs: &[u32] = if stride == 16 { &[0, 8] } else { &[0] };
16889 for &off in offs {
16890 local_get(code, c);
16891 i32_load(code, 8);
16892 local_get(code, idx);
16893 i32_const(code, stride);
16894 code.push(0x6C);
16895 code.push(0x6A); local_get(code, c);
16897 i32_load(code, 8);
16898 local_get(code, idx);
16899 i32_const(code, 1);
16900 code.push(0x6A);
16901 i32_const(code, stride);
16902 code.push(0x6C);
16903 code.push(0x6A); i64_load(code, off);
16905 i64_store(code, off);
16906 }
16907 local_get(code, idx);
16908 i32_const(code, 1);
16909 code.push(0x6A);
16910 local_set(code, idx);
16911 code.push(0x0C);
16912 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, c);
16917 local_get(code, c);
16918 i32_load(code, 0);
16919 i32_const(code, 1);
16920 code.push(0x6B);
16921 i32_store(code, 0);
16922 i32_const(code, 1);
16923 local_set(code, found);
16924 code.push(0x0C);
16925 leb_u32(code, 2); code.push(0x0B); local_get(code, idx);
16928 i32_const(code, 1);
16929 code.push(0x6A);
16930 local_set(code, idx);
16931 code.push(0x0C);
16932 leb_u32(code, 0);
16933 code.push(0x0B);
16934 code.push(0x0B);
16935 Ok(())
16936}
16937
16938fn lower_set_add(
16941 code: &mut Vec<u8>,
16942 kinds: &KindTable,
16943 ctx: &Ctx,
16944 num_regs: u32,
16945 set: u16,
16946 value: u16,
16947) -> R<()> {
16948 let is_text = matches!(
16949 kinds.get(set as usize),
16950 Some(Kind::SetText) | Some(Kind::CrdtSetText)
16951 );
16952 if is_text {
16953 if kinds.get(value as usize) != Some(Kind::Text) {
16954 return Err(WasmLowerError::Unsupported(
16955 "adding a non-Text value to a Set of Text",
16956 ));
16957 }
16958 } else if kinds.get(value as usize) != Some(Kind::Int) {
16959 return Err(WasmLowerError::Unsupported(
16960 "set with a non-Int value (only Set of Int/Text)",
16961 ));
16962 }
16963 let order = if kinds.get(set as usize) == Some(Kind::CrdtSetText) {
16964 SetOrder::Sorted
16965 } else {
16966 SetOrder::Insertion
16967 };
16968 emit_set_add_elem(
16969 code,
16970 ctx,
16971 num_regs,
16972 set as u32,
16973 value as u32,
16974 is_text,
16975 order,
16976 );
16977 Ok(())
16978}
16979
16980#[derive(Clone, Copy, PartialEq, Eq)]
16984enum SetOrder {
16985 Insertion,
16986 Sorted,
16987}
16988
16989fn emit_set_add_elem(
16998 code: &mut Vec<u8>,
16999 ctx: &Ctx,
17000 num_regs: u32,
17001 s: u32,
17002 elem: u32,
17003 is_text: bool,
17004 order: SetOrder,
17005) {
17006 let (idx, found, new) = (num_regs + 5, num_regs + 6, num_regs + 7);
17007 i32_const(code, 0);
17009 local_set(code, idx);
17010 i32_const(code, 0);
17011 local_set(code, found);
17012 code.push(0x02);
17013 code.push(0x40);
17014 code.push(0x03);
17015 code.push(0x40);
17016 local_get(code, idx);
17017 local_get(code, s);
17018 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
17021 leb_u32(code, 1); emit_set_elem_eq(code, ctx, num_regs, s, idx, elem, is_text); code.push(0x04);
17024 code.push(0x40); i32_const(code, 1);
17026 local_set(code, found);
17027 code.push(0x0C);
17028 leb_u32(code, 2); code.push(0x0B);
17030 local_get(code, idx);
17031 i32_const(code, 1);
17032 code.push(0x6A);
17033 local_set(code, idx);
17034 code.push(0x0C);
17035 leb_u32(code, 0);
17036 code.push(0x0B);
17037 code.push(0x0B);
17038 let new_cap = num_regs + 23;
17048 local_get(code, found);
17049 code.push(0x45); code.push(0x04);
17051 code.push(0x40); local_get(code, s);
17053 i32_load(code, 0); local_get(code, s);
17055 i32_load(code, 4); code.push(0x4E); code.push(0x04);
17058 code.push(0x40); {
17060 i32_const(code, 4);
17062 local_get(code, s);
17063 i32_load(code, 4);
17064 i32_const(code, 2);
17065 code.push(0x6C);
17066 local_get(code, s);
17067 i32_load(code, 4);
17068 code.push(0x45); code.push(0x1B); local_set(code, new_cap);
17071 local_get(code, new_cap);
17072 i32_const(code, 8);
17073 code.push(0x6C);
17074 emit_alloc(code, ctx, new, AllocClass::Raw); emit_seq_copy(code, idx, new, s, s, false); emit_free(
17079 code,
17080 ctx,
17081 |c| {
17082 local_get(c, s);
17083 i32_load(c, 8); },
17085 |c| {
17086 local_get(c, s);
17087 i32_load(c, 4); i32_const(c, 8);
17089 c.push(0x6C);
17090 },
17091 );
17092 local_get(code, s);
17093 local_get(code, new);
17094 i32_store(code, 8); local_get(code, s);
17096 local_get(code, new_cap);
17097 i32_store(code, 4); }
17099 code.push(0x0B); local_get(code, s);
17104 i32_load(code, 8);
17105 local_get(code, s);
17106 i32_load(code, 0);
17107 i32_const(code, 8);
17108 code.push(0x6C);
17109 code.push(0x6A);
17110 local_get(code, elem);
17111 if is_text {
17112 i32_store(code, 0); if ctx.heap_counting() {
17115 emit_true_retain_of(code, ctx, |c| local_get(c, elem));
17116 }
17117 } else {
17118 i64_store(code, 0); }
17120 local_get(code, s);
17121 local_get(code, s);
17122 i32_load(code, 0);
17123 i32_const(code, 1);
17124 code.push(0x6A);
17125 i32_store(code, 0); if order == SetOrder::Sorted {
17127 emit_sink_last_to_sorted_place(code, num_regs, s, elem, is_text);
17128 }
17129 code.push(0x0B); }
17131
17132fn emit_sink_last_to_sorted_place(
17137 code: &mut Vec<u8>,
17138 num_regs: u32,
17139 s: u32,
17140 elem: u32,
17141 is_text: bool,
17142) {
17143 let at = num_regs + 11;
17144 let prev = if is_text { num_regs + 8 } else { num_regs + 16 };
17145 let slot_at = |code: &mut Vec<u8>, minus_one: bool| {
17146 local_get(code, s);
17147 i32_load(code, 8);
17148 local_get(code, at);
17149 if minus_one {
17150 i32_const(code, 1);
17151 code.push(0x6B);
17152 }
17153 i32_const(code, 8);
17154 code.push(0x6C);
17155 code.push(0x6A);
17156 };
17157 local_get(code, s);
17159 i32_load(code, 0);
17160 i32_const(code, 1);
17161 code.push(0x6B);
17162 local_set(code, at);
17163 code.push(0x02);
17164 code.push(0x40); code.push(0x03);
17166 code.push(0x40); local_get(code, at);
17168 code.push(0x45); code.push(0x0D);
17170 leb_u32(code, 1); slot_at(code, true);
17173 if is_text {
17174 i32_load(code, 0);
17175 local_set(code, prev);
17176 emit_text_handles_lt(code, num_regs, prev, elem);
17177 } else {
17178 i64_load(code, 0);
17179 local_set(code, prev);
17180 local_get(code, prev);
17181 local_get(code, elem);
17182 code.push(0x53); }
17184 code.push(0x0D);
17185 leb_u32(code, 1); slot_at(code, false);
17188 local_get(code, prev);
17189 if is_text {
17190 i32_store(code, 0);
17191 } else {
17192 i64_store(code, 0);
17193 }
17194 local_get(code, at);
17195 i32_const(code, 1);
17196 code.push(0x6B);
17197 local_set(code, at);
17198 code.push(0x0C);
17199 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); slot_at(code, false);
17204 local_get(code, elem);
17205 if is_text {
17206 i32_store(code, 0);
17207 } else {
17208 i64_store(code, 0);
17209 }
17210}
17211
17212fn emit_text_handles_lt(code: &mut Vec<u8>, num_regs: u32, a: u32, b: u32) {
17216 let (i, res) = (num_regs + 9, num_regs + 10);
17217 i32_const(code, 0);
17218 local_set(code, i);
17219 code.push(0x02);
17220 code.push(0x40); code.push(0x03);
17222 code.push(0x40); local_get(code, i);
17225 local_get(code, a);
17226 i32_load(code, 0);
17227 code.push(0x4F); local_get(code, i);
17229 local_get(code, b);
17230 i32_load(code, 0);
17231 code.push(0x4F); code.push(0x72); code.push(0x04);
17234 code.push(0x40); local_get(code, a);
17236 i32_load(code, 0);
17237 local_get(code, b);
17238 i32_load(code, 0);
17239 code.push(0x49); local_set(code, res);
17241 code.push(0x0C);
17242 leb_u32(code, 2); code.push(0x0B); local_get(code, a);
17246 i32_load(code, 8);
17247 local_get(code, i);
17248 code.push(0x6A);
17249 i32_load8_u(code, 0);
17250 local_get(code, b);
17251 i32_load(code, 8);
17252 local_get(code, i);
17253 code.push(0x6A);
17254 i32_load8_u(code, 0);
17255 code.push(0x47); code.push(0x04);
17257 code.push(0x40); local_get(code, a);
17259 i32_load(code, 8);
17260 local_get(code, i);
17261 code.push(0x6A);
17262 i32_load8_u(code, 0);
17263 local_get(code, b);
17264 i32_load(code, 8);
17265 local_get(code, i);
17266 code.push(0x6A);
17267 i32_load8_u(code, 0);
17268 code.push(0x49); local_set(code, res);
17270 code.push(0x0C);
17271 leb_u32(code, 2); code.push(0x0B); local_get(code, i);
17274 i32_const(code, 1);
17275 code.push(0x6A);
17276 local_set(code, i);
17277 code.push(0x0C);
17278 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, res);
17282}
17283
17284fn emit_set_contains_to(code: &mut Vec<u8>, set: u32, elem: u32, out: u32, idx: u32) {
17288 i32_const(code, 0);
17289 local_set(code, out); i32_const(code, 0);
17291 local_set(code, idx);
17292 code.push(0x02);
17293 code.push(0x40); code.push(0x03);
17295 code.push(0x40); local_get(code, idx);
17297 local_get(code, set);
17298 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
17301 leb_u32(code, 1); local_get(code, set);
17303 i32_load(code, 8); local_get(code, idx);
17305 i32_const(code, 8);
17306 code.push(0x6C);
17307 code.push(0x6A);
17308 i64_load(code, 0); local_get(code, elem);
17310 code.push(0x51); code.push(0x04);
17312 code.push(0x40); i32_const(code, 1);
17314 local_set(code, out);
17315 code.push(0x0C);
17316 leb_u32(code, 2); code.push(0x0B); local_get(code, idx);
17319 i32_const(code, 1);
17320 code.push(0x6A);
17321 local_set(code, idx);
17322 code.push(0x0C);
17323 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); }
17327
17328fn emit_set_copy_loop(
17334 code: &mut Vec<u8>,
17335 ctx: &Ctx,
17336 num_regs: u32,
17337 result: u32,
17338 src: u32,
17339 filter: Option<u32>,
17340) {
17341 let outer = num_regs + 9;
17342 let elem = num_regs + 1;
17343 let (cidx, cfound) = (num_regs + 10, num_regs + 11);
17344 i32_const(code, 0);
17345 local_set(code, outer);
17346 code.push(0x02);
17347 code.push(0x40); code.push(0x03);
17349 code.push(0x40); local_get(code, outer);
17351 local_get(code, src);
17352 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
17355 leb_u32(code, 1); local_get(code, src);
17358 i32_load(code, 8);
17359 local_get(code, outer);
17360 i32_const(code, 8);
17361 code.push(0x6C);
17362 code.push(0x6A);
17363 i64_load(code, 0);
17364 local_set(code, elem);
17365 match filter {
17366 None => emit_set_add_elem(
17367 code,
17368 ctx,
17369 num_regs,
17370 result,
17371 elem,
17372 false,
17373 SetOrder::Insertion,
17374 ),
17375 Some(other) => {
17376 emit_set_contains_to(code, other, elem, cfound, cidx);
17377 local_get(code, cfound);
17378 code.push(0x04);
17379 code.push(0x40); emit_set_add_elem(
17381 code,
17382 ctx,
17383 num_regs,
17384 result,
17385 elem,
17386 false,
17387 SetOrder::Insertion,
17388 );
17389 code.push(0x0B); }
17391 }
17392 local_get(code, outer);
17394 i32_const(code, 1);
17395 code.push(0x6A);
17396 local_set(code, outer);
17397 code.push(0x0C);
17398 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); }
17402
17403fn lower_union(
17409 code: &mut Vec<u8>,
17410 kinds: &KindTable,
17411 ctx: &Ctx,
17412 num_regs: u32,
17413 dst: u16,
17414 lhs: u16,
17415 rhs: u16,
17416) -> R<()> {
17417 require_set(kinds, lhs)?;
17418 require_set(kinds, rhs)?;
17419 let result = num_regs + 8;
17420 emit_empty_header(code, ctx, num_regs, result, AllocClass::ScalarHeader);
17423 emit_set_copy_loop(code, ctx, num_regs, result, lhs as u32, None);
17424 emit_set_copy_loop(code, ctx, num_regs, result, rhs as u32, None);
17425 local_get(code, result);
17426 local_set(code, dst as u32);
17427 Ok(())
17428}
17429
17430fn lower_intersect(
17434 code: &mut Vec<u8>,
17435 kinds: &KindTable,
17436 ctx: &Ctx,
17437 num_regs: u32,
17438 dst: u16,
17439 lhs: u16,
17440 rhs: u16,
17441) -> R<()> {
17442 require_set(kinds, lhs)?;
17443 require_set(kinds, rhs)?;
17444 let result = num_regs + 8;
17445 emit_empty_header(code, ctx, num_regs, result, AllocClass::ScalarHeader);
17446 emit_set_copy_loop(code, ctx, num_regs, result, lhs as u32, Some(rhs as u32));
17447 local_get(code, result);
17448 local_set(code, dst as u32);
17449 Ok(())
17450}
17451
17452fn require_set(kinds: &KindTable, r: u16) -> R<()> {
17455 if kinds.get(r as usize) == Some(Kind::Set) {
17456 Ok(())
17457 } else {
17458 Err(WasmLowerError::Unsupported(
17459 "union/intersect of a non-Set value",
17460 ))
17461 }
17462}
17463
17464fn lower_contains(
17468 code: &mut Vec<u8>,
17469 kinds: &KindTable,
17470 ctx: &Ctx,
17471 num_regs: u32,
17472 dst: u16,
17473 collection: u16,
17474 value: u16,
17475) -> R<()> {
17476 let set_text = matches!(
17477 kinds.get(collection as usize),
17478 Some(Kind::SetText) | Some(Kind::CrdtSetText)
17479 );
17480 let elem = match kinds.get(collection as usize) {
17481 Some(Kind::Set) => Kind::Int, Some(Kind::SetText) | Some(Kind::CrdtSetText) => Kind::Text, _ => seq_elem_kind(kinds, collection)?,
17484 };
17485 if elem == Kind::Text && !set_text {
17488 return Err(WasmLowerError::Unsupported(
17489 "contains over a sequence of Text (needs byte-equality)",
17490 ));
17491 }
17492 let (elem_load, elem_eq): (fn(&mut Vec<u8>, u32), u8) = if elem == Kind::Float {
17493 (f64_load, 0x61)
17494 } else {
17495 (i64_load, 0x51)
17496 };
17497 let idx = num_regs + 5; let col = collection as u32;
17499 code.push(0x42);
17501 leb_i64(code, 0);
17502 local_set(code, dst as u32);
17503 i32_const(code, 0);
17505 local_set(code, idx);
17506 code.push(0x02);
17507 code.push(0x40); code.push(0x03);
17509 code.push(0x40); local_get(code, idx);
17512 local_get(code, col);
17513 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
17516 leb_u32(code, 1); if set_text {
17519 emit_set_elem_eq(code, ctx, num_regs, col, idx, value as u32, true);
17520 } else {
17521 local_get(code, col);
17522 i32_load(code, 8); local_get(code, idx);
17524 i32_const(code, 8);
17525 code.push(0x6C);
17526 code.push(0x6A);
17527 elem_load(code, 0);
17528 local_get(code, value as u32);
17529 code.push(elem_eq);
17530 }
17531 code.push(0x04);
17532 code.push(0x40); code.push(0x42);
17534 leb_i64(code, 1);
17535 local_set(code, dst as u32); code.push(0x0C);
17537 leb_u32(code, 2); code.push(0x0B); local_get(code, idx);
17541 i32_const(code, 1);
17542 code.push(0x6A);
17543 local_set(code, idx);
17544 code.push(0x0C);
17545 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); Ok(())
17549}
17550
17551fn lower_concat(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, dst: u16, lhs: u16, rhs: u16) -> R<()> {
17556 let (a, b) = (plan.num_regs + 8, plan.num_regs + 9);
17560 display::emit_display_of(code, plan, ctx, lhs, a)?;
17561 display::emit_display_of(code, plan, ctx, rhs, b)?;
17562 emit_text_concat(code, ctx, plan.num_regs, a, b, dst as u32);
17563 Ok(())
17564}
17565
17566fn parse_align_spec(spec: &str) -> Option<(i32, u32)> {
17570 if let Some(first) = spec.as_bytes().first() {
17571 let align = match first {
17572 b'>' => Some(0),
17573 b'<' => Some(1),
17574 b'^' => Some(2),
17575 _ => None,
17576 };
17577 if let Some(a) = align {
17578 return spec[1..].parse::<u32>().ok().map(|w| (a, w));
17579 }
17580 }
17581 spec.parse::<u32>().ok().map(|w| (0, w))
17583}
17584
17585fn lower_format_value(
17592 code: &mut Vec<u8>,
17593 plan: &Plan,
17594 ctx: &Ctx,
17595 dst: u16,
17596 src: u16,
17597 spec: u32,
17598 debug_prefix: u32,
17599) -> R<()> {
17600 let num_regs = plan.num_regs;
17601 let prefix_bytes = match debug_prefix {
17605 u32::MAX => None,
17606 idx => match ctx.constants.get(idx as usize) {
17607 Some(Constant::Text(s)) => Some(format!("{s}=")),
17608 _ => {
17609 return Err(WasmLowerError::Unsupported(
17610 "debug prefix is not a text constant",
17611 ))
17612 }
17613 },
17614 };
17615 lower_format_value_piece(code, plan, ctx, dst, src, spec)?;
17616 if let Some(prefix) = prefix_bytes {
17617 let (pfx, val) = (num_regs + 8, num_regs + 9);
17620 local_get(code, dst as u32);
17621 local_set(code, val);
17622 lower_text_literal(code, ctx, num_regs, prefix.as_bytes());
17623 local_set(code, pfx);
17624 emit_text_concat(code, ctx, num_regs, pfx, val, dst as u32);
17625 }
17626 Ok(())
17627}
17628
17629fn lower_format_value_piece(
17634 code: &mut Vec<u8>,
17635 plan: &Plan,
17636 ctx: &Ctx,
17637 dst: u16,
17638 src: u16,
17639 spec: u32,
17640) -> R<()> {
17641 let (kinds, num_regs) = (&plan.kinds, plan.num_regs);
17642 let spec_s = match spec {
17643 u32::MAX => {
17645 display::emit_display_of(code, plan, ctx, src, dst as u32)?;
17646 return Ok(());
17647 }
17648 idx => match ctx.constants.get(idx as usize) {
17649 Some(Constant::Text(s)) => s.as_str(),
17650 _ => {
17651 return Err(WasmLowerError::Unsupported(
17652 "format spec is not a text constant",
17653 ))
17654 }
17655 },
17656 };
17657 if !spec_s.starts_with('.') {
17660 let (align, width) = parse_align_spec(spec_s)
17661 .ok_or(WasmLowerError::Unsupported("unsupported format spec"))?;
17662 let fidx = (ctx.host_index)(HostFn::FmtAlignInto)
17663 .ok_or(WasmLowerError::Unsupported("align formatter not imported"))?;
17664 let (hdr, data, len, text) = (num_regs + 5, num_regs + 6, num_regs + 7, num_regs + 9);
17665 display::emit_display_of(code, plan, ctx, src, text)?;
17667 local_get(code, text);
17669 i32_load(code, 0);
17670 i32_const(code, width as i32);
17671 code.push(0x6A); emit_alloc(code, ctx, data, AllocClass::Raw);
17673 local_get(code, data);
17675 local_get(code, text);
17676 i32_const(code, width as i32);
17677 i32_const(code, align);
17678 code.push(0x10); leb_u32(code, fidx);
17680 local_set(code, len);
17681 i32_const(code, 16);
17684 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17685 local_get(code, hdr);
17686 local_get(code, len);
17687 i32_store(code, 0);
17688 local_get(code, hdr);
17689 local_get(code, text);
17690 i32_load(code, 0);
17691 i32_const(code, width as i32);
17692 code.push(0x6A); i32_store(code, 4);
17694 local_get(code, hdr);
17695 local_get(code, data);
17696 i32_store(code, 8);
17697 local_get(code, hdr);
17698 local_set(code, dst as u32);
17699 return Ok(());
17700 }
17701 let prec = spec_s
17702 .strip_prefix('.')
17703 .and_then(|r| r.parse::<u32>().ok())
17704 .ok_or(WasmLowerError::Unsupported(
17705 "unsupported format spec (only `.N` precision)",
17706 ))?;
17707 match kinds.get(src as usize) {
17708 Some(Kind::Float) | Some(Kind::Int) | Some(Kind::Bool) => {}
17709 _ => {
17710 return Err(WasmLowerError::Unsupported(
17711 "format `.N` on a non-numeric value",
17712 ))
17713 }
17714 }
17715 let (hdr, data, len) = (num_regs + 5, num_regs + 6, num_regs + 7);
17716 i32_const(code, 16);
17718 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17719 i32_const(code, (340 + prec) as i32);
17720 emit_alloc(code, ctx, data, AllocClass::Raw);
17721 let fidx = (ctx.host_index)(HostFn::FmtF64PrecInto).ok_or(WasmLowerError::Unsupported(
17723 "precision formatter not imported",
17724 ))?;
17725 local_get(code, data);
17726 push_as_f64(code, src, kinds.get(src as usize))?;
17727 i32_const(code, prec as i32);
17728 code.push(0x10); leb_u32(code, fidx);
17730 local_set(code, len);
17731 local_get(code, hdr);
17733 local_get(code, len);
17734 i32_store(code, 0);
17735 local_get(code, hdr);
17736 i32_const(code, (340 + prec) as i32);
17737 i32_store(code, 4);
17738 local_get(code, hdr);
17739 local_get(code, data);
17740 i32_store(code, 8);
17741 local_get(code, hdr);
17742 local_set(code, dst as u32);
17743 Ok(())
17744}
17745
17746fn emit_text_concat(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, a: u32, b: u32, out: u32) {
17750 if let Some(concat) = ctx.runtime.and_then(|r| r.index(RuntimeFn::TextConcat)) {
17751 local_get(code, a);
17752 local_get(code, b);
17753 code.push(0x10);
17754 leb_u32(code, concat);
17755 local_set(code, out);
17756 return;
17757 }
17758 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
17760 i32_const(code, 16);
17761 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17762 local_get(code, a);
17765 i32_load(code, 0);
17766 local_get(code, b);
17767 i32_load(code, 0);
17768 code.push(0x6A); emit_alloc(code, ctx, data, AllocClass::Raw);
17770 emit_byte_copy(code, idx, data, a, a, false); emit_byte_copy(code, idx, data, a, b, true); for off in [0u32, 4] {
17773 local_get(code, hdr);
17774 local_get(code, a);
17775 i32_load(code, 0);
17776 local_get(code, b);
17777 i32_load(code, 0);
17778 code.push(0x6A);
17779 i32_store(code, off);
17780 }
17781 local_get(code, hdr);
17782 local_get(code, data);
17783 i32_store(code, 8);
17784 local_get(code, hdr);
17785 local_set(code, out);
17786}
17787
17788const TEXT_GROWABLE: i32 = i32::MIN;
17794
17795fn emit_text_append(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, a: u32, b: u32, out: u32) {
17805 let (hdr, data, idx, cap, len) = (
17806 num_regs + 5,
17807 num_regs + 6,
17808 num_regs + 7,
17809 num_regs + 10,
17810 num_regs + 11,
17811 );
17812 local_get(code, a);
17813 i32_load(code, 0);
17814 local_get(code, b);
17815 i32_load(code, 0);
17816 code.push(0x6A); local_set(code, len);
17818 local_get(code, a);
17819 i32_load(code, 4);
17820 local_set(code, cap);
17821 code.push(0x02); code.push(0x40);
17823 code.push(0x02); code.push(0x40);
17825 local_get(code, cap);
17827 i32_const(code, TEXT_GROWABLE);
17828 code.push(0x71); code.push(0x45); code.push(0x0D); leb_u32(code, 0);
17832 local_get(code, cap);
17834 i32_const(code, i32::MAX);
17835 code.push(0x71); local_get(code, len);
17837 code.push(0x49); code.push(0x0D); leb_u32(code, 0);
17840 local_get(code, a);
17842 i32_load(code, 8);
17843 local_set(code, data);
17844 local_get(code, data);
17845 i32_const(code, 4);
17846 code.push(0x6B); i32_load(code, 0);
17848 local_get(code, a);
17849 i32_load(code, 0);
17850 code.push(0x47); code.push(0x0D); leb_u32(code, 0);
17853 emit_byte_copy(code, idx, data, a, b, true); local_get(code, data);
17856 i32_const(code, 8);
17857 code.push(0x6B);
17858 local_get(code, data);
17859 i32_const(code, 8);
17860 code.push(0x6B);
17861 i32_load(code, 0);
17862 i32_const(code, 1);
17863 code.push(0x6A);
17864 i32_store(code, 0);
17865 code.push(0x0C); leb_u32(code, 1);
17867 code.push(0x0B); local_get(code, len);
17871 i32_const(code, 1);
17872 code.push(0x74); local_tee(code, cap);
17874 i32_const(code, 16);
17875 local_get(code, cap);
17876 i32_const(code, 16);
17877 code.push(0x4B); code.push(0x1B); local_set(code, cap);
17880 local_get(code, cap);
17881 i32_const(code, 8);
17882 code.push(0x6A);
17883 emit_alloc(code, ctx, data, AllocClass::Raw);
17884 local_get(code, data);
17885 i32_const(code, 1);
17886 i32_store(code, 0); local_get(code, data);
17888 i32_const(code, 8);
17889 code.push(0x6A);
17890 local_set(code, data);
17891 emit_byte_copy(code, idx, data, a, a, false); emit_byte_copy(code, idx, data, a, b, true); local_get(code, cap);
17894 i32_const(code, TEXT_GROWABLE);
17895 code.push(0x72); local_set(code, cap);
17897 code.push(0x0B); local_get(code, data);
17900 i32_const(code, 4);
17901 code.push(0x6B);
17902 local_get(code, len);
17903 i32_store(code, 0);
17904 i32_const(code, 16);
17905 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17906 local_get(code, hdr);
17907 local_get(code, len);
17908 i32_store(code, 0);
17909 local_get(code, hdr);
17910 local_get(code, cap);
17911 i32_store(code, 4);
17912 local_get(code, hdr);
17913 local_get(code, data);
17914 i32_store(code, 8);
17915 local_get(code, hdr);
17916 local_set(code, out);
17917}
17918
17919fn emit_slot_store(code: &mut Vec<u8>, k: Option<Kind>, off: u32) -> R<()> {
17922 match k {
17923 Some(Kind::Float) => f64_store(code, off),
17924 Some(Kind::Nothing) | Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Char)
17925 | Some(Kind::Moment) | Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Span)
17926 | Some(Kind::Word64) => i64_store(code, off),
17927 Some(Kind::Date)
17928 | Some(Kind::SeqInt)
17929 | Some(Kind::SeqBool)
17930 | Some(Kind::SeqFloat)
17931 | Some(Kind::SeqText)
17932 | Some(Kind::SeqStruct)
17933 | Some(Kind::SeqEnum)
17934 | Some(Kind::SeqSeqInt)
17935 | Some(Kind::SeqHandle)
17936 | Some(Kind::SeqAny)
17937 | Some(Kind::Text)
17938 | Some(Kind::Struct)
17939 | Some(Kind::Map)
17940 | Some(Kind::Set)
17941 | Some(Kind::SetText)
17942 | Some(Kind::CrdtSetText)
17943 | Some(Kind::CrdtCounter)
17944 | Some(Kind::Enum)
17945 | Some(Kind::Closure)
17946 | Some(Kind::Tuple)
17947 | Some(Kind::Rational)
17948 | Some(Kind::Optional)
17949 | Some(Kind::Word32)
17950 | Some(Kind::SeqWord32)
17951 | Some(Kind::SeqWord64)
17952 | Some(Kind::BigInt)
17953 | Some(Kind::Complex)
17954 | Some(Kind::Modular)
17955 | Some(Kind::Decimal)
17956 | Some(Kind::Money)
17957 | Some(Kind::Quantity)
17958 | Some(Kind::Uuid)
17959 | Some(Kind::Lanes)
17960 | Some(Kind::LanesV)
17961 | Some(Kind::Dynamic)
17962 | Some(Kind::Tower) => i32_store(code, off),
17963 None => return Err(WasmLowerError::Unsupported("struct field of unknown kind")),
17964 }
17965 Ok(())
17966}
17967
17968fn emit_slot_load(code: &mut Vec<u8>, k: Option<Kind>, off: u32) -> R<()> {
17970 match k {
17971 Some(Kind::Float) => f64_load(code, off),
17972 Some(Kind::Nothing) | Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Char)
17973 | Some(Kind::Moment) | Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Span)
17974 | Some(Kind::Word64) => i64_load(code, off),
17975 Some(Kind::Date)
17976 | Some(Kind::SeqInt)
17977 | Some(Kind::SeqBool)
17978 | Some(Kind::SeqFloat)
17979 | Some(Kind::SeqText)
17980 | Some(Kind::SeqStruct)
17981 | Some(Kind::SeqEnum)
17982 | Some(Kind::SeqSeqInt)
17983 | Some(Kind::SeqHandle)
17984 | Some(Kind::SeqAny)
17985 | Some(Kind::Text)
17986 | Some(Kind::Struct)
17987 | Some(Kind::Map)
17988 | Some(Kind::Set)
17989 | Some(Kind::SetText)
17990 | Some(Kind::CrdtSetText)
17991 | Some(Kind::CrdtCounter)
17992 | Some(Kind::Enum)
17993 | Some(Kind::Closure)
17994 | Some(Kind::Tuple)
17995 | Some(Kind::Rational)
17996 | Some(Kind::Optional)
17997 | Some(Kind::Word32)
17998 | Some(Kind::SeqWord32)
17999 | Some(Kind::SeqWord64)
18000 | Some(Kind::BigInt)
18001 | Some(Kind::Complex)
18002 | Some(Kind::Modular)
18003 | Some(Kind::Decimal)
18004 | Some(Kind::Money)
18005 | Some(Kind::Quantity)
18006 | Some(Kind::Uuid)
18007 | Some(Kind::Lanes)
18008 | Some(Kind::LanesV)
18009 | Some(Kind::Dynamic)
18010 | Some(Kind::Tower) => i32_load(code, off),
18011 None => return Err(WasmLowerError::Unsupported("struct field of unknown kind")),
18012 }
18013 Ok(())
18014}
18015
18016fn lower_new_struct(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, count: u16, dst: u16) {
18020 let (hdr, data) = (num_regs + 5, num_regs + 6);
18021 i32_const(code, 16);
18022 emit_alloc(code, ctx, hdr, AllocClass::RecordHeader);
18023 i32_const(
18024 code,
18025 i32::from(count) * if ctx.heap_counting() { 9 } else { 8 },
18026 );
18027 emit_alloc(code, ctx, data, AllocClass::Raw);
18028 local_get(code, hdr);
18029 i32_const(code, i32::from(count));
18030 i32_store(code, 0); local_get(code, hdr);
18032 i32_const(code, i32::from(count));
18033 i32_store(code, 4); local_get(code, hdr);
18035 local_get(code, data);
18036 i32_store(code, 8); if ctx.heap_counting() {
18041 for k in 0..u32::from(count) {
18042 local_get(code, data);
18043 code.push(0x42); code.push(0x00);
18045 i64_store(code, k * 8);
18046 local_get(code, data);
18047 i32_const(code, 0);
18048 i32_store8(code, u32::from(count) * 8 + k);
18049 }
18050 }
18051 local_get(code, hdr);
18052 local_set(code, dst as u32);
18053}
18054
18055fn cow_struct_inserts(
18073 ops: &[Op],
18074 kinds: &KindTable,
18075 num_regs: u32,
18076 functions: &[CompiledFunction],
18077) -> Vec<bool> {
18078 let is_struct_write = |op: &Op| match op {
18084 Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. } => {
18085 kinds.get(*collection as usize) == Some(Kind::Struct)
18086 }
18087 _ => false,
18088 };
18089 let mut cow = vec![false; ops.len()];
18090 let Some(blocks) = Blocks::new(ops) else {
18091 for (pc, op) in ops.iter().enumerate() {
18093 if matches!(op, Op::StructInsert { .. }) || is_struct_write(op) {
18094 cow[pc] = true;
18095 }
18096 }
18097 return cow;
18098 };
18099 let mut owned = vec![false; num_regs as usize];
18100 let is_owned = |owned: &[bool], r: u16| (r as usize) < owned.len() && owned[r as usize];
18101 let set_owned = |owned: &mut [bool], r: u16, v: bool| {
18102 if (r as usize) < owned.len() {
18103 owned[r as usize] = v;
18104 }
18105 };
18106 for (pc, op) in ops.iter().enumerate() {
18107 if blocks.is_leader(pc) {
18108 owned.iter_mut().for_each(|o| *o = false);
18109 }
18110 match op {
18111 Op::NewStruct { dst, .. }
18112 | Op::DeepClone { dst, .. }
18113 | Op::CallBuiltin {
18114 dst,
18115 builtin: BuiltinId::Copy,
18116 ..
18117 } => set_owned(&mut owned, *dst, true),
18118 Op::StructInsert { obj, value, .. } => {
18119 if !is_owned(&owned, *obj) {
18120 cow[pc] = true; }
18122 set_owned(&mut owned, *value, false); set_owned(&mut owned, *obj, true); }
18125 Op::SetIndex {
18126 collection,
18127 index,
18128 value,
18129 }
18130 | Op::SetIndexUnchecked {
18131 collection,
18132 index,
18133 value,
18134 } if is_struct_write(op) => {
18135 if !is_owned(&owned, *collection) {
18136 cow[pc] = true;
18137 }
18138 set_owned(&mut owned, *index, false);
18139 set_owned(&mut owned, *value, false);
18140 set_owned(&mut owned, *collection, true);
18141 }
18142 Op::ListPushField { obj, src, .. } => {
18145 if !is_owned(&owned, *obj) {
18146 cow[pc] = true;
18147 }
18148 set_owned(&mut owned, *src, false);
18149 set_owned(&mut owned, *obj, true);
18150 }
18151 Op::GetField { dst, .. } => set_owned(&mut owned, *dst, false), _ => {
18153 let (defs, uses) = crate::vm::instruction::op_def_uses(op, functions);
18154 for r in defs.into_iter().chain(uses) {
18155 set_owned(&mut owned, r, false);
18156 }
18157 }
18158 }
18159 }
18160 cow
18161}
18162
18163#[allow(clippy::too_many_arguments)]
18167fn declared_record_slot_kind(
18169 structs: &kind::StructLayout,
18170 types: &[StructTypeDef],
18171 constants: &[Constant],
18172 obj: u16,
18173 slot: usize,
18174) -> Option<Kind> {
18175 if let Some(ParamShape::Struct(layout)) = structs.reg_shape.get(&obj) {
18176 return layout.get(slot).map(|(_, k, _)| *k);
18177 }
18178 if let Some(layout) = structs
18179 .struct_name_of
18180 .get(&obj)
18181 .and_then(|name| kind::resolve_named_layout(name, types, constants))
18182 {
18183 if let Some((field, _)) = structs.reg_layout.get(&obj).and_then(|v| v.get(slot)) {
18184 return layout
18185 .iter()
18186 .find(|(f, _, _)| f == field)
18187 .map(|(_, k, _)| *k);
18188 }
18189 return layout.get(slot).map(|(_, k, _)| *k);
18190 }
18191 structs
18192 .call_result
18193 .get(&obj)
18194 .and_then(|v| v.get(slot))
18195 .map(|(_, k, _)| *k)
18196}
18197
18198fn promote_rational_field(
18201 code: &mut Vec<u8>,
18202 kinds: &KindTable,
18203 structs: &kind::StructLayout,
18204 ctx: &Ctx,
18205 num_regs: u32,
18206 obj: u16,
18207 slot: usize,
18208 value: u16,
18209) -> R<Option<u32>> {
18210 if declared_record_slot_kind(structs, ctx.struct_types, ctx.constants, obj, slot) != Some(Kind::Rational) {
18211 return Ok(None);
18212 }
18213 if kinds.get(value as usize) == Some(Kind::Nothing) {
18216 return Err(WasmLowerError::Unsupported(
18217 "a record's rational field holding nothing: a compiled rational holds no nothing",
18218 ));
18219 }
18220 let widened = if ctx.linked { matches!(kinds.get(value as usize), Some(Kind::Int | Kind::BigInt)) } else { kinds.get(value as usize) == Some(Kind::Int) };
18221 if !widened {
18222 return Ok(None);
18223 }
18224 let handle = num_regs + 8;
18225 if ctx.linked {
18226 push_rational_operand(code, kinds, ctx, value)?;
18227 local_set(code, handle);
18228 } else {
18229 let data = num_regs + 9;
18230 i32_const(code, 16);
18231 emit_alloc(code, ctx, handle, AllocClass::ScalarHeader);
18232 i32_const(code, 16);
18233 emit_alloc(code, ctx, data, AllocClass::Raw);
18234 for off in [0u32, 4] {
18235 local_get(code, handle);
18236 i32_const(code, 2);
18237 i32_store(code, off);
18238 }
18239 local_get(code, handle);
18240 local_get(code, data);
18241 i32_store(code, 8);
18242 local_get(code, data);
18243 local_get(code, value as u32);
18244 i64_store(code, 0);
18245 local_get(code, data);
18246 i64c(code, 1);
18247 i64_store(code, 8);
18248 }
18249 emit_true_retain_of(code, ctx, |c| local_get(c, handle));
18251 Ok(Some(handle))
18252}
18253
18254fn lower_struct_insert(
18257 code: &mut Vec<u8>,
18258 kinds: &KindTable,
18259 structs: &kind::StructLayout,
18260 ctx: &Ctx,
18261 num_regs: u32,
18262 slot: u16,
18263 obj: u16,
18264 value: u16,
18265 cow: bool,
18266 held: Option<u32>,
18267) -> R<()> {
18268 if kinds.get(obj as usize) != Some(Kind::Struct) {
18272 return Err(WasmLowerError::Unsupported(
18273 "struct field set on a value with no known struct layout",
18274 ));
18275 }
18276 if cow {
18277 emit_record_copy(
18278 code,
18279 ctx,
18280 kinds,
18281 structs,
18282 num_regs,
18283 obj,
18284 Some(usize::from(slot)),
18285 )?;
18286 }
18287 let promoted = match held {
18288 Some(h) => Some(h),
18289 None => promote_rational_field(
18290 code,
18291 kinds,
18292 structs,
18293 ctx,
18294 num_regs,
18295 obj,
18296 usize::from(slot),
18297 value,
18298 )?,
18299 };
18300 let stored_kind = if held.is_some() {
18301 Some(Kind::Tower)
18302 } else if promoted.is_some() {
18303 Some(Kind::Rational)
18304 } else {
18305 kinds.get(value as usize)
18306 };
18307 let off = u32::from(slot) * 8;
18308 if ctx.heap_counting() && counted_kind(stored_kind) {
18311 emit_true_release(code, ctx, |c| {
18312 local_get(c, obj as u32);
18313 i32_load(c, 8); i32_load(c, off);
18315 });
18316 }
18317 local_get(code, obj as u32);
18318 i32_load(code, 8); local_get(code, promoted.unwrap_or(value as u32));
18320 emit_slot_store(code, stored_kind, off)?;
18321 emit_record_field_kind(code, ctx, obj, u32::from(slot), stored_kind);
18322 Ok(())
18323}
18324
18325fn emit_record_field_kind(code: &mut Vec<u8>, ctx: &Ctx, obj: u16, slot: u32, kind: Option<Kind>) {
18327 emit_record_field_is_handle(code, ctx, obj, slot, kind.is_some_and(kind_is_handle));
18328}
18329
18330fn emit_record_field_is_handle(
18331 code: &mut Vec<u8>,
18332 ctx: &Ctx,
18333 obj: u16,
18334 slot: u32,
18335 is_handle: bool,
18336) {
18337 if !ctx.heap_counting() {
18338 return;
18339 }
18340 local_get(code, obj as u32);
18341 i32_load(code, 8);
18342 local_get(code, obj as u32);
18343 i32_load(code, 0);
18344 i32_const(code, 8);
18345 code.push(0x6C);
18346 code.push(0x6A);
18347 i32_const(code, i32::from(is_handle));
18348 i32_store8(code, slot);
18349}
18350
18351fn lower_get_field(code: &mut Vec<u8>, kinds: &KindTable, slot: u16, dst: u16, obj: u16) -> R<()> {
18354 if kinds.get(obj as usize) != Some(Kind::Struct) {
18355 return Err(WasmLowerError::Unsupported(
18356 "field access on a value with no known struct layout",
18357 ));
18358 }
18359 let off = u32::from(slot) * 8;
18360 local_get(code, obj as u32);
18361 i32_load(code, 8); emit_slot_load(code, kinds.get(dst as usize), off)?;
18363 local_set(code, dst as u32);
18364 Ok(())
18365}
18366
18367fn lower_record_field_set(
18376 code: &mut Vec<u8>,
18377 plan: &Plan,
18378 kinds: &KindTable,
18379 ctx: &Ctx,
18380 pc: usize,
18381 cow: bool,
18382 collection: u16,
18383 value: u16,
18384) -> R<()> {
18385 let field =
18386 plan.place
18387 .field_at
18388 .get(pc)
18389 .copied()
18390 .flatten()
18391 .ok_or(WasmLowerError::Unsupported(
18392 "record field written by a name computed at run time",
18393 ))?;
18394 let slot = record_field_slot(plan, collection, field).ok_or(WasmLowerError::Unsupported(
18395 "record field write on a value with no known record layout",
18396 ))?;
18397 if cow {
18398 let clear = plan.place.clear.get(pc).copied().unwrap_or(false);
18402 let overwritten = (!clear).then_some(slot);
18403 emit_record_copy(
18404 code,
18405 ctx,
18406 kinds,
18407 &plan.structs,
18408 plan.num_regs,
18409 collection,
18410 overwritten,
18411 )?;
18412 }
18413 let clear = plan.place.clear.get(pc).copied().unwrap_or(false);
18414 let declared = declared_record_slot_kind(
18417 &plan.structs,
18418 ctx.struct_types,
18419 ctx.constants,
18420 collection,
18421 slot,
18422 );
18423 let field_kind = if declared == Some(Kind::Rational) {
18424 declared
18425 } else if clear {
18426 record_slot_kinds(kinds, &plan.structs, collection)
18427 .and_then(|ks| ks.get(slot).copied().flatten())
18428 } else {
18429 kinds.get(value as usize)
18430 };
18431 if ctx.heap_counting() && counted_kind(field_kind) {
18432 emit_true_release(code, ctx, |c| {
18433 local_get(c, collection as u32);
18434 i32_load(c, 8); i32_load(c, (slot as u32) * 8);
18436 });
18437 }
18438 if clear {
18439 local_get(code, collection as u32);
18443 i32_load(code, 8); code.push(0x42); code.push(0x00);
18446 i64_store(code, (slot as u32) * 8);
18447 emit_record_field_kind(code, ctx, collection, slot as u32, None);
18448 return Ok(());
18449 }
18450 if declared == Some(Kind::Tower) && kinds.get(value as usize) != Some(Kind::Tower) {
18453 return Err(WasmLowerError::Unsupported(
18454 "a field of an exact type set by name to a value of another kind",
18455 ));
18456 }
18457 let promoted = promote_rational_field(
18458 code,
18459 kinds,
18460 &plan.structs,
18461 ctx,
18462 plan.num_regs,
18463 collection,
18464 slot,
18465 value,
18466 )?;
18467 let stored_kind = if promoted.is_some() {
18468 Some(Kind::Rational)
18469 } else {
18470 kinds.get(value as usize)
18471 };
18472 local_get(code, collection as u32);
18473 i32_load(code, 8); local_get(code, promoted.unwrap_or(value as u32));
18475 emit_slot_store(code, stored_kind, (slot as u32) * 8)?;
18476 emit_record_field_kind(code, ctx, collection, slot as u32, stored_kind);
18477 Ok(())
18478}
18479
18480fn is_clone_trivial(kind: Option<Kind>) -> bool {
18483 matches!(
18484 kind,
18485 Some(
18486 Kind::Int
18487 | Kind::Bool
18488 | Kind::Char
18489 | Kind::Word32
18490 | Kind::Word64
18491 | Kind::Float
18492 | Kind::Date
18493 | Kind::Moment
18494 | Kind::Duration
18495 | Kind::Time
18496 | Kind::Span
18497 )
18498 )
18499}
18500
18501fn field_clone_ok(kind: Option<Kind>) -> bool {
18507 is_clone_trivial(kind)
18508 || matches!(
18509 kind,
18510 Some(
18511 Kind::Rational
18512 | Kind::Text
18513 | Kind::SeqInt
18514 | Kind::SeqBool
18515 | Kind::SeqFloat
18516 | Kind::SeqWord32
18517 | Kind::SeqWord64
18518 | Kind::SeqAny
18519 | Kind::Set
18520 | Kind::Map
18521 | Kind::Struct
18522 )
18523 )
18524}
18525
18526fn emit_buffer_clone(
18534 code: &mut Vec<u8>,
18535 ctx: &Ctx,
18536 hdr: u32,
18537 data: u32,
18538 idx: u32,
18539 src_local: u32,
18540 is_text: bool,
18541 class: AllocClass,
18542) {
18543 if !is_text {
18544 if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqClone)) {
18545 local_get(code, src_local);
18546 i32_const(code, class.code() as i32);
18547 code.push(0x10);
18548 leb_u32(code, clone);
18549 local_set(code, hdr);
18550 return;
18551 }
18552 }
18553 i32_const(code, 16);
18554 emit_alloc(code, ctx, hdr, class);
18555 local_get(code, src_local);
18556 i32_load(code, 0); if !is_text {
18558 i32_const(code, 8);
18559 code.push(0x6C); }
18561 emit_alloc(code, ctx, data, AllocClass::Raw);
18562 if is_text {
18563 emit_byte_copy(code, idx, data, src_local, src_local, false);
18564 } else {
18565 emit_seq_copy(code, idx, data, src_local, src_local, false);
18566 }
18567 for off in [0u32, 4] {
18568 local_get(code, hdr);
18569 local_get(code, src_local);
18570 i32_load(code, 0); i32_store(code, off);
18572 }
18573 local_get(code, hdr);
18574 local_get(code, data);
18575 i32_store(code, 8); }
18577
18578fn emit_map_clone(code: &mut Vec<u8>, ctx: &Ctx, hdr: u32, data: u32, idx: u32, src_local: u32) {
18585 if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapClone)) {
18586 local_get(code, src_local);
18587 code.push(0x10);
18588 leb_u32(code, clone);
18589 local_set(code, hdr);
18590 return;
18591 }
18592 i32_const(code, 16);
18594 emit_alloc(code, ctx, hdr, AllocClass::Raw);
18597 local_get(code, src_local);
18599 i32_load(code, 0); i32_const(code, 16);
18601 code.push(0x6C);
18602 emit_alloc(code, ctx, data, AllocClass::Raw);
18603 i32_const(code, 0);
18605 local_set(code, idx);
18606 code.push(0x02);
18607 code.push(0x40); code.push(0x03);
18609 code.push(0x40); local_get(code, idx);
18611 local_get(code, src_local);
18612 i32_load(code, 0);
18613 i32_const(code, 2);
18614 code.push(0x6C); code.push(0x4E); code.push(0x0D);
18617 leb_u32(code, 1); local_get(code, data);
18619 local_get(code, idx);
18620 i32_const(code, 8);
18621 code.push(0x6C);
18622 code.push(0x6A); local_get(code, src_local);
18624 i32_load(code, 8);
18625 local_get(code, idx);
18626 i32_const(code, 8);
18627 code.push(0x6C);
18628 code.push(0x6A); i64_load(code, 0);
18630 i64_store(code, 0);
18631 local_get(code, idx);
18632 i32_const(code, 1);
18633 code.push(0x6A);
18634 local_set(code, idx);
18635 code.push(0x0C);
18636 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); for off in [0u32, 4] {
18640 local_get(code, hdr);
18641 local_get(code, src_local);
18642 i32_load(code, 0);
18643 i32_store(code, off);
18644 }
18645 local_get(code, hdr);
18646 local_get(code, data);
18647 i32_store(code, 8);
18648 local_get(code, hdr);
18652 if ctx.shared_maps {
18653 i32_const(code, SHARED_MAP_MARK);
18654 i32_const(code, 0);
18655 local_get(code, src_local);
18656 i32_load(code, 12);
18657 i32_const(code, 0);
18658 code.push(0x48); code.push(0x1B); } else {
18661 i32_const(code, 0);
18662 }
18663 local_get(code, src_local);
18664 i32_load(code, 12);
18665 i32_const(code, 0xFF);
18666 code.push(0x71); code.push(0x72); i32_store(code, 12);
18669 emit_retain_children(code, ctx, hdr);
18671}
18672
18673#[allow(clippy::too_many_arguments)]
18680fn emit_clone_each_element(
18681 code: &mut Vec<u8>,
18682 ctx: &Ctx,
18683 outer_hdr: u32,
18684 data: u32,
18685 counter: u32,
18686 isrc: u32,
18687 ihdr: u32,
18688 idata: u32,
18689 iidx: u32,
18690 is_text: bool,
18691 inner_class: AllocClass,
18692) {
18693 i32_const(code, 0);
18694 local_set(code, counter);
18695 code.push(0x02);
18696 code.push(0x40); code.push(0x03);
18698 code.push(0x40); local_get(code, counter);
18700 local_get(code, outer_hdr);
18701 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
18704 leb_u32(code, 1); local_get(code, data);
18707 local_get(code, counter);
18708 i32_const(code, 8);
18709 code.push(0x6C); code.push(0x6A); i32_load(code, 0);
18712 local_set(code, isrc);
18713 emit_buffer_clone(code, ctx, ihdr, idata, iidx, isrc, is_text, inner_class);
18714 local_get(code, data);
18716 local_get(code, counter);
18717 i32_const(code, 8);
18718 code.push(0x6C); code.push(0x6A); local_get(code, ihdr);
18721 i32_store(code, 0);
18722 if ctx.heap_counting() {
18724 emit_true_retain_of(code, ctx, |c| local_get(c, ihdr));
18725 }
18726 local_get(code, counter);
18728 i32_const(code, 1);
18729 code.push(0x6A); local_set(code, counter);
18731 code.push(0x0C);
18732 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); }
18736
18737fn record_slot_kinds(
18741 kinds: &KindTable,
18742 structs: &kind::StructLayout,
18743 src: u16,
18744) -> Option<Vec<Option<Kind>>> {
18745 if let Some(ParamShape::Struct(layout)) = structs.reg_shape.get(&src) {
18746 return Some(layout.iter().map(|(_, k, _)| Some(*k)).collect());
18747 }
18748 let layout = structs.reg_layout.get(&src)?;
18749 Some(
18750 layout
18751 .iter()
18752 .map(|&(_, vr)| vr.and_then(|vr| kinds.get(vr as usize)))
18753 .collect(),
18754 )
18755}
18756
18757fn lower_deep_clone(
18764 code: &mut Vec<u8>,
18765 kinds: &KindTable,
18766 structs: &kind::StructLayout,
18767 ctx: &Ctx,
18768 num_regs: u32,
18769 dst: u16,
18770 src: u16,
18771) -> R<()> {
18772 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
18773 let s = src as u32;
18774 match kinds.get(src as usize) {
18775 Some(Kind::Rational) | Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Word32)
18777 | Some(Kind::Word64) | Some(Kind::Float) | Some(Kind::Date) | Some(Kind::Moment)
18778 | Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Span) => {
18779 local_get(code, s);
18780 local_set(code, dst as u32);
18781 return Ok(());
18782 }
18783 Some(Kind::Struct)
18790 if record_slot_kinds(kinds, structs, src)
18791 .is_some_and(|ks| ks.iter().all(|&k| field_clone_ok(k))) =>
18792 {
18793 emit_buffer_clone(
18795 code,
18796 ctx,
18797 hdr,
18798 data,
18799 idx,
18800 s,
18801 false,
18802 AllocClass::RecordHeader,
18803 );
18804 local_get(code, hdr);
18805 i32_load(code, 8);
18806 local_set(code, data);
18807 let (fsrc, fhdr, fdata, fidx) =
18811 (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
18812 let slot_kinds =
18813 record_slot_kinds(kinds, structs, src).expect("guarded by is_some_and above");
18814 for (slot, &fk) in slot_kinds.iter().enumerate() {
18815 if is_clone_trivial(fk) {
18816 if fk == Some(Kind::Int) && ctx.exact.record_ints() {
18817 exact::retain_record_integer(code, ctx, hdr, slot as u16);
18818 }
18819 continue; }
18821 let off = slot as u32 * 8;
18822 if matches!(fk, Some(Kind::Rational | Kind::Struct)) {
18823 if fk == Some(Kind::Struct) {
18825 emit_share_inline(code, |code| {
18826 local_get(code, data);
18827 i32_load(code, off);
18828 });
18829 }
18830 emit_true_retain_of(code, ctx, |code| {
18831 local_get(code, data);
18832 i32_load(code, off);
18833 });
18834 continue;
18835 }
18836 local_get(code, data);
18837 i32_load(code, off); local_set(code, fsrc);
18839 if fk == Some(Kind::Map) {
18840 emit_map_clone(code, ctx, fhdr, fdata, fidx, fsrc);
18841 } else {
18842 let is_text = fk == Some(Kind::Text);
18843 let class = if is_text {
18847 AllocClass::TextHeader
18848 } else {
18849 AllocClass::of_elements(fk == Some(Kind::SeqAny))
18850 };
18851 emit_buffer_clone(code, ctx, fhdr, fdata, fidx, fsrc, is_text, class);
18852 if class == AllocClass::HandleHeader {
18853 emit_retain_children(code, ctx, fhdr);
18854 }
18855 }
18856 local_get(code, data);
18857 local_get(code, fhdr); i32_store(code, off);
18859 if ctx.heap_counting() {
18861 emit_true_retain_of(code, ctx, |c| local_get(c, fhdr));
18862 }
18863 }
18864 local_get(code, hdr);
18865 local_set(code, dst as u32);
18866 return Ok(());
18867 }
18868 Some(k) if is_collection_clonable(k) => {
18869 emit_collection_clone(code, ctx, num_regs, k, s);
18870 local_get(code, hdr);
18871 local_set(code, dst as u32);
18872 Ok(())
18873 }
18874 _ => Err(WasmLowerError::Unsupported(
18875 "deep clone of an unsupported value kind",
18876 )),
18877 }
18878}
18879
18880fn is_collection_clonable(k: Kind) -> bool {
18882 matches!(
18883 k,
18884 Kind::Text
18885 | Kind::SeqInt
18886 | Kind::SeqBool
18887 | Kind::SeqFloat
18888 | Kind::SeqWord32
18889 | Kind::SeqWord64
18890 | Kind::SeqAny
18891 | Kind::Set
18892 | Kind::SetText
18893 | Kind::Map
18894 | Kind::SeqSeqInt
18895 | Kind::SeqText
18896 | Kind::SeqStruct
18897 | Kind::SeqEnum
18898 | Kind::SeqHandle
18899 )
18900}
18901
18902fn emit_collection_clone(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, k: Kind, src: u32) {
18906 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
18907 if let Some(mode) = seq_clone_mode(k) {
18908 if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqClone)) {
18909 local_get(code, src);
18910 i32_const(code, mode);
18911 code.push(0x10);
18912 leb_u32(code, clone);
18913 local_set(code, hdr);
18914 return;
18915 }
18916 }
18917 match k {
18918 Kind::Text
18923 | Kind::SeqInt
18924 | Kind::SeqBool
18925 | Kind::SeqFloat
18926 | Kind::SeqWord32
18927 | Kind::SeqWord64
18928 | Kind::SeqAny
18929 | Kind::Set
18930 | Kind::SetText => {
18931 let is_text = k == Kind::Text;
18932 let class = if is_text {
18933 AllocClass::TextHeader
18934 } else {
18935 AllocClass::of_elements(matches!(k, Kind::SeqAny | Kind::SetText))
18936 };
18937 emit_buffer_clone(code, ctx, hdr, data, idx, src, is_text, class);
18938 if class == AllocClass::HandleHeader {
18939 emit_retain_children(code, ctx, hdr);
18940 }
18941 }
18942 Kind::Map => emit_map_clone(code, ctx, hdr, data, idx, src),
18944 Kind::SeqSeqInt => {
18948 emit_buffer_clone(
18950 code,
18951 ctx,
18952 hdr,
18953 data,
18954 idx,
18955 src,
18956 false,
18957 AllocClass::HandleHeader,
18958 );
18959 local_get(code, hdr);
18960 i32_load(code, 8);
18961 local_set(code, data); let (isrc, ihdr, idata, iidx) =
18963 (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
18964 emit_clone_each_element(
18965 code,
18966 ctx,
18967 hdr,
18968 data,
18969 idx,
18970 isrc,
18971 ihdr,
18972 idata,
18973 iidx,
18974 false,
18975 AllocClass::ScalarHeader,
18976 );
18977 }
18978 Kind::SeqText | Kind::SeqStruct | Kind::SeqEnum | Kind::SeqHandle => {
18983 emit_buffer_clone(
18984 code,
18985 ctx,
18986 hdr,
18987 data,
18988 idx,
18989 src,
18990 false,
18991 AllocClass::HandleHeader,
18992 );
18993 emit_retain_children(code, ctx, hdr);
18994 if matches!(k, Kind::SeqStruct | Kind::SeqHandle) {
18995 emit_cow_retain_each_element(code, hdr, idx);
18996 }
18997 }
18998 _ => unreachable!("emit_collection_clone of {k:?}: callers check is_collection_clonable"),
18999 }
19000}
19001
19002fn lower_text_eq(
19005 code: &mut Vec<u8>,
19006 ctx: &Ctx,
19007 num_regs: u32,
19008 dst: u16,
19009 lhs: u16,
19010 rhs: u16,
19011 negate: bool,
19012) {
19013 emit_text_eq(code, ctx, num_regs, lhs as u32, rhs as u32);
19014 if negate {
19015 code.push(0x45); }
19017 code.push(0xAD); local_set(code, dst as u32);
19019}
19020
19021fn emit_stringify(
19027 code: &mut Vec<u8>,
19028 ctx: &Ctx,
19029 num_regs: u32,
19030 src: u32,
19031 kind: Option<Kind>,
19032 out: u32,
19033) -> R<()> {
19034 if kind == Some(Kind::SeqInt) && ctx.exact.sequence_ints() {
19035 return exact::sequence_text(code, ctx, num_regs, src, out);
19036 }
19037 match kind {
19038 Some(Kind::Text) => {
19039 local_get(code, src);
19040 local_set(code, out);
19041 }
19042 Some(Kind::Tower) => tower::text_of(code, ctx, src, out)?,
19044 Some(Kind::BigInt) => {
19047 let to_text = (ctx.host_index)(HostFn::BigintToText)
19048 .ok_or(WasmLowerError::Unsupported("bigint_to_text not imported"))?;
19049 local_get(code, src);
19050 code.push(0x10); leb_u32(code, to_text);
19052 local_set(code, out);
19053 }
19054 Some(k @ (Kind::Int | Kind::Float | Kind::Bool)) => {
19055 let (host, bufsize) = match k {
19057 Kind::Int => (HostFn::FmtI64Into, 24), Kind::Float => (HostFn::FmtF64Into, 340), _ => (HostFn::FmtBoolInto, 8), };
19061 let (h, data, tmp) = (num_regs + 5, num_regs + 6, num_regs + 7);
19062 i32_const(code, 16);
19063 emit_alloc(code, ctx, h, AllocClass::TextHeader);
19064 i32_const(code, bufsize);
19065 emit_alloc(code, ctx, data, AllocClass::Raw);
19066 let fidx = (ctx.host_index)(host)
19068 .ok_or(WasmLowerError::Unsupported("text formatter not imported"))?;
19069 local_get(code, data);
19070 local_get(code, src);
19071 code.push(0x10); leb_u32(code, fidx);
19073 local_set(code, tmp); local_get(code, h);
19076 local_get(code, tmp);
19077 i32_store(code, 0);
19078 local_get(code, h);
19079 i32_const(code, bufsize);
19080 i32_store(code, 4);
19081 local_get(code, h);
19082 local_get(code, data);
19083 i32_store(code, 8);
19084 local_get(code, h);
19085 local_set(code, out);
19086 }
19087 Some(k @ (Kind::SeqInt | Kind::SeqBool | Kind::SeqAny | Kind::Set)) => {
19092 let host = match k {
19093 Kind::Set => HostFn::FmtSetI64Into,
19094 Kind::SeqBool => HostFn::FmtSeqBoolInto, _ => HostFn::FmtSeqI64Into,
19096 };
19097 let (h, data, tmp) = (num_regs + 5, num_regs + 6, num_regs + 7);
19098 i32_const(code, 16);
19099 emit_alloc(code, ctx, h, AllocClass::TextHeader);
19100 local_get(code, src);
19102 i32_load(code, 0); i32_const(code, 24);
19104 code.push(0x6C); i32_const(code, 8);
19106 code.push(0x6A); emit_alloc(code, ctx, data, AllocClass::Raw);
19108 let fidx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported(
19110 "collection formatter not imported",
19111 ))?;
19112 local_get(code, data);
19113 local_get(code, src);
19114 code.push(0x10); leb_u32(code, fidx);
19116 local_set(code, tmp);
19117 local_get(code, h);
19118 local_get(code, tmp);
19119 i32_store(code, 0);
19120 local_get(code, h);
19121 local_get(code, src);
19122 i32_load(code, 0);
19123 i32_const(code, 24);
19124 code.push(0x6C);
19125 i32_const(code, 8);
19126 code.push(0x6A); i32_store(code, 4);
19128 local_get(code, h);
19129 local_get(code, data);
19130 i32_store(code, 8);
19131 local_get(code, h);
19132 local_set(code, out);
19133 }
19134 _ => {
19135 return Err(WasmLowerError::Unsupported(
19136 "concat operand kind cannot be stringified yet",
19137 ))
19138 }
19139 }
19140 Ok(())
19141}
19142
19143fn emit_struct_display(
19150 code: &mut Vec<u8>,
19151 ctx: &Ctx,
19152 num_regs: u32,
19153 def: &StructTypeDef,
19154 handle: u32,
19155 out: u32,
19156 part: u32,
19157 field_i32: u32,
19158) -> R<()> {
19159 let mut order: Vec<usize> = (0..def.fields.len()).collect();
19160 order.sort_by(|&a, &b| def.fields[a].0.cmp(&def.fields[b].0));
19161 if def.fields.is_empty() {
19162 lower_text_literal(code, ctx, num_regs, def.name.as_bytes());
19163 local_set(code, out);
19164 return Ok(());
19165 }
19166 lower_text_literal(code, ctx, num_regs, format!("{} {{ ", def.name).as_bytes());
19167 local_set(code, out);
19168 let n = order.len();
19169 for (j, &i) in order.iter().enumerate() {
19170 let (fname, bt) = &def.fields[i];
19171 let ek = kind::boundary_to_kind(bt);
19172 lower_text_literal(code, ctx, num_regs, format!("{fname}: ").as_bytes());
19173 local_set(code, part);
19174 emit_text_concat(code, ctx, num_regs, out, part, out);
19175 if ctx.exact.record_ints() && ek == Some(Kind::Int) {
19176 exact::record_integer_text(code, ctx, num_regs, handle, i as u16, part)?;
19177 } else if let Some(shown) =
19178 display::Shown::of_type(bt).filter(|s| s.inline_kind().is_none())
19179 {
19180 local_get(code, handle);
19181 i32_load(code, 8);
19182 i32_load(code, (i as u32) * 8);
19183 local_set(code, field_i32);
19184 display::emit_shown(code, ctx, num_regs, field_i32, &shown, part)?;
19185 } else {
19186 let elem_tmp = match ek.map(Kind::wasm_valtype) {
19188 Some(F64) => num_regs + 12,
19189 Some(I64) => num_regs + 1,
19190 _ => field_i32,
19191 };
19192 local_get(code, handle);
19193 i32_load(code, 8); emit_slot_load(code, ek, (i as u32) * 8)?;
19195 local_set(code, elem_tmp);
19196 emit_stringify(code, ctx, num_regs, elem_tmp, ek, part)?;
19197 }
19198 emit_text_concat(code, ctx, num_regs, out, part, out);
19199 if j + 1 < n {
19200 lower_text_literal(code, ctx, num_regs, b", ");
19201 local_set(code, part);
19202 emit_text_concat(code, ctx, num_regs, out, part, out);
19203 }
19204 }
19205 lower_text_literal(code, ctx, num_regs, b" }");
19206 local_set(code, part);
19207 emit_text_concat(code, ctx, num_regs, out, part, out);
19208 Ok(())
19209}
19210
19211fn lower_show_struct(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19212 let type_name = plan
19213 .structs
19214 .struct_name_of
19215 .get(&src)
19216 .or_else(|| match plan.structs.reg_declared.get(&src) {
19217 Some(BoundaryType::Struct(name)) => Some(name),
19218 _ => None,
19219 })
19220 .ok_or(WasmLowerError::Unsupported(
19221 "Show of a struct whose type is not statically known",
19222 ))?;
19223 let def = ctx
19224 .struct_types
19225 .iter()
19226 .find(|s| &s.name == type_name)
19227 .ok_or(WasmLowerError::Unsupported(
19228 "Show of an unknown struct type",
19229 ))?;
19230 let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19231 "Show struct: print_text not imported",
19232 ))?;
19233 let num_regs = plan.num_regs;
19234 let out = num_regs + 8;
19235 emit_struct_display(
19236 code,
19237 ctx,
19238 num_regs,
19239 def,
19240 src as u32,
19241 out,
19242 num_regs + 9,
19243 num_regs + 10,
19244 )?;
19245 local_get(code, out);
19246 code.push(0x10); leb_u32(code, print_idx);
19248 Ok(())
19249}
19250
19251fn lower_show_seqstruct(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19256 let type_name =
19257 plan.structs
19258 .seq_elem_struct_name
19259 .get(&src)
19260 .ok_or(WasmLowerError::Unsupported(
19261 "Show of a Seq of Struct whose element type is not statically known",
19262 ))?;
19263 let def = ctx
19264 .struct_types
19265 .iter()
19266 .find(|s| &s.name == type_name)
19267 .ok_or(WasmLowerError::Unsupported(
19268 "Show seq-struct: unknown element struct type",
19269 ))?;
19270 let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19271 "Show seq-struct: print_text not imported",
19272 ))?;
19273 let num_regs = plan.num_regs;
19274 let m = src as u32;
19275 let (outer_acc, out, i, elem) = (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
19276 let (part, field_i32) = (num_regs + 13, num_regs + 14);
19277 lower_text_literal(code, ctx, num_regs, b"[");
19278 local_set(code, outer_acc);
19279 i32_const(code, 0);
19280 local_set(code, i);
19281 code.push(0x02);
19282 code.push(0x40); code.push(0x03);
19284 code.push(0x40); local_get(code, i);
19286 local_get(code, m);
19287 i32_load(code, 0);
19288 code.push(0x4E); code.push(0x0D);
19290 leb_u32(code, 1);
19291 local_get(code, i);
19293 code.push(0x45);
19294 code.push(0x04);
19295 code.push(0x40);
19296 code.push(0x05);
19297 lower_text_literal(code, ctx, num_regs, b", ");
19298 local_set(code, part);
19299 emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19300 code.push(0x0B); local_get(code, m);
19303 i32_load(code, 8);
19304 local_get(code, i);
19305 i32_const(code, 8);
19306 code.push(0x6C);
19307 code.push(0x6A);
19308 i32_load(code, 0);
19309 local_set(code, elem);
19310 emit_struct_display(code, ctx, num_regs, def, elem, out, part, field_i32)?;
19311 emit_text_concat(code, ctx, num_regs, outer_acc, out, outer_acc);
19312 local_get(code, i);
19313 i32_const(code, 1);
19314 code.push(0x6A);
19315 local_set(code, i);
19316 code.push(0x0C);
19317 leb_u32(code, 0);
19318 code.push(0x0B); code.push(0x0B); lower_text_literal(code, ctx, num_regs, b"]");
19321 local_set(code, part);
19322 emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19323 local_get(code, outer_acc);
19324 code.push(0x10); leb_u32(code, print_idx);
19326 Ok(())
19327}
19328
19329fn lower_show_seqseq(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, src: u16) -> R<()> {
19335 let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19336 "Show seq-of-seq: print_text not imported",
19337 ))?;
19338 let m = src as u32;
19339 let (acc, part, i, inner) = (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
19342 lower_text_literal(code, ctx, num_regs, b"[");
19344 local_set(code, acc);
19345 i32_const(code, 0);
19346 local_set(code, i);
19347 code.push(0x02);
19348 code.push(0x40); code.push(0x03);
19350 code.push(0x40); local_get(code, i);
19353 local_get(code, m);
19354 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
19357 leb_u32(code, 1); local_get(code, i);
19360 code.push(0x45); code.push(0x04);
19362 code.push(0x40); code.push(0x05); lower_text_literal(code, ctx, num_regs, b", ");
19365 local_set(code, part);
19366 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19367 code.push(0x0B); local_get(code, m);
19370 i32_load(code, 8); local_get(code, i);
19372 i32_const(code, 8);
19373 code.push(0x6C); code.push(0x6A); i32_load(code, 0); local_set(code, inner);
19377 emit_stringify(code, ctx, num_regs, inner, Some(Kind::SeqInt), part)?;
19379 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19380 local_get(code, i);
19382 i32_const(code, 1);
19383 code.push(0x6A);
19384 local_set(code, i);
19385 code.push(0x0C);
19386 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); lower_text_literal(code, ctx, num_regs, b"]");
19391 local_set(code, part);
19392 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19393 local_get(code, acc);
19394 code.push(0x10); leb_u32(code, print_idx);
19396 Ok(())
19397}
19398
19399enum MapShowKinds {
19411 Entries(Option<Kind>, Option<Kind>),
19413 Empty,
19415 Unknown,
19417}
19418
19419fn map_show_kinds(plan: &Plan, src: u16) -> MapShowKinds {
19422 match plan.structs.map_set_key.get(&src) {
19423 Some(&key_reg) => match plan.structs.map_set_value.get(&src) {
19424 Some(&val_reg) => MapShowKinds::Entries(
19425 plan.kinds.get(key_reg as usize),
19426 plan.kinds.get(val_reg as usize),
19427 ),
19428 None => MapShowKinds::Unknown,
19429 },
19430 None => match plan.structs.reg_shape.get(&src) {
19431 Some(ParamShape::Map {
19432 key: Some(k),
19433 value,
19434 ..
19435 }) => MapShowKinds::Entries(Some(*k), Some(*value)),
19436 Some(ParamShape::Map { key: None, .. }) => MapShowKinds::Unknown,
19437 _ => MapShowKinds::Empty,
19438 },
19439 }
19440}
19441
19442fn lower_show_map(
19443 code: &mut Vec<u8>,
19444 plan: &Plan,
19445 _kinds: &KindTable,
19446 ctx: &Ctx,
19447 src: u16,
19448) -> R<()> {
19449 let (key_kind, val_kind) = match map_show_kinds(plan, src) {
19450 MapShowKinds::Entries(k, v) => (k, v),
19451 MapShowKinds::Empty => return lower_show_empty_map(code, plan, ctx),
19452 MapShowKinds::Unknown => {
19453 return Err(WasmLowerError::Unsupported(
19454 "Show of a map whose key or value kind is not statically known",
19455 ))
19456 }
19457 };
19458 let key_text = match key_kind {
19459 Some(Kind::Text) => true,
19460 Some(Kind::Int) => false,
19461 _ => {
19462 return Err(WasmLowerError::Unsupported(
19463 "Show of a map with a non-Int/Text key",
19464 ))
19465 }
19466 };
19467 let val_load = map_value_load(val_kind)?; let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19469 "Show map: print_text not imported",
19470 ))?;
19471 let num_regs = plan.num_regs;
19472 let m = src as u32;
19473 let (acc, part, i) = (num_regs + 8, num_regs + 9, num_regs + 10);
19477 let key_tmp = if key_text {
19478 num_regs + 11
19479 } else {
19480 num_regs + 1
19481 };
19482 let val_tmp = match val_kind.map(Kind::wasm_valtype) {
19483 Some(F64) => num_regs + 12,
19484 Some(I64) => num_regs + 1,
19485 _ => num_regs + 11,
19486 };
19487 lower_text_literal(code, ctx, num_regs, b"{");
19489 local_set(code, acc);
19490 i32_const(code, 0);
19492 local_set(code, i);
19493 code.push(0x02);
19494 code.push(0x40); code.push(0x03);
19496 code.push(0x40); local_get(code, i);
19499 local_get(code, m);
19500 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
19503 leb_u32(code, 1); local_get(code, i);
19506 code.push(0x45); code.push(0x04);
19508 code.push(0x40); code.push(0x05); lower_text_literal(code, ctx, num_regs, b", ");
19511 local_set(code, part);
19512 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19513 code.push(0x0B); emit_map_entry_addr(code, m, i);
19516 if !key_text && ctx.exact.map_ints {
19517 exact::map_integer_text(code, ctx, num_regs, m, 0, part)?;
19518 } else {
19519 if key_text {
19520 i32_load(code, 0);
19521 } else {
19522 i64_load(code, 0);
19523 }
19524 local_set(code, key_tmp);
19525 emit_stringify(code, ctx, num_regs, key_tmp, key_kind, part)?;
19526 }
19527 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19528 lower_text_literal(code, ctx, num_regs, b": ");
19530 local_set(code, part);
19531 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19532 emit_map_entry_addr(code, m, i);
19534 if val_kind == Some(Kind::Int) && ctx.exact.map_ints {
19535 exact::map_integer_text(code, ctx, num_regs, m, 8, part)?;
19536 } else {
19537 val_load(code, 8);
19538 local_set(code, val_tmp);
19539 emit_stringify(code, ctx, num_regs, val_tmp, val_kind, part)?;
19540 }
19541 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19542 local_get(code, i);
19544 i32_const(code, 1);
19545 code.push(0x6A);
19546 local_set(code, i);
19547 code.push(0x0C);
19548 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); lower_text_literal(code, ctx, num_regs, b"}");
19553 local_set(code, part);
19554 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19555 local_get(code, acc);
19556 code.push(0x10); leb_u32(code, print_idx);
19558 Ok(())
19559}
19560
19561fn lower_show_empty_map(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx) -> R<()> {
19565 let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19566 "Show map: print_text not imported",
19567 ))?;
19568 lower_text_literal(code, ctx, plan.num_regs, b"{}");
19569 code.push(0x10); leb_u32(code, print_idx);
19571 Ok(())
19572}
19573
19574fn lower_show_tuple(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19584 let elems = plan
19585 .structs
19586 .tuple_layouts
19587 .get(&src)
19588 .ok_or(WasmLowerError::Unsupported(
19589 "Show of a tuple with no static layout",
19590 ))?;
19591 let num_regs = plan.num_regs;
19592 let (acc, part) = (num_regs + 8, num_regs + 9);
19593 lower_text_literal(code, ctx, num_regs, b"(");
19595 local_set(code, acc);
19596 let n = elems.len();
19597 for (i, &elem_reg) in elems.iter().enumerate() {
19598 let ek = plan.kinds.get(elem_reg as usize);
19599 let elem_tmp = match ek.map(Kind::wasm_valtype) {
19601 Some(F64) => num_regs + 12, Some(I64) => num_regs + 1, _ => num_regs + 10, };
19605 local_get(code, src as u32);
19606 i32_load(code, 8); emit_slot_load(code, ek, (i as u32) * 8)?;
19608 local_set(code, elem_tmp);
19609 if ctx.exact.sequence_ints() && plan.kinds.get(src as usize) == Some(Kind::SeqInt) {
19611 local_get(code, elem_tmp);
19612 code.push(0x10);
19613 leb_u32(
19614 code,
19615 (ctx.host_index)(HostFn::ExactText)
19616 .ok_or(WasmLowerError::Unsupported("exact text import"))?,
19617 );
19618 local_set(code, part);
19619 } else {
19620 emit_stringify(code, ctx, num_regs, elem_tmp, ek, part)?;
19621 }
19622 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19623 if i + 1 < n {
19625 lower_text_literal(code, ctx, num_regs, b", ");
19626 local_set(code, part);
19627 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19628 }
19629 }
19630 lower_text_literal(code, ctx, num_regs, b")");
19632 local_set(code, part);
19633 emit_text_concat(code, ctx, num_regs, acc, part, acc);
19634 let idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19636 "Show tuple: print_text not imported",
19637 ))?;
19638 local_get(code, acc);
19639 code.push(0x10); leb_u32(code, idx);
19641 Ok(())
19642}
19643
19644fn emit_enum_display(
19660 code: &mut Vec<u8>,
19661 ctx: &Ctx,
19662 num_regs: u32,
19663 def: &EnumTypeDef,
19664 handle: u32,
19665 out: u32,
19666 part: u32,
19667 field_i32: u32,
19668) -> R<()> {
19669 for v in &def.variants {
19670 let Some(tag) = ctx
19674 .constants
19675 .iter()
19676 .position(|c| matches!(c, Constant::Text(n) if *n == v.name))
19677 else {
19678 continue;
19679 };
19680 let tag = tag as i32;
19681 local_get(code, handle);
19682 i32_load(code, 0); i32_const(code, tag);
19684 code.push(0x46); code.push(0x04);
19686 code.push(0x40); lower_text_literal(code, ctx, num_regs, v.name.as_bytes());
19689 local_set(code, out);
19690 if !v.field_types.is_empty() {
19691 lower_text_literal(code, ctx, num_regs, b"(");
19693 local_set(code, part);
19694 emit_text_concat(code, ctx, num_regs, out, part, out);
19695 let n = v.field_types.len();
19696 for (i, ft) in v.field_types.iter().enumerate() {
19697 let ek = kind::boundary_to_kind(ft);
19698 let elem_tmp = match ek.map(Kind::wasm_valtype) {
19699 Some(F64) => num_regs + 12,
19700 Some(I64) => num_regs + 1,
19701 _ => field_i32,
19702 };
19703 local_get(code, handle);
19704 emit_enum_payload_base(code, ctx);
19705 emit_slot_load(code, ek, enum_payload_offset(ctx, i as u32))?;
19706 local_set(code, elem_tmp);
19707 emit_stringify(code, ctx, num_regs, elem_tmp, ek, part)?;
19708 emit_text_concat(code, ctx, num_regs, out, part, out);
19709 if i + 1 < n {
19710 lower_text_literal(code, ctx, num_regs, b", ");
19711 local_set(code, part);
19712 emit_text_concat(code, ctx, num_regs, out, part, out);
19713 }
19714 }
19715 lower_text_literal(code, ctx, num_regs, b")");
19716 local_set(code, part);
19717 emit_text_concat(code, ctx, num_regs, out, part, out);
19718 }
19719 code.push(0x0B); }
19721 Ok(())
19722}
19723
19724fn lower_show_enum(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19725 let type_name = plan
19726 .structs
19727 .ind_type_of
19728 .get(&src)
19729 .ok_or(WasmLowerError::Unsupported(
19730 "Show of an enum whose type is not statically known",
19731 ))?;
19732 let def = ctx
19733 .enum_types
19734 .iter()
19735 .find(|e| &e.name == type_name)
19736 .ok_or(WasmLowerError::Unsupported("Show of an unknown enum type"))?;
19737 let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19738 "Show enum: print_text not imported",
19739 ))?;
19740 let num_regs = plan.num_regs;
19741 let out = num_regs + 8;
19743 emit_enum_display(
19744 code,
19745 ctx,
19746 num_regs,
19747 def,
19748 src as u32,
19749 out,
19750 num_regs + 9,
19751 num_regs + 10,
19752 )?;
19753 local_get(code, out);
19754 code.push(0x10); leb_u32(code, print_idx);
19756 Ok(())
19757}
19758
19759fn lower_show_seqenum(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19764 let type_name = plan
19765 .structs
19766 .seq_elem_ind_type
19767 .get(&src)
19768 .ok_or(WasmLowerError::Unsupported(
19769 "Show of a Seq of Enum whose element type is not statically known",
19770 ))?;
19771 let def =
19772 ctx.enum_types
19773 .iter()
19774 .find(|e| &e.name == type_name)
19775 .ok_or(WasmLowerError::Unsupported(
19776 "Show seq-enum: unknown element enum type",
19777 ))?;
19778 let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19779 "Show seq-enum: print_text not imported",
19780 ))?;
19781 let num_regs = plan.num_regs;
19782 let m = src as u32;
19783 let (outer_acc, out, i, elem) = (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
19786 let (part, field_i32) = (num_regs + 13, num_regs + 14);
19787 lower_text_literal(code, ctx, num_regs, b"[");
19788 local_set(code, outer_acc);
19789 i32_const(code, 0);
19790 local_set(code, i);
19791 code.push(0x02);
19792 code.push(0x40); code.push(0x03);
19794 code.push(0x40); local_get(code, i);
19797 local_get(code, m);
19798 i32_load(code, 0);
19799 code.push(0x4E); code.push(0x0D);
19801 leb_u32(code, 1);
19802 local_get(code, i);
19804 code.push(0x45); code.push(0x04);
19806 code.push(0x40);
19807 code.push(0x05); lower_text_literal(code, ctx, num_regs, b", ");
19809 local_set(code, part);
19810 emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19811 code.push(0x0B); local_get(code, m);
19814 i32_load(code, 8);
19815 local_get(code, i);
19816 i32_const(code, 8);
19817 code.push(0x6C); code.push(0x6A); i32_load(code, 0);
19820 local_set(code, elem);
19821 emit_enum_display(code, ctx, num_regs, def, elem, out, part, field_i32)?;
19823 emit_text_concat(code, ctx, num_regs, outer_acc, out, outer_acc);
19824 local_get(code, i);
19826 i32_const(code, 1);
19827 code.push(0x6A);
19828 local_set(code, i);
19829 code.push(0x0C);
19830 leb_u32(code, 0);
19831 code.push(0x0B); code.push(0x0B); lower_text_literal(code, ctx, num_regs, b"]");
19834 local_set(code, part);
19835 emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19836 local_get(code, outer_acc);
19837 code.push(0x10); leb_u32(code, print_idx);
19839 Ok(())
19840}
19841
19842fn policy_field_slot<'a>(
19845 ctx: &'a Ctx,
19846 type_name: &str,
19847 field_name: &str,
19848) -> Option<(u16, &'a BoundaryType)> {
19849 let def = ctx.struct_types.iter().find(|s| s.name == type_name)?;
19850 def.fields
19851 .iter()
19852 .position(|(n, _)| n == field_name)
19853 .map(|i| (i as u16, &def.fields[i].1))
19854}
19855
19856fn emit_load_text_field(code: &mut Vec<u8>, reg: u16, slot: u16, dst_local: u32) {
19858 local_get(code, reg as u32);
19859 i32_load(code, 8); i32_load(code, u32::from(slot) * 8); local_set(code, dst_local);
19862}
19863
19864fn emit_policy_condition(
19869 code: &mut Vec<u8>,
19870 plan: &Plan,
19871 ctx: &Ctx,
19872 cond: &PolicyCondition,
19873 subject: u16,
19874 object: u16,
19875) -> R<()> {
19876 let (f8, f11) = (plan.num_regs + 8, plan.num_regs + 11);
19877 match cond {
19878 PolicyCondition::FieldEquals {
19879 field,
19880 value,
19881 is_string_literal,
19882 } => {
19883 if !is_string_literal {
19884 return Err(WasmLowerError::Unsupported(
19885 "policy: non-Text field comparison",
19886 ));
19887 }
19888 let subj_type =
19889 plan.structs
19890 .struct_name_of
19891 .get(&subject)
19892 .ok_or(WasmLowerError::Unsupported(
19893 "policy: subject has no struct type",
19894 ))?;
19895 let field_name = ctx.interner.resolve(*field);
19896 let (slot, bt) = policy_field_slot(ctx, subj_type, field_name).ok_or(
19897 WasmLowerError::Unsupported("policy: field not in subject type"),
19898 )?;
19899 if !matches!(bt, BoundaryType::Text) {
19900 return Err(WasmLowerError::Unsupported("policy: field is not Text"));
19901 }
19902 let value_str = ctx.interner.resolve(*value).to_string();
19903 emit_load_text_field(code, subject, slot, f8);
19904 lower_text_literal(code, ctx, plan.num_regs, value_str.as_bytes());
19905 local_set(code, f11);
19906 emit_text_eq(code, ctx, plan.num_regs, f8, f11);
19907 }
19908 PolicyCondition::Predicate { predicate, .. } => {
19909 let subj_type =
19910 plan.structs
19911 .struct_name_of
19912 .get(&subject)
19913 .ok_or(WasmLowerError::Unsupported(
19914 "policy: subject has no struct type",
19915 ))?;
19916 let subj_sym = ctx
19917 .interner
19918 .lookup(subj_type)
19919 .ok_or(WasmLowerError::Unsupported(
19920 "policy: subject type not interned",
19921 ))?;
19922 let preds =
19923 ctx.policies
19924 .get_predicates(subj_sym)
19925 .ok_or(WasmLowerError::Unsupported(
19926 "policy: no predicates for subject type",
19927 ))?;
19928 let pred = preds
19929 .iter()
19930 .find(|p| p.predicate_name == *predicate)
19931 .ok_or(WasmLowerError::Unsupported(
19932 "policy: referenced predicate not found",
19933 ))?;
19934 emit_policy_condition(code, plan, ctx, &pred.condition, subject, object)?;
19935 }
19936 PolicyCondition::SubjectFieldEqualsObjectField {
19937 subject_field,
19938 object_field,
19939 ..
19940 }
19941 | PolicyCondition::ObjectFieldEquals {
19942 subject: subject_field,
19943 field: object_field,
19944 ..
19945 } => {
19946 if object == u16::MAX {
19947 return Err(WasmLowerError::Unsupported(
19948 "policy: cross-field compare needs an object",
19949 ));
19950 }
19951 let subj_type =
19952 plan.structs
19953 .struct_name_of
19954 .get(&subject)
19955 .ok_or(WasmLowerError::Unsupported(
19956 "policy: subject has no struct type",
19957 ))?;
19958 let obj_type =
19959 plan.structs
19960 .struct_name_of
19961 .get(&object)
19962 .ok_or(WasmLowerError::Unsupported(
19963 "policy: object has no struct type",
19964 ))?;
19965 let sf = ctx.interner.resolve(*subject_field);
19966 let of = ctx.interner.resolve(*object_field);
19967 let (s_slot, s_bt) = policy_field_slot(ctx, subj_type, sf).ok_or(
19968 WasmLowerError::Unsupported("policy: subject field not found"),
19969 )?;
19970 let (o_slot, o_bt) = policy_field_slot(ctx, obj_type, of).ok_or(
19971 WasmLowerError::Unsupported("policy: object field not found"),
19972 )?;
19973 if !matches!(s_bt, BoundaryType::Text) || !matches!(o_bt, BoundaryType::Text) {
19974 return Err(WasmLowerError::Unsupported(
19975 "policy: cross-field compare of non-Text fields",
19976 ));
19977 }
19978 emit_load_text_field(code, subject, s_slot, f8);
19979 emit_load_text_field(code, object, o_slot, f11);
19980 emit_text_eq(code, ctx, plan.num_regs, f8, f11);
19981 }
19982 PolicyCondition::Or(l, r) => {
19983 emit_policy_condition(code, plan, ctx, l, subject, object)?;
19984 emit_policy_condition(code, plan, ctx, r, subject, object)?;
19985 code.push(0x72); }
19987 PolicyCondition::And(l, r) => {
19988 emit_policy_condition(code, plan, ctx, l, subject, object)?;
19989 emit_policy_condition(code, plan, ctx, r, subject, object)?;
19990 code.push(0x71); }
19992 PolicyCondition::FieldBool { .. } => {
19993 return Err(WasmLowerError::Unsupported(
19994 "policy: boolean field condition",
19995 ));
19996 }
19997 }
19998 Ok(())
19999}
20000
20001fn lower_check_policy(
20006 code: &mut Vec<u8>,
20007 plan: &Plan,
20008 ctx: &Ctx,
20009 subject: u16,
20010 predicate: crate::Symbol,
20011 is_capability: bool,
20012 object: u16,
20013) -> R<()> {
20014 let subj_type =
20015 plan.structs
20016 .struct_name_of
20017 .get(&subject)
20018 .ok_or(WasmLowerError::Unsupported(
20019 "CheckPolicy on a non-struct subject",
20020 ))?;
20021 let subj_sym = ctx
20022 .interner
20023 .lookup(subj_type)
20024 .ok_or(WasmLowerError::Unsupported(
20025 "CheckPolicy subject type not interned",
20026 ))?;
20027 let cond = if is_capability {
20028 let caps = ctx
20029 .policies
20030 .get_capabilities(subj_sym)
20031 .ok_or(WasmLowerError::Unsupported(
20032 "CheckPolicy: no capabilities for subject type",
20033 ))?;
20034 caps.iter()
20035 .find(|c| c.action == predicate)
20036 .map(|c| &c.condition)
20037 .ok_or(WasmLowerError::Unsupported(
20038 "CheckPolicy: capability not found",
20039 ))?
20040 } else {
20041 let preds = ctx
20042 .policies
20043 .get_predicates(subj_sym)
20044 .ok_or(WasmLowerError::Unsupported(
20045 "CheckPolicy: no predicates for subject type",
20046 ))?;
20047 preds
20048 .iter()
20049 .find(|p| p.predicate_name == predicate)
20050 .map(|p| &p.condition)
20051 .ok_or(WasmLowerError::Unsupported(
20052 "CheckPolicy: predicate not found",
20053 ))?
20054 };
20055 emit_policy_condition(code, plan, ctx, cond, subject, object)?;
20056 code.push(0x45); code.push(0x04);
20058 code.push(0x40); code.push(0x00); code.push(0x0B); Ok(())
20062}
20063
20064const CRDT_RECORD_BYTES: i32 = 24;
20067
20068fn emit_new_counter(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u32) {
20072 let (hdr, data) = (num_regs + 5, num_regs + 6); i32_const(code, 16);
20075 emit_alloc(code, ctx, hdr, AllocClass::CounterHeader);
20076 i32_const(code, CRDT_RECORD_BYTES);
20077 emit_alloc(code, ctx, data, AllocClass::Raw);
20078 local_get(code, hdr);
20080 i32_const(code, 1);
20081 i32_store(code, 0);
20082 local_get(code, hdr);
20083 i32_const(code, 1);
20084 i32_store(code, 4);
20085 local_get(code, hdr);
20086 local_get(code, data);
20087 i32_store(code, 8);
20088 let replica = ctx.replica_global.expect("counter identity global");
20090 global_get(code, replica);
20091 i64c(code, 1);
20092 code.push(0x7C);
20093 global_set(code, replica);
20094 global_get(code, replica);
20095 code.push(0x50); code.push(0x04);
20097 code.push(0x40);
20098 code.push(0x00);
20099 code.push(0x0B);
20100 local_get(code, data);
20101 global_get(code, replica);
20102 i64_store(code, 0);
20103 local_get(code, data);
20104 code.push(0x42); leb_i64(code, 0);
20106 i64_store(code, 8); local_get(code, data);
20108 code.push(0x42);
20109 leb_i64(code, 0);
20110 i64_store(code, 16); local_get(code, hdr);
20112 local_set(code, dst);
20113}
20114
20115fn lower_get_counter_total(
20120 code: &mut Vec<u8>,
20121 plan: &Plan,
20122 slot: u16,
20123 dst: u16,
20124 obj: u16,
20125) -> R<()> {
20126 if plan.kinds.get(obj as usize) != Some(Kind::Struct) {
20127 return Err(WasmLowerError::Unsupported(
20128 "counter field access on a value with no known struct layout",
20129 ));
20130 }
20131 let (cnt, acc, i) = (plan.num_regs + 17, plan.num_regs + 15, plan.num_regs + 18); let off = u32::from(slot) * 8;
20133 local_get(code, obj as u32);
20135 i32_load(code, 8);
20136 i32_load(code, off);
20137 local_set(code, cnt);
20138 code.push(0x42);
20140 leb_i64(code, 0);
20141 local_set(code, acc);
20142 i32_const(code, 0);
20143 local_set(code, i);
20144 code.push(0x02);
20145 code.push(0x40); code.push(0x03);
20147 code.push(0x40); local_get(code, i);
20150 local_get(code, cnt);
20151 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
20154 leb_u32(code, 1); local_get(code, acc);
20158 local_get(code, cnt);
20160 i32_load(code, 8); local_get(code, i);
20162 i32_const(code, CRDT_RECORD_BYTES);
20163 code.push(0x6C); code.push(0x6A); local_tee(code, plan.num_regs + 19); i64_load(code, 8); code.push(0x7C); local_get(code, plan.num_regs + 19);
20169 i64_load(code, 16); code.push(0x7D); local_set(code, acc);
20172 local_get(code, i);
20174 i32_const(code, 1);
20175 code.push(0x6A);
20176 local_set(code, i);
20177 code.push(0x0C);
20178 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, acc);
20182 local_set(code, dst as u32);
20183 Ok(())
20184}
20185
20186fn lower_crdt_bump(
20193 code: &mut Vec<u8>,
20194 plan: &Plan,
20195 ctx: &Ctx,
20196 obj: u16,
20197 field_const: u32,
20198 amount: u16,
20199 negate: bool,
20200) -> R<()> {
20201 let _ = ctx;
20202 let layout = plan
20206 .structs
20207 .reg_layout
20208 .get(&obj)
20209 .ok_or(WasmLowerError::Unsupported(
20210 "CrdtBump on a value with no struct layout",
20211 ))?;
20212 let slot =
20213 layout
20214 .iter()
20215 .position(|(fc, _)| *fc == field_const)
20216 .ok_or(WasmLowerError::Unsupported(
20217 "CrdtBump: field not in struct layout",
20218 ))? as u32;
20219 let off = slot * 8;
20220 let rec_off = if negate { 16 } else { 8 };
20222 let rec = plan.num_regs + 17; local_get(code, obj as u32);
20225 i32_load(code, 8);
20226 i32_load(code, off); i32_load(code, 8); local_set(code, rec);
20229 local_get(code, rec);
20231 local_get(code, rec);
20232 i64_load(code, rec_off);
20233 local_get(code, amount as u32);
20234 code.push(0x7C); i64_store(code, rec_off);
20236 Ok(())
20237}
20238
20239fn lower_crdt_merge(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, target: u16, source: u16) -> R<()> {
20247 let layout = plan
20248 .structs
20249 .reg_layout
20250 .get(&target)
20251 .ok_or(WasmLowerError::Unsupported(
20252 "CrdtMerge on a value with no struct layout",
20253 ))?;
20254 let fields = layout.clone();
20255 for (slot, &(_fc, value_reg)) in fields.iter().enumerate() {
20256 let field_kind = value_reg.and_then(|r| plan.kinds.get(r as usize));
20257 if field_kind != Some(Kind::CrdtCounter) {
20258 let kind_name = match field_kind {
20264 Some(Kind::Map) => "SharedMap",
20265 Some(Kind::SetText) | Some(Kind::CrdtSetText) => "SharedSet",
20266 Some(Kind::SeqSeqInt) | Some(Kind::SeqInt) => "SharedSequence",
20267 _ => "a CRDT",
20268 };
20269 return Err(WasmLowerError::UnsupportedOwned(format!(
20270 "`{kind_name}` is a CRDT the wasm backend does not implement merging for — run \
20271 the program on the interpreter or the VM, or build it with the Rust tier \
20272 (`largo build`)"
20273 )));
20274 }
20275 emit_counter_field_merge(code, plan, ctx, target, source, (slot as u32) * 8);
20276 }
20277 Ok(())
20278}
20279
20280fn emit_counter_field_merge(
20286 code: &mut Vec<u8>,
20287 plan: &Plan,
20288 ctx: &Ctx,
20289 target: u16,
20290 source: u16,
20291 off: u32,
20292) {
20293 let nr = plan.num_regs;
20294 let (t_cnt, s_cnt) = (nr + 17, nr + 18); let (j, s_rec) = (nr + 19, nr + 20); let s_id = nr + 15; let (found, k) = (nr + 21, nr + 22); local_get(code, target as u32);
20300 i32_load(code, 8);
20301 i32_load(code, off);
20302 local_set(code, t_cnt);
20303 local_get(code, source as u32);
20304 i32_load(code, 8);
20305 i32_load(code, off);
20306 local_set(code, s_cnt);
20307 i32_const(code, 0);
20309 local_set(code, j);
20310 code.push(0x02);
20311 code.push(0x40); code.push(0x03);
20313 code.push(0x40); local_get(code, j);
20315 local_get(code, s_cnt);
20316 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
20319 leb_u32(code, 1); local_get(code, s_cnt);
20322 i32_load(code, 8);
20323 local_get(code, j);
20324 i32_const(code, CRDT_RECORD_BYTES);
20325 code.push(0x6C);
20326 code.push(0x6A);
20327 local_tee(code, s_rec);
20328 i64_load(code, 0);
20329 local_set(code, s_id);
20330 i32_const(code, 0);
20332 local_set(code, found);
20333 i32_const(code, 0);
20334 local_set(code, k);
20335 code.push(0x02);
20336 code.push(0x40); code.push(0x03);
20338 code.push(0x40); local_get(code, k);
20340 local_get(code, t_cnt);
20341 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
20344 leb_u32(code, 1); local_get(code, t_cnt);
20347 i32_load(code, 8);
20348 local_get(code, k);
20349 i32_const(code, CRDT_RECORD_BYTES);
20350 code.push(0x6C);
20351 code.push(0x6A);
20352 local_tee(code, found);
20353 i64_load(code, 0);
20355 local_get(code, s_id);
20356 code.push(0x51); code.push(0x04);
20358 code.push(0x40); code.push(0x0C);
20360 leb_u32(code, 2); code.push(0x0B); i32_const(code, 0);
20364 local_set(code, found);
20365 local_get(code, k);
20366 i32_const(code, 1);
20367 code.push(0x6A);
20368 local_set(code, k);
20369 code.push(0x0C);
20370 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, found);
20375 code.push(0x45); code.push(0x04);
20377 code.push(0x40); emit_counter_append(code, plan, ctx, t_cnt, s_rec, s_id);
20379 code.push(0x05); emit_counter_record_max(code, found, s_rec, 8); emit_counter_record_max(code, found, s_rec, 16); code.push(0x0B); local_get(code, j);
20385 i32_const(code, 1);
20386 code.push(0x6A);
20387 local_set(code, j);
20388 code.push(0x0C);
20389 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); }
20393
20394fn emit_counter_record_max(code: &mut Vec<u8>, t_rec: u32, s_rec: u32, off: u32) {
20397 local_get(code, t_rec);
20398 local_get(code, t_rec);
20400 i64_load(code, off);
20401 local_get(code, s_rec);
20402 i64_load(code, off);
20403 local_get(code, t_rec);
20404 i64_load(code, off);
20405 local_get(code, s_rec);
20406 i64_load(code, off);
20407 code.push(0x55); code.push(0x1B); i64_store(code, off);
20410}
20411
20412fn emit_counter_append(
20417 code: &mut Vec<u8>,
20418 plan: &Plan,
20419 ctx: &Ctx,
20420 t_cnt: u32,
20421 s_rec: u32,
20422 s_id: u32,
20423) {
20424 let nr = plan.num_regs;
20425 let (hs_new, hs_i, hs_cap, dst_rec) = (nr + 5, nr + 6, nr + 7, nr + 22);
20428 local_get(code, t_cnt);
20430 i32_load(code, 0); local_get(code, t_cnt);
20432 i32_load(code, 4); code.push(0x48); code.push(0x04);
20435 code.push(0x40); {
20437 local_get(code, t_cnt);
20439 i32_load(code, 8);
20440 local_get(code, t_cnt);
20441 i32_load(code, 0);
20442 i32_const(code, CRDT_RECORD_BYTES);
20443 code.push(0x6C);
20444 code.push(0x6A);
20445 local_set(code, dst_rec);
20446 }
20447 code.push(0x05); {
20449 i32_const(code, 1);
20451 local_get(code, t_cnt);
20452 i32_load(code, 4);
20453 i32_const(code, 2);
20454 code.push(0x6C);
20455 local_get(code, t_cnt);
20456 i32_load(code, 4);
20457 code.push(0x45); code.push(0x1B); local_set(code, hs_cap);
20460 local_get(code, hs_cap);
20462 i32_const(code, CRDT_RECORD_BYTES);
20463 code.push(0x6C);
20464 emit_alloc(code, ctx, hs_new, AllocClass::Raw);
20465 i32_const(code, 0);
20467 local_set(code, hs_i);
20468 code.push(0x02);
20469 code.push(0x40); code.push(0x03);
20471 code.push(0x40); local_get(code, hs_i);
20473 local_get(code, t_cnt);
20474 i32_load(code, 0);
20475 i32_const(code, CRDT_RECORD_BYTES);
20476 code.push(0x6C); code.push(0x4E); code.push(0x0D);
20479 leb_u32(code, 1); local_get(code, hs_new);
20482 local_get(code, hs_i);
20483 code.push(0x6A);
20484 local_get(code, t_cnt);
20485 i32_load(code, 8); local_get(code, hs_i);
20487 code.push(0x6A);
20488 i64_load(code, 0);
20489 i64_store(code, 0);
20490 local_get(code, hs_i);
20491 i32_const(code, 8);
20492 code.push(0x6A);
20493 local_set(code, hs_i);
20494 code.push(0x0C);
20495 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, hs_new);
20500 local_get(code, t_cnt);
20501 i32_load(code, 0);
20502 i32_const(code, CRDT_RECORD_BYTES);
20503 code.push(0x6C);
20504 code.push(0x6A);
20505 local_set(code, dst_rec);
20506 emit_free(
20510 code,
20511 ctx,
20512 |c| {
20513 local_get(c, t_cnt);
20514 i32_load(c, 8); },
20516 |c| {
20517 local_get(c, t_cnt);
20518 i32_load(c, 4); i32_const(c, CRDT_RECORD_BYTES);
20520 c.push(0x6C);
20521 },
20522 );
20523 local_get(code, t_cnt);
20525 local_get(code, hs_new);
20526 i32_store(code, 8);
20527 local_get(code, t_cnt);
20528 local_get(code, hs_cap);
20529 i32_store(code, 4);
20530 }
20531 code.push(0x0B); local_get(code, dst_rec);
20534 local_get(code, s_id);
20535 i64_store(code, 0);
20536 local_get(code, dst_rec);
20537 local_get(code, s_rec);
20538 i64_load(code, 8);
20539 i64_store(code, 8);
20540 local_get(code, dst_rec);
20541 local_get(code, s_rec);
20542 i64_load(code, 16);
20543 i64_store(code, 16);
20544 local_get(code, t_cnt);
20546 local_get(code, t_cnt);
20547 i32_load(code, 0);
20548 i32_const(code, 1);
20549 code.push(0x6A);
20550 i32_store(code, 0);
20551}
20552
20553fn lower_crdt_resolve(
20558 code: &mut Vec<u8>,
20559 plan: &Plan,
20560 kinds: &KindTable,
20561 obj: u16,
20562 field_const: u32,
20563 value: u16,
20564) -> R<()> {
20565 let layout = plan
20566 .structs
20567 .reg_layout
20568 .get(&obj)
20569 .ok_or(WasmLowerError::Unsupported(
20570 "CrdtResolve on a value with no struct layout",
20571 ))?;
20572 let slot =
20573 layout
20574 .iter()
20575 .position(|(fc, _)| *fc == field_const)
20576 .ok_or(WasmLowerError::Unsupported(
20577 "CrdtResolve: field not in struct layout",
20578 ))? as u32;
20579 let off = slot * 8;
20580 local_get(code, obj as u32);
20581 i32_load(code, 8); local_get(code, value as u32);
20583 emit_slot_store(code, kinds.get(value as usize), off)?;
20584 Ok(())
20585}
20586
20587fn lower_crdt_append(
20594 code: &mut Vec<u8>,
20595 plan: &Plan,
20596 kinds: &KindTable,
20597 ctx: &Ctx,
20598 seq: u16,
20599 value: u16,
20600) -> R<()> {
20601 match kinds.get(seq as usize) {
20602 Some(Kind::SeqText) | Some(Kind::SeqInt) | Some(Kind::SeqBool) | Some(Kind::SeqFloat)
20603 | Some(Kind::SeqAny) => lower_list_push(code, kinds, ctx, plan.num_regs, seq, value),
20604 Some(Kind::SetText) | Some(Kind::CrdtSetText) => {
20605 emit_set_add_elem(
20606 code,
20607 ctx,
20608 plan.num_regs,
20609 seq as u32,
20610 value as u32,
20611 true,
20612 SetOrder::Sorted,
20613 );
20614 Ok(())
20615 }
20616 Some(Kind::Set) => {
20617 emit_set_add_elem(
20618 code,
20619 ctx,
20620 plan.num_regs,
20621 seq as u32,
20622 value as u32,
20623 false,
20624 SetOrder::Sorted,
20625 );
20626 Ok(())
20627 }
20628 _ => Err(WasmLowerError::Unsupported(
20629 "CrdtAppend to a non-collection CRDT",
20630 )),
20631 }
20632}
20633
20634#[allow(clippy::too_many_arguments)]
20644fn lower_list_push_field(
20645 code: &mut Vec<u8>,
20646 plan: &Plan,
20647 kinds: &KindTable,
20648 ctx: &Ctx,
20649 cow: bool,
20650 obj: u16,
20651 field_const: u32,
20652 src: u16,
20653) -> R<()> {
20654 let slot = record_field_slot(plan, obj, field_const).ok_or(WasmLowerError::Unsupported(
20655 "push to a field of a value with no known record layout",
20656 ))?;
20657 if cow {
20658 emit_record_copy(code, ctx, kinds, &plan.structs, plan.num_regs, obj, None)?;
20659 }
20660 let elem = kinds.get(src as usize).ok_or(WasmLowerError::Unsupported(
20664 "ListPushField: unknown pushed-value kind",
20665 ))?;
20666 let off = (slot as u32) * 8;
20667 let handle = plan.num_regs + 8; local_get(code, obj as u32);
20670 i32_load(code, 8);
20671 i32_load(code, off);
20672 local_set(code, handle);
20673 let field_kind =
20674 record_slot_kinds(kinds, &plan.structs, obj).and_then(|ks| ks.get(slot).copied().flatten());
20675 if let Some(fk) = field_kind.filter(|&k| cow_clonable(Some(k)) && is_collection_clonable(k)) {
20676 emit_should_clone(code, handle);
20677 code.push(0x04);
20678 code.push(0x40); {
20680 emit_collection_clone(code, ctx, plan.num_regs, fk, handle);
20681 local_get(code, obj as u32);
20682 i32_load(code, 8);
20683 local_get(code, plan.num_regs + 5);
20684 i32_store(code, off);
20685 local_get(code, plan.num_regs + 5);
20686 local_set(code, handle);
20687 if ctx.heap_counting() && counted_kind(Some(fk)) {
20689 emit_true_retain_of(code, ctx, |c| local_get(c, handle));
20690 }
20691 }
20692 code.push(0x0B);
20693 }
20694 if elem == Kind::Int && ctx.exact.sequence_ints() {
20695 exact::promote_sequence(code, ctx, plan.num_regs, handle)?;
20696 exact::push_sequence_word(code, plan, ctx, handle, src)
20697 } else {
20698 lower_list_push_at(code, elem, ctx, plan.num_regs, handle, src)
20699 }
20700}
20701
20702fn shares_argument(plan: &Plan, ctx: &Ctx, func: u16, a: u16, arg: u16) -> bool {
20705 let param = ctx
20706 .fn_param_kinds
20707 .get(func as usize)
20708 .and_then(|ks| ks.get(a as usize))
20709 .copied()
20710 .flatten();
20711 counts_aliases(plan.kinds.get(arg as usize)) && param != Some(Kind::Tower)
20712}
20713
20714fn push_call_argument(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, func: u16, a: u16, arg: u16) -> R<()> {
20719 let kinds = &plan.kinds;
20720 let param = ctx
20721 .fn_param_kinds
20722 .get(func as usize)
20723 .and_then(|ks| ks.get(a as usize))
20724 .copied()
20725 .flatten();
20726 if tower::push_argument(code, plan, ctx, arg, param)?.is_some() {
20727 return Ok(());
20728 }
20729 let arg_vt = kinds.valtype(arg as usize);
20730 let param_vt = ctx
20731 .fn_param_valtypes
20732 .get(func as usize)
20733 .ok_or(WasmLowerError::Unsupported("call of unknown function"))?
20734 .get(a as usize)
20735 .copied()
20736 .unwrap_or(I64);
20737 if param == Some(Kind::Rational) && matches!(kinds.get(arg as usize), Some(Kind::Int | Kind::BigInt)) {
20738 push_rational_operand(code, kinds, ctx, arg)
20739 } else if arg_vt == param_vt {
20740 local_get(code, arg as u32);
20741 Ok(())
20742 } else if arg_vt == I64 && param_vt == F64 {
20743 push_as_f64(code, arg, kinds.get(arg as usize))
20744 } else {
20745 Err(WasmLowerError::Unsupported(
20746 "call argument type does not match the parameter",
20747 ))
20748 }
20749}
20750
20751fn emit_sync_call(
20755 code: &mut Vec<u8>,
20756 plan: &Plan,
20757 ctx: &Ctx,
20758 func: u16,
20759 args_start: u16,
20760 arg_count: u16,
20761) -> R<bool> {
20762 if ctx.fn_stubbed.get(func as usize).copied().unwrap_or(false) {
20763 code.push(0x00); return Ok(false);
20765 }
20766 if ctx
20767 .fn_inout
20768 .get(func as usize)
20769 .is_some_and(|ps| !ps.is_empty())
20770 {
20771 return Err(WasmLowerError::Unsupported(
20772 "a task that lends a variable to a `mutable` parameter",
20773 ));
20774 }
20775 for a in 0..arg_count {
20776 let arg = args_start + a;
20777 if shares_argument(plan, ctx, func, a, arg) {
20778 emit_retain(code, ctx, arg);
20779 }
20780 }
20781 for a in 0..arg_count {
20782 push_call_argument(code, plan, ctx, func, a, args_start + a)?;
20783 }
20784 code.push(0x10); leb_u32(code, ctx.fn_base + func as u32);
20786 Ok(ctx
20787 .fn_results
20788 .get(func as usize)
20789 .copied()
20790 .flatten()
20791 .is_some())
20792}
20793
20794fn lower_chan_try_recv(
20801 code: &mut Vec<u8>,
20802 kinds: &KindTable,
20803 ctx: &Ctx,
20804 num_regs: u32,
20805 dst: u16,
20806 chan: u16,
20807) -> R<()> {
20808 let elem =
20809 kinds
20810 .get(chan as usize)
20811 .and_then(Kind::seq_elem)
20812 .ok_or(WasmLowerError::Unsupported(
20813 "try-receive from a channel of unknown element kind",
20814 ))?;
20815 let ch = chan as u32;
20816 let idx = num_regs + 5; let boxp = num_regs + 6; let val = match elem {
20820 Kind::Float => num_regs + 12, Kind::Int
20822 | Kind::Bool
20823 | Kind::Char
20824 | Kind::Moment
20825 | Kind::Duration
20826 | Kind::Time
20827 | Kind::Span => num_regs + 1, _ => num_regs + 7, };
20830 local_get(code, ch);
20832 i32_load(code, 0);
20833 code.push(0x45); code.push(0x04);
20835 code.push(0x40); i32_const(code, 0);
20837 local_set(code, dst as u32); code.push(0x05); emit_pop_front(code, elem, ch, idx, val)?;
20840 i32_const(code, 8);
20841 emit_alloc(code, ctx, boxp, AllocClass::Raw);
20842 local_get(code, boxp);
20843 local_get(code, val);
20844 emit_slot_store(code, Some(elem), 0)?;
20845 local_get(code, boxp);
20846 local_set(code, dst as u32);
20847 code.push(0x0B); Ok(())
20849}
20850
20851fn lower_chan_recv(
20855 code: &mut Vec<u8>,
20856 kinds: &KindTable,
20857 num_regs: u32,
20858 dst: u16,
20859 chan: u16,
20860) -> R<()> {
20861 let elem =
20862 kinds
20863 .get(chan as usize)
20864 .and_then(Kind::seq_elem)
20865 .ok_or(WasmLowerError::Unsupported(
20866 "receive from a channel of unknown element kind",
20867 ))?;
20868 let ch = chan as u32;
20869 let idx = num_regs + 5;
20870 local_get(code, ch);
20872 i32_load(code, 0);
20873 code.push(0x45); code.push(0x04);
20875 code.push(0x40);
20876 code.push(0x00); code.push(0x0B);
20878 emit_pop_front(code, elem, ch, idx, dst as u32)
20879}
20880
20881fn emit_pop_front(code: &mut Vec<u8>, elem: Kind, ch: u32, idx: u32, dst: u32) -> R<()> {
20885 let elem_load = seq_elem_load(elem)?;
20886 local_get(code, ch);
20888 i32_load(code, 8);
20889 elem_load(code, 0);
20890 local_set(code, dst);
20891 i32_const(code, 0);
20893 local_set(code, idx);
20894 code.push(0x02);
20895 code.push(0x40);
20896 code.push(0x03);
20897 code.push(0x40);
20898 local_get(code, idx);
20899 local_get(code, ch);
20900 i32_load(code, 0);
20901 i32_const(code, 1);
20902 code.push(0x6B);
20903 code.push(0x4E); code.push(0x0D);
20905 leb_u32(code, 1);
20906 local_get(code, ch);
20907 i32_load(code, 8);
20908 local_get(code, idx);
20909 i32_const(code, 8);
20910 code.push(0x6C);
20911 code.push(0x6A);
20912 local_get(code, ch);
20913 i32_load(code, 8);
20914 local_get(code, idx);
20915 i32_const(code, 1);
20916 code.push(0x6A);
20917 i32_const(code, 8);
20918 code.push(0x6C);
20919 code.push(0x6A);
20920 i64_load(code, 0);
20921 i64_store(code, 0);
20922 local_get(code, idx);
20923 i32_const(code, 1);
20924 code.push(0x6A);
20925 local_set(code, idx);
20926 code.push(0x0C);
20927 leb_u32(code, 0);
20928 code.push(0x0B);
20929 code.push(0x0B);
20930 local_get(code, ch);
20932 local_get(code, ch);
20933 i32_load(code, 0);
20934 i32_const(code, 1);
20935 code.push(0x6B);
20936 i32_store(code, 0);
20937 Ok(())
20938}
20939
20940fn lower_select_wait(
20952 code: &mut Vec<u8>,
20953 plan: &Plan,
20954 kinds: &KindTable,
20955 blocks: &Blocks,
20956 k: usize,
20957 pc: usize,
20958 dst_arm: u16,
20959) -> R<()> {
20960 #[derive(Clone, Copy)]
20961 enum Arm {
20962 Recv { chan: u16, var: u16 },
20963 Timeout,
20964 }
20965 let mut arms: Vec<Arm> = Vec::new();
20966 for j in blocks.start(k)..pc {
20967 match plan.ops[j] {
20968 Op::SelectArmRecv { chan, var } => arms.push(Arm::Recv { chan, var }),
20969 Op::SelectArmTimeout { .. } => arms.push(Arm::Timeout),
20970 Op::SelectWait { .. } => arms.clear(),
20971 _ => {}
20972 }
20973 }
20974 let da = dst_arm as u32;
20975 let timeout_idx = arms.iter().position(|a| matches!(a, Arm::Timeout));
20976
20977 code.push(0x42); leb_i64(code, -1);
20980 local_set(code, da);
20981
20982 for (i, arm) in arms.iter().enumerate() {
20984 if let Arm::Recv { chan, var } = *arm {
20985 let elem = kinds.get(chan as usize).and_then(Kind::seq_elem).ok_or(
20986 WasmLowerError::Unsupported("select recv arm on a channel of unknown element kind"),
20987 )?;
20988 local_get(code, da);
20989 code.push(0x42); leb_i64(code, -1);
20991 code.push(0x51); local_get(code, chan as u32);
20993 i32_load(code, 0); i32_const(code, 0);
20995 code.push(0x4A); code.push(0x71); code.push(0x04);
20998 code.push(0x40); emit_pop_front(code, elem, chan as u32, plan.num_regs + 5, var as u32)?;
21000 code.push(0x42); leb_i64(code, i as i64);
21002 local_set(code, da);
21003 code.push(0x0B); }
21005 }
21006
21007 local_get(code, da);
21009 code.push(0x42); leb_i64(code, -1);
21011 code.push(0x51); code.push(0x04);
21013 code.push(0x40); match timeout_idx {
21015 Some(ti) => {
21016 code.push(0x42); leb_i64(code, ti as i64);
21018 local_set(code, da);
21019 }
21020 None => code.push(0x00), }
21022 code.push(0x0B); Ok(())
21024}
21025
21026fn i64c(code: &mut Vec<u8>, v: i64) {
21028 code.push(0x42);
21029 leb_i64(code, v);
21030}
21031
21032fn lower_magic_div(
21038 code: &mut Vec<u8>,
21039 num_regs: u32,
21040 dst: u16,
21041 lhs: u16,
21042 magic: u64,
21043 more: u8,
21044 mul_back: i64,
21045) {
21046 const SHIFT_MASK: u8 = 0x3F;
21047 const ADD_MARKER: u8 = 0x40;
21048 const SHIFT_PATH: u8 = 0x80;
21049 let shift = (more & SHIFT_MASK) as i64;
21050 let q = num_regs + 1; let n_lo = num_regs + 2;
21052 let n_hi = num_regs + 3;
21053 let hi = num_regs + 4;
21054 let mask: i64 = 0xFFFF_FFFF;
21055
21056 if more & SHIFT_PATH != 0 {
21057 local_get(code, lhs as u32);
21059 i64c(code, shift);
21060 code.push(0x88); local_set(code, q);
21062 } else {
21063 local_get(code, lhs as u32);
21065 i64c(code, mask);
21066 code.push(0x83); local_set(code, n_lo);
21068 local_get(code, lhs as u32);
21069 i64c(code, 32);
21070 code.push(0x88); local_set(code, n_hi);
21072 let m_lo = (magic & 0xFFFF_FFFF) as i64;
21073 let m_hi = (magic >> 32) as i64;
21074 i64c(code, m_lo);
21076 local_get(code, n_lo);
21077 code.push(0x7E); i64c(code, 32);
21079 code.push(0x88); i64c(code, m_hi);
21081 local_get(code, n_lo);
21082 code.push(0x7E);
21083 i64c(code, mask);
21084 code.push(0x83); code.push(0x7C); i64c(code, m_lo);
21087 local_get(code, n_hi);
21088 code.push(0x7E);
21089 i64c(code, mask);
21090 code.push(0x83);
21091 code.push(0x7C); local_set(code, q); i64c(code, m_hi);
21095 local_get(code, n_hi);
21096 code.push(0x7E); i64c(code, m_hi);
21098 local_get(code, n_lo);
21099 code.push(0x7E);
21100 i64c(code, 32);
21101 code.push(0x88);
21102 code.push(0x7C); i64c(code, m_lo);
21104 local_get(code, n_hi);
21105 code.push(0x7E);
21106 i64c(code, 32);
21107 code.push(0x88);
21108 code.push(0x7C); local_get(code, q);
21110 i64c(code, 32);
21111 code.push(0x88);
21112 code.push(0x7C); local_set(code, hi);
21114 if more & ADD_MARKER != 0 {
21115 local_get(code, lhs as u32);
21117 local_get(code, hi);
21118 code.push(0x7D); i64c(code, 1);
21120 code.push(0x88); local_get(code, hi);
21122 code.push(0x7C); i64c(code, shift);
21124 code.push(0x88); local_set(code, q);
21126 } else {
21127 local_get(code, hi);
21129 i64c(code, shift);
21130 code.push(0x88);
21131 local_set(code, q);
21132 }
21133 }
21134
21135 if mul_back == 0 {
21136 local_get(code, q);
21137 local_set(code, dst as u32);
21138 } else {
21139 local_get(code, lhs as u32);
21141 local_get(code, q);
21142 i64c(code, mul_back);
21143 code.push(0x7E); code.push(0x7D); local_set(code, dst as u32);
21146 }
21147}
21148
21149fn lower_exact_div(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, lhs: u16, rhs: u16) {
21154 let (num, den, a, b) = (num_regs + 1, num_regs + 2, num_regs + 3, num_regs + 4);
21155 let (handle, data) = (num_regs + 5, num_regs + 6);
21156 local_get(code, rhs as u32);
21158 code.push(0x50); code.push(0x04);
21160 code.push(0x40);
21161 code.push(0x00); code.push(0x0B);
21163 local_get(code, lhs as u32);
21165 local_set(code, num);
21166 local_get(code, rhs as u32);
21167 local_set(code, den);
21168 local_get(code, den);
21170 i64c(code, 0);
21171 code.push(0x53); code.push(0x04);
21173 code.push(0x40);
21174 i64c(code, 0);
21175 local_get(code, num);
21176 code.push(0x7D); local_set(code, num);
21178 i64c(code, 0);
21179 local_get(code, den);
21180 code.push(0x7D);
21181 local_set(code, den);
21182 code.push(0x0B); local_get(code, num);
21185 local_set(code, a);
21186 local_get(code, a);
21187 i64c(code, 0);
21188 code.push(0x53); code.push(0x04);
21190 code.push(0x40);
21191 i64c(code, 0);
21192 local_get(code, a);
21193 code.push(0x7D);
21194 local_set(code, a);
21195 code.push(0x0B);
21196 local_get(code, den);
21198 local_set(code, b);
21199 code.push(0x02);
21200 code.push(0x40); code.push(0x03);
21202 code.push(0x40); local_get(code, b);
21204 code.push(0x50); code.push(0x0D);
21206 leb_u32(code, 1); local_get(code, a);
21208 local_get(code, b);
21209 code.push(0x81); local_get(code, b);
21211 local_set(code, a); local_set(code, b); code.push(0x0C);
21214 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); local_get(code, num);
21219 local_get(code, a);
21220 code.push(0x7F); local_set(code, num);
21222 local_get(code, den);
21223 local_get(code, a);
21224 code.push(0x7F);
21225 local_set(code, den);
21226 i32_const(code, 16);
21228 emit_alloc(code, ctx, handle, AllocClass::ScalarHeader);
21229 i32_const(code, 16);
21230 emit_alloc(code, ctx, data, AllocClass::Raw);
21231 for off in [0u32, 4] {
21232 local_get(code, handle);
21233 i32_const(code, 2);
21234 i32_store(code, off);
21235 }
21236 local_get(code, handle);
21237 local_get(code, data);
21238 i32_store(code, 8);
21239 local_get(code, data);
21240 local_get(code, num);
21241 i64_store(code, 0);
21242 local_get(code, data);
21243 local_get(code, den);
21244 i64_store(code, 8);
21245 local_get(code, handle);
21246 local_set(code, dst as u32);
21247}
21248
21249fn emit_byte_copy(
21253 code: &mut Vec<u8>,
21254 idx: u32,
21255 dest_data: u32,
21256 a_for_offset: u32,
21257 src: u32,
21258 offset_by_a: bool,
21259) {
21260 i32_const(code, 0);
21261 local_set(code, idx);
21262 code.push(0x02);
21263 code.push(0x40); code.push(0x03);
21265 code.push(0x40); local_get(code, idx);
21267 local_get(code, src);
21268 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
21271 leb_u32(code, 1); local_get(code, dest_data);
21274 if offset_by_a {
21275 local_get(code, a_for_offset);
21276 i32_load(code, 0); local_get(code, idx);
21278 code.push(0x6A);
21279 } else {
21280 local_get(code, idx);
21281 }
21282 code.push(0x6A);
21283 local_get(code, src);
21285 i32_load(code, 8); local_get(code, idx);
21287 code.push(0x6A);
21288 i32_load8_u(code, 0);
21289 i32_store8(code, 0);
21290 local_get(code, idx);
21292 i32_const(code, 1);
21293 code.push(0x6A);
21294 local_set(code, idx);
21295 code.push(0x0C);
21296 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); }
21300
21301fn lower_text_literal(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, bytes: &[u8]) {
21307 if let Some(pool) = ctx.text_pool {
21310 let addr = pool.borrow_mut().intern(bytes);
21311 i32_const(code, addr);
21312 return;
21313 }
21314 let len = bytes.len();
21315 let cap8 = (len + 7) & !7; let (hdr, data) = (num_regs + 5, num_regs + 6);
21317 i32_const(code, 16);
21318 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
21319 i32_const(code, cap8 as i32);
21320 emit_alloc(code, ctx, data, AllocClass::Raw);
21321 for c in 0..(cap8 / 8) {
21322 let mut v: u64 = 0;
21323 for j in 0..8 {
21324 if let Some(&b) = bytes.get(c * 8 + j) {
21325 v |= (b as u64) << (j * 8);
21326 }
21327 }
21328 local_get(code, data);
21329 code.push(0x42); leb_i64(code, v as i64);
21331 i64_store(code, (c * 8) as u32);
21332 }
21333 local_get(code, hdr);
21334 i32_const(code, len as i32);
21335 i32_store(code, 0); local_get(code, hdr);
21337 i32_const(code, len as i32);
21338 i32_store(code, 4); local_get(code, hdr);
21340 local_get(code, data);
21341 i32_store(code, 8); local_get(code, hdr); }
21344
21345fn lower_chr(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, arg: u16) {
21351 let c = num_regs + 1; let packed = num_regs + 2; let len = num_regs + 7; let (hdr, data) = (num_regs + 5, num_regs + 6);
21355 let cont = |code: &mut Vec<u8>, shift: i64, pos: i64| {
21357 local_get(code, c);
21358 i64c(code, shift);
21359 code.push(0x88); i64c(code, 0x3F);
21361 code.push(0x83); i64c(code, 0x80);
21363 code.push(0x84); i64c(code, pos);
21365 code.push(0x86); };
21367 let lead = |code: &mut Vec<u8>, shift: i64, mask: i64| {
21369 local_get(code, c);
21370 i64c(code, shift);
21371 code.push(0x88); i64c(code, mask);
21373 code.push(0x84); };
21375 local_get(code, arg as u32);
21377 local_set(code, c);
21378 local_get(code, c);
21380 i64c(code, 0x10FFFF);
21381 code.push(0x56); local_get(code, c);
21383 i64c(code, 0xD800);
21384 code.push(0x5A); local_get(code, c);
21386 i64c(code, 0xDFFF);
21387 code.push(0x58); code.push(0x71); code.push(0x72); code.push(0x04);
21391 code.push(0x40); code.push(0x00); code.push(0x0B); local_get(code, c);
21396 i64c(code, 0x80);
21397 code.push(0x54); code.push(0x04);
21399 code.push(0x40); local_get(code, c);
21401 local_set(code, packed);
21402 i32_const(code, 1);
21403 local_set(code, len);
21404 code.push(0x05); local_get(code, c);
21407 i64c(code, 0x800);
21408 code.push(0x54); code.push(0x04);
21410 code.push(0x40); lead(code, 6, 0xC0);
21412 cont(code, 0, 8);
21413 code.push(0x84); local_set(code, packed);
21415 i32_const(code, 2);
21416 local_set(code, len);
21417 code.push(0x05); local_get(code, c);
21420 i64c(code, 0x10000);
21421 code.push(0x54); code.push(0x04);
21423 code.push(0x40); lead(code, 12, 0xE0);
21425 cont(code, 6, 8);
21426 code.push(0x84); cont(code, 0, 16);
21428 code.push(0x84); local_set(code, packed);
21430 i32_const(code, 3);
21431 local_set(code, len);
21432 code.push(0x05); lead(code, 18, 0xF0);
21434 cont(code, 12, 8);
21435 code.push(0x84); cont(code, 6, 16);
21437 code.push(0x84); cont(code, 0, 24);
21439 code.push(0x84); local_set(code, packed);
21441 i32_const(code, 4);
21442 local_set(code, len);
21443 code.push(0x0B); code.push(0x0B); code.push(0x0B); i32_const(code, 16);
21448 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
21449 i32_const(code, 8);
21450 emit_alloc(code, ctx, data, AllocClass::Raw);
21451 local_get(code, data);
21452 local_get(code, packed);
21453 i64_store(code, 0); local_get(code, hdr);
21455 local_get(code, len);
21456 i32_store(code, 0); local_get(code, hdr);
21458 local_get(code, len);
21459 i32_store(code, 4); local_get(code, hdr);
21461 local_get(code, data);
21462 i32_store(code, 8); local_get(code, hdr);
21464 local_set(code, dst as u32);
21465}
21466
21467fn lower_seq_concat(
21470 code: &mut Vec<u8>,
21471 kinds: &KindTable,
21472 ctx: &Ctx,
21473 num_regs: u32,
21474 dst: u16,
21475 lhs: u16,
21476 rhs: u16,
21477) -> R<()> {
21478 let elem = seq_elem_kind(kinds, lhs)?;
21479 seq_elem_kind(kinds, rhs)?;
21480 let (a, b) = (lhs as u32, rhs as u32);
21481 let exact_ints = elem == Kind::Int && ctx.exact.sequence_ints();
21482 if exact_ints {
21483 exact::promote_sequence(code, ctx, num_regs, lhs as u32)?;
21484 exact::promote_sequence(code, ctx, num_regs, rhs as u32)?;
21485 }
21486 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
21487 i32_const(code, 16);
21489 emit_alloc(
21490 code,
21491 ctx,
21492 hdr,
21493 if exact_ints {
21494 AllocClass::ExactIntegerHeader
21495 } else {
21496 AllocClass::of_elements(kind_is_handle(elem))
21497 },
21498 );
21499 local_get(code, a);
21500 i32_load(code, 0);
21501 local_get(code, b);
21502 i32_load(code, 0);
21503 code.push(0x6A); i32_const(code, 8);
21505 code.push(0x6C);
21506 emit_alloc(code, ctx, data, AllocClass::Raw);
21507 emit_seq_copy(code, idx, data, a, a, false);
21509 emit_seq_copy(code, idx, data, a, b, true);
21511 for off in [0u32, 4] {
21513 local_get(code, hdr);
21514 local_get(code, a);
21515 i32_load(code, 0);
21516 local_get(code, b);
21517 i32_load(code, 0);
21518 code.push(0x6A);
21519 i32_store(code, off);
21520 }
21521 local_get(code, hdr);
21522 local_get(code, data);
21523 i32_store(code, 8);
21524 if kind_is_handle(elem) {
21526 emit_retain_children(code, ctx, hdr);
21527 }
21528 if exact_ints {
21529 let clone = (ctx.host_index)(HostFn::ExactClone)
21530 .ok_or(WasmLowerError::Unsupported("exact clone import"))?;
21531 emit_exact_buffer_holds(code, hdr, num_regs + 21, num_regs + 22, clone, true);
21532 }
21533 local_get(code, hdr);
21534 local_set(code, dst as u32);
21535 Ok(())
21536}
21537
21538fn emit_seq_copy(
21542 code: &mut Vec<u8>,
21543 idx: u32,
21544 dest_data: u32,
21545 a_for_offset: u32,
21546 src: u32,
21547 offset_by_a: bool,
21548) {
21549 i32_const(code, 0);
21550 local_set(code, idx);
21551 code.push(0x02);
21552 code.push(0x40); code.push(0x03);
21554 code.push(0x40); local_get(code, idx);
21556 local_get(code, src);
21557 i32_load(code, 0); code.push(0x4E); code.push(0x0D);
21560 leb_u32(code, 1); local_get(code, dest_data);
21563 if offset_by_a {
21564 local_get(code, a_for_offset);
21565 i32_load(code, 0); local_get(code, idx);
21567 code.push(0x6A); } else {
21569 local_get(code, idx);
21570 }
21571 i32_const(code, 8);
21572 code.push(0x6C);
21573 code.push(0x6A);
21574 local_get(code, src);
21576 i32_load(code, 8);
21577 local_get(code, idx);
21578 i32_const(code, 8);
21579 code.push(0x6C);
21580 code.push(0x6A);
21581 i64_load(code, 0);
21582 i64_store(code, 0);
21583 local_get(code, idx);
21585 i32_const(code, 1);
21586 code.push(0x6A);
21587 local_set(code, idx);
21588 code.push(0x0C);
21589 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); }
21593
21594fn lower_slice(
21600 code: &mut Vec<u8>,
21601 kinds: &KindTable,
21602 ctx: &Ctx,
21603 num_regs: u32,
21604 dst: u16,
21605 collection: u16,
21606 start: u16,
21607 end: u16,
21608) -> R<()> {
21609 let elem = seq_elem_kind(kinds, collection)?; let col = collection as u32;
21611 let (s0, ee) = (num_regs + 1, num_regs + 2); let exact_ints = elem == Kind::Int && ctx.exact.sequence_ints();
21613 if exact_ints {
21614 exact::promote_sequence(code, ctx, num_regs, collection as u32)?;
21615 }
21616 let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7); i32_const(code, 16);
21619 emit_alloc(
21620 code,
21621 ctx,
21622 hdr,
21623 if exact_ints {
21624 AllocClass::ExactIntegerHeader
21625 } else {
21626 AllocClass::of_elements(kind_is_handle(elem))
21627 },
21628 );
21629 code.push(0x42);
21631 leb_i64(code, 0); local_get(code, start as u32);
21633 code.push(0x42);
21634 leb_i64(code, 1);
21635 code.push(0x7D); local_get(code, start as u32);
21637 code.push(0x50); code.push(0x1B); local_set(code, s0);
21640 local_get(code, end as u32);
21642 local_set(code, ee);
21643 local_get(code, s0);
21645 local_get(code, ee);
21646 code.push(0x54); local_get(code, ee);
21648 local_get(code, col);
21649 i32_load(code, 0); code.push(0xAD); code.push(0x58); code.push(0x71); code.push(0x04);
21654 code.push(0x40); {
21656 local_get(code, ee);
21658 local_get(code, s0);
21659 code.push(0x7D);
21660 code.push(0xA7); i32_const(code, 8);
21662 code.push(0x6C);
21663 emit_alloc(code, ctx, data, AllocClass::Raw);
21664 i32_const(code, 0);
21666 local_set(code, idx);
21667 code.push(0x02);
21668 code.push(0x40); code.push(0x03);
21670 code.push(0x40); local_get(code, idx);
21672 local_get(code, ee);
21673 local_get(code, s0);
21674 code.push(0x7D);
21675 code.push(0xA7); code.push(0x4E); code.push(0x0D);
21678 leb_u32(code, 1); local_get(code, data);
21681 local_get(code, idx);
21682 i32_const(code, 8);
21683 code.push(0x6C);
21684 code.push(0x6A);
21685 local_get(code, col);
21687 i32_load(code, 8);
21688 local_get(code, s0);
21689 code.push(0xA7); local_get(code, idx);
21691 code.push(0x6A); i32_const(code, 8);
21693 code.push(0x6C);
21694 code.push(0x6A);
21695 i64_load(code, 0);
21696 i64_store(code, 0);
21697 local_get(code, idx);
21699 i32_const(code, 1);
21700 code.push(0x6A);
21701 local_set(code, idx);
21702 code.push(0x0C);
21703 leb_u32(code, 0); code.push(0x0B); code.push(0x0B); for off in [0u32, 4] {
21708 local_get(code, hdr);
21709 local_get(code, ee);
21710 local_get(code, s0);
21711 code.push(0x7D);
21712 code.push(0xA7);
21713 i32_store(code, off);
21714 }
21715 local_get(code, hdr);
21716 local_get(code, data);
21717 i32_store(code, 8);
21718 }
21719 code.push(0x05); for off in [0u32, 4, 8] {
21721 local_get(code, hdr);
21722 i32_const(code, 0);
21723 i32_store(code, off);
21724 }
21725 code.push(0x0B); if kind_is_handle(elem) {
21728 emit_retain_children(code, ctx, hdr);
21729 }
21730 if exact_ints {
21731 let clone = (ctx.host_index)(HostFn::ExactClone)
21732 .ok_or(WasmLowerError::Unsupported("exact clone import"))?;
21733 emit_exact_buffer_holds(code, hdr, num_regs + 21, num_regs + 22, clone, true);
21734 }
21735 local_get(code, hdr);
21736 local_set(code, dst as u32);
21737 Ok(())
21738}
21739
21740const FRAME_LEN: u32 = 0;
21753const FRAME_CURSOR: u32 = 4;
21754const FRAME_PREV: u32 = 8;
21755const FRAME_SIZE: u32 = 12;
21756const FRAME_KIND: u32 = 16; const FRAME_PAYLOAD: u32 = 24;
21758
21759fn runs_loops(plan: &Plan) -> bool {
21761 plan.ops
21762 .iter()
21763 .any(|op| matches!(op, Op::IterPrepare { .. }))
21764}
21765
21766fn loop_base_local(plan: &Plan) -> u32 {
21769 plan.num_regs + 24
21770}
21771
21772fn emit_leave_loops(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx) {
21776 if !runs_loops(plan) {
21777 return;
21778 }
21779 local_get(code, loop_base_local(plan));
21780 match ctx.runtime.and_then(|r| r.index(RuntimeFn::IterUnwind)) {
21781 Some(unwind) => {
21782 code.push(0x10); leb_u32(code, unwind);
21784 }
21785 None => global_set(code, ctx.iter_global),
21786 }
21787}
21788
21789fn emit_iter_unwind_helper(env: &RuntimeEnv) -> Vec<u8> {
21791 let mut c = Vec::new();
21792 c.push(0x01);
21794 leb_u32(&mut c, 4);
21795 c.push(I32);
21796 c.push(0x02);
21797 c.push(0x40); c.push(0x03);
21799 c.push(0x40); global_get(&mut c, env.iter_global);
21801 local_tee(&mut c, 1);
21802 local_get(&mut c, 0);
21803 c.push(0x46); local_get(&mut c, 1);
21805 c.push(0x45); c.push(0x72); c.push(0x0D);
21808 leb_u32(&mut c, 1); if env.retain_base.is_some() {
21810 local_get(&mut c, 1);
21811 i32_load(&mut c, FRAME_KIND);
21812 c.push(0x04);
21813 c.push(0x40);
21814 i32_const(&mut c, 1);
21815 local_get(&mut c, 1);
21816 i32_load(&mut c, FRAME_LEN);
21817 local_get(&mut c, 1);
21818 i32_load(&mut c, FRAME_KIND);
21819 i32_const(&mut c, 1);
21820 c.push(0x46);
21821 c.push(0x1B); local_set(&mut c, 3);
21823 i32_const(&mut c, 0);
21824 local_set(&mut c, 2);
21825 c.push(0x02);
21826 c.push(0x40);
21827 c.push(0x03);
21828 c.push(0x40);
21829 local_get(&mut c, 2);
21830 local_get(&mut c, 3);
21831 c.push(0x4F);
21832 c.push(0x0D);
21833 leb_u32(&mut c, 1);
21834 local_get(&mut c, 1);
21835 local_get(&mut c, 2);
21836 i32_const(&mut c, 8);
21837 c.push(0x6C);
21838 c.push(0x6A);
21839 if let Some(drop) = env.exact_drop {
21840 local_set(&mut c, 4);
21841 local_get(&mut c, 1);
21842 i32_load(&mut c, FRAME_KIND);
21843 i32_const(&mut c, 3);
21844 c.extend([0x46, 0x04, 0x40]);
21845 local_get(&mut c, 4);
21846 i64_load(&mut c, FRAME_PAYLOAD);
21847 c.push(0x42);
21848 leb_i64(&mut c, 1);
21849 c.extend([0x83, 0xa7, 0x04, 0x40]);
21850 local_get(&mut c, 4);
21851 i64_load(&mut c, FRAME_PAYLOAD);
21852 c.push(0x10);
21853 leb_u32(&mut c, drop);
21854 c.extend([0x0b, 0x05]);
21855 local_get(&mut c, 4);
21856 i32_load(&mut c, FRAME_PAYLOAD);
21857 c.push(0x10);
21858 leb_u32(&mut c, env.call(RuntimeFn::Release));
21859 c.push(0x0b);
21860 } else {
21861 i32_load(&mut c, FRAME_PAYLOAD);
21862 c.push(0x10);
21863 leb_u32(&mut c, env.call(RuntimeFn::Release));
21864 }
21865 local_get(&mut c, 2);
21866 i32_const(&mut c, 1);
21867 c.push(0x6A);
21868 local_set(&mut c, 2);
21869 c.push(0x0C);
21870 leb_u32(&mut c, 0);
21871 c.push(0x0B);
21872 c.push(0x0B);
21873 c.push(0x0B);
21874 }
21875 local_get(&mut c, 1);
21876 i32_load(&mut c, FRAME_PREV);
21877 global_set(&mut c, env.iter_global);
21878 local_get(&mut c, 1);
21879 local_get(&mut c, 1);
21880 i32_load(&mut c, FRAME_SIZE);
21881 c.push(0x10); leb_u32(&mut c, env.call(RuntimeFn::Free));
21883 c.push(0x0C);
21884 leb_u32(&mut c, 0); c.push(0x0B);
21886 c.push(0x0B);
21887 c.push(0x0B); c
21889}
21890
21891fn lower_range_iter_prepare(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, start: u16, end: u16) {
21893 let frame = num_regs + 5;
21894 i32_const(code, FRAME_PAYLOAD as i32 + 16);
21895 emit_alloc(code, ctx, frame, AllocClass::Raw);
21896 local_get(code, frame);
21897 local_get(code, start as u32);
21898 i64_store(code, FRAME_PAYLOAD);
21899 local_get(code, frame);
21900 local_get(code, end as u32);
21901 i64_store(code, FRAME_PAYLOAD + 8);
21902 local_get(code, frame);
21904 local_get(code, start as u32);
21905 local_get(code, end as u32);
21906 code.push(0x57); i32_store(code, FRAME_LEN);
21908 local_get(code, frame);
21909 i32_const(code, 0);
21910 i32_store(code, FRAME_CURSOR);
21911 local_get(code, frame);
21912 i32_const(code, 0);
21913 i32_store(code, FRAME_KIND);
21914 local_get(code, frame);
21915 i32_const(code, FRAME_PAYLOAD as i32 + 16);
21916 i32_store(code, FRAME_SIZE);
21917 local_get(code, frame);
21918 global_get(code, ctx.iter_global);
21919 i32_store(code, FRAME_PREV);
21920 local_get(code, frame);
21921 global_set(code, ctx.iter_global);
21922}
21923
21924#[allow(clippy::too_many_arguments)]
21925fn lower_range_iter_next(
21926 code: &mut Vec<u8>,
21927 plan: &Plan,
21928 ctx: &Ctx,
21929 blocks: &Blocks,
21930 k: usize,
21931 dst: u16,
21932 exit: usize,
21933 pc: usize,
21934) -> R<()> {
21935 global_get(code, ctx.iter_global);
21936 i32_load(code, FRAME_LEN);
21937 code.push(0x04);
21938 code.push(0x40);
21939 global_get(code, ctx.iter_global);
21940 i64_load(code, FRAME_PAYLOAD);
21941 exact::set_word(code, plan, ctx, dst)?;
21942 global_get(code, ctx.iter_global);
21944 i64_load(code, FRAME_PAYLOAD);
21945 global_get(code, ctx.iter_global);
21946 i64_load(code, FRAME_PAYLOAD + 8);
21947 code.push(0x51); code.push(0x04);
21949 code.push(0x40);
21950 global_get(code, ctx.iter_global);
21951 i32_const(code, 0);
21952 i32_store(code, FRAME_LEN);
21953 code.push(0x05);
21954 global_get(code, ctx.iter_global);
21955 global_get(code, ctx.iter_global);
21956 i64_load(code, FRAME_PAYLOAD);
21957 code.push(0x42);
21958 leb_i64(code, 1);
21959 code.push(0x7C);
21960 i64_store(code, FRAME_PAYLOAD);
21961 code.push(0x0B);
21962 set_next_block(code, plan.num_regs, blocks.block_of(pc + 1));
21963 code.push(0x05);
21964 set_next_block(code, plan.num_regs, blocks.block_of(exit));
21965 code.push(0x0B);
21966 code.push(0x0C);
21967 leb_u32(code, blocks.br_loop(k));
21968 Ok(())
21969}
21970
21971fn lower_iter_prepare(
21973 code: &mut Vec<u8>,
21974 kinds: &KindTable,
21975 ctx: &Ctx,
21976 num_regs: u32,
21977 iterable: u16,
21978) -> R<()> {
21979 let exact_ints =
21980 ctx.exact.sequence_ints() && kinds.get(iterable as usize) == Some(Kind::SeqInt);
21981 if exact_ints {
21982 exact::promote_sequence(code, ctx, num_regs, iterable as u32)?;
21983 }
21984 let it = iterable as u32;
21985 let (frame, idx) = (num_regs + 5, num_regs + 6); let text = kinds.get(iterable as usize) == Some(Kind::Text);
21987 let handles = empty_collection_class(kinds.get(iterable as usize))
21988 .held_handles()
21989 .0;
21990 if !text
21991 && !kinds
21992 .get(iterable as usize)
21993 .map(Kind::is_seq)
21994 .unwrap_or(false)
21995 {
21996 return Err(WasmLowerError::Unsupported(
21997 "iteration over a value that is neither a sequence nor a Text",
21998 ));
21999 }
22000 if text {
22001 i32_const(code, FRAME_PAYLOAD as i32 + 8);
22002 emit_alloc(code, ctx, frame, AllocClass::Raw);
22003 local_get(code, frame);
22004 local_get(code, it);
22005 i32_store(code, FRAME_PAYLOAD);
22006 emit_true_retain(code, ctx, iterable);
22007 } else {
22008 local_get(code, it);
22010 i32_load(code, 0);
22011 i32_const(code, 8);
22012 code.push(0x6C);
22013 i32_const(code, FRAME_PAYLOAD as i32);
22014 code.push(0x6A);
22015 emit_alloc(code, ctx, frame, AllocClass::Raw);
22016 i32_const(code, 0);
22017 local_set(code, idx);
22018 code.push(0x02);
22019 code.push(0x40); code.push(0x03);
22021 code.push(0x40); local_get(code, idx);
22023 local_get(code, it);
22024 i32_load(code, 0);
22025 code.push(0x4E); code.push(0x0D);
22027 leb_u32(code, 1); local_get(code, frame);
22029 local_get(code, idx);
22030 i32_const(code, 8);
22031 code.push(0x6C);
22032 code.push(0x6A);
22033 local_get(code, it);
22034 i32_load(code, 8);
22035 local_get(code, idx);
22036 i32_const(code, 8);
22037 code.push(0x6C);
22038 code.push(0x6A);
22039 i64_load(code, 0);
22040 if exact_ints {
22041 exact::clone_sequence_word(code, ctx, num_regs)?;
22042 }
22043 i64_store(code, FRAME_PAYLOAD);
22044 if handles {
22045 emit_true_retain_of(code, ctx, |c| {
22046 local_get(c, frame);
22047 local_get(c, idx);
22048 i32_const(c, 8);
22049 c.push(0x6C);
22050 c.push(0x6A);
22051 i32_load(c, FRAME_PAYLOAD);
22052 });
22053 }
22054 local_get(code, idx);
22055 i32_const(code, 1);
22056 code.push(0x6A);
22057 local_set(code, idx);
22058 code.push(0x0C);
22059 leb_u32(code, 0); code.push(0x0B);
22061 code.push(0x0B);
22062 }
22063 local_get(code, frame);
22064 i32_const(
22065 code,
22066 if text {
22067 1
22068 } else if exact_ints {
22069 3
22070 } else if handles {
22071 2
22072 } else {
22073 0
22074 },
22075 );
22076 i32_store(code, FRAME_KIND);
22077 local_get(code, frame);
22079 local_get(code, it);
22080 i32_load(code, 0);
22081 i32_store(code, FRAME_LEN);
22082 local_get(code, frame);
22083 i32_const(code, 0);
22084 i32_store(code, FRAME_CURSOR);
22085 local_get(code, frame);
22087 if text {
22088 i32_const(code, FRAME_PAYLOAD as i32 + 8);
22089 } else {
22090 local_get(code, it);
22091 i32_load(code, 0);
22092 i32_const(code, 8);
22093 code.push(0x6C);
22094 i32_const(code, FRAME_PAYLOAD as i32);
22095 code.push(0x6A);
22096 }
22097 i32_store(code, FRAME_SIZE);
22098 local_get(code, frame);
22100 global_get(code, ctx.iter_global);
22101 i32_store(code, FRAME_PREV);
22102 local_get(code, frame);
22103 global_set(code, ctx.iter_global);
22104 Ok(())
22105}
22106
22107#[allow(clippy::too_many_arguments)]
22114fn lower_iter_next(
22115 code: &mut Vec<u8>,
22116 plan: &Plan,
22117 ctx: &Ctx,
22118 blocks: &Blocks,
22119 k: usize,
22120 dst: u16,
22121 exit: usize,
22122 pc: usize,
22123) -> R<()> {
22124 if !ctx.linked
22125 && plan
22126 .iter_iterable
22127 .get(pc)
22128 .copied()
22129 .flatten()
22130 .is_some_and(|r| plan.range_loops.contains_key(&(r as u16)))
22131 {
22132 return lower_range_iter_next(code, plan, ctx, blocks, k, dst, exit, pc);
22133 }
22134 let (kinds, num_regs) = (&plan.kinds, plan.num_regs);
22135 let text = plan
22136 .iter_iterable
22137 .get(pc)
22138 .copied()
22139 .flatten()
22140 .is_some_and(|r| kinds.get(r) == Some(Kind::Text));
22141 let ig = ctx.iter_global;
22142 let pc_local = num_regs;
22143 let fallthrough = blocks.block_of(pc + 1) as u32;
22144 let exit_block = blocks.block_of(exit) as u32;
22145 global_get(code, ig);
22147 i32_load(code, FRAME_CURSOR);
22148 global_get(code, ig);
22149 i32_load(code, FRAME_LEN);
22150 code.push(0x48); code.push(0x04);
22152 code.push(0x40); if text {
22154 let (src, bytes, hdr, buf, i) = (
22155 num_regs + 5,
22156 num_regs + 6,
22157 num_regs + 7,
22158 num_regs + 8,
22159 num_regs + 9,
22160 );
22161 global_get(code, ig);
22163 i32_load(code, FRAME_PAYLOAD);
22164 i32_load(code, 8);
22165 global_get(code, ig);
22166 i32_load(code, FRAME_CURSOR);
22167 code.push(0x6A);
22168 local_set(code, src);
22169 i32_const(code, 1);
22171 i32_const(code, 2);
22172 i32_const(code, 3);
22173 i32_const(code, 4);
22174 local_get(code, src);
22175 i32_load8_u(code, 0);
22176 i32_const(code, 0xF0);
22177 code.push(0x49); code.push(0x1B); local_get(code, src);
22180 i32_load8_u(code, 0);
22181 i32_const(code, 0xE0);
22182 code.push(0x49);
22183 code.push(0x1B); local_get(code, src);
22185 i32_load8_u(code, 0);
22186 i32_const(code, 0x80);
22187 code.push(0x49);
22188 code.push(0x1B); local_set(code, bytes);
22190 i32_const(code, 16);
22192 emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
22193 local_get(code, bytes);
22194 emit_alloc(code, ctx, buf, AllocClass::Raw);
22195 i32_const(code, 0);
22196 local_set(code, i);
22197 code.push(0x02);
22198 code.push(0x40); code.push(0x03);
22200 code.push(0x40); local_get(code, i);
22202 local_get(code, bytes);
22203 code.push(0x4E); code.push(0x0D);
22205 leb_u32(code, 1);
22206 local_get(code, buf);
22207 local_get(code, i);
22208 code.push(0x6A);
22209 local_get(code, src);
22210 local_get(code, i);
22211 code.push(0x6A);
22212 i32_load8_u(code, 0);
22213 i32_store8(code, 0);
22214 local_get(code, i);
22215 i32_const(code, 1);
22216 code.push(0x6A);
22217 local_set(code, i);
22218 code.push(0x0C);
22219 leb_u32(code, 0);
22220 code.push(0x0B);
22221 code.push(0x0B);
22222 for off in [0u32, 4] {
22223 local_get(code, hdr);
22224 local_get(code, bytes);
22225 i32_store(code, off);
22226 }
22227 local_get(code, hdr);
22228 local_get(code, buf);
22229 i32_store(code, 8);
22230 local_get(code, hdr);
22231 local_set(code, dst as u32);
22232 global_get(code, ig);
22234 global_get(code, ig);
22235 i32_load(code, FRAME_CURSOR);
22236 local_get(code, bytes);
22237 code.push(0x6A);
22238 i32_store(code, FRAME_CURSOR);
22239 } else {
22240 let elem_load: fn(&mut Vec<u8>, u32) = match kinds.get(dst as usize).map(Kind::wasm_valtype)
22243 {
22244 Some(F64) => f64_load,
22245 Some(I64) => i64_load,
22246 _ => i32_load,
22247 };
22248 global_get(code, ig);
22250 global_get(code, ig);
22251 i32_load(code, FRAME_CURSOR);
22252 i32_const(code, 8);
22253 code.push(0x6C); code.push(0x6A); elem_load(code, FRAME_PAYLOAD);
22256 if ctx.exact.sequence_ints()
22257 && plan
22258 .iter_iterable
22259 .get(pc)
22260 .copied()
22261 .flatten()
22262 .is_some_and(|r| kinds.get(r) == Some(Kind::SeqInt))
22263 {
22264 exact::take_sequence_tagged(code, plan, ctx, dst)?;
22265 } else {
22266 exact::set_word(code, plan, ctx, dst)?;
22267 }
22268 global_get(code, ig);
22270 global_get(code, ig);
22271 i32_load(code, FRAME_CURSOR);
22272 i32_const(code, 1);
22273 code.push(0x6A); i32_store(code, FRAME_CURSOR);
22275 }
22276 set_next_block(code, pc_local, fallthrough as usize);
22278 code.push(0x05); set_next_block(code, pc_local, exit_block as usize);
22281 code.push(0x0B); code.push(0x0C); leb_u32(code, blocks.br_loop(k));
22284 Ok(())
22285}
22286
22287fn op_uses_heap(op: &Op) -> bool {
22290 matches!(
22291 op,
22292 Op::NewEmptyList { .. }
22293 | Op::NewEmptyListWithCapacity { .. }
22294 | Op::NewEmptyListI32 { .. }
22295 | Op::NewEmptyListFixed { .. }
22296 | Op::Length { .. }
22297 | Op::ListPush { .. }
22298 | Op::ListPop { .. }
22299 | Op::Index { .. }
22300 | Op::IndexUnchecked { .. }
22301 | Op::SetIndex { .. }
22302 | Op::SetIndexUnchecked { .. }
22303 | Op::ListPushField { .. }
22304 | Op::ExactDiv { .. }
22306 | Op::NewRange { .. }
22307 | Op::NewList { .. }
22308 | Op::IterPrepare { .. }
22309 | Op::IterNext { .. }
22310 | Op::IterPop
22311 | Op::Contains { .. }
22312 | Op::SliceOp { .. }
22313 | Op::SeqConcat { .. }
22314 | Op::Concat { .. }
22315 | Op::FormatValue { .. }
22316 | Op::DeepClone { .. }
22317 | Op::NewStruct { .. }
22318 | Op::StructInsert { .. }
22319 | Op::GetField { .. }
22320 | Op::CheckPolicy { .. }
22321 | Op::CrdtBump { .. }
22322 | Op::CrdtMerge { .. }
22323 | Op::CrdtJoin { .. }
22324 | Op::NewCrdt { .. }
22325 | Op::CrdtResolve { .. }
22326 | Op::CrdtAppend { .. }
22327 | Op::ChanNew { .. }
22328 | Op::ChanSend { .. }
22329 | Op::ChanRecv { .. }
22330 | Op::ChanTrySend { .. }
22332 | Op::ChanTryRecv { .. }
22333 | Op::SelectWait { .. }
22335 | Op::NetListen { .. }
22337 | Op::NetSend { .. }
22338 | Op::NetStream { .. }
22339 | Op::NetAwait { .. }
22340 | Op::NewEmptyMap { .. }
22341 | Op::NewEmptyMapWithCapacity { .. }
22342 | Op::NewEmptySet { .. }
22343 | Op::SetAdd { .. }
22344 | Op::RemoveFrom { .. }
22345 | Op::UnionOp { .. }
22346 | Op::IntersectOp { .. }
22347 | Op::NewInductive { .. }
22348 | Op::BindArm { .. }
22349 | Op::NewTuple { .. }
22350 | Op::DestructureTuple { .. }
22351 | Op::MakeClosure { .. }
22352 | Op::CallValue { .. }
22353 | Op::Args { .. }
22356 | Op::CallBuiltin { builtin: BuiltinId::Chr, .. }
22358 | Op::CallBuiltin { builtin: BuiltinId::EnvValue, .. }
22360 | Op::CallBuiltin { builtin: BuiltinId::RepeatSeq, .. }
22362 | Op::CallBuiltin { builtin: BuiltinId::TextBytes, .. }
22364 | Op::CallBuiltin { builtin: BuiltinId::UuidBytes, .. }
22365 | Op::CallBuiltin { builtin: BuiltinId::TextFromBytes, .. }
22366 | Op::CallBuiltin { builtin: BuiltinId::UuidFromBytes, .. }
22367 | Op::CallBuiltin { builtin: BuiltinId::Lanes4Of, .. }
22368 | Op::CallBuiltin { builtin: BuiltinId::Lanes4Word32Make, .. }
22369 | Op::CallBuiltin { builtin: BuiltinId::SeqOfLanes4W32, .. }
22370 | Op::CallBuiltin { builtin: BuiltinId::ReadWireProgram, .. }
22374 )
22375}
22376
22377fn encode_locals(plan: &Plan, root_count: usize) -> Vec<u8> {
22381 let mut groups: Vec<(u32, u8)> = Vec::new();
22382 let push = |vt: u8, groups: &mut Vec<(u32, u8)>| match groups.last_mut() {
22383 Some((count, t)) if *t == vt => *count += 1,
22384 _ => groups.push((1, vt)),
22385 };
22386 for r in plan.num_params..plan.num_regs {
22387 push(plan.kinds.valtype(r as usize), &mut groups);
22388 }
22389 push(I32, &mut groups); push(I64, &mut groups);
22393 push(I64, &mut groups);
22394 push(I64, &mut groups);
22395 push(I64, &mut groups);
22396 push(I32, &mut groups);
22401 push(I32, &mut groups);
22402 push(I32, &mut groups);
22403 push(I32, &mut groups);
22404 push(I32, &mut groups);
22405 push(I32, &mut groups);
22406 push(I32, &mut groups);
22407 push(F64, &mut groups);
22410 push(I32, &mut groups);
22414 push(I32, &mut groups);
22415 push(I64, &mut groups); push(I64, &mut groups); push(I32, &mut groups); push(I32, &mut groups); push(I32, &mut groups); push(I32, &mut groups); push(I32, &mut groups); push(I32, &mut groups); push(I32, &mut groups); push(I32, &mut groups); for _ in 0..exact::extra_locals(plan) {
22441 push(I64, &mut groups);
22442 }
22443 for _ in 0..absence::extra_locals(plan) {
22444 push(I32, &mut groups);
22445 }
22446 for _ in 0..tower::extra_locals(plan) {
22447 push(I32, &mut groups);
22448 }
22449 for _ in 0..root_count {
22450 push(I32, &mut groups);
22451 } let mut out = Vec::new();
22454 leb_u32(&mut out, groups.len() as u32);
22455 for (count, vt) in groups {
22456 leb_u32(&mut out, count);
22457 out.push(vt);
22458 }
22459 out
22460}
22461
22462fn encode_name(out: &mut Vec<u8>, name: &str) {
22464 leb_u32(out, name.len() as u32);
22465 out.extend_from_slice(name.as_bytes());
22466}
22467
22468fn unsupported_op(op: &Op) -> WasmLowerError {
22471 let what = match op {
22472 Op::ExactDiv { .. } => "exact division (Rational)",
22473 Op::DivPow2 { .. } | Op::MagicDivU { .. } => "oracle division op",
22474 Op::Concat { .. } => "text op",
22475 Op::IndexUnchecked { .. } => "unchecked index (IndexUnchecked)",
22476 Op::CallValue { .. } | Op::MakeClosure { .. } => "closure call",
22477 _ => "op",
22478 };
22479 WasmLowerError::Unsupported(what)
22480}
22481
22482#[cfg(test)]
22483#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/vm/wasm/module/alloc_class_tests.rs"]
22484mod alloc_class_tests;
22485
22486#[cfg(test)]
22487#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/vm/wasm/module/transient_reads_tests.rs"]
22488mod transient_reads_tests;
22489
22490#[cfg(test)]
22491#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/vm/wasm/module/range_storage_tests.rs"]
22492mod range_storage_tests;