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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/// Output of [`emit_ir_function`]: the emitted bytes plus the call / token
/// patches the caller must still resolve against the full bytecode buffer.
type EmitIrOutput = Result<(Vec<u8>, Vec<CallPatch>, Vec<MethodTokenPatch>), String>;
fn emit_ir_function(
function: &ir::Function,
module: &ir::Module,
method: &FunctionMetadata,
use_callt: bool,
) -> EmitIrOutput {
use std::{collections::HashMap, convert::TryFrom};
let mut local = Vec::new();
// Task #106 — for externally-callable functions, INITSLOT arg_count must
// reflect the FLATTENED struct-field count so Ethereum-style callers
// that push tuple fields individually (the canonical ABI encoding of a
// struct arg) can deposit each field into its own slot. Without this,
// INITSLOT pops only one item for `f(P p)` and the other fields leak
// onto the stack, breaking selector/payload round-trips.
//
// Internal functions keep the nominal parameter count because they are
// called via `CallFunction` which never unpacks structs.
let nominal_arg_count = method.parameters.len();
let flat_arg_count = if matches!(
method.visibility,
VisibilityKind::External | VisibilityKind::Public
) {
flat_param_slot_count_from_value_types(&function.parameters)
} else {
nominal_arg_count
};
let arg_count = u8::try_from(flat_arg_count).unwrap_or(u8::MAX);
let local_count = u8::try_from(function.local_count).unwrap_or(u8::MAX);
if local_count > 0 || arg_count > 0 {
local.push(0x57); // INITSLOT
local.push(local_count);
local.push(arg_count);
}
let mut label_offsets: HashMap<usize, u32> = HashMap::new();
let mut jump_patches: Vec<(usize, usize)> = Vec::new();
let mut call_patches: Vec<CallPatch> = Vec::new();
let mut token_patches: Vec<MethodTokenPatch> = Vec::new();
for block in &function.basic_blocks {
for instruction in &block.instructions {
match instruction {
ir::Instruction::Drop(_) => local.push(0x45),
ir::Instruction::LoadParameter(index) => {
emit_load_parameter(&mut local, method, *index)
}
ir::Instruction::StoreParameter(index) => {
emit_store_parameter(&mut local, *index)
}
ir::Instruction::PushLiteral(literal) => {
push_literal_value(&mut local, literal);
}
ir::Instruction::BinaryOp(operator) => emit_binary_op(&mut local, *operator),
ir::Instruction::Return | ir::Instruction::ReturnVoid => local.push(0x40),
ir::Instruction::ReturnDefault(value_type) => {
append_default_value(&mut local, value_type);
local.push(0x40);
}
ir::Instruction::LoadState(index) => emit_load_state(&mut local, module, *index),
ir::Instruction::StoreState(index) => emit_store_state(&mut local, module, *index),
ir::Instruction::LoadStorageDynamic => emit_load_storage_dynamic(&mut local),
ir::Instruction::LoadLocal(index) => emit_load_local(&mut local, *index),
ir::Instruction::StoreLocal(index) => emit_store_local(&mut local, *index),
ir::Instruction::LoadMappingElement {
state_index,
key_types,
} => emit_load_mapping(
&mut local,
module,
*state_index,
key_types,
use_callt,
&mut token_patches,
),
ir::Instruction::StoreMappingElement {
state_index,
key_types,
} => emit_store_mapping(
&mut local,
module,
*state_index,
key_types,
use_callt,
&mut token_patches,
),
ir::Instruction::StoreArrayDeepCopy {
state_index,
key_types,
} => emit_store_mapping_array_deep_copy(
&mut local,
module,
*state_index,
key_types,
use_callt,
&mut token_patches,
),
ir::Instruction::LoadStructField {
state_index,
key_types,
field_keys,
field_type,
..
} => emit_load_struct_field(
&mut local,
module,
*state_index,
key_types,
StructFieldAccess {
field_keys: field_keys.as_slice(),
ty: field_type,
},
use_callt,
&mut token_patches,
),
ir::Instruction::StoreStructField {
state_index,
key_types,
field_keys,
field_type,
..
} => {
emit_store_struct_field(
&mut local,
module,
*state_index,
key_types,
StructFieldAccess {
field_keys: field_keys.as_slice(),
ty: field_type,
},
use_callt,
&mut token_patches,
)
}
ir::Instruction::LoadStructArrayElement {
state_index,
key_types,
field_keys,
element_type,
} => emit_load_struct_array_element(
&mut local,
module,
*state_index,
key_types,
StructArrayElementAccess {
field_keys: field_keys.as_slice(),
element_type,
},
use_callt,
&mut token_patches,
),
ir::Instruction::StoreStructArrayElement {
state_index,
key_types,
field_keys,
element_type,
} => emit_store_struct_array_element(
&mut local,
module,
*state_index,
key_types,
StructArrayElementAccess {
field_keys: field_keys.as_slice(),
element_type,
},
use_callt,
&mut token_patches,
),
ir::Instruction::LoadStructFieldMappingElement {
state_index,
key_types,
field_keys,
trailing_key_types,
value_type,
} => {
let slot = StructFieldMappingSlot {
module,
state_index: *state_index,
key_types,
field_keys: field_keys.as_slice(),
trailing_key_types,
use_callt,
};
emit_load_struct_field_mapping_element(
&mut local,
&slot,
value_type,
&mut token_patches,
)
}
ir::Instruction::StoreStructFieldMappingElement {
state_index,
key_types,
field_keys,
trailing_key_types,
} => {
let slot = StructFieldMappingSlot {
module,
state_index: *state_index,
key_types,
field_keys: field_keys.as_slice(),
trailing_key_types,
use_callt,
};
emit_store_struct_field_mapping_element(
&mut local,
&slot,
&mut token_patches,
)
}
ir::Instruction::LoadRuntimeValue(value) => {
emit_load_runtime_value(&mut local, value, use_callt, &mut token_patches)
}
ir::Instruction::GetSize => local.push(0xCA),
ir::Instruction::CallBuiltin { builtin, arg_count } => {
emit_builtin_call(
&mut local,
builtin,
*arg_count,
use_callt,
&mut token_patches,
);
}
ir::Instruction::CallFunction { name, arg_count } => {
// NeoVM's `INITSLOT` assigns argument slots by popping values from the
// evaluation stack in order, meaning the callee sees the last-pushed value
// as `arg0`. Solidity evaluates arguments left-to-right, so call sites push
// `arg0, arg1, ...` onto the stack. Before calling, reverse the argument
// segment so that `arg0` is on top and parameters arrive in the expected
// order inside the callee.
if *arg_count > 1 {
push_integer_bigint(&mut local, &BigInt::from(*arg_count));
local.push(0x55); // REVERSEN
}
// NeoVM CALL_L uses a 4-byte signed offset relative to the
// beginning of the CALL_L instruction. We always use the
// wide form for simplicity.
local.push(0x35); // CALL_L
let patch_pos = local.len();
local.extend_from_slice(&[0, 0, 0, 0]);
call_patches.push(CallPatch {
position: patch_pos,
target: name.clone(),
kind: CallPatchKind::CallRelative,
});
}
ir::Instruction::PushFunctionOffset { name } => {
// Task #186 — push the target function as a code POINTER via
// PUSHA (a signed offset relative to the PUSHA opcode, fixed
// up after all methods are emitted), which `CALLA` consumes.
// Real NeoVM `CALLA` requires a `Pointer` produced by `PUSHA`;
// the previous `PUSHINT32` pushed a bare Integer that faults
// on-chain ("not a Pointer"), even though the local runtime —
// which models CALLA as popping an integer position — masked it.
local.push(0x0A); // PUSHA
let patch_pos = local.len();
local.extend_from_slice(&[0, 0, 0, 0]);
call_patches.push(CallPatch {
position: patch_pos,
target: name.clone(),
kind: CallPatchKind::AbsoluteOffset,
});
}
ir::Instruction::CallIndirect { arg_count, .. } => {
// Task #186 — indirect call through an internal function-
// pointer value.
//
// IR-layer convention: emit `PushFunctionOffset` FIRST,
// then the N argument expressions left-to-right. The stack
// going into this instruction is therefore:
// [..., target, arg0, arg1, ..., argN-1]
// (argN-1 on top).
//
// NeoVM `INITSLOT` binds arg0 = first popped = top-of-stack,
// so the callee needs `arg0` on top after CALLA consumes
// `target`. REVERSEN(arg_count + 1) flips the window to:
// [..., argN-1, ..., arg1, arg0, target]
// CALLA then pops `target` and jumps, leaving:
// [..., argN-1, ..., arg1, arg0]
// which INITSLOT pops into slot 0 = arg0, slot 1 = arg1, ...
if *arg_count >= 1 {
push_integer_bigint(&mut local, &BigInt::from(*arg_count + 1));
local.push(0x55); // REVERSEN
}
local.push(0x36); // CALLA
}
ir::Instruction::EmitEvent {
event_index,
arg_count,
} => emit_event(&mut local, module, *event_index, *arg_count),
ir::Instruction::EmitEventByName { name, arg_count } => {
emit_event_by_name(&mut local, name, *arg_count)
}
ir::Instruction::Convert { target } => emit_convert(&mut local, *target),
ir::Instruction::IsType { target } => emit_is_type(&mut local, *target),
ir::Instruction::NewBuffer => emit_new_buffer(&mut local),
ir::Instruction::NewArray { .. } => emit_new_array(&mut local),
ir::Instruction::NewMap => local.push(0xC8), // NEWMAP
ir::Instruction::ArrayGet => emit_array_get(&mut local),
ir::Instruction::ArraySet => emit_array_set(&mut local),
ir::Instruction::HasKey => local.push(0xCB), // HASKEY
ir::Instruction::MemCpy => {
local.push(0x89); // MEMCPY
}
ir::Instruction::Substr => {
local.push(0x8C); // SUBSTR
}
ir::Instruction::ReverseItems => {
local.push(0xD1); // REVERSEITEMS
}
ir::Instruction::BitwiseNot => {
local.push(0x90); // INVERT
}
ir::Instruction::LogicalNot => {
local.push(0xAA); // NOT (logical boolean negation)
}
ir::Instruction::Try { catch_target } => {
// NeoVM TRY_L uses 4-byte signed offsets (catch, finally) relative to
// the beginning of the TRY_L instruction. We always emit the wide form
// and omit `finally` (offset = 0).
local.push(0x3C); // TRY_L
let position = local.len();
local.extend_from_slice(&[0, 0, 0, 0]); // catch offset placeholder
jump_patches.push((position, *catch_target));
local.extend_from_slice(&[0, 0, 0, 0]); // finally offset (absent)
}
ir::Instruction::EndTry { target } => {
// NeoVM ENDTRY_L uses a 4-byte signed offset relative to the beginning
// of the ENDTRY_L instruction. We always emit the wide form.
local.push(0x3E); // ENDTRY_L
let position = local.len();
local.extend_from_slice(&[0, 0, 0, 0]);
jump_patches.push((position, *target));
}
ir::Instruction::Jump { target } => {
// NeoVM JMP_L uses a 4-byte signed offset relative to the
// beginning of the JMP_L instruction. We always use the
// wide form for simplicity.
local.push(0x23); // JMP_L
let position = local.len();
local.extend_from_slice(&[0, 0, 0, 0]);
jump_patches.push((position, *target));
}
ir::Instruction::JumpIf { target } => {
// IR JumpIf branches when the condition is false.
// NeoVM JMPIFNOT_L uses a 4-byte signed offset relative to the
// beginning of the JMPIFNOT_L instruction.
local.push(0x27); // JMPIFNOT_L
let position = local.len();
local.extend_from_slice(&[0, 0, 0, 0]);
jump_patches.push((position, *target));
}
ir::Instruction::Label(label) => {
label_offsets.insert(*label, local.len() as u32);
}
ir::Instruction::AbortMsg => {
local.push(0xE0); // ABORTMSG
}
ir::Instruction::Abort => {
local.push(0x38); // ABORT
}
ir::Instruction::Throw => {
local.push(0x3A); // THROW
}
ir::Instruction::Dup => {
local.push(0x4A); // DUP
}
ir::Instruction::Swap => {
local.push(0x50); // SWAP
}
}
}
}
for (position, label) in jump_patches {
// M-BC1 fix — guard against an unresolved label or an out-of-range
// patch position. An unresolved label previously fell through to
// `local.len()` silently (turning the jump into a jump-to-RET); an
// out-of-range `position` (possible if the dead-code pruner removed a
// label but left its jump operand) would panic the slice write. Both
// are compiler-internal bugs; surface them as a hard error instead.
let Some(&target) = label_offsets.get(&label) else {
return Err(format!(
"bytecode emission: jump target label {label} unresolved (dead-code pruner likely removed it)"
));
};
if position + 4 > local.len() {
return Err(format!(
"bytecode emission: jump patch position {position} out of range (local len {})",
local.len()
));
}
let target_offset = target as i32;
// `position` points at the beginning of the 4-byte operand; the opcode
// is immediately before it.
let opcode_pos = (position - 1) as i32;
let relative = target_offset.checked_sub(opcode_pos).unwrap_or(0);
local[position..position + 4].copy_from_slice(&relative.to_le_bytes());
}
Ok((local, call_patches, token_patches))
}
fn append_default_value(bytecode: &mut Vec<u8>, value_type: &ValueType) {
match value_type {
ValueType::Integer { .. } => bytecode.push(0x10),
// Solidity booleans are represented as 0/1 values on the stack. Use PUSH0 for the
// default `false` to match numeric/ABI semantics.
ValueType::Boolean => bytecode.push(0x10), // PUSH0
ValueType::String => push_data(bytecode, &[]),
ValueType::Address => push_data(bytecode, &[0u8; 20]),
ValueType::ByteArray { fixed_len } => {
if let Some(len) = fixed_len {
let zeros = vec![0u8; *len as usize];
push_data(bytecode, &zeros);
} else {
push_data(bytecode, &[]);
}
}
ValueType::Array(_) => bytecode.push(0xC2), // NEWARRAY0
ValueType::Mapping { .. } => bytecode.push(0xC8), // NEWMAP
ValueType::Struct { .. } => bytecode.push(0xC5), // NEWSTRUCT0
ValueType::Any => bytecode.push(0x0B), // NULL
}
}
/// Task #106 — count flattened parameter slots for INITSLOT. Struct params
/// expand to their direct field count; all other types count as 1. Nested
/// struct fields remain a single slot for now (nested expansion is a
/// follow-up when the ABI payload path adds recursive field-tuple
/// canonicalisation).
fn flat_param_slot_count_from_value_types(param_types: &[ir::ValueType]) -> usize {
param_types
.iter()
.map(|ty| match ty {
ir::ValueType::Struct { fields, .. } => fields.len(),
_ => 1,
})
.sum()
}