-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathmod.rs
1182 lines (1080 loc) · 47.5 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::{HashMap, HashSet};
use std::fmt::Debug;
use std::ops::RangeInclusive;
use self::acir_ir::acir_variable::{AcirContext, AcirType, AcirVar};
use super::ir::dfg::CallStack;
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, RuntimeError};
pub(crate) use acir_ir::generated_acir::GeneratedAcir;
use acvm::{
acir::{circuit::opcodes::BlockId, native_types::Expression},
FieldElement,
};
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>,
/// Number of the next BlockId, it is used to construct
/// a new BlockId
max_block_id: u32,
}
#[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,
}
impl Debug for AcirDynamicArray {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "id: {}, len: {}", self.block_id.0, self.len)
}
}
#[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 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 {
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::new(),
current_side_effects_enabled_var,
acir_context,
initialized_arrays: HashSet::new(),
memory_blocks: HashMap::new(),
max_block_id: 0,
}
}
/// 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)?;
for instruction_id in entry_block.instructions() {
self.convert_ssa_instruction(*instruction_id, dfg, ssa, &brillig, last_array_uses)?;
}
self.convert_ssa_return(entry_block.unwrap_terminator(), dfg)?;
Ok(self.acir_context.finish(input_witness.collect()))
}
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)?;
let output_values = self.acir_context.brillig(
self.current_side_effects_enabled_var,
code,
inputs,
outputs,
)?;
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))
}
/// 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<RangeInclusive<u32>, RuntimeError> {
// The first witness (if any) is the next one
let start_witness = self.acir_context.current_witness_index().0 + 1;
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(values) => {
let block_id = self.block_id(param_id);
let v = vecmap(values, |v| v.clone());
self.initialize_array(block_id, values.len(), Some(&v))?;
}
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;
Ok(start_witness..=end_witness)
}
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
}
/// 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)?;
}
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<(), RuntimeError> {
let instruction = &dfg[instruction_id];
self.acir_context.set_call_stack(dfg.get_call_stack(instruction_id));
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(value_id) => {
let constrain_condition = self.convert_numeric_value(*value_id, dfg)?;
self.acir_context.assert_eq_one(constrain_condition)?;
}
Instruction::Cast(value_id, typ) => {
let result_acir_var = self.convert_ssa_cast(value_id, typ, dfg)?;
self.define_result_var(dfg, instruction_id, result_acir_var);
}
Instruction::Call { func, arguments } => {
let result_ids = dfg.instruction_results(instruction_id);
match &dfg[*func] {
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)?;
// 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) {
self.ssa_values.insert(*result.0, result.1);
}
}
}
}
Value::Intrinsic(intrinsic) => {
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) {
self.ssa_values.insert(*result, output);
}
}
Value::ForeignFunction(_) => unreachable!(
"All `oracle` methods should be wrapped in an unconstrained fn"
),
_ => unreachable!("expected calling a function"),
}
}
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 { array, index } => {
self.handle_array_operation(
instruction_id,
*array,
*index,
None,
dfg,
last_array_uses,
)?;
}
Instruction::ArraySet { array, index, value } => {
self.handle_array_operation(
instruction_id,
*array,
*index,
Some(*value),
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")
}
}
self.acir_context.set_call_stack(CallStack::new());
Ok(())
}
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,
array: ValueId,
index: ValueId,
store_value: Option<ValueId>,
dfg: &DataFlowGraph,
last_array_uses: &HashMap<ValueId, InstructionId>,
) -> Result<(), RuntimeError> {
let index_const = dfg.get_numeric_constant(index);
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 index >= array_size {
// Ignore the error if side effects are disabled.
if self.acir_context.is_constant_one(&self.current_side_effects_enabled_var)
{
let call_stack = self.acir_context.get_call_stack();
return Err(RuntimeError::IndexOutOfBounds {
index,
array_size,
call_stack,
});
}
let result_type =
dfg.type_of_value(dfg.instruction_results(instruction)[0]);
let value = self.create_default_value(&result_type)?;
self.define_result(dfg, instruction, value);
return Ok(());
}
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(());
}
}
AcirValue::DynamicArray(_) => (),
}
let resolved_array = dfg.resolve(array);
let map_array = last_array_uses.get(&resolved_array) == Some(&instruction);
if let Some(store) = store_value {
self.array_set(instruction, array, index, store, dfg, map_array)?;
} else {
self.array_get(instruction, array, index, dfg)?;
}
Ok(())
}
/// Generates a read opcode for the array
fn array_get(
&mut self,
instruction: InstructionId,
array: ValueId,
index: ValueId,
dfg: &DataFlowGraph,
) -> Result<(), RuntimeError> {
let array = dfg.resolve(array);
let block_id = self.block_id(&array);
if !self.initialized_arrays.contains(&block_id) {
match &dfg[array] {
Value::Array { array, .. } => {
let values: Vec<AcirValue> =
array.iter().map(|i| self.convert_value(*i, dfg)).collect();
self.initialize_array(block_id, array.len(), Some(&values))?;
}
_ => {
return Err(RuntimeError::UnInitialized {
name: "array".to_string(),
call_stack: self.acir_context.get_call_stack(),
})
}
}
}
let index_var = self.convert_value(index, dfg).into_var()?;
let read = self.acir_context.read_from_memory(block_id, &index_var)?;
let typ = match dfg.type_of_value(array) {
Type::Array(typ, _) => {
if typ.len() != 1 {
unimplemented!(
"Non-const array indices is not implemented for non-homogenous array"
);
}
typ[0].clone()
}
_ => unreachable!("ICE - expected an array"),
};
let typ = AcirType::from(typ);
self.define_result(dfg, instruction, AcirValue::Var(read, typ));
Ok(())
}
/// 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,
array: ValueId,
index: ValueId,
store_value: ValueId,
dfg: &DataFlowGraph,
map_array: bool,
) -> Result<(), InternalError> {
// Fetch the internal SSA ID for the array
let array = dfg.resolve(array);
// Use the SSA ID to get or create its block ID
let block_id = self.block_id(&array);
// Every array has a length in its type, so we fetch that from
// the SSA IR.
let len = match dfg.type_of_value(array) {
Type::Array(_, len) => len,
_ => unreachable!("ICE - expected an array"),
};
// Check if the array has already been initialized in ACIR gen
// if not, we initialize it using the values from SSA
let already_initialized = self.initialized_arrays.contains(&block_id);
if !already_initialized {
match &dfg[array] {
Value::Array { array, .. } => {
let values: Vec<AcirValue> =
array.iter().map(|i| self.convert_value(*i, dfg)).collect();
self.initialize_array(block_id, array.len(), Some(&values))?;
}
_ => {
return Err(InternalError::General {
message: format!("Array {array} should be initialized"),
call_stack: self.acir_context.get_call_stack(),
})
}
}
}
// 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);
let init_values = try_vecmap(0..len, |i| {
let index = AcirValue::Var(
self.acir_context.add_constant(FieldElement::from(i as u128)),
AcirType::NumericType(NumericType::NativeField),
);
let var = index.into_var()?;
let read = self.acir_context.read_from_memory(block_id, &var)?;
Ok(AcirValue::Var(read, AcirType::NumericType(NumericType::NativeField)))
})?;
self.initialize_array(result_block_id, len, Some(&init_values))?;
}
// Write the new value into the new array at the specified index
let index_var = self.convert_value(index, dfg).into_var()?;
let value_var = self.convert_value(store_value, dfg).into_var()?;
self.acir_context.write_to_memory(result_block_id, &index_var, &value_var)?;
let result_value =
AcirValue::DynamicArray(AcirDynamicArray { block_id: result_block_id, len });
self.define_result(dfg, instruction, result_value);
Ok(())
}
/// Initializes an array with the given values and caches the fact that we
/// have initialized this array.
fn initialize_array(
&mut self,
array: BlockId,
len: usize,
values: Option<&[AcirValue]>,
) -> Result<(), InternalError> {
self.acir_context.initialize_array(array, len, values)?;
self.initialized_arrays.insert(array);
Ok(())
}
/// Remember the result of an instruction returning a single value
fn define_result(
&mut self,
dfg: &DataFlowGraph,
instruction: InstructionId,
result: AcirValue,
) {
let result_ids = dfg.instruction_results(instruction);
self.ssa_values.insert(result_ids[0], result);
}
/// Remember the result of instruction returning a single numeric value
fn define_result_var(
&mut self,
dfg: &DataFlowGraph,
instruction: InstructionId,
result: AcirVar,
) {
let result_ids = dfg.instruction_results(instruction);
let typ = dfg.type_of_value(result_ids[0]).into();
self.define_result(dfg, instruction, AcirValue::Var(result, typ));
}
/// Converts an SSA terminator's return values into their ACIR representations
fn convert_ssa_return(
&mut self,
terminator: &TerminatorInstruction,
dfg: &DataFlowGraph,
) -> Result<(), InternalError> {
let return_values = match terminator {
TerminatorInstruction::Return { return_values } => return_values,
_ => unreachable!("ICE: Program must have a singular return"),
};
// The return value may or may not be an array reference. Calling `flatten_value_list`
// will expand the array if there is one.
let return_acir_vars = self.flatten_value_list(return_values, dfg);
for acir_var in return_acir_vars {
self.acir_context.return_var(acir_var)?;
}
Ok(())
}
/// Gets the cached `AcirVar` that was converted from the corresponding `ValueId`. If it does
/// not already exist in the cache, a conversion is attempted and cached for simple values
/// that require no further context such as numeric types - values requiring more context
/// should have already been cached elsewhere.
///
/// Conversion is assumed to have already been performed for instruction results and block
/// parameters. This is because block parameters are converted before anything else, and
/// because instructions results are converted when the corresponding instruction is
/// encountered. (An instruction result cannot be referenced before the instruction occurs.)
///
/// It is not safe to call this function on value ids that represent addresses. Instructions
/// involving such values are evaluated via a separate path and stored in
/// `ssa_value_to_array_address` instead.
fn convert_value(&mut self, value_id: ValueId, dfg: &DataFlowGraph) -> AcirValue {
let value_id = dfg.resolve(value_id);
let value = &dfg[value_id];
if let Some(acir_value) = self.ssa_values.get(&value_id) {
return acir_value.clone();
}
let acir_value = match value {
Value::NumericConstant { constant, typ } => {
AcirValue::Var(self.acir_context.add_constant(*constant), typ.into())
}
Value::Array { array, .. } => {
let elements = array.iter().map(|element| self.convert_value(*element, dfg));
AcirValue::Array(elements.collect())
}
Value::Intrinsic(..) => todo!(),
Value::Function(..) => unreachable!("ICE: All functions should have been inlined"),
Value::ForeignFunction(_) => unimplemented!(
"Oracle calls directly in constrained functions are not yet available."
),
Value::Instruction { .. } | Value::Param { .. } => {
unreachable!("ICE: Should have been in cache {value_id} {value:?}")
}
};
self.ssa_values.insert(value_id, acir_value.clone());
acir_value
}
fn convert_numeric_value(
&mut self,
value_id: ValueId,
dfg: &DataFlowGraph,
) -> Result<AcirVar, InternalError> {
match self.convert_value(value_id, dfg) {
AcirValue::Var(acir_var, _) => Ok(acir_var),
AcirValue::Array(array) => Err(InternalError::UnExpected {
expected: "a numeric value".to_string(),
found: format!("{array:?}"),
call_stack: self.acir_context.get_call_stack(),
}),
AcirValue::DynamicArray(_) => Err(InternalError::UnExpected {
expected: "a numeric value".to_string(),
found: "an array".to_string(),
call_stack: self.acir_context.get_call_stack(),
}),
}
}
/// Processes a binary operation and converts the result into an `AcirVar`
fn convert_ssa_binary(
&mut self,
binary: &Binary,
dfg: &DataFlowGraph,
) -> Result<AcirVar, RuntimeError> {
let lhs = self.convert_numeric_value(binary.lhs, dfg)?;
let rhs = self.convert_numeric_value(binary.rhs, dfg)?;
let binary_type = self.type_of_binary_operation(binary, dfg);
match &binary_type {
Type::Numeric(NumericType::Unsigned { bit_size })
| Type::Numeric(NumericType::Signed { bit_size }) => {
// Conservative max bit size that is small enough such that two operands can be
// multiplied and still fit within the field modulus. This is necessary for the
// truncation technique: result % 2^bit_size to be valid.
let max_integer_bit_size = FieldElement::max_num_bits() / 2;
if *bit_size > max_integer_bit_size {
return Err(RuntimeError::UnsupportedIntegerSize {
num_bits: *bit_size,
max_num_bits: max_integer_bit_size,
call_stack: self.acir_context.get_call_stack(),
});
}
}
_ => {}
}
let binary_type = AcirType::from(binary_type);
let bit_count = binary_type.bit_size();
match binary.operator {
BinaryOp::Add => self.acir_context.add_var(lhs, rhs),
BinaryOp::Sub => self.acir_context.sub_var(lhs, rhs),
BinaryOp::Mul => self.acir_context.mul_var(lhs, rhs),
BinaryOp::Div => self.acir_context.div_var(
lhs,
rhs,
binary_type,
self.current_side_effects_enabled_var,
),
// Note: that this produces unnecessary constraints when
// this Eq instruction is being used for a constrain statement
BinaryOp::Eq => self.acir_context.eq_var(lhs, rhs),
BinaryOp::Lt => self.acir_context.less_than_var(
lhs,
rhs,
bit_count,
self.current_side_effects_enabled_var,
),
BinaryOp::Xor => self.acir_context.xor_var(lhs, rhs, binary_type),
BinaryOp::And => self.acir_context.and_var(lhs, rhs, binary_type),
BinaryOp::Or => self.acir_context.or_var(lhs, rhs, binary_type),
BinaryOp::Mod => self.acir_context.modulo_var(
lhs,
rhs,
bit_count,
self.current_side_effects_enabled_var,
),
}
}
/// Operands in a binary operation are checked to have the same type.
///
/// In Noir, binary operands should have the same type due to the language
/// semantics.
///
/// There are some edge cases to consider:
/// - Constants are not explicitly type casted, so we need to check for this and
/// return the type of the other operand, if we have a constant.
/// - 0 is not seen as `Field 0` but instead as `Unit 0`
/// TODO: The latter seems like a bug, if we cannot differentiate between a function returning
/// TODO nothing and a 0.
///
/// TODO: This constant coercion should ideally be done in the type checker.
fn type_of_binary_operation(&self, binary: &Binary, dfg: &DataFlowGraph) -> Type {
let lhs_type = dfg.type_of_value(binary.lhs);
let rhs_type = dfg.type_of_value(binary.rhs);
match (lhs_type, rhs_type) {
// Function type should not be possible, since all functions
// have been inlined.
(_, Type::Function) | (Type::Function, _) => {
unreachable!("all functions should be inlined")
}
(_, Type::Reference) | (Type::Reference, _) => {
unreachable!("References are invalid in binary operations")
}
(_, Type::Array(..)) | (Type::Array(..), _) => {
unreachable!("Arrays are invalid in binary operations")
}
(_, Type::Slice(..)) | (Type::Slice(..), _) => {
unreachable!("Arrays are invalid in binary operations")
}
// If either side is a Field constant then, we coerce into the type
// of the other operand
(Type::Numeric(NumericType::NativeField), typ)
| (typ, Type::Numeric(NumericType::NativeField)) => typ,
// If either side is a numeric type, then we expect their types to be
// the same.
(Type::Numeric(lhs_type), Type::Numeric(rhs_type)) => {
assert_eq!(
lhs_type, rhs_type,
"lhs and rhs types in {:?} are not the same",
binary
);
Type::Numeric(lhs_type)
}
}
}
/// Returns an `AcirVar` that is constrained to fit in the target type by truncating the input.
/// If the target cast is to a `NativeField`, no truncation is required so the cast becomes a
/// no-op.
fn convert_ssa_cast(
&mut self,
value_id: &ValueId,
typ: &Type,
dfg: &DataFlowGraph,
) -> Result<AcirVar, RuntimeError> {
let (variable, incoming_type) = match self.convert_value(*value_id, dfg) {
AcirValue::Var(variable, typ) => (variable, typ),
AcirValue::DynamicArray(_) | AcirValue::Array(_) => {
unreachable!("Cast is only applied to numerics")
}
};
let target_numeric = match typ {
Type::Numeric(numeric) => numeric,
_ => unreachable!("Can only cast to a numeric"),
};
match target_numeric {
NumericType::NativeField => {
// Casting into a Field as a no-op
Ok(variable)
}
NumericType::Unsigned { bit_size } => {
if incoming_type.is_signed() {
todo!("Cast from unsigned to signed")
}
let max_bit_size = incoming_type.bit_size();
if max_bit_size <= *bit_size {
// Incoming variable already fits into target bit size - this is a no-op
return Ok(variable);
}
self.acir_context.truncate_var(variable, *bit_size, max_bit_size)
}
NumericType::Signed { .. } => todo!("Cast into signed"),
}
}
/// Returns an `AcirVar`that is constrained to be result of the truncation.
fn convert_ssa_truncate(
&mut self,
value_id: ValueId,
bit_size: u32,
max_bit_size: u32,
dfg: &DataFlowGraph,
) -> Result<AcirVar, RuntimeError> {
let mut var = self.convert_numeric_value(value_id, dfg)?;
match &dfg[value_id] {
Value::Instruction { instruction, .. } => {
if matches!(
&dfg[*instruction],
Instruction::Binary(Binary { operator: BinaryOp::Sub, .. })
) {
// Subtractions must first have the integer modulus added before truncation can be
// applied. This is done in order to prevent underflow.
let integer_modulus =
self.acir_context.add_constant(FieldElement::from(2_u128.pow(bit_size)));
var = self.acir_context.add_var(var, integer_modulus)?;
}
}
Value::Param { .. } => {
// Binary operations on params may have been entirely simplified if the operation
// results in the identity of the parameter
}
_ => unreachable!(
"ICE: Truncates are only ever applied to the result of a binary op or a param"
),
};
self.acir_context.truncate_var(var, bit_size, max_bit_size)
}
/// Returns a vector of `AcirVar`s constrained to be result of the function call.
///
/// The function being called is required to be intrinsic.
fn convert_ssa_intrinsic_call(
&mut self,
intrinsic: Intrinsic,
arguments: &[ValueId],
dfg: &DataFlowGraph,
result_ids: &[ValueId],
) -> Result<Vec<AcirValue>, RuntimeError> {
match intrinsic {
Intrinsic::BlackBox(black_box) => {
let inputs = vecmap(arguments, |arg| self.convert_value(*arg, dfg));
let output_count = result_ids.iter().fold(0usize, |sum, result_id| {
sum + dfg.try_get_array_length(*result_id).unwrap_or(1)
});
let vars = self.acir_context.black_box_function(black_box, inputs, output_count)?;
Ok(Self::convert_vars_to_values(vars, dfg, result_ids))
}
Intrinsic::ToRadix(endian) => {
let field = self.convert_value(arguments[0], dfg).into_var()?;
let radix = self.convert_value(arguments[1], dfg).into_var()?;
let limb_size = self.convert_value(arguments[2], dfg).into_var()?;
let result_type = Self::array_element_type(dfg, result_ids[1]);
self.acir_context.radix_decompose(endian, field, radix, limb_size, result_type)
}
Intrinsic::ToBits(endian) => {