1
//! The unit prologue of the session's struct instances (rstruct S5): each is
2
//! allocated into an exported global holding nil fields, then every field
3
//! takes its carried constant, all in bounded helper functions. All are
4
//! allocated first, so a cycle resolves. The unit's cells are seeded after
5
//! them in the same guarded run, so SHOULD-APPLY sees them as `process` does.
6

            
7
use wasm_encoder::BlockType;
8

            
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::fold::stores::StoreScan;
12
use crate::compiler::native::push_constant_arm;
13
use crate::error::{Error, Result};
14
use crate::runtime::{StructInstance, SymbolTable};
15

            
16
use super::cells::{adopt_closures, allocate_cells};
17

            
18
2341606
pub(in crate::compiler) fn allocate_instances(
19
2341606
    ctx: &mut CompileContext,
20
2341606
    emit: &mut FunctionEmitter,
21
2341606
    symbols: &mut SymbolTable,
22
2341606
    scan: &StoreScan,
23
2341606
) -> Result<()> {
24
2341606
    ctx.set_struct_serial_base(symbols.next_serial());
25
2341606
    let heap: Vec<(u32, StructInstance)> = symbols
26
2341606
        .instances()
27
1941494
        .map(|(serial, instance)| (serial, instance.clone()))
28
        .collect();
29
2341606
    let homes = heap
30
2341606
        .iter()
31
1941494
        .map(|(serial, instance)| declare_instance(ctx, symbols, *serial, instance))
32
        .collect::<Result<Vec<_>>>()?;
33
2341606
    let mut steps = Vec::new();
34
2341606
    for (index, chunk) in homes.chunks(INSTANCES_PER_FUNCTION).enumerate() {
35
59069
        let name = format!("__instance_alloc_{index}");
36
59069
        steps.push(in_helper(ctx, &name, |ctx, helper| {
37
59069
            chunk
38
59069
                .iter()
39
1941494
                .try_for_each(|home| allocate_instance(ctx, helper, home))
40
59069
        })?);
41
    }
42
2341606
    for (index, chunk) in heap.chunks(INSTANCES_PER_FUNCTION).enumerate() {
43
59069
        let name = format!("__instance_fill_{index}");
44
59069
        steps.push(in_helper(ctx, &name, |ctx, helper| {
45
1941494
            chunk.iter().try_for_each(|(serial, instance)| {
46
1941494
                fill_instance(ctx, helper, symbols, *serial, instance)
47
1941494
            })
48
59069
        })?);
49
    }
50
2341606
    let done = ctx.alloc_prologue_flag()?;
51
2341606
    steps.push(in_helper(ctx, "__cells_init", |ctx, helper| {
52
2341606
        allocate_cells(ctx, helper, symbols, scan)?;
53
2341606
        adopt_closures(ctx, helper, symbols, scan)
54
2341606
    })?);
55
2341398
    let init = in_helper(ctx, "__instances_init", |_, helper| {
56
2341398
        emit_guarded_steps(helper, done, &steps)
57
2341398
    })?;
58
2341398
    ctx.set_instances_init(init);
59
2341398
    ctx.call_instances_init(emit)
60
2341606
}
61

            
62
/// Runs `steps` unless the flag `done` says they ran, then raises the flag, so
63
/// a trap partway leaves it down and the carried heap untouched.
64
2341398
fn emit_guarded_steps(helper: &mut FunctionEmitter, done: u32, steps: &[u32]) -> Result<()> {
65
2341398
    helper.global_get(done);
66
2341398
    helper.i32_eqz();
67
2341398
    helper.if_block(BlockType::Empty);
68
2459536
    steps.iter().for_each(|&step| helper.call(step));
69
2341398
    helper.i32_const(1);
70
2341398
    helper.global_set(done);
71
2341398
    helper.block_end()
72
2341398
}
73

            
74
/// The engine compiles a function in time superlinear in its size, so the
75
/// prologue rides bounded functions called in order.
76
const INSTANCES_PER_FUNCTION: usize = 256;
77

            
78
/// Emits `body` into a fresh helper function and returns its index.
79
4801142
fn in_helper(
80
4801142
    ctx: &mut CompileContext,
81
4801142
    name: &str,
82
4801142
    body: impl FnOnce(&mut CompileContext, &mut FunctionEmitter) -> Result<()>,
83
4801142
) -> Result<u32> {
84
4801142
    let func_idx = ctx.register_function(name, &[], &[])?;
85
4801142
    let slot = ctx.reserve_helper();
86
4801142
    let snapshot = ctx.take_local_pool(0);
87
4801142
    let mut helper = FunctionEmitter::new();
88
4801142
    let emitted = body(ctx, &mut helper);
89
4801142
    let locals = ctx.build_helper_locals(0);
90
4801142
    ctx.restore_local_pool(snapshot);
91
4801142
    emitted?;
92
4800934
    let locals = locals?;
93
4800934
    ctx.fill_helper(slot, helper.finish(&locals)?)?;
94
4800934
    Ok(func_idx)
95
4801142
}
96

            
97
/// A session instance's global and the layout it is allocated from.
98
struct Home {
99
    serial: u32,
100
    global: u32,
101
    layout_global: u32,
102
    size: usize,
103
}
104

            
105
1941494
fn declare_instance(
106
1941494
    ctx: &mut CompileContext,
107
1941494
    symbols: &SymbolTable,
108
1941494
    serial: u32,
109
1941494
    instance: &StructInstance,
110
1941494
) -> Result<Home> {
111
1941494
    let layout = symbols
112
1941494
        .struct_layout(instance.layout)
113
        .ok_or_else(|| Error::Compile(format!("instance {serial} has no struct layout")))?;
114
1941494
    let layout_global = ctx.struct_layout_global(instance.layout, layout)?;
115
1941494
    let global = ctx.alloc_instance_global(serial)?;
116
1941494
    Ok(Home {
117
1941494
        serial,
118
1941494
        global,
119
1941494
        layout_global,
120
1941494
        size: layout.fields.len(),
121
1941494
    })
122
1941494
}
123

            
124
1941494
fn allocate_instance(ctx: &CompileContext, emit: &mut FunctionEmitter, home: &Home) -> Result<()> {
125
1941494
    let serial = i32::try_from(home.serial)
126
        .map_err(|_| Error::Resource("too many struct instances".to_string()))?;
127
1941494
    let size = i32::try_from(home.size)
128
        .map_err(|_| Error::Compile("struct layout exceeds i32".to_string()))?;
129
1941494
    emit.i32_const(serial);
130
1941494
    emit.global_get(home.layout_global);
131
1941494
    emit.i32_const(size);
132
1941494
    emit.array_new_default(ctx.ids.ty_slots);
133
1941494
    emit.struct_new(ctx.ids.ty_struct);
134
1941494
    emit.global_set(home.global);
135
1941494
    Ok(())
136
1941494
}
137

            
138
1941494
fn fill_instance(
139
1941494
    ctx: &mut CompileContext,
140
1941494
    emit: &mut FunctionEmitter,
141
1941494
    symbols: &mut SymbolTable,
142
1941494
    serial: u32,
143
1941494
    instance: &StructInstance,
144
1941494
) -> Result<()> {
145
1941494
    let global = ctx.instance_global(serial)?;
146
1941494
    for (slot, value) in (0..).zip(&instance.fields) {
147
1943782
        emit.global_get(global);
148
1943782
        emit.struct_get(ctx.ids.ty_struct, 2);
149
1943782
        emit.i32_const(slot);
150
1943782
        let arm = push_constant_arm(ctx, emit, symbols, value)?;
151
1943782
        emit.array_set(ctx.ids.ty_slots);
152
1943782
        symbols.note_field_store(instance.layout, u16::try_from(slot).map_err(too_many)?, arm);
153
    }
154
1941494
    Ok(())
155
1941494
}
156

            
157
fn too_many(_: std::num::TryFromIntError) -> Error {
158
    Error::Compile("struct layout exceeds u16 fields".to_string())
159
}
160

            
161
#[cfg(test)]
162
#[path = "instances_tests.rs"]
163
mod tests;