wardite 0.9.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +191 -0
  3. data/Makefile +14 -0
  4. data/README.md +107 -2
  5. data/Rakefile +5 -0
  6. data/Steepfile +1 -0
  7. data/assets/wardite.svg +12 -0
  8. data/benchmark/README.md +500 -0
  9. data/benchmark/build_call_profile.rb +42 -0
  10. data/benchmark/call_cost_worker.rb +27 -0
  11. data/benchmark/compare.rb +93 -0
  12. data/benchmark/compare_call_types.rb +212 -0
  13. data/benchmark/compare_dispatch.rb +123 -0
  14. data/benchmark/compare_engines.rb +119 -0
  15. data/benchmark/compare_optimizations.rb +139 -0
  16. data/benchmark/engine_phases.rb +30 -0
  17. data/benchmark/figures/README.md +35 -0
  18. data/benchmark/figures/plot_spinel_comparison.py +137 -0
  19. data/benchmark/figures/spinel_new_vm_candlestick.png +0 -0
  20. data/benchmark/figures/spinel_new_vm_candlestick.svg +7615 -0
  21. data/benchmark/figures/spinel_new_vm_summary.csv +9 -0
  22. data/benchmark/figures/spinel_new_vm_summary.json +82 -0
  23. data/benchmark/float_m5.wat +42 -0
  24. data/benchmark/i32_call_arities.wat +89 -0
  25. data/benchmark/i32_calls.wat +174 -0
  26. data/benchmark/i32_memory.wat +58 -0
  27. data/benchmark/i32_mix.wat +80 -0
  28. data/benchmark/i64_m4.wat +55 -0
  29. data/benchmark/investigate_calls.rb +231 -0
  30. data/benchmark/investigate_generated_guards.rb +218 -0
  31. data/benchmark/m3_call_worker.rb +38 -0
  32. data/benchmark/measure_m1.rb +51 -0
  33. data/benchmark/measure_m2.rb +55 -0
  34. data/benchmark/measure_m3_calls.rb +89 -0
  35. data/benchmark/measure_m4.rb +134 -0
  36. data/benchmark/measure_m5_boundary.rb +41 -0
  37. data/benchmark/measure_mir_cache_verify.rb +58 -0
  38. data/benchmark/measure_ruby_wasm_cache_hit.rb +59 -0
  39. data/benchmark/measure_ruby_wasm_startup.rb +43 -0
  40. data/benchmark/measure_wasi_write.rb +75 -0
  41. data/benchmark/optimization_worker.rb +23 -0
  42. data/benchmark/results/call_arities_exploratory_2026-11-04.json +4320 -0
  43. data/benchmark/results/call_arities_spinel_2026-11-04.json +1200 -0
  44. data/benchmark/results/call_cost_spinel_2026-11-04.json +2392 -0
  45. data/benchmark/results/call_protocol_exploratory_2026-11-04.json +3947 -0
  46. data/benchmark/results/call_protocol_profile_2026-11-04.json +383 -0
  47. data/benchmark/results/call_protocol_ruby_2026-11-04.json +1213 -0
  48. data/benchmark/results/call_protocol_spinel_2026-11-04.json +913 -0
  49. data/benchmark/results/call_types_ruby_2026-11-04.json +1212 -0
  50. data/benchmark/results/call_types_spinel_2026-11-04.json +923 -0
  51. data/benchmark/results/efflorescence-m1-cruby.json +799 -0
  52. data/benchmark/results/efflorescence-m1-spinel.json +799 -0
  53. data/benchmark/results/efflorescence-m2-bulk-loop.json +820 -0
  54. data/benchmark/results/efflorescence-m2-i32-cruby.json +799 -0
  55. data/benchmark/results/efflorescence-m2-i32-spinel.json +799 -0
  56. data/benchmark/results/efflorescence-m2-memory.json +408 -0
  57. data/benchmark/results/efflorescence-mir2-cache-integrity.json +390 -0
  58. data/benchmark/results/efflorescence-unboxed-globals.json +3451 -0
  59. data/benchmark/results/generated_guards_exploratory_2026-11-04.json +1225 -0
  60. data/benchmark/results/generated_guards_profile_2026-11-04.json +592 -0
  61. data/benchmark/results/generated_guards_spinel_2026-11-04.json +1650 -0
  62. data/benchmark/results/generated_guards_validation_2026-11-04.json +256 -0
  63. data/benchmark/results/inlining_engines_2026-11-04.json +241 -0
  64. data/benchmark/results/inlining_ruby_2026-11-04.json +1213 -0
  65. data/benchmark/results/inlining_spinel_2026-11-04.json +893 -0
  66. data/benchmark/results/operand_decode_exploratory_2026-11-04.json +1319 -0
  67. data/benchmark/results/operand_decode_ruby_2026-11-04.json +1213 -0
  68. data/benchmark/results/operand_decode_spinel_2026-11-04.json +924 -0
  69. data/benchmark/results/selective_reset_spinel_2026-11-04.json +454 -0
  70. data/benchmark/results/selective_reset_spinel_2026-11-04_exploratory.json +2679 -0
  71. data/benchmark/results/spinel_fetch_root_patch_2026-11-04.json +4523 -0
  72. data/benchmark/results/while_final_compiler_comparison_2026-11-04.json +324 -0
  73. data/benchmark/results/while_patched_external_2026-11-04.json +220 -0
  74. data/benchmark/results/while_user_unpatched_2026-11-04.json +230 -0
  75. data/benchmark/summarize_call_profile.py +54 -0
  76. data/benchmark/validate_m1_eh.rb +34 -0
  77. data/benchmark/validate_m2.rb +119 -0
  78. data/benchmark/validate_m3.rb +44 -0
  79. data/benchmark/validate_m4.rb +95 -0
  80. data/benchmark/validate_m5.rb +108 -0
  81. data/docs/adr/0001-efflorescence-m1-control-and-eh.md +319 -0
  82. data/docs/adr/0002-efflorescence-m2-memory-and-globals.md +185 -0
  83. data/docs/adr/0003-efflorescence-m3-host-and-indirect-calls.md +228 -0
  84. data/docs/adr/0004-efflorescence-m4-i64.md +202 -0
  85. data/docs/adr/0005-efflorescence-m5-floating-point.md +127 -0
  86. data/docs/adr/0006-efflorescence-m6-coverage-parity.md +101 -0
  87. data/docs/adr/0007-efflorescence-ruby-wasm-phase1.md +75 -0
  88. data/docs/adr/0008-efflorescence-ruby-wasm-phase2.md +75 -0
  89. data/docs/adr/0009-efflorescence-mir2-cache-integrity-modes.md +77 -0
  90. data/docs/adr/0010-efflorescence-mir2-cache-function-restore.md +80 -0
  91. data/docs/adr/0011-efflorescence-unboxed-globals.md +89 -0
  92. data/docs/adr/0012-efflorescence-startup-snapshot.md +173 -0
  93. data/docs/adr/0013-efflorescence-frame-acquisition.md +114 -0
  94. data/docs/efflorescence-call-arities.md +115 -0
  95. data/docs/efflorescence-call-investigation.md +155 -0
  96. data/docs/efflorescence-call-transfer.md +128 -0
  97. data/docs/efflorescence-call-types.md +102 -0
  98. data/docs/efflorescence-coverage-ja.md +351 -0
  99. data/docs/efflorescence-generated-c-guards.md +410 -0
  100. data/docs/efflorescence-inlining.md +165 -0
  101. data/docs/efflorescence-ja.md +155 -0
  102. data/docs/efflorescence-m1.md +160 -0
  103. data/docs/efflorescence-m2.md +233 -0
  104. data/docs/efflorescence-m3.md +131 -0
  105. data/docs/efflorescence-m4.md +88 -0
  106. data/docs/efflorescence-m5.md +82 -0
  107. data/docs/efflorescence-m6.md +95 -0
  108. data/docs/efflorescence-mir2-cache.md +123 -0
  109. data/docs/efflorescence-operand-decoding.md +105 -0
  110. data/docs/efflorescence-phase2-ja.md +225 -0
  111. data/docs/efflorescence-phase2.md +240 -0
  112. data/docs/efflorescence-register-initialization.md +75 -0
  113. data/docs/efflorescence-ruby-wasm-phase1.md +90 -0
  114. data/docs/efflorescence-spinel-linear-memory.md +72 -0
  115. data/docs/efflorescence-startup-snapshot.md +60 -0
  116. data/docs/efflorescence-unboxed-globals.md +61 -0
  117. data/docs/efflorescence.md +144 -0
  118. data/docs/spinel-string-aset-inplace-proposal.md +200 -0
  119. data/lib/wardite/alu_f32.generated.rb +11 -2
  120. data/lib/wardite/alu_f64.generated.rb +11 -2
  121. data/lib/wardite/alu_i32.generated.rb +54 -17
  122. data/lib/wardite/alu_i64.generated.rb +73 -31
  123. data/lib/wardite/cli/cli.rb +112 -29
  124. data/lib/wardite/const.rb +1 -0
  125. data/lib/wardite/efflorescence/float_arithmetic.rb +216 -0
  126. data/lib/wardite/efflorescence/i64_arithmetic.rb +257 -0
  127. data/lib/wardite/efflorescence/inspection.rb +165 -0
  128. data/lib/wardite/efflorescence/ir.rb +1164 -0
  129. data/lib/wardite/efflorescence/mir_cache.rb +657 -0
  130. data/lib/wardite/efflorescence/optimizer.rb +580 -0
  131. data/lib/wardite/efflorescence/register_validation.rb +362 -0
  132. data/lib/wardite/efflorescence/snapshot.rb +229 -0
  133. data/lib/wardite/efflorescence/store_access.rb +366 -0
  134. data/lib/wardite/efflorescence/translator.rb +866 -0
  135. data/lib/wardite/efflorescence/vm.rb +1170 -0
  136. data/lib/wardite/efflorescence/wasi.rb +52 -0
  137. data/lib/wardite/efflorescence.rb +17 -0
  138. data/lib/wardite/errors.rb +20 -0
  139. data/lib/wardite/float_bits.rb +46 -0
  140. data/lib/wardite/instruction.rb +35 -4
  141. data/lib/wardite/leb128.rb +33 -12
  142. data/lib/wardite/load.rb +292 -143
  143. data/lib/wardite/value.rb +169 -175
  144. data/lib/wardite/version.rb +1 -1
  145. data/lib/wardite/wasi/consts.rb +1 -0
  146. data/lib/wardite/wasi/spinel.rb +41 -0
  147. data/lib/wardite/wasi.rb +483 -268
  148. data/lib/wardite/wasm_module.rb +6 -3
  149. data/lib/wardite.rb +360 -98
  150. data/rbs_collection.lock.yaml +36 -96
  151. data/scripts/gen_alu.rb +121 -21
  152. data/scripts/verify_ruby_wasm.rb +70 -0
  153. data/sig/generated/wardite/cli/cli.rbs +23 -6
  154. data/sig/generated/wardite/const.rbs +2 -0
  155. data/sig/generated/wardite/efflorescence/float_arithmetic.rbs +65 -0
  156. data/sig/generated/wardite/efflorescence/i64_arithmetic.rbs +99 -0
  157. data/sig/generated/wardite/efflorescence/inspection.rbs +64 -0
  158. data/sig/generated/wardite/efflorescence/ir.rbs +888 -0
  159. data/sig/generated/wardite/efflorescence/mir_cache.rbs +236 -0
  160. data/sig/generated/wardite/efflorescence/optimizer.rbs +189 -0
  161. data/sig/generated/wardite/efflorescence/register_validation.rbs +104 -0
  162. data/sig/generated/wardite/efflorescence/snapshot.rbs +83 -0
  163. data/sig/generated/wardite/efflorescence/store_access.rbs +145 -0
  164. data/sig/generated/wardite/efflorescence/translator.rbs +218 -0
  165. data/sig/generated/wardite/efflorescence/vm.rbs +240 -0
  166. data/sig/generated/wardite/efflorescence/wasi.rbs +34 -0
  167. data/sig/generated/wardite/errors.rbs +12 -0
  168. data/sig/generated/wardite/float_bits.rbs +30 -0
  169. data/sig/generated/wardite/instruction.rbs +22 -1
  170. data/sig/generated/wardite/leb128.rbs +3 -1
  171. data/sig/generated/wardite/load.rbs +59 -7
  172. data/sig/generated/wardite/value.rbs +70 -11
  173. data/sig/generated/wardite/wasi/consts.rbs +2 -0
  174. data/sig/generated/wardite/wasi/spinel.rbs +15 -0
  175. data/sig/generated/wardite/wasi.rbs +111 -4
  176. data/sig/generated/wardite.rbs +114 -13
  177. data/sig/mir_cache_stdlib.rbs +5 -0
  178. data/sig/vernier.rbs +2 -2
  179. data/spinel/README.md +30 -0
  180. data/spinel/bin/wardite.rb +6 -0
  181. data/spinel/patches/0001-io-buffer-string-view.patch +699 -0
  182. data/spinel/patches/0002-io-buffer-allocation-error.patch +47 -0
  183. data/spinel/spin.toml +7 -0
  184. metadata +154 -3
@@ -0,0 +1,866 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module Wardite
5
+ module Efflorescence
6
+ # The operand/control stacks exist only during translation. Execution uses
7
+ # typed register banks, absolute PCs and explicit per-frame handler stacks.
8
+ class Translator
9
+ class Control
10
+ attr_reader :kind #: Symbol
11
+ attr_reader :entry_stack #: Array[Integer]
12
+ attr_reader :start_pc #: Integer
13
+ attr_reader :result_types #: Array[Symbol]
14
+ attr_reader :result_registers #: Array[Integer]
15
+ attr_reader :patches #: Array[Integer]
16
+ attr_reader :catch_patches #: Array[Wardite::Efflorescence::CatchTarget]
17
+ attr_reader :handler_depth #: Integer
18
+ attr_reader :entry_reachable #: bool
19
+ attr_accessor :polymorphic #: bool
20
+ attr_accessor :has_branch #: bool
21
+ attr_accessor :false_patch #: Integer
22
+ attr_accessor :else_seen #: bool
23
+ attr_accessor :then_reachable #: bool
24
+
25
+ # @rbs kind: Symbol
26
+ # @rbs entry_stack: Array[Integer]
27
+ # @rbs start_pc: Integer
28
+ # @rbs result_types: Array[Symbol]
29
+ # @rbs result_registers: Array[Integer]
30
+ # @rbs handler_depth: Integer
31
+ # @rbs reachable: bool
32
+ def initialize(kind, entry_stack, start_pc, result_types, result_registers, handler_depth, reachable)
33
+ @kind, @entry_stack, @start_pc = kind, entry_stack.dup, start_pc
34
+ @result_types, @result_registers = result_types, result_registers
35
+ @handler_depth, @entry_reachable = handler_depth, reachable
36
+ @patches, @catch_patches = [], []
37
+ @has_branch, @else_seen, @then_reachable = false, false, false
38
+ @false_patch = -1
39
+ @polymorphic = false
40
+ end
41
+ end
42
+
43
+ BINARY = {
44
+ i32_add: Opcode::I32_ADD, i32_sub: Opcode::I32_SUB, i32_mul: Opcode::I32_MUL,
45
+ i32_xor: Opcode::I32_XOR, i32_shl: Opcode::I32_SHL, i32_shr_u: Opcode::I32_SHR_U,
46
+ i32_eq: Opcode::I32_EQ, i32_ne: Opcode::I32_NE, i32_lts: Opcode::I32_LTS,
47
+ i32_ltu: Opcode::I32_LTU, i32_gts: Opcode::I32_GTS, i32_gtu: Opcode::I32_GTU,
48
+ i32_les: Opcode::I32_LES, i32_leu: Opcode::I32_LEU, i32_ges: Opcode::I32_GES,
49
+ i32_geu: Opcode::I32_GEU, i32_div_s: Opcode::I32_DIV_S, i32_div_u: Opcode::I32_DIV_U,
50
+ i32_rem_s: Opcode::I32_REM_S, i32_rem_u: Opcode::I32_REM_U,
51
+ i32_and: Opcode::I32_AND, i32_or: Opcode::I32_OR, i32_shr_s: Opcode::I32_SHR_S,
52
+ i32_rotl: Opcode::I32_ROTL, i32_rotr: Opcode::I32_ROTR
53
+ }.freeze
54
+ UNARY = { i32_eqz: Opcode::I32_EQZ, i32_clz: Opcode::I32_CLZ,
55
+ i32_ctz: Opcode::I32_CTZ, i32_popcnt: Opcode::I32_POPCNT,
56
+ i32_extend8_s: Opcode::I32_EXTEND8_S, i32_extend16_s: Opcode::I32_EXTEND16_S }.freeze
57
+
58
+ I64_ALU = {
59
+ i64_eqz: Opcode::I64_EQZ,
60
+ i32_wrap_i64: Opcode::I32_WRAP_I64,
61
+ i64_eq: Opcode::I64_EQ,
62
+ i64_ne: Opcode::I64_NE,
63
+ i64_lts: Opcode::I64_LTS,
64
+ i64_ltu: Opcode::I64_LTU,
65
+ i64_gts: Opcode::I64_GTS,
66
+ i64_gtu: Opcode::I64_GTU,
67
+ i64_les: Opcode::I64_LES,
68
+ i64_leu: Opcode::I64_LEU,
69
+ i64_ges: Opcode::I64_GES,
70
+ i64_geu: Opcode::I64_GEU,
71
+ i64_clz: Opcode::I64_CLZ,
72
+ i64_ctz: Opcode::I64_CTZ,
73
+ i64_popcnt: Opcode::I64_POPCNT,
74
+ i64_extend8_s: Opcode::I64_EXTEND8_S,
75
+ i64_extend16_s: Opcode::I64_EXTEND16_S,
76
+ i64_extend32_s: Opcode::I64_EXTEND32_S,
77
+ i64_extend_i32_s: Opcode::I64_EXTEND_I32_S,
78
+ i64_extend_i32_u: Opcode::I64_EXTEND_I32_U,
79
+ i64_and: Opcode::I64_AND,
80
+ i64_or: Opcode::I64_OR,
81
+ i64_xor: Opcode::I64_XOR,
82
+ i64_shl: Opcode::I64_SHL,
83
+ i64_shr_s: Opcode::I64_SHR_S,
84
+ i64_shr_u: Opcode::I64_SHR_U,
85
+ i64_rotl: Opcode::I64_ROTL,
86
+ i64_rotr: Opcode::I64_ROTR,
87
+ i64_add: Opcode::I64_ADD,
88
+ i64_sub: Opcode::I64_SUB,
89
+ i64_mul: Opcode::I64_MUL,
90
+ i64_div_s: Opcode::I64_DIV_S,
91
+ i64_div_u: Opcode::I64_DIV_U,
92
+ i64_rem_s: Opcode::I64_REM_S,
93
+ i64_rem_u: Opcode::I64_REM_U,
94
+ }.freeze
95
+
96
+ # Natural alignment exponents; alignment is a hint, not an address rule.
97
+ FLOAT_ALU = {
98
+ f32_eq: Opcode::F32_EQ,
99
+ f32_ne: Opcode::F32_NE,
100
+ f32_lt: Opcode::F32_LT,
101
+ f32_gt: Opcode::F32_GT,
102
+ f32_le: Opcode::F32_LE,
103
+ f32_ge: Opcode::F32_GE,
104
+ f32_abs: Opcode::F32_ABS,
105
+ f32_neg: Opcode::F32_NEG,
106
+ f32_ceil: Opcode::F32_CEIL,
107
+ f32_floor: Opcode::F32_FLOOR,
108
+ f32_trunc: Opcode::F32_TRUNC,
109
+ f32_nearest: Opcode::F32_NEAREST,
110
+ f32_sqrt: Opcode::F32_SQRT,
111
+ f32_add: Opcode::F32_ADD,
112
+ f32_sub: Opcode::F32_SUB,
113
+ f32_mul: Opcode::F32_MUL,
114
+ f32_div: Opcode::F32_DIV,
115
+ f32_min: Opcode::F32_MIN,
116
+ f32_max: Opcode::F32_MAX,
117
+ f32_copysign: Opcode::F32_COPYSIGN,
118
+ f64_eq: Opcode::F64_EQ,
119
+ f64_ne: Opcode::F64_NE,
120
+ f64_lt: Opcode::F64_LT,
121
+ f64_gt: Opcode::F64_GT,
122
+ f64_le: Opcode::F64_LE,
123
+ f64_ge: Opcode::F64_GE,
124
+ f64_abs: Opcode::F64_ABS,
125
+ f64_neg: Opcode::F64_NEG,
126
+ f64_ceil: Opcode::F64_CEIL,
127
+ f64_floor: Opcode::F64_FLOOR,
128
+ f64_trunc: Opcode::F64_TRUNC,
129
+ f64_nearest: Opcode::F64_NEAREST,
130
+ f64_sqrt: Opcode::F64_SQRT,
131
+ f64_add: Opcode::F64_ADD,
132
+ f64_sub: Opcode::F64_SUB,
133
+ f64_mul: Opcode::F64_MUL,
134
+ f64_div: Opcode::F64_DIV,
135
+ f64_min: Opcode::F64_MIN,
136
+ f64_max: Opcode::F64_MAX,
137
+ f64_copysign: Opcode::F64_COPYSIGN,
138
+ i32_trunc_f32_s: Opcode::I32_TRUNC_F32_S,
139
+ i32_trunc_f32_u: Opcode::I32_TRUNC_F32_U,
140
+ i32_trunc_f64_s: Opcode::I32_TRUNC_F64_S,
141
+ i32_trunc_f64_u: Opcode::I32_TRUNC_F64_U,
142
+ i64_trunc_f32_s: Opcode::I64_TRUNC_F32_S,
143
+ i64_trunc_f32_u: Opcode::I64_TRUNC_F32_U,
144
+ i64_trunc_f64_s: Opcode::I64_TRUNC_F64_S,
145
+ i64_trunc_f64_u: Opcode::I64_TRUNC_F64_U,
146
+ i32_trunc_sat_f32_s: Opcode::I32_TRUNC_SAT_F32_S,
147
+ i32_trunc_sat_f32_u: Opcode::I32_TRUNC_SAT_F32_U,
148
+ i32_trunc_sat_f64_s: Opcode::I32_TRUNC_SAT_F64_S,
149
+ i32_trunc_sat_f64_u: Opcode::I32_TRUNC_SAT_F64_U,
150
+ i64_trunc_sat_f32_s: Opcode::I64_TRUNC_SAT_F32_S,
151
+ i64_trunc_sat_f32_u: Opcode::I64_TRUNC_SAT_F32_U,
152
+ i64_trunc_sat_f64_s: Opcode::I64_TRUNC_SAT_F64_S,
153
+ i64_trunc_sat_f64_u: Opcode::I64_TRUNC_SAT_F64_U,
154
+ f32_convert_i32_s: Opcode::F32_CONVERT_I32_S,
155
+ f32_convert_i32_u: Opcode::F32_CONVERT_I32_U,
156
+ f32_convert_i64_s: Opcode::F32_CONVERT_I64_S,
157
+ f32_convert_i64_u: Opcode::F32_CONVERT_I64_U,
158
+ f64_convert_i32_s: Opcode::F64_CONVERT_I32_S,
159
+ f64_convert_i32_u: Opcode::F64_CONVERT_I32_U,
160
+ f64_convert_i64_s: Opcode::F64_CONVERT_I64_S,
161
+ f64_convert_i64_u: Opcode::F64_CONVERT_I64_U,
162
+ f32_demote_f64: Opcode::F32_DEMOTE_F64,
163
+ f64_promote_f32: Opcode::F64_PROMOTE_F32,
164
+ i32_reinterpret_f32: Opcode::I32_REINTERPRET_F32,
165
+ i64_reinterpret_f64: Opcode::I64_REINTERPRET_F64,
166
+ f32_reinterpret_i32: Opcode::F32_REINTERPRET_I32,
167
+ f64_reinterpret_i64: Opcode::F64_REINTERPRET_I64,
168
+ }.freeze #: Hash[Symbol, Integer]
169
+
170
+ MEMORY_WIDTHS = { i32_load: 2, i32_load8_s: 0, i32_load8_u: 0,
171
+ i32_load16_s: 1, i32_load16_u: 1,
172
+ i32_store: 2, i32_store8: 0, i32_store16: 1,
173
+ i64_load: 3, i64_load8_s: 0, i64_load8_u: 0,
174
+ i64_load16_s: 1, i64_load16_u: 1, i64_load32_s: 2, i64_load32_u: 2,
175
+ i64_store: 3, i64_store8: 0, i64_store16: 1, i64_store32: 2,
176
+ f32_load: 2, f32_store: 2, f64_load: 3, f64_store: 3 }.freeze
177
+ MEMORY_OPCODES = { i32_load: Opcode::I32_LOAD, i32_load8_s: Opcode::I32_LOAD8_S,
178
+ i32_load8_u: Opcode::I32_LOAD8_U, i32_load16_s: Opcode::I32_LOAD16_S,
179
+ i32_load16_u: Opcode::I32_LOAD16_U, i32_store: Opcode::I32_STORE,
180
+ i32_store8: Opcode::I32_STORE8, i32_store16: Opcode::I32_STORE16,
181
+ i64_load: Opcode::I64_LOAD,
182
+ i64_load8_s: Opcode::I64_LOAD8_S,
183
+ i64_load8_u: Opcode::I64_LOAD8_U,
184
+ i64_load16_s: Opcode::I64_LOAD16_S,
185
+ i64_load16_u: Opcode::I64_LOAD16_U,
186
+ i64_load32_s: Opcode::I64_LOAD32_S,
187
+ i64_load32_u: Opcode::I64_LOAD32_U,
188
+ i64_store: Opcode::I64_STORE,
189
+ i64_store8: Opcode::I64_STORE8,
190
+ i64_store16: Opcode::I64_STORE16,
191
+ i64_store32: Opcode::I64_STORE32,
192
+ f32_load: Opcode::F32_LOAD, f32_store: Opcode::F32_STORE,
193
+ f64_load: Opcode::F64_LOAD, f64_store: Opcode::F64_STORE }.freeze
194
+ STORE_CODES = (MEMORY_WIDTHS.keys + %i[global_get global_set memory_size memory_grow memory_init memory_copy memory_fill]).freeze
195
+
196
+ # @rbs @instance: Wardite::Instance
197
+ # @rbs @entries: Array[Wardite::Efflorescence::FunctionEntry]
198
+ # @rbs @stack: Array[Integer]
199
+ # @rbs @controls: Array[Wardite::Efflorescence::Translator::Control]
200
+ # @rbs @constants: Hash[Integer, Integer]
201
+ # @rbs @i64_constants: Hash[Integer, Integer]?
202
+ # @rbs @f32_constants: Hash[Integer, Integer]?
203
+ # @rbs @f64_constants: Hash[Integer, Integer]?
204
+ # @rbs @function: Wardite::Efflorescence::Function
205
+ # @rbs @reachable: bool
206
+ # @rbs @wasm_pc: Integer
207
+ # @rbs @handler_depth: Integer
208
+
209
+ # @rbs instance: Wardite::Instance
210
+ def initialize(instance)
211
+ @instance = instance
212
+ @entries = []
213
+ @stack, @controls, @constants = [], [], {}
214
+ @i64_constants = nil
215
+ @f32_constants = nil
216
+ @f64_constants = nil
217
+ @reachable, @wasm_pc, @handler_depth = true, 0, 0
218
+ @function = Function.new(0, [], [], 0)
219
+ end
220
+
221
+ # @rbs return: Wardite::Efflorescence::IR
222
+ def link
223
+ hosts = [] #: Array[Wardite::Efflorescence::HostFunction]
224
+ defined_count = 0
225
+ entries = @instance.store.funcs.map do |function|
226
+ if function.is_a?(Wardite::ExternalFunction)
227
+ entry = FunctionEntry.new(:host, function.callsig, function.retsig, -1, hosts.size)
228
+ callable = function.callable #: Wardite::_WasmCallable & Object
229
+ unless callable.respond_to?(:call)
230
+ raise Wardite::LoadError, "import #{function.name} is not callable"
231
+ end
232
+ unboxed_wasi = nil
233
+ if RUBY_ENGINE != "spinel"
234
+ wasi = @instance.wasi
235
+ if wasi && wasi.equal?(function.target_module) && wasi.is_a?(Wardite::Efflorescence::WasiSnapshotPreview1)
236
+ unboxed_wasi = Wardite::Efflorescence::WasiSnapshotPreview1.unboxed_callable(wasi, function)
237
+ end
238
+ end
239
+ hosts << HostFunction.new(function, entry, callable, unboxed_wasi)
240
+ entry
241
+ else
242
+ entry = FunctionEntry.new(:defined, function.callsig, function.retsig, defined_count, -1)
243
+ defined_count += 1
244
+ entry
245
+ end
246
+ end
247
+ IR.new([], entries: entries, hosts: hosts)
248
+ end
249
+
250
+ # @rbs linked: Wardite::Efflorescence::IR
251
+ # @rbs return: Wardite::Efflorescence::IR
252
+ def translate(linked = link)
253
+ @entries = linked.entries
254
+ functions = [] #: Array[Wardite::Efflorescence::Function]
255
+ @instance.store.funcs.each_with_index do |function, index|
256
+ if function.is_a?(Wardite::WasmFunction)
257
+ functions << translate_function(function, index, functions.size)
258
+ end
259
+ end
260
+ IR.new(functions, entries: @entries, hosts: linked.hosts)
261
+ end
262
+
263
+ # @rbs wasm: Wardite::WasmFunction
264
+ # @rbs index: Integer
265
+ # @rbs pool_index: Integer
266
+ # @rbs return: Wardite::Efflorescence::Function
267
+ def translate_function(wasm, index, pool_index)
268
+ FunctionEntry.check_signature(wasm.callsig, wasm.retsig, "function #{index}")
269
+ unless wasm.locals_type.all? { |type| FunctionEntry.numeric_type?(type) || type == :exnref }
270
+ raise UnsupportedFeature, "Efflorescence: function #{index} has unsupported locals"
271
+ end
272
+ locals = [] #: Array[Symbol]
273
+ wasm.locals_type.each_with_index { |type, i| wasm.locals_count.fetch(i).times { locals << type } }
274
+ @function = Function.new(index, wasm.callsig, wasm.retsig, locals.size, local_types: locals, pool_index: pool_index)
275
+ @stack, @controls, @constants = [], [], {}
276
+ @i64_constants = nil
277
+ @f32_constants = nil
278
+ @f64_constants = nil
279
+ @reachable, @handler_depth = true, 0
280
+ @controls << new_control(:function, wasm.retsig)
281
+ wasm.body.each_with_index do |instruction, pc|
282
+ @wasm_pc = pc
283
+ fail_translation("instruction after function end") if @controls.empty?
284
+ code, operands = instruction[1], instruction[2]
285
+ validate_store_instruction(code, operands) if STORE_CODES.include?(code)
286
+ if BINARY.key?(code)
287
+ right, left = pop_typed(:i32), pop_typed(:i32)
288
+ dst = register
289
+ emit([BINARY.fetch(code), dst, left, right]) if @reachable
290
+ @stack << dst
291
+ next
292
+ elsif UNARY.key?(code)
293
+ source = pop_typed(:i32)
294
+ dst = register
295
+ emit([UNARY.fetch(code), dst, source]) if @reachable
296
+ @stack << dst
297
+ next
298
+ end
299
+ case code
300
+ when :block, :loop, :if, :try_table
301
+ block = operands[0]
302
+ fail_translation("expected block signature") unless block.is_a?(Wardite::Block)
303
+ unless block.parameter_types.empty? && block.result_types.all? { |type| FunctionEntry.numeric_type?(type) || type == :exnref }
304
+ raise UnsupportedFeature, context("block parameters and unsupported block result types are not supported")
305
+ end
306
+ condition = code == :if ? pop_typed(:i32) : -1
307
+ snapshot_locals if @reachable
308
+ control = new_control(code, block.result_types)
309
+ if code == :if && @reachable
310
+ control.false_patch = emit([Opcode::BR_IF_ZERO, condition, -1])
311
+ elsif code == :try_table
312
+ @function.uses_eh = true
313
+ clauses = operands[1]
314
+ fail_translation("expected catch clauses") unless clauses.is_a?(Wardite::OperandVector)
315
+ descriptor = make_handler(clauses.entries)
316
+ id = @function.handlers.size
317
+ @function.handlers << descriptor
318
+ emit([Opcode::EH_ENTER, id]) if @reachable
319
+ @handler_depth += 1
320
+ end
321
+ @function.uses_eh = true if block.result_types.include?(:exnref)
322
+ @controls << control
323
+ when :else
324
+ else_control
325
+ when :end
326
+ end_control
327
+ when :i32_load, :i32_load8_s, :i32_load8_u, :i32_load16_s, :i32_load16_u,
328
+ :i32_store, :i32_store8, :i32_store16,
329
+ :i64_load, :i64_load8_s, :i64_load8_u, :i64_load16_s, :i64_load16_u, :i64_load32_s, :i64_load32_u,
330
+ :i64_store, :i64_store8, :i64_store16, :i64_store32,
331
+ :f32_load, :f64_load, :f32_store, :f64_store
332
+ opcode = MEMORY_OPCODES.fetch(code)
333
+ offset = integer_operand(operands[1])
334
+ store_type = Opcode::EXTENDED_STORE_TYPES[opcode]
335
+ type = store_type || Opcode::EXTENDED_LOAD_TYPES[opcode] || :i32
336
+ @function.uses_i64 = true if type == :i64
337
+ @function.uses_float = true if FloatBits.float_type?(type)
338
+ if store_type || code == :i32_store || code == :i32_store8 || code == :i32_store16
339
+ value = pop_typed(type)
340
+ address = pop_typed(:i32)
341
+ emit([opcode, value, address, offset]) if @reachable
342
+ else
343
+ address = pop_typed(:i32)
344
+ dst = register(type)
345
+ emit([opcode, dst, address, offset]) if @reachable
346
+ @stack << dst
347
+ end
348
+ when :memory_init, :memory_copy, :memory_fill
349
+ length, source, destination = pop_typed(:i32), pop_typed(:i32), pop_typed(:i32)
350
+ next unless @reachable
351
+ data_index = code == :memory_init ? integer_operand(operands[0]) : -1
352
+ site = MemorySite.new([destination, source, length], data_index: data_index)
353
+ id = @function.memory_sites.size
354
+ @function.memory_sites << site
355
+ opcode = case code
356
+ when :memory_init then Opcode::MEMORY_INIT
357
+ when :memory_copy then Opcode::MEMORY_COPY
358
+ else Opcode::MEMORY_FILL
359
+ end
360
+ emit([opcode, id])
361
+ when :memory_size, :memory_grow
362
+ source = code == :memory_grow ? pop_typed(:i32) : -1
363
+ dst = register
364
+ emit(code == :memory_grow ? [Opcode::MEMORY_GROW, dst, source] : [Opcode::MEMORY_SIZE, dst]) if @reachable
365
+ @stack << dst
366
+ when :global_get, :global_set
367
+ index = integer_operand(operands[0])
368
+ type = @instance.store.globals.fetch(index).type
369
+ @function.uses_i64 = true if type == :i64
370
+ @function.uses_float = true if FloatBits.float_type?(type)
371
+ if code == :global_get
372
+ dst = register(type)
373
+ opcode = case type
374
+ when :i64 then Opcode::I64_GLOBAL_GET
375
+ when :f32 then Opcode::F32_GLOBAL_GET
376
+ when :f64 then Opcode::F64_GLOBAL_GET
377
+ else Opcode::GLOBAL_GET
378
+ end
379
+ emit([opcode, dst, index]) if @reachable
380
+ @stack << dst
381
+ else
382
+ source = pop_typed(type)
383
+ opcode = case type
384
+ when :i64 then Opcode::I64_GLOBAL_SET
385
+ when :f32 then Opcode::F32_GLOBAL_SET
386
+ when :f64 then Opcode::F64_GLOBAL_SET
387
+ else Opcode::GLOBAL_SET
388
+ end
389
+ emit([opcode, index, source]) if @reachable
390
+ end
391
+ when :local_get, :local_set, :local_tee
392
+ local = integer_operand(operands[0])
393
+ fail_translation("invalid local index #{local}") unless local >= 0 && local < @function.parameter_count + @function.local_count
394
+ if code == :local_get
395
+ @stack << local
396
+ else
397
+ source = pop_typed(type_of(local))
398
+ if @reachable
399
+ preserve_local(local)
400
+ copy_value(local, source) unless local == source
401
+ end
402
+ @stack << local if code == :local_tee
403
+ end
404
+ when :i32_const, :i64_const
405
+ immediate = integer_operand(operands[0])
406
+ if code == :i64_const
407
+ @function.uses_i64 = true
408
+ @stack << constant(I64Arithmetic.normalize(immediate), :i64)
409
+ else
410
+ @stack << constant(immediate & 0xffffffff)
411
+ end
412
+ when :f32_const, :f64_const
413
+ operand = operands[0]
414
+ type = code == :f32_const ? :f32 : :f64
415
+ unless operand.is_a?(FloatImmediate) && operand.type == type
416
+ fail_translation("invalid float immediate")
417
+ end
418
+ @stack << constant(operand.bits, type)
419
+ when :br, :br_if
420
+ target = label(integer_operand(operands[0]))
421
+ condition = code == :br_if ? pop_typed(:i32) : -1
422
+ types = label_types(target)
423
+ sources = top_values(types)
424
+ unless @reachable
425
+ if code == :br
426
+ mark_unreachable
427
+ else
428
+ types.size.times { pop_value }
429
+ @stack.concat(target.result_registers) unless target.kind == :loop
430
+ end
431
+ next
432
+ end
433
+ if code == :br_if && (types.size > 0 || @handler_depth != target.handler_depth)
434
+ skip = emit([Opcode::BR_IF_ZERO, condition, -1])
435
+ branch(target, sources)
436
+ patch(skip, @function.instructions.size)
437
+ else
438
+ branch(target, sources, condition)
439
+ end
440
+ mark_unreachable if code == :br
441
+ when :br_table
442
+ depths = operands[0]
443
+ fail_translation("expected branch table") unless depths.is_a?(Wardite::OperandVector)
444
+ targets = depths.entries.map { |depth| label(depth) }
445
+ default = label(integer_operand(operands[1]))
446
+ types = label_types(default)
447
+ fail_translation("inconsistent br_table label types") unless targets.all? { |target| label_types(target) == types }
448
+ selector = pop_typed(:i32)
449
+ sources = top_values(types)
450
+ unless @reachable
451
+ mark_unreachable
452
+ next
453
+ end
454
+ targets.each_with_index do |target, i|
455
+ comparison = register
456
+ emit([Opcode::I32_EQ, comparison, selector, constant(i)])
457
+ skip = emit([Opcode::BR_IF_ZERO, comparison, -1])
458
+ branch(target, sources)
459
+ patch(skip, @function.instructions.size)
460
+ end
461
+ branch(default, sources)
462
+ mark_unreachable
463
+ when :select
464
+ condition, right, left = pop_typed(:i32), pop_value, pop_value
465
+ type = right < 0 ? type_of(left) : type_of(right)
466
+ unless (FunctionEntry.numeric_type?(type) || type == :unknown) && (left < 0 || type_of(left) == type)
467
+ fail_translation("select requires matching integer operands")
468
+ end
469
+ dst = type == :unknown ? -1 : register(type)
470
+ @stack << dst
471
+ next unless @reachable
472
+ copy_value(dst, right)
473
+ skip = emit([Opcode::BR_IF_ZERO, condition, -1])
474
+ copy_value(dst, left)
475
+ patch(skip, @function.instructions.size)
476
+ when :call
477
+ index = integer_operand(operands[0])
478
+ fail_translation("invalid call target #{index}") if index < 0
479
+ callee = @entries[index]
480
+ fail_translation("invalid call target #{index}") unless callee
481
+ FunctionEntry.check_signature(callee.parameter_types, callee.result_types, "function #{index}")
482
+ @function.uses_dynamic_calls = true if callee.kind == :host
483
+ arguments = callee.parameter_types.reverse.map { |type| pop_typed(type) }.reverse
484
+ dst = callee.result_types.empty? ? -1 : register(callee.result_types.fetch(0))
485
+ @stack << dst if dst >= 0
486
+ next unless @reachable
487
+ if callee.kind == :host
488
+ id = @function.dynamic_sites.size
489
+ @function.dynamic_sites << DynamicCallSite.new(callee.host_index, arguments, callee.parameter_types, callee.result_types)
490
+ emit([Opcode::CALL_HOST, dst, id, 0])
491
+ else
492
+ emit([Opcode::CALL, dst, index] + arguments)
493
+ end
494
+ when :call_indirect
495
+ type_index = integer_operand(operands[0])
496
+ table_index = integer_operand(operands[1])
497
+ raise UnsupportedFeature, context("only call_indirect through table 0 is supported") unless table_index == 0
498
+ table = @instance.store.tables[0]
499
+ fail_translation("call_indirect requires funcref table 0") unless table && table.type == :funcref
500
+ type = @instance.types[type_index] if type_index >= 0
501
+ fail_translation("invalid indirect call type index #{type_index}") unless type
502
+ FunctionEntry.check_signature(type.callsig, type.retsig, "type #{type_index}")
503
+ @function.uses_dynamic_calls = true
504
+ selector = pop_typed(:i32)
505
+ arguments = type.callsig.reverse.map { |param| pop_typed(param) }.reverse
506
+ dst = type.retsig.empty? ? -1 : register(type.retsig.fetch(0))
507
+ @stack << dst if dst >= 0
508
+ next unless @reachable
509
+ id = @function.dynamic_sites.size
510
+ @function.dynamic_sites << DynamicCallSite.new(-1, arguments, type.callsig, type.retsig, table_index: table_index)
511
+ emit([Opcode::CALL_INDIRECT, dst, id, selector])
512
+ when :throw
513
+ tag_index = integer_operand(operands[0])
514
+ tag = tag_at(tag_index)
515
+ @function.uses_eh = true
516
+ payload = tag.parameter_types.reverse.map { |type| pop_typed(type) }.reverse
517
+ if @reachable
518
+ id = @function.throw_sites.size
519
+ @function.throw_sites << ThrowSite.new(tag_index, payload)
520
+ emit([Opcode::THROW, id])
521
+ end
522
+ mark_unreachable
523
+ when :throw_ref
524
+ @function.uses_eh = true
525
+ reference = pop_typed(:exnref)
526
+ emit([Opcode::THROW_REF, reference]) if @reachable
527
+ mark_unreachable
528
+ when :return
529
+ source = @function.result_types.empty? ? -1 : pop_typed(@function.result_types.fetch(0))
530
+ emit([Opcode::RETURN, source]) if @reachable
531
+ mark_unreachable
532
+ when :unreachable
533
+ emit([Opcode::TRAP]) if @reachable
534
+ mark_unreachable
535
+ when :drop
536
+ pop_value
537
+ when :nop
538
+ else
539
+ opcode = I64_ALU[code] || FLOAT_ALU[code]
540
+ raise UnsupportedFeature, context("unsupported instruction #{code}") unless opcode
541
+ types = Opcode.extended_alu_types(opcode) || raise(TranslationError, context("missing ALU signature"))
542
+ if opcode >= Opcode::F32_EQ
543
+ @function.uses_float = true
544
+ else
545
+ @function.uses_i64 = true
546
+ end
547
+ sources = types.drop(1).reverse.map { |type| pop_typed(type) }.reverse
548
+ dst = register(types.fetch(0))
549
+ emit([opcode, dst] + sources) if @reachable
550
+ @stack << dst
551
+ end
552
+ end
553
+ fail_translation("missing function end") unless @controls.empty?
554
+ @function
555
+ end
556
+
557
+ private
558
+
559
+ # Validate even dead instructions before deciding whether to emit MIR.
560
+ # @rbs code: Symbol
561
+ # @rbs operands: Array[Wardite::operandItem]
562
+ # @rbs return: void
563
+ def validate_store_instruction(code, operands)
564
+ @function.uses_store = true
565
+ if code == :global_get || code == :global_set
566
+ index = integer_operand(operands[0])
567
+ global = index >= 0 ? @instance.store.globals[index] : nil
568
+ fail_translation("invalid global index #{index}") unless global
569
+ case global.type
570
+ when :i32
571
+ fail_translation("global initializer type mismatch") unless global.value.is_a?(Wardite::I32)
572
+ when :i64
573
+ fail_translation("global initializer type mismatch") unless global.value.is_a?(Wardite::I64)
574
+ when :f32
575
+ fail_translation("global initializer type mismatch") unless global.value.is_a?(Wardite::F32)
576
+ when :f64
577
+ fail_translation("global initializer type mismatch") unless global.value.is_a?(Wardite::F64)
578
+ else
579
+ raise UnsupportedFeature, context("only numeric global access is supported")
580
+ end
581
+ fail_translation("global.set on immutable global #{index}") if code == :global_set && !global.mutable
582
+ return
583
+ end
584
+ fail_translation("memory instruction requires memory 0") if @instance.store.memories.empty?
585
+ alignment = MEMORY_WIDTHS[code]
586
+ if alignment
587
+ hint = integer_operand(operands[0])
588
+ offset = integer_operand(operands[1])
589
+ fail_translation("invalid memory alignment") unless hint >= 0 && hint <= alignment
590
+ fail_translation("invalid memory offset") unless offset >= 0 && offset <= 0xffffffff
591
+ elsif code == :memory_init
592
+ data_index = integer_operand(operands[0])
593
+ fail_translation("memory.init requires data count") unless @instance.data_count_section
594
+ count = @instance.data_section&.segments&.size || 0
595
+ fail_translation("invalid data index #{data_index}") unless data_index >= 0 && data_index < count
596
+ check_memory_index(integer_operand(operands[1]))
597
+ elsif code == :memory_copy
598
+ check_memory_index(integer_operand(operands[0]))
599
+ check_memory_index(integer_operand(operands[1]))
600
+ else
601
+ check_memory_index(integer_operand(operands[0]))
602
+ end
603
+ end
604
+
605
+ # @rbs index: Integer
606
+ # @rbs return: void
607
+ def check_memory_index(index)
608
+ raise UnsupportedFeature, context("only memory 0 is supported") unless index == 0
609
+ end
610
+
611
+ # @rbs value: Wardite::operandItem?
612
+ # @rbs return: Integer
613
+ def integer_operand(value)
614
+ fail_translation("expected integer operand") unless value.is_a?(Integer)
615
+ value
616
+ end
617
+
618
+ # @rbs type: Symbol
619
+ # @rbs return: Integer
620
+ def register(type = :i32)
621
+ @function.allocate_register(0, type: type)
622
+ end
623
+
624
+ # @rbs value: Integer
625
+ # @rbs return: Integer
626
+ # @rbs type: Symbol
627
+ def constant(value, type = :i32)
628
+ constants = case type
629
+ when :i64 then @i64_constants ||= {} #: Hash[Integer, Integer]
630
+ when :f32 then @f32_constants ||= {} #: Hash[Integer, Integer]
631
+ when :f64 then @f64_constants ||= {} #: Hash[Integer, Integer]
632
+ else @constants
633
+ end
634
+ constants[value] ||= @function.allocate_constant(value, type: type)
635
+ end
636
+
637
+ # @rbs kind: Symbol
638
+ # @rbs types: Array[Symbol]
639
+ # @rbs return: Wardite::Efflorescence::Translator::Control
640
+ def new_control(kind, types)
641
+ Control.new(kind, @stack, @function.instructions.size, types, types.map { |type| register(type) }, @handler_depth, @reachable)
642
+ end
643
+
644
+ # @rbs instruction: Array[Integer]
645
+ # @rbs return: Integer
646
+ def emit(instruction)
647
+ position = @function.instructions.size
648
+ @function.instructions << Instruction.new(instruction)
649
+ position
650
+ end
651
+
652
+ # @rbs pc: Integer
653
+ # @rbs target: Integer
654
+ # @rbs return: void
655
+ def patch(pc, target)
656
+ instruction = @function.instructions.fetch(pc)
657
+ instruction[instruction.size - 1] = target
658
+ end
659
+
660
+ # @rbs return: Integer
661
+ def pop_value
662
+ control = @controls.last || raise(TranslationError, "missing control")
663
+ if @stack.size == control.entry_stack.size
664
+ return -1 if control.polymorphic
665
+ fail_translation("operand stack underflow")
666
+ end
667
+ @stack.pop || raise(TranslationError, "missing operand")
668
+ end
669
+
670
+ # @rbs register: Integer
671
+ # @rbs return: Symbol
672
+ def type_of(register)
673
+ register < 0 ? :unknown : @function.register_types.fetch(register)
674
+ end
675
+
676
+ # @rbs type: Symbol
677
+ # @rbs return: Integer
678
+ def pop_typed(type)
679
+ value = pop_value
680
+ fail_translation("expected #{type}, got #{type_of(value)}") unless value < 0 || type_of(value) == type
681
+ value
682
+ end
683
+
684
+ # @rbs destination: Integer
685
+ # @rbs source: Integer
686
+ # @rbs return: void
687
+ def copy_value(destination, source)
688
+ fail_translation("copy type mismatch") unless type_of(destination) == type_of(source)
689
+ emit([type_of(source) == :exnref ? Opcode::COPY_REF : Opcode::COPY, destination, source])
690
+ end
691
+
692
+ # @rbs destinations: Array[Integer]
693
+ # @rbs sources: Array[Integer]
694
+ # @rbs return: void
695
+ def parallel_copy(destinations, sources)
696
+ if sources.size > 1
697
+ sources = sources.map do |source|
698
+ temp = register(type_of(source))
699
+ copy_value(temp, source)
700
+ temp
701
+ end
702
+ end
703
+ destinations.each_with_index { |dst, i| copy_value(dst, sources.fetch(i)) }
704
+ end
705
+
706
+ # @rbs local: Integer
707
+ # @rbs return: void
708
+ def preserve_local(local)
709
+ return unless @stack.include?(local)
710
+ snapshot = register(type_of(local))
711
+ copy_value(snapshot, local)
712
+ @stack.map! { |source| source == local ? snapshot : source }
713
+ end
714
+
715
+ # @rbs return: void
716
+ def snapshot_locals
717
+ @stack.dup.each { |source| preserve_local(source) if source < @function.parameter_count + @function.local_count }
718
+ end
719
+
720
+ # @rbs depth: Integer
721
+ # @rbs return: Wardite::Efflorescence::Translator::Control
722
+ def label(depth)
723
+ fail_translation("invalid branch depth #{depth}") unless depth >= 0 && depth < @controls.size
724
+ @controls.fetch(@controls.size - 1 - depth)
725
+ end
726
+
727
+ # @rbs target: Wardite::Efflorescence::Translator::Control
728
+ # @rbs return: Array[Symbol]
729
+ def label_types(target)
730
+ target.kind == :loop ? [] : target.result_types
731
+ end
732
+
733
+ # @rbs types: Array[Symbol]
734
+ # @rbs return: Array[Integer]
735
+ def top_values(types)
736
+ return [] if types.empty?
737
+
738
+ control = @controls.last || raise(TranslationError, "missing control")
739
+ available = @stack.size - control.entry_stack.size
740
+ if available < types.size
741
+ fail_translation("operand stack underflow") unless control.polymorphic
742
+ values = Array.new(types.size - available, -1) + @stack.last(available)
743
+ else
744
+ values = @stack.last(types.size)
745
+ end
746
+ values.each_with_index do |value, i|
747
+ fail_translation("branch result type mismatch") if value >= 0 && type_of(value) != types.fetch(i)
748
+ end
749
+ values
750
+ end
751
+
752
+ # @rbs target: Wardite::Efflorescence::Translator::Control
753
+ # @rbs sources: Array[Integer]
754
+ # @rbs condition: Integer
755
+ # @rbs return: void
756
+ def branch(target, sources, condition = -1)
757
+ parallel_copy(target.result_registers, sources) unless target.kind == :loop
758
+ emit([Opcode::EH_TRIM, target.handler_depth]) if @handler_depth != target.handler_depth
759
+ pc = target.kind == :loop ? target.start_pc : -1
760
+ position = emit(condition < 0 ? [Opcode::BR, pc] : [Opcode::BR_IF, condition, pc])
761
+ unless target.kind == :loop
762
+ target.patches << position
763
+ target.has_branch = true
764
+ end
765
+ end
766
+
767
+ # @rbs index: Integer
768
+ # @rbs return: Wardite::Efflorescence::Tag
769
+ def tag_at(index)
770
+ fail_translation("invalid tag index #{index}") if index < 0
771
+ @instance.tags[index] || raise(TranslationError, context("invalid tag index #{index}"))
772
+ end
773
+
774
+ # Catch labels resolve before pushing the try_table's own label.
775
+ # @rbs clauses: Array[Integer]
776
+ # @rbs return: Wardite::Efflorescence::HandlerDescriptor
777
+ def make_handler(clauses)
778
+ targets = [] #: Array[Wardite::Efflorescence::CatchTarget]
779
+ clauses.each_slice(3) do |clause|
780
+ kind, tag_index, depth = clause.fetch(0), clause.fetch(1), clause.fetch(2)
781
+ target = label(depth)
782
+ types = kind <= 1 ? tag_at(tag_index).parameter_types.dup : [] #: Array[Symbol]
783
+ reference = kind == 1 || kind == 3
784
+ types << :exnref if reference
785
+ fail_translation("catch payload/label type mismatch") unless types == label_types(target)
786
+ destinations = target.kind == :loop ? [] : target.result_registers.dup #: Array[Integer]
787
+ ref = reference ? (destinations.pop || raise(TranslationError, "missing reference result")) : -1
788
+ entry = CatchTarget.new(tag_index, destinations, ref, target.kind == :loop ? target.start_pc : -1, target.handler_depth)
789
+ if target.kind != :loop
790
+ target.catch_patches << entry
791
+ target.has_branch = true if @reachable
792
+ end
793
+ targets << entry
794
+ end
795
+ HandlerDescriptor.new(targets)
796
+ end
797
+
798
+ # @rbs control: Wardite::Efflorescence::Translator::Control
799
+ # @rbs return: void
800
+ def finish_arm(control)
801
+ height = @stack.size - control.entry_stack.size
802
+ fail_translation("incorrect stack height at end") if height > control.result_types.size
803
+ sources = top_values(control.result_types)
804
+ parallel_copy(control.result_registers, sources) if @reachable && !sources.empty?
805
+ end
806
+
807
+ # @rbs return: void
808
+ def else_control
809
+ control = @controls.last || raise(TranslationError, "unexpected else")
810
+ fail_translation("unexpected else") unless control.kind == :if && !control.else_seen
811
+ finish_arm(control)
812
+ control.then_reachable = @reachable
813
+ control.patches << emit([Opcode::BR, -1]) if @reachable
814
+ patch(control.false_patch, @function.instructions.size) if control.false_patch >= 0
815
+ control.else_seen = true
816
+ control.polymorphic = false
817
+ @stack = control.entry_stack.dup
818
+ @reachable = control.entry_reachable
819
+ end
820
+
821
+ # @rbs return: void
822
+ def end_control
823
+ control = @controls.last || raise(TranslationError, "unexpected end")
824
+ finish_arm(control)
825
+ if control.kind == :try_table
826
+ @handler_depth = control.handler_depth
827
+ emit([Opcode::EH_TRIM, @handler_depth]) if @reachable
828
+ end
829
+ if control.kind == :if && !control.else_seen
830
+ fail_translation("result-bearing if requires else") unless control.result_types.empty?
831
+ patch(control.false_patch, @function.instructions.size) if control.false_patch >= 0
832
+ @reachable ||= control.entry_reachable
833
+ end
834
+ @controls.pop
835
+ pc = @function.instructions.size
836
+ control.patches.each { |position| patch(position, pc) }
837
+ control.catch_patches.each { |entry| entry.target_pc = pc }
838
+ @stack = control.entry_stack.dup + control.result_registers
839
+ @reachable = @reachable || control.has_branch || control.then_reachable
840
+ if control.kind == :function
841
+ emit([Opcode::RETURN, control.result_registers.empty? ? -1 : control.result_registers.fetch(0)])
842
+ end
843
+ end
844
+
845
+ # @rbs return: void
846
+ def mark_unreachable
847
+ control = @controls.last || raise(TranslationError, "missing control")
848
+ control.polymorphic = true
849
+ @stack = control.entry_stack.dup
850
+ @reachable = false
851
+ end
852
+
853
+ # @rbs message: String
854
+ # @rbs return: String
855
+ def context(message)
856
+ "Efflorescence: function #{@function.index}, Wasm PC #{@wasm_pc}: #{message}"
857
+ end
858
+
859
+ # @rbs message: String
860
+ # @rbs return: bot
861
+ def fail_translation(message)
862
+ raise TranslationError, context(message)
863
+ end
864
+ end
865
+ end
866
+ end