wasi_virt_layer_cli/generator/
shared_global.rs1use eyre::{Context as _, ContextCompat as _};
2use walrus::FunctionId;
3
4use crate::{
5 args::TargetMemoryType,
6 generator::{
7 Generator,
8 start_section::{StartFnInfo, StartFnPriority, StartSource},
9 },
10 instrs::InstrRewrite as _,
11 unique_name::UniqueName,
12 util::{
13 WalrusFID as _, WalrusUtilExport, WalrusUtilFuncs as _, WalrusUtilImport as _,
14 WalrusUtilModule as _,
15 },
16};
17
18#[derive(Debug, Default)]
51pub struct SharedGlobal;
52
53#[derive(Debug, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
55#[strum(serialize_all = "snake_case")]
56pub enum SharedGlobalFnsName {
57 GlobalAltSet,
59 GlobalAltGet,
61 GlobalAltGetNoWait,
63 GlobalAltInitOnce,
65 GlobalAltPos,
67 Locker(usize),
69 #[strum(serialize = "locker")]
70 LockerBase,
72 #[strum(serialize = "alt")]
73 MemoryGrowAlt,
75}
76
77impl SharedGlobalFnsName {
78 pub fn check_locker(str: impl AsRef<str>) -> Option<SharedGlobalFnsName> {
80 let s = str.as_ref();
81 let prefix = crate::unique_name::fmt!(SharedGlobalFns; "{}", SharedGlobalFnsName::Locker(0).as_ref());
82 if s.starts_with(&prefix) && s.len() > prefix.len() {
83 let index_str = &s[prefix.len() + 1..];
84 if let Ok(index) = index_str.parse::<usize>() {
85 return Some(SharedGlobalFnsName::Locker(index));
86 }
87 }
88 None
89 }
90}
91
92impl SharedGlobal {
93 fn post_lower_memory_inner(
94 module: &mut walrus::Module,
95 ctx: &crate::generator::GeneratorCtx,
96 ) -> eyre::Result<()> {
97 use std::collections::{HashMap, HashSet};
98 use walrus::ir::*;
99
100 if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
101 unreachable!();
102 }
103
104 if !ctx.threads {
105 return Ok(());
106 }
107
108 let used_mem_id = module
109 .funcs
110 .all_read(
111 |instr, _| {
112 if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
113 Some(*memory)
114 } else {
115 None
116 }
117 },
118 &[] as &[walrus::FunctionId],
119 )?
120 .into_iter()
121 .filter_map(|v| v)
122 .collect::<HashSet<_>>();
123
124 let lockers = used_mem_id
125 .into_iter()
126 .map(|mem_id| {
127 Self::gen_custom_locker(module, mem_id, ctx.unstable_print_debug)
128 .wrap_err("Failed to generate custom locker function")
129 .map(|(locker_id, export_name)| (mem_id, (locker_id, export_name)))
130 })
131 .collect::<eyre::Result<HashMap<_, _>>>()?;
132
133 Self::remove_gen_custom_locker_base(module, ctx.unstable_print_debug)
134 .wrap_err("Failed to remove base locker function")?;
135
136 module.funcs.all_rewrite(
137 |instr, _| {
138 if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
139 *instr = Instr::Call(Call {
140 func: lockers.get(memory).unwrap().to_owned().0,
141 });
142 }
143 },
144 &lockers.values().map(|(v, _)| *v).collect::<Vec<_>>(),
145 )?;
146
147 let global_set_alt_without_lock =
148 UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltSet)
149 .get_fid(&module.exports)?;
150 let global_init_alt_without_lock_once =
151 UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltInitOnce)
152 .get_fid(&module.exports)?;
153 let global_get_alt_with_lock =
154 UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltGet)
155 .get_fid(&module.exports)?;
156 let global_get_alt_without_lock =
157 UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltGetNoWait)
158 .get_fid(&module.exports)?;
159
160 let global = module
161 .globals
162 .iter()
163 .last()
164 .map(|g| g)
165 .wrap_err_with(|| eyre::eyre!("Failed to get global ID"))?;
166
167 let init = match global.kind {
168 walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(value))) => {
169 value
170 }
171 _ => unreachable!(),
172 };
173
174 let global_id = global.id();
175
176 let global_alt_pos = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltPos)
178 .get_fid(&module.exports)?;
179 module
194 .exports
195 .erase_with(global_alt_pos, ctx.unstable_print_debug)?;
196
197 let start_id = if let Some(id) = module.start {
199 module
200 .nested_copy_func(id, &[id], false, false)
201 .wrap_err("Failed to create start function copy")?
202 } else {
203 module.add_func(&[], &[], |_, _| Ok(()))?
205 };
206 module.start = Some(start_id);
207
208 if 0usize
209 < module
210 .funcs
211 .flat_rewrite(
212 |instr, _| match instr {
213 walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
214 if *global == global_id =>
215 {
216 1usize
217 }
218 walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
219 if *global == global_id =>
220 {
221 *instr = walrus::ir::Instr::Const(walrus::ir::Const {
222 value: walrus::ir::Value::I32(init),
223 });
224 0usize
226 }
227 _ => 0usize,
228 },
229 start_id,
230 false,
231 )?
232 .into_iter()
233 .sum()
234 {
235 eyre::bail!(
236 "The start section already contains a global set instruction. \
237 Please remove it manually and try again."
238 );
239 }
240
241 let start_local = module.funcs.get_mut(start_id).kind.unwrap_local_mut();
242 start_local
243 .builder_mut()
244 .func_body()
245 .i32_const(init)
246 .call(global_init_alt_without_lock_once);
247
248 for (_, (locker_id, name)) in lockers {
250 use walrus::ir::*;
252 let new_locker =
253 module.nested_copy_func(locker_id, &[] as &[FunctionId], true, true)?;
255
256 module.funcs.flat_rewrite(
257 |instr, _| match instr {
258 Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
259 *instr = Instr::Call(Call {
260 func: global_get_alt_without_lock,
261 });
262 }
263 _ => {}
264 },
265 new_locker,
266 true,
267 )?;
268
269 module.renew_call_fn(locker_id, new_locker)?;
270
271 module.exports.erase_with(&name, ctx.unstable_print_debug)?;
272 }
273
274 module
275 .funcs
276 .all_rewrite(
277 |instr, _| match instr {
278 walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
279 if *global == global_id =>
280 {
281 *instr = walrus::ir::Instr::Call(walrus::ir::Call {
282 func: global_set_alt_without_lock,
283 });
284 }
285 walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
286 if *global == global_id =>
287 {
288 *instr = walrus::ir::Instr::Call(walrus::ir::Call {
289 func: global_get_alt_with_lock,
290 });
291 }
292 _ => {}
293 },
294 &[] as &[walrus::FunctionId],
295 )
296 .wrap_err("Failed to rewrite global set/get")?;
297
298 module.globals.delete(global_id);
299
300 module
301 .exports
302 .erase_with(global_set_alt_without_lock, ctx.unstable_print_debug)?;
303 module
304 .exports
305 .erase_with(global_init_alt_without_lock_once, ctx.unstable_print_debug)?;
306 module
307 .exports
308 .erase_with(global_get_alt_with_lock, ctx.unstable_print_debug)?;
309 module
310 .exports
311 .erase_with(global_get_alt_without_lock, ctx.unstable_print_debug)?;
312
313 Ok(())
314 }
315}
316
317impl Generator for SharedGlobal {
318 fn post_lower_memory(
319 &mut self,
320 _module: &mut walrus::Module,
321 ctx: &crate::generator::GeneratorCtx,
322 ) -> eyre::Result<()> {
323 if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
324 unreachable!();
325 }
326
327 if !ctx.threads {
328 return Ok(());
329 }
330
331 ctx.start_section_builder
332 .as_ref()
333 .unwrap()
334 .add_start_fn(StartFnInfo {
335 priority: StartFnPriority::AfterAll,
336 source: StartSource::Rewrite(Some(Box::new(|module, ctx| {
337 SharedGlobal::post_lower_memory_inner(module, ctx)
338 }))),
339 });
340
341 Ok(())
342 }
343}
344
345impl SharedGlobal {
346 #[allow(unused_variables)]
347 fn gen_custom_locker(
348 module: &mut walrus::Module,
349 mem_id: walrus::MemoryId,
350 is_debug: bool,
351 ) -> eyre::Result<(walrus::FunctionId, String)> {
352 let alt_id = (
353 "wasip1-vfs_single_memory",
354 &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
355 )
356 .get_fid(&module.imports)?;
357 let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
358 .get_fid(&module.exports)?;
359
360 let locker_id = module.copy_func(base_locker)?;
361
362 let export_name =
363 UniqueName::SharedGlobalFns(&SharedGlobalFnsName::Locker(mem_id.index())).to_string();
364 {
366 module.exports.add(&export_name, locker_id);
367 }
368
369 let locker = module.funcs.get_mut(locker_id);
370
371 use walrus::ir::*;
372
373 locker
374 .kind
375 .unwrap_local_mut()
376 .builder_mut()
377 .func_body()
378 .rewrite(|instr, _| {
379 if let Instr::Call(Call { func }) = instr {
380 if *func == alt_id {
381 *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
382 }
383 }
384 })?;
385
386 Ok((locker_id, export_name))
387 }
388
389 fn remove_gen_custom_locker_base(module: &mut walrus::Module, debug: bool) -> eyre::Result<()> {
390 use walrus::ir::*;
391
392 let alt_id = (
393 "wasip1-vfs_single_memory",
394 &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
395 )
396 .get_fid(&module.imports)?;
397 let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
398 .get_fid(&module.exports)?;
399 if !debug {
400 module.funcs.delete(base_locker);
401 module.funcs.delete(alt_id);
402
403 module.exports.erase_with(base_locker, debug)?;
404 } else {
405 let mem_id = module.memories.iter().next().unwrap().id();
406
407 module
408 .funcs
409 .get_mut(base_locker)
410 .kind
411 .unwrap_local_mut()
412 .builder_mut()
413 .func_body()
414 .rewrite(|instr, _| {
415 if let Instr::Call(Call { func }) = instr {
416 if *func == alt_id {
417 *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
418 }
419 }
420 })?;
421 }
422
423 module.imports.erase(alt_id)?;
424
425 Ok(())
426 }
427}