-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathlib.rs
3332 lines (2940 loc) · 122 KB
/
lib.rs
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A specialized executor for our RISC-V assembly that can speedup witgen and
//! help with making partition decisions.
//!
//! WARNING: the general witness generation/execution code over the polynomial
//! constraints try to ensure the determinism of the instructions. If we bypass
//! much of witness generation using the present module, we lose the
//! non-determinism verification.
//!
//! TODO: perform determinism verification for each instruction independently
//! from execution.
use std::{
collections::{BTreeMap, HashMap},
fmt::{self, Display, Formatter},
path::Path,
sync::Arc,
time::Instant,
};
use num_derive::{FromPrimitive, ToPrimitive};
use builder::TraceBuilder;
use itertools::Itertools;
use powdr_ast::{
analyzed::{AlgebraicExpression, Analyzed, Identity, LookupIdentity},
asm_analysis::{AnalysisASMFile, CallableSymbol, FunctionStatement, LabelStatement, Machine},
parsed::{
asm::{parse_absolute_path, AssignmentRegister, DebugDirective},
BinaryOperation, Expression, FunctionCall, Number, UnaryOperation,
},
};
use tiny_keccak::keccakf;
use powdr_executor::constant_evaluator::VariablySizedColumn;
use powdr_number::{write_polys_csv_file, FieldElement, LargeInt};
pub use profiler::ProfilerOptions;
pub mod arith;
mod poseidon2_gl;
pub mod poseidon_gl;
mod profiler;
mod submachines;
use submachines::*;
mod memory;
use memory::*;
mod pil;
use crate::profiler::Profiler;
#[derive(Debug)]
struct SubmachineOp<F: FieldElement> {
// pil identity id of the link
identity_id: u64,
// these are the RHS values of the lookup (i.e., inside brackets in the PIL lookup).
// This is a fixed size to avoid allocations in the common case.
lookup_args: [F; 4],
// TODO: this is just for the hand-written poseidon_gl submachine,
// we give it the input values because it doesn't have access to memory
extra: Vec<F>,
}
/// Enum with asm machine RISCV instruction. Helps avoid using raw strings in the code.
macro_rules! instructions {
($($name:ident),*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(non_camel_case_types)]
enum Instruction {
$($name,)*
Count
}
impl Instruction {
fn count() -> usize {
Self::Count as usize
}
fn from_name(s: &str) -> Option<Self> {
match s {
$(stringify!($name) => Some(Self::$name),)*
_ => None
}
}
fn flag(&self) -> &'static str {
match *self {
$(Self::$name => concat!("main::instr_", stringify!($name)),)*
Self::Count => panic!(),
}
}
}
};
}
instructions! {
set_reg,
get_reg,
affine,
mstore,
mstore_bootloader,
mload,
load_bootloader_input,
assert_bootloader_input,
load_label,
jump,
jump_dyn,
jump_to_bootloader_input,
branch_if_diff_nonzero,
branch_if_diff_equal,
skip_if_equal,
branch_if_diff_greater_than,
is_diff_greater_than,
is_equal_zero,
is_not_equal,
add_wrap,
wrap16,
sub_wrap_with_offset,
sign_extend_byte,
sign_extend_16_bits,
to_signed,
divremu,
mul,
and,
or,
xor,
shl,
shr,
invert_gl,
split_gl,
poseidon_gl,
poseidon2_gl,
affine_256,
mod_256,
ec_add,
ec_double,
commit_public,
fail,
keccakf,
split_gl_vec,
merge_gl
}
/// Enum with columns directly accessed by the executor (as to avoid matching on strings)
macro_rules! known_witness_col {
($($name:ident),*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, ToPrimitive, FromPrimitive)]
#[allow(non_camel_case_types)]
#[repr(usize)]
enum KnownWitnessCol {
$($name,)*
Count // this is a sentinel so we know how many variants we have
}
impl KnownWitnessCol {
fn count() -> usize {
Self::Count as usize
}
fn all() -> Vec<Self> {
vec![
$(Self::$name,)*
]
}
fn name(&self) -> &'static str {
match *self {
$(Self::$name => concat!("main::", stringify!($name)),)*
Self::Count => panic!(),
}
}
}
};
}
known_witness_col! {
_operation_id,
pc_update,
X,
Y,
Z,
W,
Y_free_value,
X_free_value,
tmp1_col,
tmp2_col,
tmp3_col,
tmp4_col,
X_b1,
X_b2,
X_b3,
X_b4,
XX,
XXIsZero,
XX_inv,
Y_b5,
Y_b6,
Y_b7,
Y_b8,
Y_7bit,
Y_15bit,
REM_b1,
REM_b2,
REM_b3,
REM_b4,
wrap_bit,
instr_load_label_param_l,
instr_jump_param_l,
instr_branch_if_diff_nonzero_param_l,
instr_branch_if_diff_equal_param_l,
instr_branch_if_diff_greater_than_param_l,
jump_to_shutdown_routine,
// instructions
instr_set_reg,
instr_get_reg,
instr_affine,
instr_mstore,
instr_mstore_bootloader,
instr_mload,
instr_load_bootloader_input,
instr_assert_bootloader_input,
instr_load_label,
instr_jump,
instr_jump_dyn,
instr_jump_to_bootloader_input,
instr_branch_if_diff_nonzero,
instr_branch_if_diff_equal,
instr_skip_if_equal,
instr_branch_if_diff_greater_than,
instr_is_diff_greater_than,
instr_is_equal_zero,
instr_is_not_equal,
instr_add_wrap,
instr_wrap16,
instr_sub_wrap_with_offset,
instr_sign_extend_byte,
instr_sign_extend_16_bits,
instr_to_signed,
instr_divremu,
instr_mul,
instr_and,
instr_or,
instr_xor,
instr_shl,
instr_shr,
instr_invert_gl,
instr_split_gl,
instr_poseidon_gl,
instr_poseidon2_gl,
instr_affine_256,
instr_mod_256,
instr_ec_add,
instr_ec_double,
instr_commit_public,
instr_fail
}
/// Enum with submachines known to the RISCV executor
macro_rules! machine_instances {
($($name:ident),*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, ToPrimitive, FromPrimitive)]
#[allow(non_camel_case_types)]
#[repr(usize)]
enum MachineInstance {
$($name,)*
Count
}
#[allow(unused)]
impl MachineInstance {
fn count() -> usize {
Self::Count as usize
}
fn all() -> Vec<Self> {
vec![
$(Self::$name,)*
]
}
fn name(&self) -> &'static str {
match *self {
$(Self::$name => stringify!($name),)*
Self::Count => panic!(),
}
}
fn namespace(&self) -> &'static str {
match *self {
$(Self::$name => concat!("main_", stringify!($name)),)*
Self::Count => panic!(),
}
}
}
};
}
machine_instances! {
memory,
regs,
publics,
binary,
shift,
split_gl,
poseidon_gl
// TODO: these are not implemented yet
// poseidon2_gl,
// keccakf
// arith,
}
macro_rules! known_fixed_col {
($($name:ident),*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, ToPrimitive, FromPrimitive)]
#[allow(non_camel_case_types)]
#[repr(usize)]
enum KnownFixedCol {
$($name,)*
}
impl KnownFixedCol {
fn all() -> Vec<Self> {
vec![
$(Self::$name,)*
]
}
fn name(&self) -> &'static str {
match *self {
$(Self::$name => concat!("main__rom::p_", stringify!($name)),)*
}
}
}
};
}
known_fixed_col! {
X_const,
Y_const,
Z_const,
W_const,
Y_read_free,
X_read_free
}
/// Initial value of the PC.
///
/// To match the ZK proof witness, the PC must start after some offset used for
/// proof initialization.
///
/// TODO: get this value from some authoritative place
const PC_INITIAL_VAL: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Elem<F: FieldElement> {
/// Only the ranges of i32 and u32 are actually valid for a Binary value.
/// I.e., [-2**31, 2**32).
Binary(i64),
Field(F),
}
impl<F: FieldElement> Default for Elem<F> {
fn default() -> Self {
Self::Binary(0)
}
}
impl<F: FieldElement> Elem<F> {
/// Try to interpret the value of a field as a binary, if it can be represented either as a
/// u32 or a i32.
pub fn try_from_fe_as_bin(value: &F) -> Option<Self> {
let integer = value.to_signed_integer();
u32::try_from(&integer)
.map(From::from)
.or_else(|_| i32::try_from(integer).map(From::from))
.map(Self::Binary)
.ok()
}
pub fn from_u32_as_fe(value: u32) -> Self {
Self::Field(F::from(value))
}
pub fn from_i32_as_fe(value: i32) -> Self {
Self::Field(F::from(value))
}
pub fn from_bool_as_fe(value: bool) -> Self {
if value {
Self::Field(F::one())
} else {
Self::Field(F::zero())
}
}
/// Interprets the value of self as a field element.
pub fn into_fe(self) -> F {
match self {
Self::Field(f) => f,
Self::Binary(b) => b.into(),
}
}
/// Interprets the value of self as an i64, ignoring higher bytes if a field element
pub fn as_i64_from_lower_bytes(&self) -> i64 {
match self {
Self::Binary(b) => *b,
Self::Field(f) => {
let mut bytes = f.to_bytes_le();
bytes.truncate(8);
i64::from_le_bytes(bytes.try_into().unwrap())
}
}
}
pub fn bin(&self) -> i64 {
match self {
Self::Binary(b) => *b,
Self::Field(_) => panic!(),
}
}
fn u(&self) -> u32 {
self.bin().try_into().unwrap()
}
fn s(&self) -> i32 {
self.bin().try_into().unwrap()
}
fn is_zero(&self) -> bool {
match self {
Self::Binary(b) => *b == 0,
Self::Field(f) => f.is_zero(),
}
}
fn add(&self, other: &Self) -> Self {
match (self, other) {
(Self::Binary(a), Self::Binary(b)) => Self::Binary(a.checked_add(*b).unwrap()),
(Self::Field(a), Self::Field(b)) => Self::Field(*a + *b),
(Self::Binary(a), Self::Field(b)) => Self::Field(F::from(*a) + *b),
(Self::Field(a), Self::Binary(b)) => Self::Field(*a + F::from(*b)),
}
}
fn sub(&self, other: &Self) -> Self {
match (self, other) {
(Self::Binary(a), Self::Binary(b)) => Self::Binary(a.checked_sub(*b).unwrap()),
(Self::Field(a), Self::Field(b)) => Self::Field(*a - *b),
(Self::Binary(a), Self::Field(b)) => Self::Field(F::from(*a) - *b),
(Self::Field(a), Self::Binary(b)) => Self::Field(*a - F::from(*b)),
}
}
fn mul(&self, other: &Self) -> Self {
match (self, other) {
(Self::Binary(a), Self::Binary(b)) => match a.checked_mul(*b) {
Some(v) => Self::Binary(v),
None => {
let a = F::from(*a);
let b = F::from(*b);
Self::Field(a * b)
}
},
(Self::Field(a), Self::Field(b)) => Self::Field(*a * *b),
(Self::Binary(a), Self::Field(b)) => Self::Field(F::from(*a) * *b),
(Self::Field(a), Self::Binary(b)) => Self::Field(*a * F::from(*b)),
}
}
fn div(&self, other: &Self) -> Self {
match (self, other) {
(Self::Binary(a), Self::Binary(b)) => Self::Binary(a / b),
(Self::Field(a), Self::Field(b)) => Self::Field(*a / *b),
(Self::Binary(a), Self::Field(b)) => Self::Field(F::from(*a) / *b),
(Self::Field(a), Self::Binary(b)) => Self::Field(*a / F::from(*b)),
}
}
}
fn decompose_lower32(x: i64) -> (u8, u8, u8, u8, u8) {
let b1 = (x & 0xff) as u8;
let b2 = ((x >> 8) & 0xff) as u8;
let b3 = ((x >> 16) & 0xff) as u8;
let b4 = ((x >> 24) & 0xff) as u8;
let sign = ((x >> 31) & 1) as u8;
(b1, b2, b3, b4, sign)
}
impl<F: FieldElement> From<i64> for Elem<F> {
fn from(value: i64) -> Self {
Self::Binary(value)
}
}
impl<F: FieldElement> From<u32> for Elem<F> {
fn from(value: u32) -> Self {
Self::Binary(value as i64)
}
}
impl<F: FieldElement> From<i32> for Elem<F> {
fn from(value: i32) -> Self {
Self::Binary(value as i64)
}
}
impl<F: FieldElement> From<usize> for Elem<F> {
fn from(value: usize) -> Self {
Self::Binary(value as i64)
}
}
impl<F: FieldElement> Display for Elem<F> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Binary(b) => write!(f, "{b}"),
Self::Field(fe) => write!(f, "{fe}"),
}
}
}
pub type MemoryState<F> = HashMap<u32, Elem<F>>;
pub type RegisterMemoryState<F> = HashMap<u32, F>;
#[derive(Debug)]
pub enum MemOperationKind {
Read,
Write,
}
#[derive(Debug)]
pub struct MemOperation {
/// The row of the execution trace the memory operation happened.
pub row: usize,
pub kind: MemOperationKind,
pub address: u32,
}
pub struct ExecutionTrace<F: FieldElement> {
reg_map: HashMap<String, u16>,
/// Writes and reads to memory.
mem_ops: Vec<MemOperation>,
/// The length of the trace, after applying the reg_writes.
len: usize,
/// the pc value at each row
pc_trace: Vec<u32>,
/// values of non-pc asm registers at each row
reg_trace: Vec<Vec<F>>,
/// reg writes to be set on the trace on the next row
reg_writes: Vec<Option<F>>,
/// Calls into submachines
submachine_ops: Vec<Vec<SubmachineOp<F>>>,
/// Columns directly accessed by the executor, indexed by the enum value for
/// fast access. Some columns may be optimized away, so we rely on the PIL
/// columns to know what should be present in the end.
/// We keep a row based flat vec for memory locality.
known_cols: Vec<F>,
/// all witness columns obtained from the optimized pil.
all_cols: Vec<String>,
}
impl<F: FieldElement> ExecutionTrace<F> {
pub fn new(witness_cols: Vec<String>, reg_map: HashMap<String, u16>) -> Self {
ExecutionTrace {
reg_trace: reg_map.keys().map(|_| Vec::new()).collect(),
reg_writes: vec![None; reg_map.len()],
reg_map,
mem_ops: Vec::new(),
len: PC_INITIAL_VAL + 1,
pc_trace: Vec::new(),
submachine_ops: MachineInstance::all().iter().map(|_| Vec::new()).collect(),
known_cols: vec![],
all_cols: witness_cols,
}
}
/// transpose the register write operations into value columns
fn generate_registers_trace(&mut self) -> Vec<(String, Vec<F>)> {
let mut reg_values: Vec<Vec<F>> =
vec![Vec::with_capacity(self.pc_trace.len().next_power_of_two()); self.reg_map.len()];
// reverse lookup
let idx_reg: HashMap<u16, &str> =
self.reg_map.iter().map(|(k, &v)| (v, k.as_str())).collect();
for i in 0..self.reg_map.len() {
let reg = idx_reg[&(i as u16)];
if reg == "pc" {
reg_values[i].extend(self.pc_trace.iter().map(|&v| F::from(v)));
} else {
reg_values[i] = std::mem::take(&mut self.reg_trace[i]);
}
}
reg_values
.into_iter()
.enumerate()
.map(|(i, values)| (format!("main::{}", idx_reg[&(i as u16)]), values))
.collect()
}
}
#[derive(Default)]
pub struct RegisterMemory<F: FieldElement> {
last: HashMap<u32, Elem<F>>,
second_last: HashMap<u32, Elem<F>>,
}
impl<F: FieldElement> RegisterMemory<F> {
pub fn for_bootloader(&self) -> HashMap<u32, F> {
self.second_last
.iter()
.map(|(k, v)| (*k, v.into_fe()))
.collect()
}
}
mod builder {
use std::{cell::RefCell, cmp, collections::HashMap, time::Instant};
use powdr_ast::{
analyzed::{Analyzed, DegreeRange},
asm_analysis::{Machine, RegisterTy},
};
use powdr_number::FieldElement;
use rayon::iter::{IntoParallelIterator, ParallelBridge, ParallelExtend, ParallelIterator};
use crate::{
pil, BinaryMachine, Elem, ExecMode, Execution, ExecutionTrace, KnownWitnessCol,
MachineInstance, MemOperation, MemOperationKind, MemoryMachine, MemoryState,
PoseidonGlMachine, PublicsMachine, RegisterMemory, ShiftMachine, SplitGlMachine,
Submachine, SubmachineBoxed, SubmachineOp, PC_INITIAL_VAL,
};
fn namespace_degree_range<F: FieldElement>(
opt_pil: &Analyzed<F>,
namespace: &str,
) -> DegreeRange {
opt_pil
.committed_polys_in_source_order()
.find(|(s, _)| s.absolute_name.contains(&format!("{namespace}::")))
.and_then(|(s, _)| s.degree)
// all machines/columns should have a degree range defined
.unwrap()
}
fn register_names(main: &Machine) -> Vec<&str> {
main.registers
.iter()
.filter_map(|statement| {
if statement.ty != RegisterTy::Assignment {
Some(&statement.name[..])
} else {
None
}
})
.collect()
}
pub struct TraceBuilder<'b, F: FieldElement> {
trace: ExecutionTrace<F>,
submachines: HashMap<MachineInstance, RefCell<Box<dyn Submachine<F>>>>,
/// Maximum rows we can run before we stop the execution.
max_rows: usize,
// index of special case registers to look after:
pc_idx: u16,
/// The value of PC at the start of the execution of the current row.
curr_pc: Elem<F>,
/// The PC in the register bank refers to the batches, we have to track our
/// actual program counter independently.
next_statement_line: u32,
/// When PC is written, we need to know what line to actually execute next
/// from this map of batch to statement line.
batch_to_line_map: &'b [u32],
/// Current register bank
regs: Vec<Elem<F>>,
/// Current memory.
mem: MemoryState<F>,
/// Separate register memory, last and second last.
reg_mem: RegisterMemory<F>,
/// The execution mode we running.
/// Fast: do not save the register's trace and memory accesses.
/// Trace: save everything - needed for continuations.
mode: ExecMode,
}
impl<'a, 'b: 'a, F: FieldElement> TraceBuilder<'b, F> {
/// Creates a new builder.
///
/// May fail if max_rows_len is too small or if the main machine is
/// empty. In this case, the final (empty) execution trace is returned
/// in Err.
pub fn new(
main: &'a Machine,
opt_pil: Option<&Analyzed<F>>,
witness_cols: Vec<String>,
mem: MemoryState<F>,
batch_to_line_map: &'b [u32],
max_rows_len: usize,
mode: ExecMode,
) -> Result<Self, Box<Execution<F>>> {
let reg_map = register_names(main)
.into_iter()
.enumerate()
.map(|(i, name)| (name.to_string(), i as u16))
.collect::<HashMap<String, u16>>();
let reg_len = reg_map.len();
// To save cache/memory bandwidth, I set the register index to be
// u16, so panic if it doesn't fit (it obviously will fit for RISC-V).
<usize as TryInto<u16>>::try_into(reg_len).unwrap();
let pc_idx = reg_map["pc"];
let mut regs = vec![0.into(); reg_len];
regs[pc_idx as usize] = PC_INITIAL_VAL.into();
let submachines: HashMap<_, RefCell<Box<dyn Submachine<F>>>> =
if let ExecMode::Witness = mode {
[
(
MachineInstance::memory,
RefCell::new(Box::new(MemoryMachine::new("main_memory", &witness_cols)))
as RefCell<Box<dyn Submachine<F>>>, // this first `as` is needed to coerce the type of the array
),
(
MachineInstance::regs,
RefCell::new(Box::new(MemoryMachine::new("main_regs", &witness_cols))),
),
(
MachineInstance::binary,
RefCell::new(BinaryMachine::new_boxed("main_binary", &witness_cols)),
),
(
MachineInstance::shift,
RefCell::new(ShiftMachine::new_boxed("main_shift", &witness_cols)),
),
(
MachineInstance::split_gl,
RefCell::new(SplitGlMachine::new_boxed("main_split_gl", &witness_cols)),
),
(
MachineInstance::publics,
RefCell::new(PublicsMachine::new_boxed("main_publics", &witness_cols)),
),
(
MachineInstance::poseidon_gl,
RefCell::new(PoseidonGlMachine::new_boxed(
"main_poseidon_gl",
&witness_cols,
)),
),
]
.into_iter()
.collect()
} else {
Default::default()
};
let mut ret = Self {
pc_idx,
curr_pc: PC_INITIAL_VAL.into(),
trace: ExecutionTrace::new(witness_cols, reg_map),
submachines,
next_statement_line: 1,
batch_to_line_map,
max_rows: max_rows_len,
regs,
mem,
reg_mem: Default::default(),
mode,
};
if ret.has_enough_rows() || ret.set_next_pc().is_none() {
Err(Box::new(ret.finish(opt_pil, vec![])))
} else {
Ok(ret)
}
}
pub(crate) fn pc_trace(&self) -> &[u32] {
&self.trace.pc_trace
}
pub(crate) fn submachine_op(
&mut self,
m: MachineInstance,
identity_id: u64,
lookup_args: &[F],
extra: &[F],
) {
if let ExecMode::Witness = self.mode {
self.trace
.submachine_ops
.get_mut(m as usize)
.unwrap()
.push(SubmachineOp {
identity_id,
lookup_args: lookup_args.try_into().unwrap(),
extra: extra.to_vec(),
});
}
}
pub(crate) fn main_columns_len(&self) -> usize {
let cols_len = self.trace.known_cols.len() / KnownWitnessCol::count();
// sanity check
if let ExecMode::Witness = self.mode {
assert!(self.trace.len <= cols_len);
}
cols_len
}
// convert the flat array of rows into a hashmap of columns.
pub(crate) fn generate_main_columns(&mut self) -> HashMap<String, Vec<F>> {
let main_columns_len = self.main_columns_len();
let cols: HashMap<String, Vec<F>> = KnownWitnessCol::all()
.into_par_iter()
.map(|col| {
let mut values = Vec::with_capacity(main_columns_len.next_power_of_two());
for i in 0..main_columns_len {
values.push(
self.trace.known_cols[i * KnownWitnessCol::count() + col as usize],
);
}
(col.name().to_string(), values)
})
.collect();
cols
}
/// get the value of PC as of the start of the execution of the current row.
pub(crate) fn get_pc(&self) -> Elem<F> {
self.curr_pc
}
/// get the value of PC as updated by the last executed instruction.
/// The actual PC is only updated when moving to a new row.
pub(crate) fn get_next_pc(&self) -> Elem<F> {
self.regs[self.pc_idx as usize]
}
/// get current value of register
pub(crate) fn get_reg(&self, idx: &str) -> Elem<F> {
self.get_reg_idx(self.trace.reg_map[idx])
}
/// get current value of register by register index instead of name
fn get_reg_idx(&self, idx: u16) -> Elem<F> {
if idx == self.pc_idx {
return self.get_pc();
}
self.regs[idx as usize]
}
/// sets the PC
pub(crate) fn set_pc(&mut self, value: Elem<F>) {
// updates the internal statement-based program counter accordingly:
self.next_statement_line = self.batch_to_line_map[value.u() as usize];
self.set_reg_idx(self.pc_idx, value);
}
/// set next value of register, accounting to x0 writes
///
/// to set the PC, use set_pc() instead of this
pub(crate) fn set_reg(&mut self, idx: &str, value: impl Into<Elem<F>>) {
self.set_reg_impl(idx, value.into())
}
fn set_reg_impl(&mut self, idx: &str, value: Elem<F>) {
let idx = self.trace.reg_map[idx];
assert!(idx != self.pc_idx);
self.set_reg_idx(idx, value);
}
/// raw set next value of register by register index instead of name
fn set_reg_idx(&mut self, idx: u16, value: Elem<F>) {
// Record register write in trace. Only for non-pc, non-assignment registers.
if let ExecMode::Trace | ExecMode::Witness = self.mode {
if idx != self.pc_idx {
self.trace.reg_writes[idx as usize] = Some(value.into_fe());
}
}
self.regs[idx as usize] = value;
}
pub fn set_col_idx(&mut self, col: KnownWitnessCol, idx: usize, value: Elem<F>) {
if let ExecMode::Witness = self.mode {
let idx = (KnownWitnessCol::count() * idx) + col as usize;
*self.trace.known_cols.get_mut(idx).unwrap() = value.into_fe();
}
}
pub fn set_col(&mut self, col: KnownWitnessCol, value: Elem<F>) {
if let ExecMode::Witness = self.mode {
let idx = (self.trace.known_cols.len() - KnownWitnessCol::count()) + col as usize;
*self.trace.known_cols.get_mut(idx).unwrap() = value.into_fe();
}
}
pub fn col_is_defined(&self, name: &str) -> bool {
if let ExecMode::Trace | ExecMode::Witness = self.mode {
self.trace.all_cols.contains(&name.to_string())
} else {
false
}
}
pub fn push_row(&mut self, pc: u32) {
if let ExecMode::Trace | ExecMode::Witness = self.mode {
self.trace.pc_trace.push(pc);
self.trace
.reg_trace
.iter_mut()
.enumerate()
.for_each(|(idx, v)| {
// set the value from the write or copy the previous value
if let Some(w) = self.trace.reg_writes[idx].take() {
v.push(w);
} else {
v.push(v.last().cloned().unwrap_or(F::zero()));
}
});
}
if let ExecMode::Witness = self.mode {
let new_len = self.trace.known_cols.len() + KnownWitnessCol::count();
self.trace.known_cols.resize(new_len, F::zero());
}
}
/// advance to next row, returns the index to the statement that must be
/// executed now, or None if the execution is finished
pub fn advance(&mut self) -> Option<u32> {
let next_pc = self.regs[self.pc_idx as usize];
if self.curr_pc != next_pc {
// If we are at the limit of rows, stop the execution
if self.has_enough_rows() {
return None;
}
self.trace.len += 1;
self.set_col(KnownWitnessCol::pc_update, next_pc);
self.push_row(next_pc.u());
self.curr_pc = next_pc;
}
// advance to the next statement
let st_line = self.next_statement_line;
// optimistically advance the internal and register PCs
self.next_statement_line += 1;
self.set_next_pc().and(Some(st_line))
}
pub(crate) fn set_mem(&mut self, addr: u32, val: Elem<F>, step: u32, identity_id: u64) {
self.log_mem_op(addr, step, identity_id, val, MemOperationKind::Write);
self.mem.insert(addr, val);
}
pub(crate) fn get_mem(&mut self, addr: u32, step: u32, identity_id: u64) -> Elem<F> {
let val = self.mem.get(&addr).cloned().unwrap_or_default();
self.log_mem_op(addr, step, identity_id, val, MemOperationKind::Read);
val
}
fn log_mem_op(
&mut self,
addr: u32,
step: u32,
identity_id: u64,
val: Elem<F>,
kind: MemOperationKind,
) {
if let ExecMode::Witness = self.mode {
let selector = match kind {
MemOperationKind::Read => F::zero(),
MemOperationKind::Write => F::one(),
};
self.submachine_op(