1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use crate::emit::{Emit, EmitContext, Section};
use crate::parse::IndicesToIds;
use crate::{ImportId, InitExpr, Module, Result, ValType};
use id_arena::{Arena, Id};
pub type GlobalId = Id<Global>;
#[derive(Debug)]
pub struct Global {
id: GlobalId,
pub ty: ValType,
pub mutable: bool,
pub kind: GlobalKind,
}
#[derive(Debug)]
pub enum GlobalKind {
Import(ImportId),
Local(InitExpr),
}
impl Global {
pub fn id(&self) -> GlobalId {
self.id
}
}
impl Emit for Global {
fn emit(&self, cx: &mut EmitContext) {
Emit::emit(&self.ty, cx);
cx.encoder.byte(self.mutable as u8);
}
}
#[derive(Debug, Default)]
pub struct ModuleGlobals {
arena: Arena<Global>,
}
impl ModuleGlobals {
pub fn add_import(&mut self, ty: ValType, mutable: bool, import_id: ImportId) -> GlobalId {
let id = self.arena.next_id();
self.arena.alloc(Global {
id,
ty,
mutable,
kind: GlobalKind::Import(import_id),
})
}
pub fn add_local(&mut self, ty: ValType, mutable: bool, init: InitExpr) -> GlobalId {
let id = self.arena.next_id();
self.arena.alloc(Global {
id,
ty,
mutable,
kind: GlobalKind::Local(init),
})
}
pub fn get(&self, id: GlobalId) -> &Global {
&self.arena[id]
}
pub fn get_mut(&mut self, id: GlobalId) -> &mut Global {
&mut self.arena[id]
}
pub fn iter(&self) -> impl Iterator<Item = &Global> {
self.arena.iter().map(|(_, f)| f)
}
}
impl Module {
pub(crate) fn parse_globals(
&mut self,
section: wasmparser::GlobalSectionReader,
ids: &mut IndicesToIds,
) -> Result<()> {
log::debug!("parse global section");
for g in section {
let g = g?;
let id = self.globals.add_local(
ValType::parse(&g.ty.content_type)?,
g.ty.mutable,
InitExpr::eval(&g.init_expr, ids)?,
);
ids.push_global(id);
}
Ok(())
}
}
impl Emit for ModuleGlobals {
fn emit(&self, cx: &mut EmitContext) {
log::debug!("emit global section");
fn get_local<'a>(cx: &EmitContext, global: &'a Global) -> Option<&'a InitExpr> {
if !cx.used.globals.contains(&global.id) {
return None;
}
match &global.kind {
GlobalKind::Import(_) => None,
GlobalKind::Local(local) => Some(local),
}
}
let globals = self
.arena
.iter()
.filter(|(_id, global)| get_local(cx, global).is_some())
.count();
if globals == 0 {
return;
}
let mut cx = cx.start_section(Section::Global);
cx.encoder.usize(globals);
for (id, global) in self.arena.iter() {
if let Some(local) = get_local(&cx, global) {
cx.indices.push_global(id);
global.emit(&mut cx);
local.emit(&mut cx);
}
}
}
}