-
Notifications
You must be signed in to change notification settings - Fork 295
/
Copy pathmod.rs
3639 lines (3268 loc) · 156 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.
use fxhash::FxHashMap as HashMap;
use im::Vector;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Debug;
use acvm::acir::{
circuit::{
brillig::{BrilligBytecode, BrilligFunctionId},
opcodes::{AcirFunctionId, BlockType},
AssertionPayload, ErrorSelector, ExpressionWidth, OpcodeLocation,
},
native_types::Witness,
BlackBoxFunc,
};
use acvm::{acir::circuit::opcodes::BlockId, acir::AcirField, FieldElement};
use bn254_blackbox_solver::Bn254BlackBoxSolver;
use iter_extended::{try_vecmap, vecmap};
use noirc_frontend::monomorphization::ast::InlineType;
mod acir_variable;
mod big_int;
mod brillig_directive;
mod generated_acir;
use crate::brillig::brillig_gen::gen_brillig_for;
use crate::brillig::{
brillig_gen::brillig_fn::FunctionContext as BrilligFunctionContext,
brillig_ir::artifact::{BrilligParameter, GeneratedBrillig},
Brillig,
};
use crate::errors::{InternalError, InternalWarning, RuntimeError, SsaReport};
use crate::ssa::{
function_builder::data_bus::DataBus,
ir::{
dfg::{CallStack, DataFlowGraph},
function::{Function, FunctionId, RuntimeType},
instruction::{
Binary, BinaryOp, ConstrainError, Instruction, InstructionId, Intrinsic,
TerminatorInstruction,
},
map::Id,
printer::try_to_extract_string_from_error_payload,
types::{NumericType, Type},
value::{Value, ValueId},
},
ssa_gen::Ssa,
};
use acir_variable::{AcirContext, AcirType, AcirVar};
use generated_acir::BrilligStdlibFunc;
pub(crate) use generated_acir::GeneratedAcir;
use noirc_frontend::hir_def::types::Type as HirType;
#[derive(Default)]
struct SharedContext<F> {
/// Final list of Brillig functions which will be part of the final program
/// This is shared across `Context` structs as we want one list of Brillig
/// functions across all ACIR artifacts
generated_brillig: Vec<GeneratedBrillig<F>>,
/// Maps SSA function index -> Final generated Brillig artifact index.
/// There can be Brillig functions specified in SSA which do not act as
/// entry points in ACIR (e.g. only called by other Brillig functions)
/// This mapping is necessary to use the correct function pointer for a Brillig call.
/// This uses the brillig parameters in the map since using slices with different lengths
/// needs to create different brillig entrypoints
brillig_generated_func_pointers:
BTreeMap<(FunctionId, Vec<BrilligParameter>), BrilligFunctionId>,
/// Maps a Brillig std lib function (a handwritten primitive such as for inversion) -> Final generated Brillig artifact index.
/// A separate mapping from normal Brillig calls is necessary as these methods do not have an associated function id from SSA.
brillig_stdlib_func_pointer: HashMap<BrilligStdlibFunc, BrilligFunctionId>,
/// Keeps track of Brillig std lib calls per function that need to still be resolved
/// with the correct function pointer from the `brillig_stdlib_func_pointer` map.
brillig_stdlib_calls_to_resolve: HashMap<FunctionId, Vec<(OpcodeLocation, BrilligFunctionId)>>,
}
impl<F: AcirField> SharedContext<F> {
fn generated_brillig_pointer(
&self,
func_id: FunctionId,
arguments: Vec<BrilligParameter>,
) -> Option<&BrilligFunctionId> {
self.brillig_generated_func_pointers.get(&(func_id, arguments))
}
fn generated_brillig(&self, func_pointer: usize) -> &GeneratedBrillig<F> {
&self.generated_brillig[func_pointer]
}
fn insert_generated_brillig(
&mut self,
func_id: FunctionId,
arguments: Vec<BrilligParameter>,
generated_pointer: BrilligFunctionId,
code: GeneratedBrillig<F>,
) {
self.brillig_generated_func_pointers.insert((func_id, arguments), generated_pointer);
self.generated_brillig.push(code);
}
fn new_generated_pointer(&self) -> BrilligFunctionId {
BrilligFunctionId(self.generated_brillig.len() as u32)
}
fn generate_brillig_calls_to_resolve(
&mut self,
brillig_stdlib_func: &BrilligStdlibFunc,
func_id: FunctionId,
opcode_location: OpcodeLocation,
) {
if let Some(generated_pointer) =
self.brillig_stdlib_func_pointer.get(brillig_stdlib_func).copied()
{
self.add_call_to_resolve(func_id, (opcode_location, generated_pointer));
} else {
let code = brillig_stdlib_func.get_generated_brillig();
let generated_pointer = self.new_generated_pointer();
self.insert_generated_brillig_stdlib(
*brillig_stdlib_func,
generated_pointer,
func_id,
opcode_location,
code,
);
}
}
/// Insert a newly generated Brillig stdlib function
fn insert_generated_brillig_stdlib(
&mut self,
brillig_stdlib_func: BrilligStdlibFunc,
generated_pointer: BrilligFunctionId,
func_id: FunctionId,
opcode_location: OpcodeLocation,
code: GeneratedBrillig<F>,
) {
self.brillig_stdlib_func_pointer.insert(brillig_stdlib_func, generated_pointer);
self.add_call_to_resolve(func_id, (opcode_location, generated_pointer));
self.generated_brillig.push(code);
}
fn add_call_to_resolve(
&mut self,
func_id: FunctionId,
call_to_resolve: (OpcodeLocation, BrilligFunctionId),
) {
self.brillig_stdlib_calls_to_resolve.entry(func_id).or_default().push(call_to_resolve);
}
}
/// Context struct for the acir generation pass.
/// May be similar to the Evaluator struct in the current SSA IR.
struct Context<'a> {
/// 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<FieldElement, Bn254BlackBoxSolver>,
/// 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,
/// Contains state that is generated and also used across ACIR functions
shared_context: &'a mut SharedContext<FieldElement>,
}
#[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,
/// An ACIR dynamic array is a flat structure, so we use
/// the inner structure of an `AcirType::NumericType` directly.
/// Some usages of ACIR arrays (e.g. black box functions) require the bit size
/// of every value to be known, thus we store the types as part of the dynamic
/// array definition.
///
/// A dynamic non-homogenous array can potentially have values of differing types.
/// Thus, we store a vector of types rather than a single type, as a dynamic non-homogenous array
/// is still represented in ACIR by a single `AcirDynamicArray` structure.
///
/// The length of the value types vector must match the `len` field in this structure.
value_types: Vec<NumericType>,
/// 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(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"),
}
}
fn flat_numeric_types(self) -> Vec<NumericType> {
match self {
AcirValue::Array(_) => {
self.flatten().into_iter().map(|(_, typ)| typ.to_numeric_type()).collect()
}
AcirValue::DynamicArray(AcirDynamicArray { value_types, .. }) => value_types,
_ => unreachable!("An AcirValue::Var cannot be used as an array value"),
}
}
}
pub(crate) type Artifacts = (
Vec<GeneratedAcir<FieldElement>>,
Vec<BrilligBytecode<FieldElement>>,
Vec<String>,
BTreeMap<ErrorSelector, HirType>,
);
impl Ssa {
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) fn into_acir(
self,
brillig: &Brillig,
expression_width: ExpressionWidth,
) -> Result<Artifacts, RuntimeError> {
let mut acirs = Vec::new();
// TODO: can we parallelize this?
let mut shared_context = SharedContext::default();
for function in self.functions.values() {
let context = Context::new(&mut shared_context, expression_width);
if let Some(mut generated_acir) =
context.convert_ssa_function(&self, function, brillig)?
{
// We want to be able to insert Brillig stdlib functions anywhere during the ACIR generation process (e.g. such as on the `GeneratedAcir`).
// As we don't want a reference to the `SharedContext` on the generated ACIR itself,
// we instead store the opcode location at which a Brillig call to a std lib function occurred.
// We then defer resolving the function IDs of those Brillig functions to when we have generated Brillig
// for all normal Brillig calls.
for (opcode_location, brillig_stdlib_func) in
&generated_acir.brillig_stdlib_func_locations
{
shared_context.generate_brillig_calls_to_resolve(
brillig_stdlib_func,
function.id(),
*opcode_location,
);
}
// Fetch the Brillig stdlib calls to resolve for this function
if let Some(calls_to_resolve) =
shared_context.brillig_stdlib_calls_to_resolve.get(&function.id())
{
// Resolve the Brillig stdlib calls
// We have to do a separate loop as the generated ACIR cannot be borrowed as mutable after an immutable borrow
for (opcode_location, brillig_function_pointer) in calls_to_resolve {
generated_acir.resolve_brillig_stdlib_call(
*opcode_location,
*brillig_function_pointer,
);
}
}
generated_acir.name = function.name().to_owned();
acirs.push(generated_acir);
}
}
let (brillig_bytecode, brillig_names) = shared_context
.generated_brillig
.into_iter()
.map(|brillig| (BrilligBytecode { bytecode: brillig.byte_code }, brillig.name))
.unzip();
Ok((acirs, brillig_bytecode, brillig_names, self.error_selector_to_type))
}
}
impl<'a> Context<'a> {
fn new(
shared_context: &'a mut SharedContext<FieldElement>,
expression_width: ExpressionWidth,
) -> Context<'a> {
let mut acir_context = AcirContext::default();
acir_context.set_expression_width(expression_width);
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(),
shared_context,
}
}
fn convert_ssa_function(
self,
ssa: &Ssa,
function: &Function,
brillig: &Brillig,
) -> Result<Option<GeneratedAcir<FieldElement>>, RuntimeError> {
match function.runtime() {
RuntimeType::Acir(inline_type) => {
match inline_type {
InlineType::Inline | InlineType::InlineAlways => {
if function.id() != ssa.main_id {
panic!("ACIR function should have been inlined earlier if not marked otherwise");
}
}
InlineType::NoPredicates => {
panic!("All ACIR functions marked with #[no_predicates] should be inlined before ACIR gen. This is an SSA exclusive codegen attribute");
}
InlineType::Fold => {}
}
// We only want to convert entry point functions. This being `main` and those marked with `InlineType::Fold`
Ok(Some(self.convert_acir_main(function, ssa, brillig)?))
}
RuntimeType::Brillig(_) => {
if function.id() == ssa.main_id {
Ok(Some(self.convert_brillig_main(function, brillig)?))
} else {
Ok(None)
}
}
}
}
fn convert_acir_main(
mut self,
main_func: &Function,
ssa: &Ssa,
brillig: &Brillig,
) -> Result<GeneratedAcir<FieldElement>, 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)?;
let num_return_witnesses =
self.get_num_return_witnesses(entry_block.unwrap_terminator(), dfg);
// Create a witness for each return witness we have to guarantee that the return witnesses match the standard
// layout for serializing those types as if they were being passed as inputs.
//
// This is required for recursion as otherwise in situations where we cannot make use of the program's ABI
// (e.g. for `std::verify_proof` or the solidity verifier), we need extra knowledge about the program we're
// working with rather than following the standard ABI encoding rules.
//
// We allocate these witnesses now before performing ACIR gen for the rest of the program as the location of
// the function's return values can then be determined through knowledge of its ABI alone.
let return_witness_vars =
vecmap(0..num_return_witnesses, |_| self.acir_context.add_variable());
let return_witnesses = vecmap(&return_witness_vars, |return_var| {
let expr = self.acir_context.var_to_expression(*return_var).unwrap();
expr.to_witness().expect("return vars should be witnesses")
});
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)?);
}
let (return_vars, return_warnings) =
self.convert_ssa_return(entry_block.unwrap_terminator(), dfg)?;
// TODO: This is a naive method of assigning the return values to their witnesses as
// we're likely to get a number of constraints which are asserting one witness to be equal to another.
//
// We should search through the program and relabel these witnesses so we can remove this constraint.
for (witness_var, return_var) in return_witness_vars.iter().zip(return_vars) {
self.acir_context.assert_eq_var(*witness_var, return_var, None)?;
}
self.initialize_databus(&return_witnesses, dfg)?;
warnings.extend(return_warnings);
warnings.extend(self.acir_context.warnings.clone());
// Add the warnings from the alter Ssa passes
Ok(self.acir_context.finish(
input_witness,
// Don't embed databus return witnesses into the circuit.
if self.data_bus.return_data.is_some() { Vec::new() } else { return_witnesses },
warnings,
))
}
fn initialize_databus(
&mut self,
witnesses: &Vec<Witness>,
dfg: &DataFlowGraph,
) -> Result<(), RuntimeError> {
// Initialize return_data using provided witnesses
if let Some(return_data) = self.data_bus.return_data {
let block_id = self.block_id(&return_data);
let already_initialized = self.initialized_arrays.contains(&block_id);
if !already_initialized {
// We hijack ensure_array_is_initialized() because we want the return data to use the return value witnesses,
// but the databus contains the computed values instead, that have just been asserted to be equal to the return values.
// We do not use initialize_array either for the case where a constant value is returned.
// In that case, the constant value has already been assigned a witness and the returned acir vars will be
// converted to it, instead of the corresponding return value witness.
self.acir_context.initialize_return_data(block_id, witnesses.to_owned());
}
}
// Initialize call_data
let call_data_arrays: Vec<ValueId> =
self.data_bus.call_data.iter().map(|cd| cd.array_id).collect();
for call_data_array in call_data_arrays {
self.ensure_array_is_initialized(call_data_array, dfg)?;
}
Ok(())
}
fn convert_brillig_main(
mut self,
main_func: &Function,
brillig: &Brillig,
) -> Result<GeneratedAcir<FieldElement>, 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 arguments = self.gen_brillig_parameters(dfg[main_func.entry_block()].parameters(), dfg);
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 = gen_brillig_for(main_func, arguments.clone(), 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_call(
self.current_side_effects_enabled_var,
&code,
inputs,
outputs,
false,
true,
// We are guaranteed to have a Brillig function pointer of `0` as main itself is marked as unconstrained
BrilligFunctionId(0),
None,
)?;
self.shared_context.insert_generated_brillig(
main_func.id(),
arguments,
BrilligFunctionId(0),
code,
);
let return_witnesses: Vec<Witness> = output_values
.iter()
.flat_map(|value| value.clone().flatten())
.map(|(value, _)| self.acir_context.var_to_witness(value))
.collect::<Result<_, _>>()?;
let generated_acir = self.acir_context.finish(witness_inputs, return_witnesses, Vec::new());
assert_eq!(
generated_acir.opcodes().len(),
1,
"Unconstrained programs should only generate a single opcode but multiple were emitted"
);
Ok(generated_acir)
}
/// 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() as usize
} 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,
) -> 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_payload = if let Some(error) = assert_message {
match error {
ConstrainError::StaticString(string) => Some(
self.acir_context.generate_assertion_message_payload(string.clone()),
),
ConstrainError::Dynamic(error_selector, is_string_type, values) => {
if let Some(constant_string) = try_to_extract_string_from_error_payload(
*is_string_type,
values,
dfg,
) {
Some(
self.acir_context
.generate_assertion_message_payload(constant_string),
)
} else {
let acir_vars: Vec<_> = values
.iter()
.map(|value| self.convert_value(*value, dfg))
.collect();
let expressions_or_memory =
self.acir_context.vars_to_expressions_or_memory(&acir_vars)?;
Some(AssertionPayload {
error_selector: error_selector.as_u64(),
payload: expressions_or_memory,
})
}
}
}
} else {
None
};
self.acir_context.assert_eq_var(lhs, rhs, assert_payload)?;
}
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::EnableSideEffectsIf { 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)?;
}
Instruction::Allocate => {
return Err(RuntimeError::UnknownReference {
call_stack: self.acir_context.get_call_stack().clone(),
});
}
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 { .. } | Instruction::DecrementRc { .. } => {
// 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(),
)?;
}
Instruction::IfElse { .. } => {
unreachable!("IfElse instruction remaining in acir-gen")
}
Instruction::MakeArray { elements, typ: _ } => {
let elements = elements.iter().map(|element| self.convert_value(*element, dfg));
let value = AcirValue::Array(elements.collect());
let result = dfg.instruction_results(instruction_id)[0];
self.ssa_values.insert(result, value);
}
}
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(inline_type) => {
assert!(!matches!(inline_type, InlineType::Inline), "ICE: Got an ACIR function named {} that should have already been inlined", func.name());
let inputs = vecmap(arguments, |arg| self.convert_value(*arg, dfg));
let output_count = result_ids
.iter()
.map(|result_id| {
dfg.type_of_value(*result_id).flattened_size() as usize
})
.sum();
let Some(acir_function_id) =
ssa.entry_point_to_generated_index.get(id)
else {
unreachable!("Expected an associated final index for call to acir function {id} with args {arguments:?}");
};
let output_vars = self.acir_context.call_acir_function(
AcirFunctionId(*acir_function_id),
inputs,
output_count,
self.current_side_effects_enabled_var,
)?;
let output_values =
self.convert_vars_to_values(output_vars, dfg, result_ids);
self.handle_ssa_call_outputs(result_ids, output_values, dfg)?;
}
RuntimeType::Brillig(_) => {
// Check that we are not attempting to return a slice from
// an unconstrained runtime to a constrained runtime
for result_id in result_ids {
if dfg.type_of_value(*result_id).contains_slice_element() {
return Err(
RuntimeError::UnconstrainedSliceReturnToConstrained {
call_stack: self.acir_context.get_call_stack(),
},
);
}
}
let inputs = vecmap(arguments, |arg| self.convert_value(*arg, dfg));
let arguments = self.gen_brillig_parameters(arguments, dfg);
let outputs: Vec<AcirType> = vecmap(result_ids, |result_id| {
dfg.type_of_value(*result_id).into()
});
// Check whether we have already generated Brillig for this function
// If we have, re-use the generated code to set-up the Brillig call.
let output_values = if let Some(generated_pointer) = self
.shared_context
.generated_brillig_pointer(*id, arguments.clone())
{
let code = self
.shared_context
.generated_brillig(generated_pointer.as_usize());
self.acir_context.brillig_call(
self.current_side_effects_enabled_var,
code,
inputs,
outputs,
true,
false,
*generated_pointer,
None,
)?
} else {
let code = gen_brillig_for(func, arguments.clone(), brillig)?;
let generated_pointer =
self.shared_context.new_generated_pointer();
let output_values = self.acir_context.brillig_call(
self.current_side_effects_enabled_var,
&code,
inputs,
outputs,
true,
false,
generated_pointer,
None,
)?;
self.shared_context.insert_generated_brillig(
*id,
arguments,
generated_pointer,
code,
);
output_values
};
// 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");
self.handle_ssa_call_outputs(result_ids, output_values, dfg)?;
}
}
}
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());
self.handle_ssa_call_outputs(result_ids, outputs, dfg)?;
}
Value::ForeignFunction(_) => {
// TODO: Remove this once elaborator is default frontend. This is now caught by a lint inside the frontend.
return Err(RuntimeError::UnconstrainedOracleReturnToConstrained {
call_stack: self.acir_context.get_call_stack(),
});
}
_ => unreachable!("expected calling a function but got {function_value:?}"),
}
}
_ => unreachable!("expected calling a call instruction"),
}
Ok(warnings)
}
fn handle_ssa_call_outputs(
&mut self,
result_ids: &[ValueId],
output_values: Vec<AcirValue>,
dfg: &DataFlowGraph,
) -> Result<(), RuntimeError> {
for (result_id, output) in result_ids.iter().zip(output_values) {
if let AcirValue::Array(_) = &output {
let array_id = dfg.resolve(*result_id);
let block_id = self.block_id(&array_id);
let array_typ = dfg.type_of_value(array_id);
let len = if matches!(array_typ, Type::Array(_, _)) {
array_typ.flattened_size() as usize
} else {
Self::flattened_value_size(&output)
};
self.initialize_array(block_id, len, Some(output.clone()))?;
}
// Do nothing for AcirValue::DynamicArray and AcirValue::Var
// A dynamic array returned from a function call should already be initialized
// and a single variable does not require any extra initialization.
self.ssa_values.insert(*result_id, output);
}
Ok(())
}
fn gen_brillig_parameters(
&self,
values: &[ValueId],
dfg: &DataFlowGraph,
) -> Vec<BrilligParameter> {
values
.iter()
.map(|&value_id| {
let typ = dfg.type_of_value(value_id);
if let Type::Slice(item_types) = typ {
let len = match self
.ssa_values
.get(&value_id)
.expect("ICE: Unknown slice input to brillig")
{
AcirValue::DynamicArray(AcirDynamicArray { len, .. }) => *len,
AcirValue::Array(array) => array.len(),
_ => unreachable!("ICE: Slice value is not an array"),
};
BrilligParameter::Slice(
item_types
.iter()
.map(BrilligFunctionContext::ssa_type_to_parameter)
.collect(),
len / item_types.len(),
)
} else {
BrilligFunctionContext::ssa_type_to_parameter(&typ)
}
})
.collect()
}