1
//! The homes the unit allocated for its stored globals and what its stores
2
//! write into them (plan 0014 stage GJ): a global's home type is the join of
3
//! its init and every store, found by compiling the unit again.
4
//!
5
//! The book is shared by every clone the compile makes, like the work budget,
6
//! because a DOLIST body or a monomorph compiles on a clone. It is replaced
7
//! with each attempt and journalled with the rest of a trial's state.
8

            
9
use std::collections::{BTreeMap, BTreeSet, HashMap};
10
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
11

            
12
use crate::ast::{Expr, StructId, WasmType};
13
use crate::compiler::join::{Arm, fact, reconcile_arms};
14

            
15
use super::table::SymbolTable;
16

            
17
/// What a home belongs to: a stored global, a field every instance of a
18
/// struct layout shares, or an assigned binder: its enclosing function, form
19
/// digest, variable and constant-scope digest.
20
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
21
pub(crate) enum HomeKey {
22
    Global(String),
23
    Field(StructId, u16),
24
    Binder(Option<u64>, u64, String, u64),
25
}
26

            
27
impl HomeKey {
28
1245313
    pub(crate) fn global(name: &str) -> Self {
29
1245313
        Self::Global(name.to_string())
30
1245313
    }
31
}
32

            
33
#[derive(Clone, Debug)]
34
struct Home {
35
    base: Vec<Arm>,
36
    datum: Option<Expr>,
37
    ty: WasmType,
38
    arms: Vec<Arm>,
39
    /// The home is a placeholder `AnyRef` no writer has typed yet.
40
    provisional: bool,
41
    /// The closure a provisional home was first stored.
42
    closure: Option<ClosureShape>,
43
}
44

            
45
/// A global the unit made a cell of before any of its forms compiled.
46
#[derive(Clone, Copy, Debug)]
47
pub(super) struct Cell {
48
    /// The i32 global that is 1 once the cell holds a value.
49
    flag: u32,
50
    seed: Seed,
51
    /// What the unit's definitions compiled so far did to the cell.
52
    defined: CellBinding,
53
}
54

            
55
/// What a cell holds when its unit starts.
56
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57
pub(crate) enum Seed {
58
    Unbound,
59
    /// An earlier unit's constant, so the cell starts bound.
60
    Constant,
61
    /// An earlier unit's lambda, so the cell starts as a closure of it.
62
    Closure,
63
    /// An earlier unit's value no constant holds: the cell starts bound but
64
    /// unreadable, and its flag is 1 once the unit stored a value.
65
    Lost,
66
}
67

            
68
/// Whether the definitions a unit compiled so far bound a cell at run time.
69
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
70
pub(crate) enum CellBinding {
71
    #[default]
72
    Unbound,
73
    /// Only a definition that may be skipped reached it.
74
    Maybe,
75
    Bound,
76
}
77

            
78
impl Home {
79
851380
    fn typed(base: Vec<Arm>, datum: Option<Expr>, ty: WasmType) -> Self {
80
851380
        Self {
81
851380
            base,
82
851380
            datum,
83
851380
            ty,
84
851380
            arms: Vec::new(),
85
851380
            provisional: false,
86
851380
            closure: None,
87
851380
        }
88
851380
    }
89

            
90
18762
    fn provisional() -> Self {
91
18762
        Self {
92
18762
            provisional: true,
93
18762
            ..Self::typed(Vec::new(), None, WasmType::AnyRef)
94
18762
        }
95
18762
    }
96

            
97
51270
    fn joined(&self) -> WasmType {
98
51270
        let arms: Vec<Arm> = self.base.iter().chain(&self.arms).copied().collect();
99
51270
        fact(reconcile_arms(&arms))
100
51270
    }
101

            
102
387861
    fn holds_every_store(&self) -> bool {
103
387861
        if self.provisional {
104
16040
            return self.arms.is_empty() || self.joined() == self.ty;
105
371821
        }
106
371821
        let arms: Vec<Arm> = std::iter::once(Arm::Value(self.ty))
107
371821
            .chain(self.base.iter().copied())
108
371821
            .chain(self.arms.iter().copied())
109
371821
            .collect();
110
371821
        reconcile_arms(&arms) == self.ty
111
387861
    }
112
}
113

            
114
#[derive(Clone, Debug, Default)]
115
pub(crate) struct HomeBook {
116
    hints: BTreeMap<HomeKey, WasmType>,
117
    closure_hints: BTreeMap<String, ClosureShape>,
118
    homes: BTreeMap<HomeKey, Home>,
119
    expired: BTreeSet<String>,
120
    /// The cells of this attempt: each global the unit writes, made at its
121
    /// start. Shared with every scratch copy of the table.
122
    cells: BTreeMap<String, Cell>,
123
    /// The definition forms of this attempt, by slot, and the flag each sets
124
    /// once it has run. Shared with every scratch copy of the table.
125
    pub(super) definitions:
126
        BTreeMap<(String, super::definitions::Slot), Vec<super::definitions::Version>>,
127
    /// The symbols the unit writes, as they stood before it.
128
    pub(super) pre_unit: BTreeMap<String, super::definitions::Written>,
129
    /// The rebind globals of each special global a binder of this attempt saves.
130
    pub(super) rebinds: BTreeMap<u32, super::rebind::Rebind>,
131
    /// The globals this attempt makes cells of because an earlier attempt
132
    /// found their one definition's init runs at run time.
133
    forced: BTreeSet<String>,
134
    /// The globals this attempt found such a definition for, with what its
135
    /// init probes to.
136
    asked: BTreeMap<String, Asked>,
137
    /// The cells this attempt starts without the closure an earlier unit
138
    /// carried, because a store of the previous attempt refused it, and the
139
    /// ones this attempt found such a store for.
140
    unseeded: BTreeSet<String>,
141
    refused: BTreeSet<String>,
142
    /// The global functions the closures this attempt created call, by name.
143
    pub(super) closure_deps: BTreeSet<String>,
144
}
145

            
146
impl HomeBook {
147
    /// The hints for the next attempt, when some home of this one is
148
    /// narrower than its stores: the join recomputed from this attempt's
149
    /// stores for each narrow home, over the hints this attempt started with. A
150
    /// closure joins to `AnyRef`; a provisional home that holds one asks for it.
151
2352322
    fn widened(&self) -> Option<HashMap<HomeKey, WasmType>> {
152
2352322
        let verdicts: Vec<(&HomeKey, &Home, bool)> = self
153
2352322
            .homes
154
2352322
            .iter()
155
778726
            .filter(|(_, home)| !home.arms.is_empty())
156
387857
            .map(|(name, home)| (name, home, home.holds_every_store()))
157
            .collect();
158
2352322
        let narrow = verdicts.iter().any(|(_, _, holds)| !holds)
159
2317304
            || self.holds_new_closure()
160
2314957
            || !self.asked.is_empty()
161
2262465
            || !self.refused.is_empty();
162
2352322
        let mut hints: HashMap<HomeKey, WasmType> = self
163
2352322
            .hints
164
2352322
            .iter()
165
85928
            .map(|(key, ty)| (key.clone(), *ty))
166
            .collect();
167
2352322
        hints.extend(
168
2352322
            verdicts
169
2352322
                .into_iter()
170
387857
                .filter(|(_, _, holds)| !holds)
171
35230
                .map(|(key, home, _)| (key.clone(), home.joined())),
172
        );
173
2352322
        hints.extend(self.asked.iter().filter_map(|(name, asked)| match asked {
174
47759
            Asked::Typed(ty) => Some((HomeKey::global(name), fact(*ty))),
175
5442
            Asked::Closure(_) | Asked::Untyped => None,
176
53201
        }));
177
2352322
        narrow.then_some(hints)
178
2352322
    }
179

            
180
2317304
    fn holds_new_closure(&self) -> bool {
181
2317304
        self.homes.values().any(|home| home.closure.is_some())
182
2317304
    }
183

            
184
    /// The closures the next attempt allocates cells for: those this attempt
185
    /// started with and the ones its provisional homes were first stored.
186
90049
    fn closure_shapes(&self) -> HashMap<String, ClosureShape> {
187
90049
        let mut shapes: HashMap<String, ClosureShape> = self
188
90049
            .closure_hints
189
90049
            .iter()
190
            .map(|(name, shape)| (name.clone(), shape.clone()))
191
            .collect();
192
90102
        shapes.extend(self.homes.iter().filter_map(|(key, home)| match key {
193
29158
            HomeKey::Global(name) => home.closure.clone().map(|shape| (name.clone(), shape)),
194
40865
            HomeKey::Field(..) | HomeKey::Binder(..) => None,
195
70023
        }));
196
90049
        shapes.extend(self.asked.iter().filter_map(|(name, asked)| match asked {
197
3772
            Asked::Closure(shape) => Some((name.clone(), shape.clone())),
198
49429
            Asked::Typed(_) | Asked::Untyped => None,
199
53201
        }));
200
90049
        shapes
201
90049
    }
202
}
203

            
204
26713234
pub(super) fn locked(book: &Mutex<HomeBook>) -> MutexGuard<'_, HomeBook> {
205
26713234
    book.lock().unwrap_or_else(PoisonError::into_inner)
206
26713234
}
207

            
208
impl SymbolTable {
209
    /// Starts an attempt at the unit with a fresh book that carries `hints`.
210
2352333
    pub(crate) fn begin_home_attempt(&mut self, hints: HashMap<HomeKey, WasmType>) {
211
2352333
        self.homes = Arc::new(Mutex::new(HomeBook {
212
2352333
            hints: hints.into_iter().collect(),
213
2352333
            ..HomeBook::default()
214
2352333
        }));
215
2352333
    }
216

            
217
2262243
    pub(crate) fn end_home_attempt(&mut self) {
218
2262243
        self.homes = Arc::default();
219
2262243
    }
220

            
221
    /// The type the stores of the previous attempt asked the home `key` to have.
222
    #[must_use]
223
1146742
    pub(crate) fn hint(&self, key: &HomeKey) -> Option<WasmType> {
224
1146742
        locked(&self.homes).hints.get(key).copied()
225
1146742
    }
226

            
227
    /// Records the home this attempt allocated for `name`, typed `ty` from the
228
    /// `base` arms of its init; a constant init keeps its `datum`.
229
461400
    pub(crate) fn note_home(&self, name: &str, base: Vec<Arm>, datum: Option<Expr>, ty: WasmType) {
230
461400
        if matches!(ty, WasmType::Closure(_)) {
231
1
            return;
232
461399
        }
233
461399
        locked(&self.homes)
234
461399
            .homes
235
461399
            .insert(HomeKey::global(name), Home::typed(base, datum, ty));
236
461400
    }
237

            
238
    /// Records the placeholder home of a cell no writer has typed yet: the
239
    /// next attempt gives it the join of the stores this one compiles.
240
14370
    pub(crate) fn note_provisional_home(&self, name: &str) {
241
14370
        locked(&self.homes)
242
14370
            .homes
243
14370
            .insert(HomeKey::global(name), Home::provisional());
244
14370
    }
245

            
246
    /// Records the closure stored into the provisional home `name`, the first
247
    /// one deciding.
248
3874
    pub(crate) fn note_closure_shape(&self, name: &str, shape: ClosureShape) {
249
3874
        if let Some(home) = locked(&self.homes).homes.get_mut(&HomeKey::global(name))
250
3874
            && home.provisional
251
3861
            && home.closure.is_none()
252
        {
253
2347
            home.closure = Some(shape);
254
1527
        }
255
3874
    }
256

            
257
    /// Keeps the first constant written to `name`'s home as the init a store
258
    /// is typed against.
259
178448
    pub(crate) fn note_home_datum(&self, name: &str, datum: &Expr) {
260
178448
        if let Some(home) = locked(&self.homes).homes.get_mut(&HomeKey::global(name))
261
178444
            && home.datum.is_none()
262
        {
263
14843
            home.datum = Some(datum.clone());
264
163605
        }
265
178448
    }
266

            
267
379227
    fn home_datum(&self, key: &HomeKey) -> Option<Expr> {
268
379227
        locked(&self.homes)
269
379227
            .homes
270
379227
            .get(key)
271
379227
            .and_then(|home| home.datum.clone())
272
379227
    }
273

            
274
    /// Records what a store writes into the home `key`; a home an earlier unit
275
    /// allocated is not in the book and records nothing.
276
810811
    pub(crate) fn note_store(&self, key: &HomeKey, arm: Arm) {
277
810811
        if let Some(home) = locked(&self.homes).homes.get_mut(key) {
278
801089
            home.arms.push(arm);
279
9722
        }
280
810811
    }
281

            
282
    /// The hints for the next attempt, unless every home of this one already
283
    /// has the join of its stores.
284
    #[must_use]
285
2352322
    pub(crate) fn widened_homes(&self) -> Option<HashMap<HomeKey, WasmType>> {
286
2352322
        locked(&self.homes).widened()
287
2352322
    }
288

            
289
    /// A copy of the table where the variable of the home `key` is the
290
    /// constant its home was initialised with, for typing a store as its first
291
    /// execution sees it. None inside such a copy, so a store its trial
292
    /// compiles runs no trial.
293
    #[must_use]
294
379227
    pub(crate) fn probe_at_init(&self, key: &HomeKey, name: &str) -> Option<Self> {
295
379227
        let datum = self.home_datum(key).filter(|_| !self.in_init_trial)?;
296
366513
        let mut probe = self.clone();
297
366513
        probe.in_init_trial = true;
298
366513
        probe.stored_globals.remove(name);
299
366513
        probe.dynamic_specials.remove(name);
300
366513
        probe.lookup_mut(name)?.set_value(datum);
301
366513
        Some(probe)
302
379227
    }
303

            
304
    /// Drops the runtime value of every global or local an earlier unit's
305
    /// module allocated, and with it the manifest no host took: the unit about to
306
    /// compile is a fresh module without them.
307
2352246
    pub(crate) fn expire_homes(&mut self) {
308
2352246
        self.unit_slots.clear();
309
2352246
        self.unit_closures.clear();
310
2352246
        let expired: Vec<String> = self
311
2352246
            .symbols
312
2352246
            .iter_mut()
313
631668848
            .filter(|(_, symbol)| {
314
631668848
                matches!(
315
631668848
                    symbol.value(),
316
                    Some(Expr::WasmGlobal(..) | Expr::WasmLocal(..))
317
                )
318
631668848
            })
319
5
            .map(|(name, symbol)| {
320
5
                symbol.clear_value();
321
5
                name.clone()
322
5
            })
323
            .collect();
324
2352246
        for name in &expired {
325
5
            self.lost_homes.remove(name);
326
        }
327
2352246
        locked(&self.homes).expired.extend(expired);
328
2352246
    }
329

            
330
214741
    pub(super) fn is_expired(&self, name: &str) -> bool {
331
214741
        locked(&self.homes).expired.contains(name)
332
214741
    }
333

            
334
178807
    pub(crate) fn home_book(&self) -> HomeBook {
335
178807
        locked(&self.homes).clone()
336
178807
    }
337

            
338
120043
    pub(crate) fn restore_home_book(&self, book: HomeBook) {
339
120043
        *locked(&self.homes) = book;
340
120043
    }
341
}
342

            
343
mod binders;
344
mod cells;
345
mod fields;
346
mod shapes;
347

            
348
pub(crate) use shapes::{Asked, ClosureShape};
349

            
350
#[cfg(test)]
351
#[path = "homes_tests.rs"]
352
mod tests;