Skip to content
← Back

src/ir/wasmgc/wasmgc_clone.ghul

1
namespace IR.WasmGC is
2
use IR.Program
3
4
use Wasm.FUNCTION
5
use Wasm.INSTRUCTION
6
use Wasm.INDEX_INSTRUCTION
7
use Wasm.HEAP_TYPE_INSTRUCTION
8
use Wasm.TYPE_INSTRUCTION
9
use Wasm.TYPE_FIELD_INSTRUCTION
10
use Wasm.HEAP_TYPE
11
use Wasm.VALUE_TYPE
12
use Wasm.Opcode
13
14
use Collections.LIST
15
16
/// The cloners: for each class, a function that makes a shallow copy of
17
/// an instance, reached through the class's descriptor by
18
/// `memberwise_clone`. WasmGC has no instruction that copies a struct of
19
/// a type it does not know, so each class copies its own fields.
20
///
21
/// A field of struct type is held in a box, which is copied too, so the
22
/// copy's struct is its own as it is on .NET. Cloners are made only
23
/// where the program reaches `memberwise_clone`.
24
class WASMGC_CLONE is
25
_registry: WASMGC_TYPE_REGISTRY
26
27
init(registry: WASMGC_TYPE_REGISTRY) is
28
_registry = registry
29
si
30
31
/// Reserves the cloner of each class, where the program copies an
32
/// object, and records it in the class's descriptor.
33
///
34
/// - numbering: the defined functions the cloners are numbered among
35
reserve(numbering: WASMGC_FUNCTION_NUMBERING) is
36
let registry = _registry
37
38
if !registry.clones_wanted then
39
return
40
fi
41
42
let signature = registry.clone_signature
43
44
for type in registry.classes_and_arrays do
45
if !registry.is_array(type) /\ registry.type_index(type)? /\ registry.is_instantiated(type) then
46
let index = registry.type_index(type)!
47
48
registry.set_cloner(
49
type,
50
numbering.reserve(() -> FUNCTION => FUNCTION(signature, [VALUE_TYPE.of_type_index(index, true)], _body(type, index))))
51
fi
52
od
53
si
54
55
// Copies the object in parameter 0, which is an instance of `type`,
56
// field by field into a new one, the descriptor included.
57
_body(type: CLASS_INSTANCE, index: int) -> LIST[INSTRUCTION] is
58
let registry = _registry
59
let layout = registry.field_value_types(type)
60
let layout_types = registry.field_types(type)
61
let body = LIST[INSTRUCTION]()
62
63
body.add(INDEX_INSTRUCTION(Opcode.LOCAL_GET, 0))
64
body.add(HEAP_TYPE_INSTRUCTION(Opcode.REF_CAST, HEAP_TYPE.of_type_index(index)))
65
body.add(INDEX_INSTRUCTION(Opcode.LOCAL_SET, 1))
66
67
for i in 0..layout.count do
68
body.add(INDEX_INSTRUCTION(Opcode.LOCAL_GET, 1))
69
body.add(TYPE_FIELD_INSTRUCTION(Opcode.STRUCT_GET, index, i))
70
71
if i > 0 then
72
if let held = if i < layout_types.count then registry.struct_of(layout_types[i]) else null fi,
73
cloner = registry.cloner_of(held),
74
held_index = registry.type_index(held)
75
then
76
body.add(INDEX_INSTRUCTION(Opcode.CALL, cloner))
77
body.add(HEAP_TYPE_INSTRUCTION(Opcode.REF_CAST, HEAP_TYPE.of_type_index(held_index)))
78
fi
79
fi
80
od
81
82
body.add(TYPE_INSTRUCTION(Opcode.STRUCT_NEW, index))
83
84
return body
85
si
86
si
87
si