-
Notifications
You must be signed in to change notification settings - Fork 231
/
Copy pathbrillig_block.rs
1793 lines (1625 loc) · 76.5 KB
/
brillig_block.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
use crate::brillig::brillig_ir::brillig_variable::{
type_to_heap_value_type, BrilligArray, BrilligVariable, BrilligVector, SingleAddrVariable,
};
use crate::brillig::brillig_ir::{
BrilligBinaryOp, BrilligContext, BRILLIG_MEMORY_ADDRESSING_BIT_SIZE,
};
use crate::ssa::ir::dfg::CallStack;
use crate::ssa::ir::instruction::{ConstrainError, UserDefinedConstrainError};
use crate::ssa::ir::{
basic_block::{BasicBlock, BasicBlockId},
dfg::DataFlowGraph,
function::FunctionId,
instruction::{
Binary, BinaryOp, Endian, Instruction, InstructionId, Intrinsic, TerminatorInstruction,
},
types::{NumericType, Type},
value::{Value, ValueId},
};
use acvm::acir::brillig::{MemoryAddress, ValueOrArray};
use acvm::brillig_vm::brillig::HeapVector;
use acvm::FieldElement;
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use iter_extended::vecmap;
use num_bigint::BigUint;
use super::brillig_black_box::convert_black_box_call;
use super::brillig_block_variables::BlockVariables;
use super::brillig_fn::FunctionContext;
/// Generate the compilation artifacts for compiling a function into brillig bytecode.
pub(crate) struct BrilligBlock<'block> {
pub(crate) function_context: &'block mut FunctionContext,
/// The basic block that is being converted
pub(crate) block_id: BasicBlockId,
/// Context for creating brillig opcodes
pub(crate) brillig_context: &'block mut BrilligContext,
/// Tracks the available variable during the codegen of the block
pub(crate) variables: BlockVariables,
/// For each instruction, the set of values that are not used anymore after it.
pub(crate) last_uses: HashMap<InstructionId, HashSet<ValueId>>,
}
impl<'block> BrilligBlock<'block> {
/// Converts an SSA Basic block into a sequence of Brillig opcodes
pub(crate) fn compile(
function_context: &'block mut FunctionContext,
brillig_context: &'block mut BrilligContext,
block_id: BasicBlockId,
dfg: &DataFlowGraph,
) {
let live_in = function_context.liveness.get_live_in(&block_id);
let variables =
BlockVariables::new(live_in.clone(), function_context.all_block_parameters());
brillig_context.set_allocated_registers(
variables
.get_available_variables(function_context)
.into_iter()
.flat_map(|variable| variable.extract_registers())
.collect(),
);
let last_uses = function_context.liveness.get_last_uses(&block_id).clone();
let mut brillig_block =
BrilligBlock { function_context, block_id, brillig_context, variables, last_uses };
brillig_block.convert_block(dfg);
}
fn convert_block(&mut self, dfg: &DataFlowGraph) {
// Add a label for this block
let block_label = self.create_block_label_for_current_function(self.block_id);
self.brillig_context.enter_context(block_label);
// Convert the block parameters
let block = &dfg[self.block_id];
self.convert_block_params(block, dfg);
// Convert all of the instructions into the block
for instruction_id in block.instructions() {
self.convert_ssa_instruction(*instruction_id, dfg);
}
// Process the block's terminator instruction
let terminator_instruction =
block.terminator().expect("block is expected to be constructed");
self.convert_ssa_terminator(terminator_instruction, dfg);
}
/// Creates a unique global label for a block.
///
/// This uses the current functions's function ID and the block ID
/// Making the assumption that the block ID passed in belongs to this
/// function.
fn create_block_label_for_current_function(&self, block_id: BasicBlockId) -> String {
Self::create_block_label(self.function_context.function_id, block_id)
}
/// Creates a unique label for a block using the function Id and the block ID.
///
/// We implicitly assume that the function ID and the block ID is enough
/// for us to create a unique label across functions and blocks.
///
/// This is so that during linking there are no duplicates or labels being overwritten.
fn create_block_label(function_id: FunctionId, block_id: BasicBlockId) -> String {
format!("{function_id}-{block_id}")
}
/// Converts an SSA terminator instruction into the necessary opcodes.
///
/// TODO: document why the TerminatorInstruction::Return includes a stop instruction
/// TODO along with the `Self::compile`
fn convert_ssa_terminator(
&mut self,
terminator_instruction: &TerminatorInstruction,
dfg: &DataFlowGraph,
) {
match terminator_instruction {
TerminatorInstruction::JmpIf { condition, then_destination, else_destination } => {
let condition = self.convert_ssa_single_addr_value(*condition, dfg);
self.brillig_context.jump_if_instruction(
condition.address,
self.create_block_label_for_current_function(*then_destination),
);
self.brillig_context.jump_instruction(
self.create_block_label_for_current_function(*else_destination),
);
}
TerminatorInstruction::Jmp {
destination: destination_block,
arguments,
call_stack: _,
} => {
let target_block = &dfg[*destination_block];
for (src, dest) in arguments.iter().zip(target_block.parameters()) {
// Destinations are block parameters so they should have been allocated previously.
let destination = self.variables.get_block_param(
self.function_context,
*destination_block,
*dest,
dfg,
);
let source = self.convert_ssa_value(*src, dfg);
self.pass_variable(source, destination);
}
self.brillig_context.jump_instruction(
self.create_block_label_for_current_function(*destination_block),
);
}
TerminatorInstruction::Return { return_values, .. } => {
let return_registers: Vec<_> = return_values
.iter()
.flat_map(|value_id| {
let return_variable = self.convert_ssa_value(*value_id, dfg);
return_variable.extract_registers()
})
.collect();
self.brillig_context.codegen_return(&return_registers);
}
}
}
/// Passes an arbitrary variable from the registers of the source to the registers of the destination
fn pass_variable(&mut self, source: BrilligVariable, destination: BrilligVariable) {
match (source, destination) {
(
BrilligVariable::SingleAddr(source_var),
BrilligVariable::SingleAddr(destination_var),
) => {
self.brillig_context.mov_instruction(destination_var.address, source_var.address);
}
(
BrilligVariable::BrilligArray(BrilligArray {
pointer: source_pointer,
size: _,
rc: source_rc,
}),
BrilligVariable::BrilligArray(BrilligArray {
pointer: destination_pointer,
size: _,
rc: destination_rc,
}),
) => {
self.brillig_context.mov_instruction(destination_pointer, source_pointer);
self.brillig_context.mov_instruction(destination_rc, source_rc);
}
(
BrilligVariable::BrilligVector(BrilligVector {
pointer: source_pointer,
size: source_size,
rc: source_rc,
}),
BrilligVariable::BrilligVector(BrilligVector {
pointer: destination_pointer,
size: destination_size,
rc: destination_rc,
}),
) => {
self.brillig_context.mov_instruction(destination_pointer, source_pointer);
self.brillig_context.mov_instruction(destination_size, source_size);
self.brillig_context.mov_instruction(destination_rc, source_rc);
}
(_, _) => {
unreachable!("ICE: Cannot pass value from {:?} to {:?}", source, destination);
}
}
}
/// Converts SSA Block parameters into Brillig Registers.
fn convert_block_params(&mut self, block: &BasicBlock, dfg: &DataFlowGraph) {
for param_id in block.parameters() {
let value = &dfg[*param_id];
let param_type = match value {
Value::Param { typ, .. } => typ,
_ => unreachable!("ICE: Only Param type values should appear in block parameters"),
};
match param_type {
// Simple parameters and arrays are passed as already filled registers
// In the case of arrays, the values should already be in memory and the register should
// Be a valid pointer to the array.
// For slices, two registers are passed, the pointer to the data and a register holding the size of the slice.
Type::Numeric(_) | Type::Array(..) | Type::Slice(..) | Type::Reference(_) => {
self.variables.get_block_param(
self.function_context,
self.block_id,
*param_id,
dfg,
);
}
Type::Function => todo!("ICE: Type::Function Param not supported"),
}
}
}
/// Converts an SSA instruction into a sequence of Brillig opcodes.
fn convert_ssa_instruction(&mut self, instruction_id: InstructionId, dfg: &DataFlowGraph) {
let instruction = &dfg[instruction_id];
self.brillig_context.set_call_stack(dfg.get_call_stack(instruction_id));
match instruction {
Instruction::Binary(binary) => {
let result_var = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
dfg.instruction_results(instruction_id)[0],
dfg,
);
self.convert_ssa_binary(binary, dfg, result_var);
}
Instruction::Constrain(lhs, rhs, assert_message) => {
let (has_revert_data, static_assert_message) = if let Some(error) = assert_message {
match error.as_ref() {
ConstrainError::Intrinsic(string) => (false, Some(string.clone())),
ConstrainError::UserDefined(UserDefinedConstrainError::Static(string)) => {
(true, Some(string.clone()))
}
ConstrainError::UserDefined(UserDefinedConstrainError::Dynamic(
call_instruction,
)) => {
let Instruction::Call { func, arguments } = call_instruction else {
unreachable!("expected a call instruction")
};
let Value::Function(func_id) = &dfg[*func] else {
unreachable!("expected a function value")
};
self.convert_ssa_function_call(*func_id, arguments, dfg, &[]);
// Dynamic assert messages are handled in the generated function call.
// We then don't need to attach one to the constrain instruction.
(false, None)
}
}
} else {
(false, None)
};
let condition = SingleAddrVariable {
address: self.brillig_context.allocate_register(),
bit_size: 1,
};
self.convert_ssa_binary(
&Binary { lhs: *lhs, rhs: *rhs, operator: BinaryOp::Eq },
dfg,
condition,
);
if has_revert_data {
self.brillig_context
.codegen_constrain_with_revert_data(condition, static_assert_message);
} else {
self.brillig_context.codegen_constrain(condition, static_assert_message);
}
self.brillig_context.deallocate_single_addr(condition);
}
Instruction::Allocate => {
let result_value = dfg.instruction_results(instruction_id)[0];
let address_register = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
result_value,
dfg,
);
match dfg.type_of_value(result_value) {
Type::Reference(element) => match *element {
Type::Array(..) => {
self.brillig_context
.codegen_allocate_array_reference(address_register.address);
}
Type::Slice(..) => {
self.brillig_context
.codegen_allocate_vector_reference(address_register.address);
}
_ => {
self.brillig_context
.codegen_allocate_single_addr_reference(address_register.address);
}
},
_ => {
unreachable!("ICE: Allocate on non-reference type")
}
}
}
Instruction::Store { address, value } => {
let address_var = self.convert_ssa_single_addr_value(*address, dfg);
let source_variable = self.convert_ssa_value(*value, dfg);
self.brillig_context.codegen_store_variable(address_var.address, source_variable);
}
Instruction::Load { address } => {
let target_variable = self.variables.define_variable(
self.function_context,
self.brillig_context,
dfg.instruction_results(instruction_id)[0],
dfg,
);
let address_variable = self.convert_ssa_single_addr_value(*address, dfg);
self.brillig_context
.codegen_load_variable(target_variable, address_variable.address);
}
Instruction::Not(value) => {
let condition_register = self.convert_ssa_single_addr_value(*value, dfg);
let result_register = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
dfg.instruction_results(instruction_id)[0],
dfg,
);
self.brillig_context.not_instruction(condition_register, result_register);
}
Instruction::Call { func, arguments } => match &dfg[*func] {
Value::ForeignFunction(func_name) => {
let result_ids = dfg.instruction_results(instruction_id);
let input_registers = vecmap(arguments, |value_id| {
self.convert_ssa_value(*value_id, dfg).to_value_or_array()
});
let input_value_types = vecmap(arguments, |value_id| {
let value_type = dfg.type_of_value(*value_id);
type_to_heap_value_type(&value_type)
});
let output_registers = vecmap(result_ids, |value_id| {
self.allocate_external_call_result(*value_id, dfg).to_value_or_array()
});
let output_value_types = vecmap(result_ids, |value_id| {
let value_type = dfg.type_of_value(*value_id);
type_to_heap_value_type(&value_type)
});
self.brillig_context.foreign_call_instruction(
func_name.to_owned(),
&input_registers,
&input_value_types,
&output_registers,
&output_value_types,
);
for (i, output_register) in output_registers.iter().enumerate() {
if let ValueOrArray::HeapVector(HeapVector { size, .. }) = output_register {
// Update the stack pointer so that we do not overwrite
// dynamic memory returned from other external calls
self.brillig_context.increase_free_memory_pointer_instruction(*size);
// Update the dynamic slice length maintained in SSA
if let ValueOrArray::MemoryAddress(len_index) = output_registers[i - 1]
{
let element_size = dfg[result_ids[i]].get_type().element_size();
self.brillig_context.mov_instruction(len_index, *size);
self.brillig_context.codegen_usize_op_in_place(
len_index,
BrilligBinaryOp::UnsignedDiv,
element_size,
);
} else {
unreachable!("ICE: a vector must be preceded by a register containing its length");
}
}
// Single values and allocation of fixed sized arrays has already been handled
// inside of `allocate_external_call_result`
}
}
Value::Function(func_id) => {
let result_ids = dfg.instruction_results(instruction_id);
self.convert_ssa_function_call(*func_id, arguments, dfg, result_ids);
}
Value::Intrinsic(Intrinsic::BlackBox(bb_func)) => {
// Slices are represented as a tuple of (length, slice contents).
// We must check the inputs to determine if there are slices
// and make sure that we pass the correct inputs to the black box function call.
// The loop below only keeps the slice contents, so that
// setting up a black box function with slice inputs matches the expected
// number of arguments specified in the function signature.
let mut arguments_no_slice_len = Vec::new();
for (i, arg) in arguments.iter().enumerate() {
if matches!(dfg.type_of_value(*arg), Type::Numeric(_)) {
if i < arguments.len() - 1 {
if !matches!(dfg.type_of_value(arguments[i + 1]), Type::Slice(_)) {
arguments_no_slice_len.push(*arg);
}
} else {
arguments_no_slice_len.push(*arg);
}
} else {
arguments_no_slice_len.push(*arg);
}
}
let function_arguments =
vecmap(&arguments_no_slice_len, |arg| self.convert_ssa_value(*arg, dfg));
let function_results = dfg.instruction_results(instruction_id);
let function_results = vecmap(function_results, |result| {
self.allocate_external_call_result(*result, dfg)
});
convert_black_box_call(
self.brillig_context,
bb_func,
&function_arguments,
&function_results,
);
}
Value::Intrinsic(Intrinsic::ArrayLen) => {
let result_variable = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
dfg.instruction_results(instruction_id)[0],
dfg,
);
let param_id = arguments[0];
// Slices are represented as a tuple in the form: (length, slice contents).
// Thus, we can expect the first argument to a field in the case of a slice
// or an array in the case of an array.
if let Type::Numeric(_) = dfg.type_of_value(param_id) {
let len_variable = self.convert_ssa_value(arguments[0], dfg);
let length = len_variable.extract_single_addr();
self.brillig_context
.mov_instruction(result_variable.address, length.address);
} else {
self.convert_ssa_array_len(arguments[0], result_variable.address, dfg);
}
}
Value::Intrinsic(Intrinsic::AsSlice) => {
let source_variable = self.convert_ssa_value(arguments[0], dfg);
let result_ids = dfg.instruction_results(instruction_id);
let destination_len_variable = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
result_ids[0],
dfg,
);
let destination_variable = self.variables.define_variable(
self.function_context,
self.brillig_context,
result_ids[1],
dfg,
);
let source_size_as_register =
self.convert_ssa_array_set(source_variable, destination_variable, None);
// we need to explicitly set the destination_len_variable
self.brillig_context
.mov_instruction(destination_len_variable.address, source_size_as_register);
self.brillig_context.deallocate_register(source_size_as_register);
}
Value::Intrinsic(
Intrinsic::SlicePushBack
| Intrinsic::SlicePopBack
| Intrinsic::SlicePushFront
| Intrinsic::SlicePopFront
| Intrinsic::SliceInsert
| Intrinsic::SliceRemove,
) => {
self.convert_ssa_slice_intrinsic_call(
dfg,
&dfg[dfg.resolve(*func)],
instruction_id,
arguments,
);
}
Value::Intrinsic(Intrinsic::ToRadix(endianness)) => {
let source = self.convert_ssa_single_addr_value(arguments[0], dfg);
let radix = self.convert_ssa_single_addr_value(arguments[1], dfg);
let limb_count = self.convert_ssa_single_addr_value(arguments[2], dfg);
let results = dfg.instruction_results(instruction_id);
let target_len = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
results[0],
dfg,
);
let target_vector = self
.variables
.define_variable(
self.function_context,
self.brillig_context,
results[1],
dfg,
)
.extract_vector();
// Update the user-facing slice length
self.brillig_context.cast_instruction(target_len, limb_count);
self.brillig_context.codegen_to_radix(
source,
target_vector,
radix,
limb_count,
matches!(endianness, Endian::Big),
8,
);
}
Value::Intrinsic(Intrinsic::ToBits(endianness)) => {
let source = self.convert_ssa_single_addr_value(arguments[0], dfg);
let limb_count = self.convert_ssa_single_addr_value(arguments[1], dfg);
let results = dfg.instruction_results(instruction_id);
let target_len_variable = self.variables.define_variable(
self.function_context,
self.brillig_context,
results[0],
dfg,
);
let target_len = target_len_variable.extract_single_addr();
let target_vector = match self.variables.define_variable(
self.function_context,
self.brillig_context,
results[1],
dfg,
) {
BrilligVariable::BrilligArray(array) => {
self.brillig_context.array_to_vector_instruction(&array)
}
BrilligVariable::BrilligVector(vector) => vector,
BrilligVariable::SingleAddr(..) => unreachable!("ICE: ToBits on non-array"),
};
let radix = self.brillig_context.make_constant_instruction(2_usize.into(), 32);
// Update the user-facing slice length
self.brillig_context.cast_instruction(target_len, limb_count);
self.brillig_context.codegen_to_radix(
source,
target_vector,
radix,
limb_count,
matches!(endianness, Endian::Big),
1,
);
self.brillig_context.deallocate_single_addr(radix);
}
_ => {
unreachable!("unsupported function call type {:?}", dfg[*func])
}
},
Instruction::Truncate { value, bit_size, .. } => {
let result_ids = dfg.instruction_results(instruction_id);
let destination_register = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
result_ids[0],
dfg,
);
let source_register = self.convert_ssa_single_addr_value(*value, dfg);
self.brillig_context.codegen_truncate(
destination_register,
source_register,
*bit_size,
);
}
Instruction::Cast(value, _) => {
let result_ids = dfg.instruction_results(instruction_id);
let destination_variable = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
result_ids[0],
dfg,
);
let source_variable = self.convert_ssa_single_addr_value(*value, dfg);
self.convert_cast(destination_variable, source_variable);
}
Instruction::ArrayGet { array, index } => {
let result_ids = dfg.instruction_results(instruction_id);
let destination_variable = self.variables.define_variable(
self.function_context,
self.brillig_context,
result_ids[0],
dfg,
);
let array_variable = self.convert_ssa_value(*array, dfg);
let array_pointer = match array_variable {
BrilligVariable::BrilligArray(BrilligArray { pointer, .. }) => pointer,
BrilligVariable::BrilligVector(BrilligVector { pointer, .. }) => pointer,
_ => unreachable!("ICE: array get on non-array"),
};
let index_variable = self.convert_ssa_single_addr_value(*index, dfg);
self.validate_array_index(array_variable, index_variable);
self.retrieve_variable_from_array(
array_pointer,
index_variable,
destination_variable,
);
}
Instruction::ArraySet { array, index, value, .. } => {
let source_variable = self.convert_ssa_value(*array, dfg);
let index_register = self.convert_ssa_single_addr_value(*index, dfg);
let value_variable = self.convert_ssa_value(*value, dfg);
let result_ids = dfg.instruction_results(instruction_id);
let destination_variable = self.variables.define_variable(
self.function_context,
self.brillig_context,
result_ids[0],
dfg,
);
self.validate_array_index(source_variable, index_register);
let source_size_as_register = self.convert_ssa_array_set(
source_variable,
destination_variable,
Some((index_register.address, value_variable)),
);
self.brillig_context.deallocate_register(source_size_as_register);
}
Instruction::RangeCheck { value, max_bit_size, assert_message } => {
let value = self.convert_ssa_single_addr_value(*value, dfg);
// SSA generates redundant range checks. A range check with a max bit size >= value.bit_size will always pass.
if value.bit_size > *max_bit_size {
// Cast original value to field
let left = SingleAddrVariable {
address: self.brillig_context.allocate_register(),
bit_size: FieldElement::max_num_bits(),
};
self.convert_cast(left, value);
// Create a field constant with the max
let max = BigUint::from(2_u128).pow(*max_bit_size) - BigUint::from(1_u128);
let right = self.brillig_context.make_constant_instruction(
FieldElement::from_be_bytes_reduce(&max.to_bytes_be()),
FieldElement::max_num_bits(),
);
// Check if lte max
let condition =
SingleAddrVariable::new(self.brillig_context.allocate_register(), 1);
self.brillig_context.binary_instruction(
left,
right,
condition,
BrilligBinaryOp::LessThanEquals,
);
self.brillig_context.codegen_constrain(condition, assert_message.clone());
self.brillig_context.deallocate_single_addr(condition);
self.brillig_context.deallocate_single_addr(left);
self.brillig_context.deallocate_single_addr(right);
}
}
Instruction::IncrementRc { value } => {
let rc_register = match self.convert_ssa_value(*value, dfg) {
BrilligVariable::BrilligArray(BrilligArray { rc, .. })
| BrilligVariable::BrilligVector(BrilligVector { rc, .. }) => rc,
other => unreachable!("ICE: increment rc on non-array: {other:?}"),
};
self.brillig_context.codegen_usize_op_in_place(
rc_register,
BrilligBinaryOp::Add,
1,
);
}
Instruction::DecrementRc { value } => {
let rc_register = match self.convert_ssa_value(*value, dfg) {
BrilligVariable::BrilligArray(BrilligArray { rc, .. })
| BrilligVariable::BrilligVector(BrilligVector { rc, .. }) => rc,
other => unreachable!("ICE: decrement rc on non-array: {other:?}"),
};
self.brillig_context.codegen_usize_op_in_place(
rc_register,
BrilligBinaryOp::Sub,
1,
);
}
Instruction::EnableSideEffects { .. } => {
todo!("enable_side_effects not supported by brillig")
}
};
let dead_variables = self
.last_uses
.get(&instruction_id)
.expect("Last uses for instruction should have been computed");
for dead_variable in dead_variables {
self.variables.remove_variable(
dead_variable,
self.function_context,
self.brillig_context,
);
}
self.brillig_context.set_call_stack(CallStack::new());
}
fn convert_ssa_function_call(
&mut self,
func_id: FunctionId,
arguments: &[ValueId],
dfg: &DataFlowGraph,
result_ids: &[ValueId],
) {
// Convert the arguments to registers casting those to the types of the receiving function
let argument_registers: Vec<MemoryAddress> = arguments
.iter()
.flat_map(|argument_id| self.convert_ssa_value(*argument_id, dfg).extract_registers())
.collect();
// Create label for the function that will be called
let label_of_function_to_call = FunctionContext::function_id_to_function_label(func_id);
let variables_to_save = self.variables.get_available_variables(self.function_context);
let saved_registers = self
.brillig_context
.codegen_pre_call_save_registers_prep_args(&argument_registers, &variables_to_save);
// We don't save and restore constants, so we dump them before a external call since the callee might use the registers where they are allocated.
self.variables.dump_constants();
// Call instruction, which will interpret above registers 0..num args
self.brillig_context.add_external_call_instruction(label_of_function_to_call);
// Important: resolve after pre_call_save_registers_prep_args
// This ensures we don't save the results to registers unnecessarily.
// Allocate the registers for the variables where we are assigning the returns
let variables_assigned_to = vecmap(result_ids, |result_id| {
self.variables.define_variable(
self.function_context,
self.brillig_context,
*result_id,
dfg,
)
});
// Collect the registers that should have been returned
let returned_registers: Vec<MemoryAddress> = variables_assigned_to
.iter()
.flat_map(|returned_variable| returned_variable.extract_registers())
.collect();
assert!(
!saved_registers.iter().any(|x| returned_registers.contains(x)),
"should not save registers used as function results"
);
// puts the returns into the returned_registers and restores saved_registers
self.brillig_context
.codegen_post_call_prep_returns_load_registers(&returned_registers, &saved_registers);
}
fn validate_array_index(
&mut self,
array_variable: BrilligVariable,
index_register: SingleAddrVariable,
) {
let (size_as_register, should_deallocate_size) = match array_variable {
BrilligVariable::BrilligArray(BrilligArray { size, .. }) => {
(self.brillig_context.make_usize_constant_instruction(size.into()), true)
}
BrilligVariable::BrilligVector(BrilligVector { size, .. }) => {
(SingleAddrVariable::new_usize(size), false)
}
_ => unreachable!("ICE: validate array index on non-array"),
};
let condition = SingleAddrVariable::new(self.brillig_context.allocate_register(), 1);
self.brillig_context.memory_op_instruction(
index_register.address,
size_as_register.address,
condition.address,
BrilligBinaryOp::LessThan,
);
self.brillig_context
.codegen_constrain(condition, Some("Array index out of bounds".to_owned()));
if should_deallocate_size {
self.brillig_context.deallocate_single_addr(size_as_register);
}
self.brillig_context.deallocate_single_addr(condition);
}
pub(crate) fn retrieve_variable_from_array(
&mut self,
array_pointer: MemoryAddress,
index_var: SingleAddrVariable,
destination_variable: BrilligVariable,
) {
match destination_variable {
BrilligVariable::SingleAddr(destination_register) => {
self.brillig_context.codegen_array_get(
array_pointer,
index_var,
destination_register.address,
);
}
BrilligVariable::BrilligArray(..) | BrilligVariable::BrilligVector(..) => {
let reference = self.brillig_context.allocate_register();
self.brillig_context.codegen_array_get(array_pointer, index_var, reference);
self.brillig_context.codegen_load_variable(destination_variable, reference);
self.brillig_context.deallocate_register(reference);
}
}
}
/// Array set operation in SSA returns a new array or slice that is a copy of the parameter array or slice
/// With a specific value changed.
///
/// Returns `source_size_as_register`, which is expected to be deallocated with:
/// `self.brillig_context.deallocate_register(source_size_as_register)`
fn convert_ssa_array_set(
&mut self,
source_variable: BrilligVariable,
destination_variable: BrilligVariable,
opt_index_and_value: Option<(MemoryAddress, BrilligVariable)>,
) -> MemoryAddress {
let destination_pointer = match destination_variable {
BrilligVariable::BrilligArray(BrilligArray { pointer, .. }) => pointer,
BrilligVariable::BrilligVector(BrilligVector { pointer, .. }) => pointer,
_ => unreachable!("ICE: array_set SSA returns non-array"),
};
let reference_count = match source_variable {
BrilligVariable::BrilligArray(BrilligArray { rc, .. })
| BrilligVariable::BrilligVector(BrilligVector { rc, .. }) => rc,
_ => unreachable!("ICE: array_set SSA on non-array"),
};
let (source_pointer, source_size_as_register) = match source_variable {
BrilligVariable::BrilligArray(BrilligArray { size, pointer, rc: _ }) => {
let source_size_register = self.brillig_context.allocate_register();
self.brillig_context.usize_const_instruction(source_size_register, size.into());
(pointer, source_size_register)
}
BrilligVariable::BrilligVector(BrilligVector { size, pointer, rc: _ }) => {
let source_size_register = self.brillig_context.allocate_register();
self.brillig_context.mov_instruction(source_size_register, size);
(pointer, source_size_register)
}
_ => unreachable!("ICE: array_set SSA on non-array"),
};
// Here we want to compare the reference count against 1.
let one = self.brillig_context.make_usize_constant_instruction(1_usize.into());
let condition = self.brillig_context.allocate_register();
self.brillig_context.memory_op_instruction(
reference_count,
one.address,
condition,
BrilligBinaryOp::Equals,
);
self.brillig_context.codegen_branch(condition, |ctx, cond| {
if cond {
// Reference count is 1, we can mutate the array directly
ctx.mov_instruction(destination_pointer, source_pointer);
} else {
// First issue a array copy to the destination
ctx.codegen_allocate_array(destination_pointer, source_size_as_register);
ctx.codegen_copy_array(
source_pointer,
destination_pointer,
SingleAddrVariable::new(
source_size_as_register,
BRILLIG_MEMORY_ADDRESSING_BIT_SIZE,
),
);
}
});
match destination_variable {
BrilligVariable::BrilligArray(BrilligArray { rc: target_rc, .. }) => {
self.brillig_context.usize_const_instruction(target_rc, 1_usize.into());
}
BrilligVariable::BrilligVector(BrilligVector {
size: target_size,
rc: target_rc,
..
}) => {
self.brillig_context.mov_instruction(target_size, source_size_as_register);
self.brillig_context.usize_const_instruction(target_rc, 1_usize.into());
}
_ => unreachable!("ICE: array_set SSA on non-array"),
}
if let Some((index_register, value_variable)) = opt_index_and_value {
// Then set the value in the newly created array
self.store_variable_in_array(
destination_pointer,
SingleAddrVariable::new_usize(index_register),
value_variable,
);
}
self.brillig_context.deallocate_register(condition);
source_size_as_register
}
pub(crate) fn store_variable_in_array_with_ctx(
ctx: &mut BrilligContext,
destination_pointer: MemoryAddress,
index_register: SingleAddrVariable,
value_variable: BrilligVariable,
) {
match value_variable {
BrilligVariable::SingleAddr(value_variable) => {
ctx.codegen_array_set(destination_pointer, index_register, value_variable.address);
}
BrilligVariable::BrilligArray(_) => {
let reference: MemoryAddress = ctx.allocate_register();
ctx.codegen_allocate_array_reference(reference);
ctx.codegen_store_variable(reference, value_variable);
ctx.codegen_array_set(destination_pointer, index_register, reference);
ctx.deallocate_register(reference);
}
BrilligVariable::BrilligVector(_) => {
let reference = ctx.allocate_register();
ctx.codegen_allocate_vector_reference(reference);
ctx.codegen_store_variable(reference, value_variable);
ctx.codegen_array_set(destination_pointer, index_register, reference);
ctx.deallocate_register(reference);
}
}
}
pub(crate) fn store_variable_in_array(
&mut self,
destination_pointer: MemoryAddress,
index_variable: SingleAddrVariable,
value_variable: BrilligVariable,
) {
Self::store_variable_in_array_with_ctx(
self.brillig_context,
destination_pointer,
index_variable,
value_variable,
);
}
/// Convert the SSA slice operations to brillig slice operations
fn convert_ssa_slice_intrinsic_call(
&mut self,
dfg: &DataFlowGraph,
intrinsic: &Value,
instruction_id: InstructionId,
arguments: &[ValueId],
) {
let slice_id = arguments[1];
let element_size = dfg.type_of_value(slice_id).element_size();
let source_variable = self.convert_ssa_value(slice_id, dfg);
let source_vector = self.convert_array_or_vector_to_vector(source_variable);
let results = dfg.instruction_results(instruction_id);
match intrinsic {
Value::Intrinsic(Intrinsic::SlicePushBack) => {
let target_len = match self.variables.define_variable(
self.function_context,
self.brillig_context,
results[0],
dfg,
) {