-
Notifications
You must be signed in to change notification settings - Fork 219
/
brillig_block.rs
1936 lines (1749 loc) · 83.3 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::artifact::Label;
use crate::brillig::brillig_ir::brillig_variable::{
type_to_heap_value_type, BrilligArray, BrilligVariable, SingleAddrVariable,
};
use crate::brillig::brillig_ir::registers::Stack;
use crate::brillig::brillig_ir::{
BrilligBinaryOp, BrilligContext, ReservedRegisters, BRILLIG_MEMORY_ADDRESSING_BIT_SIZE,
};
use crate::ssa::ir::call_stack::CallStack;
use crate::ssa::ir::instruction::{ConstrainError, Hint};
use crate::ssa::ir::{
basic_block::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::{acir::AcirField, FieldElement};
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use iter_extended::vecmap;
use num_bigint::BigUint;
use std::sync::Arc;
use super::brillig_black_box::convert_black_box_call;
use super::brillig_block_variables::BlockVariables;
use super::brillig_fn::FunctionContext;
use super::constant_allocation::InstructionLocation;
/// 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<FieldElement, Stack>,
/// 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<FieldElement, Stack>,
block_id: BasicBlockId,
dfg: &DataFlowGraph,
) {
let live_in = function_context.liveness.get_live_in(&block_id);
let variables = BlockVariables::new(live_in.clone());
brillig_context.set_allocated_registers(
variables
.get_available_variables(function_context)
.into_iter()
.map(|variable| variable.extract_register())
.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);
self.convert_block_params(dfg);
let block = &dfg[self.block_id];
// 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) -> Label {
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) -> Label {
Label::block(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,
) {
self.initialize_constants(
&self
.function_context
.constant_allocation
.allocated_at_location(self.block_id, InstructionLocation::Terminator),
dfg,
);
match terminator_instruction {
TerminatorInstruction::JmpIf {
condition,
then_destination,
else_destination,
call_stack: _,
} => {
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_allocation(self.function_context, *dest, dfg);
let source = self.convert_ssa_value(*src, dfg);
self.brillig_context
.mov_instruction(destination.extract_register(), source.extract_register());
}
self.brillig_context.jump_instruction(
self.create_block_label_for_current_function(*destination_block),
);
}
TerminatorInstruction::Return { return_values, .. } => {
let return_registers = vecmap(return_values, |value_id| {
self.convert_ssa_value(*value_id, dfg).extract_register()
});
self.brillig_context.codegen_return(&return_registers);
}
}
}
/// Allocates the block parameters that the given block is defining
fn convert_block_params(&mut self, dfg: &DataFlowGraph) {
// We don't allocate the block parameters here, we allocate the parameters the block is defining.
// Since predecessors to a block have to know where the parameters of the block are allocated to pass data to it,
// the block parameters need to be defined/allocated before the given block. Variable liveness provides when the block parameters are defined.
// For the entry block, the defined block params will be the params of the function + any extra params of blocks it's the immediate dominator of.
for param_id in self.function_context.liveness.defined_block_params(&self.block_id) {
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.define_variable(
self.function_context,
self.brillig_context,
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_instruction_call_stack(instruction_id));
self.initialize_constants(
&self.function_context.constant_allocation.allocated_at_location(
self.block_id,
InstructionLocation::Instruction(instruction_id),
),
dfg,
);
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 (condition, deallocate) = match (
dfg.get_numeric_constant_with_type(*lhs),
dfg.get_numeric_constant_with_type(*rhs),
) {
// If the constraint is of the form `x == u1 1` then we can simply constrain `x` directly
(Some((constant, NumericType::Unsigned { bit_size: 1 })), None)
if constant == FieldElement::one() =>
{
(self.convert_ssa_single_addr_value(*rhs, dfg), false)
}
(None, Some((constant, NumericType::Unsigned { bit_size: 1 })))
if constant == FieldElement::one() =>
{
(self.convert_ssa_single_addr_value(*lhs, dfg), false)
}
// Otherwise we need to perform the equality explicitly.
_ => {
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,
);
(condition, true)
}
};
match assert_message {
Some(ConstrainError::Dynamic(selector, _, values)) => {
let payload_values =
vecmap(values, |value| self.convert_ssa_value(*value, dfg));
let payload_as_params = vecmap(values, |value| {
let value_type = dfg.type_of_value(*value);
FunctionContext::ssa_type_to_parameter(&value_type)
});
self.brillig_context.codegen_constrain_with_revert_data(
condition,
payload_values,
payload_as_params,
*selector,
);
}
Some(ConstrainError::StaticString(message)) => {
self.brillig_context.codegen_constrain(condition, Some(message.clone()));
}
None => {
self.brillig_context.codegen_constrain(condition, None);
}
}
if deallocate {
self.brillig_context.deallocate_single_addr(condition);
}
}
Instruction::Allocate => {
let result_value = dfg.instruction_results(instruction_id)[0];
let pointer = self.variables.define_single_addr_variable(
self.function_context,
self.brillig_context,
result_value,
dfg,
);
self.brillig_context.codegen_allocate_immediate_mem(pointer.address, 1);
}
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
.store_instruction(address_var.address, source_variable.extract_register());
}
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
.load_instruction(target_variable.extract_register(), 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_values = vecmap(arguments, |value_id| {
let variable = self.convert_ssa_value(*value_id, dfg);
self.brillig_context.variable_to_value_or_array(variable)
});
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_variables = vecmap(result_ids, |value_id| {
self.allocate_external_call_result(*value_id, dfg)
});
let output_values = vecmap(&output_variables, |variable| {
self.brillig_context.variable_to_value_or_array(*variable)
});
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_values,
&input_value_types,
&output_values,
&output_value_types,
);
// Deallocate the temporary heap arrays and vectors of the inputs
for input_value in input_values {
match input_value {
ValueOrArray::HeapArray(array) => {
self.brillig_context.deallocate_heap_array(array);
}
ValueOrArray::HeapVector(vector) => {
self.brillig_context.deallocate_heap_vector(vector);
}
_ => {}
}
}
// Deallocate the temporary heap arrays and vectors of the outputs
for (i, (output_register, output_variable)) in
output_values.iter().zip(output_variables).enumerate()
{
match output_register {
// Returned vectors need to emit some bytecode to format the result as a BrilligVector
ValueOrArray::HeapVector(heap_vector) => {
self.brillig_context.initialize_externally_returned_vector(
output_variable.extract_vector(),
*heap_vector,
);
// Update the dynamic slice length maintained in SSA
if let ValueOrArray::MemoryAddress(len_index) = output_values[i - 1]
{
let element_size = dfg[result_ids[i]].get_type().element_size();
self.brillig_context
.mov_instruction(len_index, heap_vector.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");
}
self.brillig_context.deallocate_heap_vector(*heap_vector);
}
ValueOrArray::HeapArray(array) => {
self.brillig_context.deallocate_heap_array(*array);
}
ValueOrArray::MemoryAddress(_) => {}
}
}
}
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) => {
// This match could be combined with the above but without it rust analyzer
// can't automatically insert any missing cases
match 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,
);
}
}
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 destination_vector = destination_variable.extract_vector();
let source_array = source_variable.extract_array();
let element_size = dfg.type_of_value(arguments[0]).element_size();
let source_size_register = self
.brillig_context
.make_usize_constant_instruction(source_array.size.into());
// we need to explicitly set the destination_len_variable
self.brillig_context.codegen_usize_op(
source_size_register.address,
destination_len_variable.address,
BrilligBinaryOp::UnsignedDiv,
element_size,
);
self.brillig_context.codegen_initialize_vector(
destination_vector,
source_size_register,
None,
);
// Items
let vector_items_pointer = self
.brillig_context
.codegen_make_vector_items_pointer(destination_vector);
let array_items_pointer =
self.brillig_context.codegen_make_array_items_pointer(source_array);
self.brillig_context.codegen_mem_copy(
array_items_pointer,
vector_items_pointer,
source_size_register,
);
self.brillig_context.deallocate_single_addr(source_size_register);
self.brillig_context.deallocate_register(vector_items_pointer);
self.brillig_context.deallocate_register(array_items_pointer);
}
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,
);
}
Intrinsic::ToBits(endianness) => {
let results = dfg.instruction_results(instruction_id);
let source = self.convert_ssa_single_addr_value(arguments[0], dfg);
let target_array = self
.variables
.define_variable(
self.function_context,
self.brillig_context,
results[0],
dfg,
)
.extract_array();
let two = self
.brillig_context
.make_usize_constant_instruction(2_usize.into());
self.brillig_context.codegen_to_radix(
source,
target_array,
two,
matches!(endianness, Endian::Little),
true,
);
self.brillig_context.deallocate_single_addr(two);
}
Intrinsic::ToRadix(endianness) => {
let results = dfg.instruction_results(instruction_id);
let source = self.convert_ssa_single_addr_value(arguments[0], dfg);
let radix = self.convert_ssa_single_addr_value(arguments[1], dfg);
let target_array = self
.variables
.define_variable(
self.function_context,
self.brillig_context,
results[0],
dfg,
)
.extract_array();
self.brillig_context.codegen_to_radix(
source,
target_array,
radix,
matches!(endianness, Endian::Little),
false,
);
}
Intrinsic::Hint(Hint::BlackBox) => {
let result_ids = dfg.instruction_results(instruction_id);
self.convert_ssa_identity_call(arguments, dfg, result_ids);
}
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,
);
}
// `Intrinsic::AsWitness` is used to provide hints to acir-gen on optimal expression splitting.
// It is then useless in the brillig runtime and so we can ignore it
Intrinsic::AsWitness => (),
Intrinsic::FieldLessThan => {
let lhs = self.convert_ssa_single_addr_value(arguments[0], dfg);
assert!(lhs.bit_size == FieldElement::max_num_bits());
let rhs = self.convert_ssa_single_addr_value(arguments[1], dfg);
assert!(rhs.bit_size == FieldElement::max_num_bits());
let results = dfg.instruction_results(instruction_id);
let destination = self
.variables
.define_variable(
self.function_context,
self.brillig_context,
results[0],
dfg,
)
.extract_single_addr();
assert!(destination.bit_size == 1);
self.brillig_context.binary_instruction(
lhs,
rhs,
destination,
BrilligBinaryOp::LessThan,
);
}
Intrinsic::ArrayRefCount | Intrinsic::SliceRefCount => {
let array = self.convert_ssa_value(arguments[0], dfg);
let result = dfg.instruction_results(instruction_id)[0];
let destination = self.variables.define_variable(
self.function_context,
self.brillig_context,
result,
dfg,
);
let destination = destination.extract_register();
let array = array.extract_register();
self.brillig_context.load_instruction(destination, array);
}
Intrinsic::FromField
| Intrinsic::AsField
| Intrinsic::IsUnconstrained
| Intrinsic::DerivePedersenGenerators
| Intrinsic::ApplyRangeConstraint
| Intrinsic::StrAsBytes
| Intrinsic::AssertConstant
| Intrinsic::StaticAssert
| Intrinsic::ArrayAsStrUnchecked => {
unreachable!("unsupported function call type {:?}", dfg[*func])
}
}
}
Value::Instruction { .. } | Value::Param { .. } | Value::NumericConstant { .. } => {
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 index_variable = self.convert_ssa_single_addr_value(*index, dfg);
if !dfg.is_safe_index(*index, *array) {
self.validate_array_index(array_variable, index_variable);
}
let items_pointer =
self.brillig_context.codegen_make_array_or_vector_items_pointer(array_variable);
self.brillig_context.codegen_load_with_offset(
items_pointer,
index_variable,
destination_variable.extract_register(),
);
self.brillig_context.deallocate_register(items_pointer);
}
Instruction::ArraySet { array, index, value, mutable } => {
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,
);
if !dfg.is_safe_index(*index, *array) {
self.validate_array_index(source_variable, index_register);
}
self.convert_ssa_array_set(
source_variable,
destination_variable,
index_register,
value_variable,
*mutable,
);
}
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 array_or_vector = self.convert_ssa_value(*value, dfg);
let rc_register = self.brillig_context.allocate_register();
// RC is always directly pointed by the array/vector pointer
self.brillig_context
.load_instruction(rc_register, array_or_vector.extract_register());
self.brillig_context.codegen_usize_op_in_place(
rc_register,
BrilligBinaryOp::Add,
1,
);
self.brillig_context
.store_instruction(array_or_vector.extract_register(), rc_register);
self.brillig_context.deallocate_register(rc_register);
}
Instruction::DecrementRc { value } => {
let array_or_vector = self.convert_ssa_value(*value, dfg);
let rc_register = self.brillig_context.allocate_register();
self.brillig_context
.load_instruction(rc_register, array_or_vector.extract_register());
self.brillig_context.codegen_usize_op_in_place(
rc_register,
BrilligBinaryOp::Sub,
1,
);
self.brillig_context
.store_instruction(array_or_vector.extract_register(), rc_register);
self.brillig_context.deallocate_register(rc_register);
}
Instruction::EnableSideEffectsIf { .. } => {
todo!("enable_side_effects not supported by brillig")
}
Instruction::IfElse { .. } => {
unreachable!("IfElse instructions should not be possible in brillig")
}
Instruction::MakeArray { elements: array, typ } => {
let value_id = dfg.instruction_results(instruction_id)[0];
if !self.variables.is_allocated(&value_id) {
let new_variable = self.variables.define_variable(
self.function_context,
self.brillig_context,
value_id,
dfg,
);
// Initialize the variable
match new_variable {
BrilligVariable::BrilligArray(brillig_array) => {
self.brillig_context.codegen_initialize_array(brillig_array);
}
BrilligVariable::BrilligVector(vector) => {
let size = self
.brillig_context
.make_usize_constant_instruction(array.len().into());
self.brillig_context.codegen_initialize_vector(vector, size, None);
self.brillig_context.deallocate_single_addr(size);
}
_ => unreachable!(
"ICE: Cannot initialize array value created as {new_variable:?}"
),
};
// Write the items
let items_pointer = self
.brillig_context
.codegen_make_array_or_vector_items_pointer(new_variable);
self.initialize_constant_array(array, typ, dfg, items_pointer);
self.brillig_context.deallocate_register(items_pointer);
}
}
};
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],
) {
let argument_variables =
vecmap(arguments, |argument_id| self.convert_ssa_value(*argument_id, dfg));
let return_variables = vecmap(result_ids, |result_id| {
self.variables.define_variable(
self.function_context,
self.brillig_context,
*result_id,
dfg,
)
});
self.brillig_context.codegen_call(func_id, &argument_variables, &return_variables);
}
/// Copy the input arguments to the results.
fn convert_ssa_identity_call(
&mut self,
arguments: &[ValueId],
dfg: &DataFlowGraph,
result_ids: &[ValueId],
) {
let argument_variables =
vecmap(arguments, |argument_id| self.convert_ssa_value(*argument_id, dfg));
let return_variables = vecmap(result_ids, |result_id| {
self.variables.define_variable(
self.function_context,
self.brillig_context,
*result_id,
dfg,
)
});
for (src, dst) in argument_variables.into_iter().zip(return_variables) {
self.brillig_context.mov_instruction(dst.extract_register(), src.extract_register());
}
}
fn validate_array_index(
&mut self,
array_variable: BrilligVariable,
index_register: SingleAddrVariable,
) {
let size = self.brillig_context.codegen_make_array_or_vector_length(array_variable);
let condition = SingleAddrVariable::new(self.brillig_context.allocate_register(), 1);
self.brillig_context.memory_op_instruction(
index_register.address,
size.address,
condition.address,
BrilligBinaryOp::LessThan,
);
self.brillig_context
.codegen_constrain(condition, Some("Array index out of bounds".to_owned()));
self.brillig_context.deallocate_single_addr(size);
self.brillig_context.deallocate_single_addr(condition);
}
/// 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,
index_register: SingleAddrVariable,
value_variable: BrilligVariable,
mutable: bool,
) {
assert!(index_register.bit_size == BRILLIG_MEMORY_ADDRESSING_BIT_SIZE);
match (source_variable, destination_variable) {
(
BrilligVariable::BrilligArray(source_array),
BrilligVariable::BrilligArray(destination_array),
) => {
if !mutable {
self.brillig_context.call_array_copy_procedure(source_array, destination_array);
}
}
(
BrilligVariable::BrilligVector(source_vector),
BrilligVariable::BrilligVector(destination_vector),
) => {
if !mutable {
self.brillig_context
.call_vector_copy_procedure(source_vector, destination_vector);
}
}
_ => unreachable!("ICE: array set on non-array"),
}
let destination_for_store = if mutable { source_variable } else { destination_variable };
// Then set the value in the newly created array
let items_pointer =
self.brillig_context.codegen_make_array_or_vector_items_pointer(destination_for_store);
self.brillig_context.codegen_store_with_offset(
items_pointer,
index_register,
value_variable.extract_register(),
);
// If we mutated the source array we want instructions that use the destination array to point to the source array
if mutable {
self.brillig_context.mov_instruction(
destination_variable.extract_register(),
source_variable.extract_register(),
);
}
self.brillig_context.deallocate_register(items_pointer);
}
/// 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_vector = self.convert_ssa_value(slice_id, dfg).extract_vector();
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,