-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy pathmod.rs
2209 lines (1990 loc) · 96.8 KB
/
mod.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
//! This file holds the pass to convert from Noir's SSA IR to ACIR.
mod acir_ir;
use std::collections::HashSet;
use std::fmt::Debug;
use self::acir_ir::acir_variable::{AcirContext, AcirType, AcirVar};
use super::function_builder::data_bus::DataBus;
use super::ir::dfg::CallStack;
use super::ir::instruction::ConstrainError;
use super::{
ir::{
dfg::DataFlowGraph,
function::{Function, RuntimeType},
instruction::{
Binary, BinaryOp, Instruction, InstructionId, Intrinsic, TerminatorInstruction,
},
map::Id,
types::{NumericType, Type},
value::{Value, ValueId},
},
ssa_gen::Ssa,
};
use crate::brillig::brillig_ir::artifact::GeneratedBrillig;
use crate::brillig::brillig_ir::BrilligContext;
use crate::brillig::{brillig_gen::brillig_fn::FunctionContext as BrilligFunctionContext, Brillig};
use crate::errors::{InternalError, InternalWarning, RuntimeError, SsaReport};
pub(crate) use acir_ir::generated_acir::GeneratedAcir;
use acvm::acir::native_types::Witness;
use acvm::acir::BlackBoxFunc;
use acvm::{
acir::{circuit::opcodes::BlockId, native_types::Expression},
FieldElement,
};
use fxhash::FxHashMap as HashMap;
use im::Vector;
use iter_extended::{try_vecmap, vecmap};
use noirc_frontend::Distinctness;
/// Context struct for the acir generation pass.
/// May be similar to the Evaluator struct in the current SSA IR.
struct Context {
/// Maps SSA values to `AcirVar`.
///
/// This is needed so that we only create a single
/// AcirVar per SSA value. Before creating an `AcirVar`
/// for an SSA value, we check this map. If an `AcirVar`
/// already exists for this Value, we return the `AcirVar`.
ssa_values: HashMap<Id<Value>, AcirValue>,
/// The `AcirVar` that describes the condition belonging to the most recently invoked
/// `SideEffectsEnabled` instruction.
current_side_effects_enabled_var: AcirVar,
/// Manages and builds the `AcirVar`s to which the converted SSA values refer.
acir_context: AcirContext,
/// Track initialized acir dynamic arrays
///
/// An acir array must start with a MemoryInit ACIR opcodes
/// and then have MemoryOp opcodes
/// This set is used to ensure that a MemoryOp opcode is only pushed to the circuit
/// if there is already a MemoryInit opcode.
initialized_arrays: HashSet<BlockId>,
/// Maps SSA values to BlockId
/// A BlockId is an ACIR structure which identifies a memory block
/// Each acir memory block corresponds to a different SSA array.
memory_blocks: HashMap<Id<Value>, BlockId>,
/// Maps SSA values to a BlockId used internally
/// A BlockId is an ACIR structure which identifies a memory block
/// Each memory blocks corresponds to a different SSA value
/// which utilizes this internal memory for ACIR generation.
internal_memory_blocks: HashMap<Id<Value>, BlockId>,
/// Maps an internal memory block to its length
///
/// This is necessary to keep track of an internal memory block's size.
/// We do not need a separate map to keep track of `memory_blocks` as
/// the length is set when we construct a `AcirValue::DynamicArray` and is tracked
/// as part of the `AcirValue` in the `ssa_values` map.
/// The length of an internal memory block is determined before an array operation
/// takes place thus we track it separate here in this map.
internal_mem_block_lengths: HashMap<BlockId, usize>,
/// Number of the next BlockId, it is used to construct
/// a new BlockId
max_block_id: u32,
data_bus: DataBus,
}
#[derive(Clone)]
pub(crate) struct AcirDynamicArray {
/// Identification for the Acir dynamic array
/// This is essentially a ACIR pointer to the array
block_id: BlockId,
/// Length of the array
len: usize,
/// Identification for the ACIR dynamic array
/// inner element type sizes array
element_type_sizes: Option<BlockId>,
}
impl Debug for AcirDynamicArray {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"id: {}, len: {}, element_type_sizes: {:?}",
self.block_id.0,
self.len,
self.element_type_sizes.map(|block_id| block_id.0)
)
}
}
#[derive(Debug, Clone)]
pub(crate) enum AcirValue {
Var(AcirVar, AcirType),
Array(im::Vector<AcirValue>),
DynamicArray(AcirDynamicArray),
}
impl AcirValue {
fn into_var(self) -> Result<AcirVar, InternalError> {
match self {
AcirValue::Var(var, _) => Ok(var),
AcirValue::DynamicArray(_) | AcirValue::Array(_) => Err(InternalError::General {
message: "Called AcirValue::into_var on an array".to_string(),
call_stack: CallStack::new(),
}),
}
}
fn borrow_var(&self) -> Result<AcirVar, InternalError> {
match self {
AcirValue::Var(var, _) => Ok(*var),
AcirValue::DynamicArray(_) | AcirValue::Array(_) => Err(InternalError::General {
message: "Called AcirValue::borrow_var on an array".to_string(),
call_stack: CallStack::new(),
}),
}
}
fn flatten(self) -> Vec<(AcirVar, AcirType)> {
match self {
AcirValue::Var(var, typ) => vec![(var, typ)],
AcirValue::Array(array) => array.into_iter().flat_map(AcirValue::flatten).collect(),
AcirValue::DynamicArray(_) => unimplemented!("Cannot flatten a dynamic array"),
}
}
}
impl Ssa {
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) fn into_acir(
self,
brillig: Brillig,
abi_distinctness: Distinctness,
last_array_uses: &HashMap<ValueId, InstructionId>,
) -> Result<GeneratedAcir, RuntimeError> {
let context = Context::new();
let mut generated_acir = context.convert_ssa(self, brillig, last_array_uses)?;
match abi_distinctness {
Distinctness::Distinct => {
// Create a witness for each return witness we have
// to guarantee that the return witnesses are distinct
let distinct_return_witness: Vec<_> = generated_acir
.return_witnesses
.clone()
.into_iter()
.map(|return_witness| {
generated_acir
.create_witness_for_expression(&Expression::from(return_witness))
})
.collect();
generated_acir.return_witnesses = distinct_return_witness;
Ok(generated_acir)
}
Distinctness::DuplicationAllowed => Ok(generated_acir),
}
}
}
impl Context {
fn new() -> Context {
let mut acir_context = AcirContext::default();
let current_side_effects_enabled_var = acir_context.add_constant(FieldElement::one());
Context {
ssa_values: HashMap::default(),
current_side_effects_enabled_var,
acir_context,
initialized_arrays: HashSet::new(),
memory_blocks: HashMap::default(),
internal_memory_blocks: HashMap::default(),
internal_mem_block_lengths: HashMap::default(),
max_block_id: 0,
data_bus: DataBus::default(),
}
}
/// Converts SSA into ACIR
fn convert_ssa(
self,
ssa: Ssa,
brillig: Brillig,
last_array_uses: &HashMap<ValueId, InstructionId>,
) -> Result<GeneratedAcir, RuntimeError> {
let main_func = ssa.main();
match main_func.runtime() {
RuntimeType::Acir => self.convert_acir_main(main_func, &ssa, brillig, last_array_uses),
RuntimeType::Brillig => self.convert_brillig_main(main_func, brillig),
}
}
fn convert_acir_main(
mut self,
main_func: &Function,
ssa: &Ssa,
brillig: Brillig,
last_array_uses: &HashMap<ValueId, InstructionId>,
) -> Result<GeneratedAcir, RuntimeError> {
let dfg = &main_func.dfg;
let entry_block = &dfg[main_func.entry_block()];
let input_witness = self.convert_ssa_block_params(entry_block.parameters(), dfg)?;
self.data_bus = dfg.data_bus.to_owned();
let mut warnings = Vec::new();
for instruction_id in entry_block.instructions() {
warnings.extend(self.convert_ssa_instruction(
*instruction_id,
dfg,
ssa,
&brillig,
last_array_uses,
)?);
}
warnings.extend(self.convert_ssa_return(entry_block.unwrap_terminator(), dfg)?);
Ok(self.acir_context.finish(input_witness, warnings))
}
fn convert_brillig_main(
mut self,
main_func: &Function,
brillig: Brillig,
) -> Result<GeneratedAcir, RuntimeError> {
let dfg = &main_func.dfg;
let inputs = try_vecmap(dfg[main_func.entry_block()].parameters(), |param_id| {
let typ = dfg.type_of_value(*param_id);
self.create_value_from_type(&typ, &mut |this, _| Ok(this.acir_context.add_variable()))
})?;
let witness_inputs = self.acir_context.extract_witness(&inputs);
let outputs: Vec<AcirType> =
vecmap(main_func.returns(), |result_id| dfg.type_of_value(*result_id).into());
let code = self.gen_brillig_for(main_func, &brillig)?;
// We specifically do not attempt execution of the brillig code being generated as this can result in it being
// replaced with constraints on witnesses to the program outputs.
let output_values = self.acir_context.brillig(
self.current_side_effects_enabled_var,
code,
inputs,
outputs,
false,
)?;
let output_vars: Vec<_> = output_values
.iter()
.flat_map(|value| value.clone().flatten())
.map(|value| value.0)
.collect();
for acir_var in output_vars {
self.acir_context.return_var(acir_var)?;
}
Ok(self.acir_context.finish(witness_inputs, Vec::new()))
}
/// Adds and binds `AcirVar`s for each numeric block parameter or block parameter array element.
fn convert_ssa_block_params(
&mut self,
params: &[ValueId],
dfg: &DataFlowGraph,
) -> Result<Vec<Witness>, RuntimeError> {
// The first witness (if any) is the next one
let start_witness = self.acir_context.current_witness_index().0;
for param_id in params {
let typ = dfg.type_of_value(*param_id);
let value = self.convert_ssa_block_param(&typ)?;
match &value {
AcirValue::Var(_, _) => (),
AcirValue::Array(_) => {
let block_id = self.block_id(param_id);
let len = if matches!(typ, Type::Array(_, _)) {
typ.flattened_size()
} else {
return Err(InternalError::Unexpected {
expected: "Block params should be an array".to_owned(),
found: format!("Instead got {:?}", typ),
call_stack: self.acir_context.get_call_stack(),
}
.into());
};
self.initialize_array(block_id, len, Some(value.clone()))?;
}
AcirValue::DynamicArray(_) => unreachable!(
"The dynamic array type is created in Acir gen and therefore cannot be a block parameter"
),
}
self.ssa_values.insert(*param_id, value);
}
let end_witness = self.acir_context.current_witness_index().0;
let witnesses = (start_witness..=end_witness).map(Witness::from).collect();
Ok(witnesses)
}
fn convert_ssa_block_param(&mut self, param_type: &Type) -> Result<AcirValue, RuntimeError> {
self.create_value_from_type(param_type, &mut |this, typ| this.add_numeric_input_var(&typ))
}
fn create_value_from_type(
&mut self,
param_type: &Type,
make_var: &mut impl FnMut(&mut Self, NumericType) -> Result<AcirVar, RuntimeError>,
) -> Result<AcirValue, RuntimeError> {
match param_type {
Type::Numeric(numeric_type) => {
let typ = AcirType::new(*numeric_type);
Ok(AcirValue::Var(make_var(self, *numeric_type)?, typ))
}
Type::Array(element_types, length) => {
let mut elements = im::Vector::new();
for _ in 0..*length {
for element in element_types.iter() {
elements.push_back(self.create_value_from_type(element, make_var)?);
}
}
Ok(AcirValue::Array(elements))
}
_ => unreachable!("ICE: Params to the program should only contains numbers and arrays"),
}
}
/// Get the BlockId corresponding to the ValueId
/// If there is no matching BlockId, we create a new one.
fn block_id(&mut self, value: &ValueId) -> BlockId {
if let Some(block_id) = self.memory_blocks.get(value) {
return *block_id;
}
let block_id = BlockId(self.max_block_id);
self.max_block_id += 1;
self.memory_blocks.insert(*value, block_id);
block_id
}
/// Get the next BlockId for internal memory
/// used during ACIR generation.
/// This is useful for referencing information that can
/// only be computed dynamically, such as the type structure
/// of non-homogenous arrays.
fn internal_block_id(&mut self, value: &ValueId) -> BlockId {
if let Some(block_id) = self.internal_memory_blocks.get(value) {
return *block_id;
}
let block_id = BlockId(self.max_block_id);
self.max_block_id += 1;
self.internal_memory_blocks.insert(*value, block_id);
block_id
}
/// Creates an `AcirVar` corresponding to a parameter witness to appears in the abi. A range
/// constraint is added if the numeric type requires it.
///
/// This function is used not only for adding numeric block parameters, but also for adding
/// any array elements that belong to reference type block parameters.
fn add_numeric_input_var(
&mut self,
numeric_type: &NumericType,
) -> Result<AcirVar, RuntimeError> {
let acir_var = self.acir_context.add_variable();
if matches!(numeric_type, NumericType::Signed { .. } | NumericType::Unsigned { .. }) {
self.acir_context.range_constrain_var(acir_var, numeric_type, None)?;
}
Ok(acir_var)
}
/// Converts an SSA instruction into its ACIR representation
fn convert_ssa_instruction(
&mut self,
instruction_id: InstructionId,
dfg: &DataFlowGraph,
ssa: &Ssa,
brillig: &Brillig,
last_array_uses: &HashMap<ValueId, InstructionId>,
) -> Result<Vec<SsaReport>, RuntimeError> {
let instruction = &dfg[instruction_id];
self.acir_context.set_call_stack(dfg.get_call_stack(instruction_id));
let mut warnings = Vec::new();
match instruction {
Instruction::Binary(binary) => {
let result_acir_var = self.convert_ssa_binary(binary, dfg)?;
self.define_result_var(dfg, instruction_id, result_acir_var);
}
Instruction::Constrain(lhs, rhs, assert_message) => {
let lhs = self.convert_numeric_value(*lhs, dfg)?;
let rhs = self.convert_numeric_value(*rhs, dfg)?;
let assert_message = if let Some(error) = assert_message {
match error.as_ref() {
ConstrainError::Static(string) => Some(string.clone()),
ConstrainError::Dynamic(call_instruction) => {
self.convert_ssa_call(call_instruction, dfg, ssa, brillig, &[])?;
None
}
}
} else {
None
};
self.acir_context.assert_eq_var(lhs, rhs, assert_message)?;
}
Instruction::Cast(value_id, _) => {
let acir_var = self.convert_numeric_value(*value_id, dfg)?;
self.define_result_var(dfg, instruction_id, acir_var);
}
Instruction::Call { .. } => {
let result_ids = dfg.instruction_results(instruction_id);
warnings.extend(self.convert_ssa_call(
instruction,
dfg,
ssa,
brillig,
result_ids,
)?);
}
Instruction::Not(value_id) => {
let (acir_var, typ) = match self.convert_value(*value_id, dfg) {
AcirValue::Var(acir_var, typ) => (acir_var, typ),
_ => unreachable!("NOT is only applied to numerics"),
};
let result_acir_var = self.acir_context.not_var(acir_var, typ)?;
self.define_result_var(dfg, instruction_id, result_acir_var);
}
Instruction::Truncate { value, bit_size, max_bit_size } => {
let result_acir_var =
self.convert_ssa_truncate(*value, *bit_size, *max_bit_size, dfg)?;
self.define_result_var(dfg, instruction_id, result_acir_var);
}
Instruction::EnableSideEffects { condition } => {
let acir_var = self.convert_numeric_value(*condition, dfg)?;
self.current_side_effects_enabled_var = acir_var;
}
Instruction::ArrayGet { .. } | Instruction::ArraySet { .. } => {
self.handle_array_operation(instruction_id, dfg, last_array_uses)?;
}
Instruction::Allocate => {
unreachable!("Expected all allocate instructions to be removed before acir_gen")
}
Instruction::Store { .. } => {
unreachable!("Expected all store instructions to be removed before acir_gen")
}
Instruction::Load { .. } => {
unreachable!("Expected all load instructions to be removed before acir_gen")
}
Instruction::IncrementRc { .. } => {
// Do nothing. Only Brillig needs to worry about reference counted arrays
}
Instruction::RangeCheck { value, max_bit_size, assert_message } => {
let acir_var = self.convert_numeric_value(*value, dfg)?;
self.acir_context.range_constrain_var(
acir_var,
&NumericType::Unsigned { bit_size: *max_bit_size },
assert_message.clone(),
)?;
}
}
self.acir_context.set_call_stack(CallStack::new());
Ok(warnings)
}
fn convert_ssa_call(
&mut self,
instruction: &Instruction,
dfg: &DataFlowGraph,
ssa: &Ssa,
brillig: &Brillig,
result_ids: &[ValueId],
) -> Result<Vec<SsaReport>, RuntimeError> {
let mut warnings = Vec::new();
match instruction {
Instruction::Call { func, arguments } => {
let function_value = &dfg[*func];
match function_value {
Value::Function(id) => {
let func = &ssa.functions[id];
match func.runtime() {
RuntimeType::Acir => unimplemented!(
"expected an intrinsic/brillig call, but found {func:?}. All ACIR methods should be inlined"
),
RuntimeType::Brillig => {
let inputs = vecmap(arguments, |arg| self.convert_value(*arg, dfg));
let code = self.gen_brillig_for(func, brillig)?;
let outputs: Vec<AcirType> = vecmap(result_ids, |result_id| dfg.type_of_value(*result_id).into());
let output_values = self.acir_context.brillig(self.current_side_effects_enabled_var, code, inputs, outputs, true)?;
// Compiler sanity check
assert_eq!(result_ids.len(), output_values.len(), "ICE: The number of Brillig output values should match the result ids in SSA");
for result in result_ids.iter().zip(output_values) {
if let AcirValue::Array(_) = &result.1 {
let array_id = dfg.resolve(*result.0);
let block_id = self.block_id(&array_id);
let array_typ = dfg.type_of_value(array_id);
self.initialize_array(block_id, array_typ.flattened_size(), Some(result.1.clone()))?;
}
self.ssa_values.insert(*result.0, result.1);
}
}
}
}
Value::Intrinsic(intrinsic) => {
if matches!(
intrinsic,
Intrinsic::BlackBox(BlackBoxFunc::RecursiveAggregation)
) {
warnings.push(SsaReport::Warning(InternalWarning::VerifyProof {
call_stack: self.acir_context.get_call_stack(),
}));
}
let outputs = self
.convert_ssa_intrinsic_call(*intrinsic, arguments, dfg, result_ids)?;
// Issue #1438 causes this check to fail with intrinsics that return 0
// results but the ssa form instead creates 1 unit result value.
// assert_eq!(result_ids.len(), outputs.len());
for (result, output) in result_ids.iter().zip(outputs) {
match &output {
// We need to make sure we initialize arrays returned from intrinsic calls
// or else they will fail if accessed with a dynamic index
AcirValue::Array(_) => {
let block_id = self.block_id(result);
let array_typ = dfg.type_of_value(*result);
let len = if matches!(array_typ, Type::Array(_, _)) {
array_typ.flattened_size()
} else {
Self::flattened_value_size(&output)
};
self.initialize_array(block_id, len, Some(output.clone()))?;
}
AcirValue::DynamicArray(_) => {
// Do nothing as a dynamic array returned from a slice intrinsic should already be initialized
}
AcirValue::Var(_, _) => {
// Do nothing
}
}
self.ssa_values.insert(*result, output);
}
}
Value::ForeignFunction(_) => unreachable!(
"All `oracle` methods should be wrapped in an unconstrained fn"
),
_ => unreachable!("expected calling a function but got {function_value:?}"),
}
}
_ => unreachable!("expected calling a call instruction"),
}
Ok(warnings)
}
fn gen_brillig_for(
&self,
func: &Function,
brillig: &Brillig,
) -> Result<GeneratedBrillig, InternalError> {
// Create the entry point artifact
let mut entry_point = BrilligContext::new_entry_point_artifact(
BrilligFunctionContext::parameters(func),
BrilligFunctionContext::return_values(func),
BrilligFunctionContext::function_id_to_function_label(func.id()),
);
// Link the entry point with all dependencies
while let Some(unresolved_fn_label) = entry_point.first_unresolved_function_call() {
let artifact = &brillig.find_by_function_label(unresolved_fn_label.clone());
let artifact = match artifact {
Some(artifact) => artifact,
None => {
return Err(InternalError::General {
message: format!("Cannot find linked fn {unresolved_fn_label}"),
call_stack: CallStack::new(),
})
}
};
entry_point.link_with(artifact);
}
// Generate the final bytecode
Ok(entry_point.finish())
}
/// Handles an ArrayGet or ArraySet instruction.
/// To set an index of the array (and create a new array in doing so), pass Some(value) for
/// store_value. To just retrieve an index of the array, pass None for store_value.
fn handle_array_operation(
&mut self,
instruction: InstructionId,
dfg: &DataFlowGraph,
last_array_uses: &HashMap<ValueId, InstructionId>,
) -> Result<(), RuntimeError> {
// Pass the instruction between array methods rather than the internal fields themselves
let (array, index, store_value) = match dfg[instruction] {
Instruction::ArrayGet { array, index } => (array, index, None),
Instruction::ArraySet { array, index, value, .. } => (array, index, Some(value)),
_ => {
return Err(InternalError::Unexpected {
expected: "Instruction should be an ArrayGet or ArraySet".to_owned(),
found: format!("Instead got {:?}", dfg[instruction]),
call_stack: self.acir_context.get_call_stack(),
}
.into())
}
};
if self.handle_constant_index(instruction, dfg, index, array, store_value)? {
return Ok(());
}
let (new_index, new_value) =
self.convert_array_operation_inputs(array, dfg, index, store_value)?;
let resolved_array = dfg.resolve(array);
let map_array = last_array_uses.get(&resolved_array) == Some(&instruction);
if let Some(new_value) = new_value {
self.array_set(instruction, new_index, new_value, dfg, map_array)?;
} else {
self.array_get(instruction, array, new_index, dfg)?;
}
Ok(())
}
/// Handle constant index: if there is no predicate and we have the array values,
/// we can perform the operation directly on the array
fn handle_constant_index(
&mut self,
instruction: InstructionId,
dfg: &DataFlowGraph,
index: ValueId,
array: ValueId,
store_value: Option<ValueId>,
) -> Result<bool, RuntimeError> {
let index_const = dfg.get_numeric_constant(index);
let value_type = dfg.type_of_value(array);
// Compiler sanity checks
assert!(
!value_type.is_nested_slice(),
"ICE: Nested slice type has reached ACIR generation"
);
let (Type::Array(_, _) | Type::Slice(_)) = &value_type else {
unreachable!("ICE: expected array or slice type");
};
match self.convert_value(array, dfg) {
AcirValue::Var(acir_var, _) => {
return Err(RuntimeError::InternalError(InternalError::Unexpected {
expected: "an array value".to_string(),
found: format!("{acir_var:?}"),
call_stack: self.acir_context.get_call_stack(),
}))
}
AcirValue::Array(array) => {
if let Some(index_const) = index_const {
let array_size = array.len();
let index = match index_const.try_to_u64() {
Some(index_const) => index_const as usize,
None => {
let call_stack = self.acir_context.get_call_stack();
return Err(RuntimeError::TypeConversion {
from: "array index".to_string(),
into: "u64".to_string(),
call_stack,
});
}
};
if self.acir_context.is_constant_one(&self.current_side_effects_enabled_var) {
// Report the error if side effects are enabled.
if index >= array_size {
let call_stack = self.acir_context.get_call_stack();
return Err(RuntimeError::IndexOutOfBounds {
index,
array_size,
call_stack,
});
} else {
let value = match store_value {
Some(store_value) => {
let store_value = self.convert_value(store_value, dfg);
AcirValue::Array(array.update(index, store_value))
}
None => array[index].clone(),
};
self.define_result(dfg, instruction, value);
return Ok(true);
}
}
// If there is a predicate and the index is not out of range, we can directly perform the read
else if index < array_size && store_value.is_none() {
self.define_result(dfg, instruction, array[index].clone());
return Ok(true);
}
}
}
AcirValue::DynamicArray(_) => (),
};
Ok(false)
}
/// We need to properly setup the inputs for array operations in ACIR.
/// From the original SSA values we compute the following AcirVars:
/// - new_index is the index of the array. ACIR memory operations work with a flat memory, so we fully flattened the specified index
/// in case we have a nested array. The index for SSA array operations only represents the flattened index of the current array.
/// Thus internal array element type sizes need to be computed to accurately transform the index.
/// - predicate_index is 0, or the index if the predicate is true
/// - new_value is the optional value when the operation is an array_set
/// When there is a predicate, it is predicate*value + (1-predicate)*dummy, where dummy is the value of the array at the requested index.
/// It is a dummy value because in the case of a false predicate, the value stored at the requested index will be itself.
fn convert_array_operation_inputs(
&mut self,
array: ValueId,
dfg: &DataFlowGraph,
index: ValueId,
store_value: Option<ValueId>,
) -> Result<(AcirVar, Option<AcirValue>), RuntimeError> {
let (array_id, array_typ, block_id) = self.check_array_is_initialized(array, dfg)?;
let index_var = self.convert_numeric_value(index, dfg)?;
let index_var = self.get_flattened_index(&array_typ, array_id, index_var, dfg)?;
let predicate_index =
self.acir_context.mul_var(index_var, self.current_side_effects_enabled_var)?;
let new_value = if let Some(store) = store_value {
let store_value = self.convert_value(store, dfg);
if self.acir_context.is_constant_one(&self.current_side_effects_enabled_var) {
Some(store_value)
} else {
let store_type = dfg.type_of_value(store);
let mut dummy_predicate_index = predicate_index;
// We must setup the dummy value to match the type of the value we wish to store
let dummy =
self.array_get_value(&store_type, block_id, &mut dummy_predicate_index)?;
Some(self.convert_array_set_store_value(&store_value, &dummy)?)
}
} else {
None
};
let new_index = if self.acir_context.is_constant_one(&self.current_side_effects_enabled_var)
{
index_var
} else {
predicate_index
};
Ok((new_index, new_value))
}
fn convert_array_set_store_value(
&mut self,
store_value: &AcirValue,
dummy_value: &AcirValue,
) -> Result<AcirValue, RuntimeError> {
match (store_value, dummy_value) {
(AcirValue::Var(store_var, _), AcirValue::Var(dummy_var, _)) => {
let true_pred =
self.acir_context.mul_var(*store_var, self.current_side_effects_enabled_var)?;
let one = self.acir_context.add_constant(FieldElement::one());
let not_pred =
self.acir_context.sub_var(one, self.current_side_effects_enabled_var)?;
let false_pred = self.acir_context.mul_var(not_pred, *dummy_var)?;
// predicate*value + (1-predicate)*dummy
let new_value = self.acir_context.add_var(true_pred, false_pred)?;
Ok(AcirValue::Var(new_value, AcirType::field()))
}
(AcirValue::Array(values), AcirValue::Array(dummy_values)) => {
let mut elements = im::Vector::new();
assert_eq!(
values.len(),
dummy_values.len(),
"ICE: The store value and dummy must have the same number of inner values"
);
for (val, dummy_val) in values.iter().zip(dummy_values) {
elements.push_back(self.convert_array_set_store_value(val, dummy_val)?);
}
Ok(AcirValue::Array(elements))
}
(
AcirValue::DynamicArray(AcirDynamicArray { block_id, len, .. }),
AcirValue::Array(dummy_values),
) => {
let dummy_values = dummy_values
.into_iter()
.flat_map(|val| val.clone().flatten())
.map(|(var, typ)| AcirValue::Var(var, typ))
.collect::<Vec<_>>();
assert_eq!(
*len,
dummy_values.len(),
"ICE: The store value and dummy must have the same number of inner values"
);
let values = try_vecmap(0..*len, |i| {
let index_var = self.acir_context.add_constant(i);
let read = self.acir_context.read_from_memory(*block_id, &index_var)?;
Ok::<AcirValue, RuntimeError>(AcirValue::Var(read, AcirType::field()))
})?;
let mut elements = im::Vector::new();
for (val, dummy_val) in values.iter().zip(dummy_values) {
elements.push_back(self.convert_array_set_store_value(val, &dummy_val)?);
}
Ok(AcirValue::Array(elements))
}
(AcirValue::DynamicArray(_), AcirValue::DynamicArray(_)) => {
unimplemented!("ICE: setting a dynamic array not supported");
}
_ => {
unreachable!("ICE: The store value and dummy value must match");
}
}
}
/// Generates a read opcode for the array
fn array_get(
&mut self,
instruction: InstructionId,
array: ValueId,
mut var_index: AcirVar,
dfg: &DataFlowGraph,
) -> Result<AcirValue, RuntimeError> {
let (array_id, _, block_id) = self.check_array_is_initialized(array, dfg)?;
let results = dfg.instruction_results(instruction);
let res_typ = dfg.type_of_value(results[0]);
// Get operations to call-data parameters are replaced by a get to the call-data-bus array
if let Some(call_data) = self.data_bus.call_data {
if self.data_bus.call_data_map.contains_key(&array_id) {
// TODO: the block_id of call-data must be notified to the backend
// TODO: should we do the same for return-data?
let type_size = res_typ.flattened_size();
let type_size =
self.acir_context.add_constant(FieldElement::from(type_size as i128));
let offset = self.acir_context.mul_var(var_index, type_size)?;
let bus_index = self.acir_context.add_constant(FieldElement::from(
self.data_bus.call_data_map[&array_id] as i128,
));
let new_index = self.acir_context.add_var(offset, bus_index)?;
return self.array_get(instruction, call_data, new_index, dfg);
}
}
// Compiler sanity check
assert!(
!res_typ.contains_slice_element(),
"ICE: Nested slice result found during ACIR generation"
);
let value = self.array_get_value(&res_typ, block_id, &mut var_index)?;
self.define_result(dfg, instruction, value.clone());
Ok(value)
}
fn array_get_value(
&mut self,
ssa_type: &Type,
block_id: BlockId,
var_index: &mut AcirVar,
) -> Result<AcirValue, RuntimeError> {
let one = self.acir_context.add_constant(FieldElement::one());
match ssa_type.clone() {
Type::Numeric(numeric_type) => {
// Read the value from the array at the specified index
let read = self.acir_context.read_from_memory(block_id, var_index)?;
// Increment the var_index in case of a nested array
*var_index = self.acir_context.add_var(*var_index, one)?;
let typ = AcirType::NumericType(numeric_type);
Ok(AcirValue::Var(read, typ))
}
Type::Array(element_types, len) => {
let mut values = Vector::new();
for _ in 0..len {
for typ in element_types.as_ref() {
values.push_back(self.array_get_value(typ, block_id, var_index)?);
}
}
Ok(AcirValue::Array(values))
}
_ => unreachable!("ICE: Expected an array or numeric but got {ssa_type:?}"),
}
}
/// Copy the array and generates a write opcode on the new array
///
/// Note: Copying the array is inefficient and is not the way we want to do it in the end.
fn array_set(
&mut self,
instruction: InstructionId,
mut var_index: AcirVar,
store_value: AcirValue,
dfg: &DataFlowGraph,
map_array: bool,
) -> Result<(), RuntimeError> {
// Pass the instruction between array methods rather than the internal fields themselves
let array = match dfg[instruction] {
Instruction::ArraySet { array, .. } => array,
_ => {
return Err(InternalError::Unexpected {
expected: "Instruction should be an ArraySet".to_owned(),
found: format!("Instead got {:?}", dfg[instruction]),
call_stack: self.acir_context.get_call_stack(),
}
.into())
}
};
let (array_id, array_typ, block_id) = self.check_array_is_initialized(array, dfg)?;
// Every array has a length in its type, so we fetch that from
// the SSA IR.
//
// A slice's size must be fetched from the SSA value that represents the slice.
// However, this size is simply the capacity of a slice. The capacity is dependent upon the witness
// and may contain data for which we want to restrict access. The true slice length is tracked in a
// a separate SSA value and restrictions on slice indices should be generated elsewhere in the SSA.
let array_len = if !array_typ.contains_slice_element() {
array_typ.flattened_size()
} else {
self.flattened_slice_size(array_id, dfg)
};
// Since array_set creates a new array, we create a new block ID for this
// array, unless map_array is true. In that case, we operate directly on block_id
// and we do not create a new block ID.
let result_id = dfg
.instruction_results(instruction)
.first()
.expect("Array set does not have one result");
let result_block_id;
if map_array {
self.memory_blocks.insert(*result_id, block_id);
result_block_id = block_id;
} else {
// Initialize the new array with the values from the old array
result_block_id = self.block_id(result_id);
self.copy_dynamic_array(block_id, result_block_id, array_len)?;
}
self.array_set_value(&store_value, result_block_id, &mut var_index)?;
let element_type_sizes = if !can_omit_element_sizes_array(&array_typ) {
Some(self.init_element_type_sizes_array(&array_typ, array_id, None, dfg)?)
} else {
None
};
let result_value = AcirValue::DynamicArray(AcirDynamicArray {
block_id: result_block_id,
len: array_len,
element_type_sizes,
});
self.define_result(dfg, instruction, result_value);
Ok(())
}