-
Notifications
You must be signed in to change notification settings - Fork 40
/
mod.rs
1653 lines (1567 loc) · 51.1 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
//! IR term definition
//!
//! Generally based on SMT-LIB, and its theories.
//!
//! The most important types and functions are:
//!
//! * Term structure
//! * [Term]: perfectly-shared terms. Think of them as shared pointers to
//! * [TermData]: the underlying term. An operator and some children.
//! * [Op]: an operator
//! * Term types
//! * [Sort]: the type of a term
//! * [check]: get the type of a term
//! * Term construction
//! * [term!]: from an operator and a syntactic list of children
//! * [leaf_term]: from an operator alone
//! * [term()]: from an operator and vector of children
//! * Term data-structures and algorithms
//! * [TermMap], [TermSet]: maps from and sets of terms
//! * [PostOrderIter]: an iterator over the descendents of a term. Children-first.
//! * [Computation]: a collection of variables and assertions about them
//! * [Value]: a variable-free (and evaluated) term
//!
use crate::util::once::OnceQueue;
use fxhash::{FxHashMap, FxHashSet};
use hashconsing::{HConsed, WHConsed};
use lazy_static::lazy_static;
use log::debug;
use rug::Integer;
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Display, Formatter};
use std::sync::{Arc, RwLock};
pub mod bv;
pub mod dist;
pub mod extras;
pub mod field;
pub mod ty;
pub use bv::BitVector;
pub use field::FieldElem;
pub use ty::{check, check_rec, TypeError, TypeErrorReason};
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// An operator
pub enum Op {
/// a variable
Var(String, Sort),
/// a constant
Const(Value),
/// if-then-else: ternary
Ite,
/// equality
Eq,
/// bit-vector binary operator
BvBinOp(BvBinOp),
/// bit-vector binary predicate
BvBinPred(BvBinPred),
/// bit-vector n-ary operator
BvNaryOp(BvNaryOp),
/// bit-vector unary operator
BvUnOp(BvUnOp),
/// single-bit bit-vector from a boolean
BoolToBv,
/// Get bits (high) through (low) from the underlying bit-vector.
///
/// Zero-indexed and inclusive.
BvExtract(usize, usize),
/// bit-vector concatenation. n-ary. Low-index arguements map to high-order bits
BvConcat,
/// add this many zero bits
BvUext(usize),
/// add this many sign-extend bits
BvSext(usize),
/// translate a prime-field element into a certain-width bit-vector.
PfToBv(usize),
/// boolean implication (binary)
Implies,
/// boolean n-ary operator
BoolNaryOp(BoolNaryOp),
/// boolean not
Not,
/// get this index bit from an input bit-vector
BvBit(usize),
// Ternary majority operator.
/// boolean majority (ternary)
BoolMaj,
/// floating-point binary operator
FpBinOp(FpBinOp),
/// floating-point binary predicate
FpBinPred(FpBinPred),
/// floating-point unary predicate
FpUnPred(FpBinPred),
/// floating-point unary operator
FpUnOp(FpUnOp),
//FpFma,
/// cast bit-vector to floating-point, as bits
BvToFp,
/// translate the (unsigned) bit-vector number represented by the argument to a floating-point
/// value of this width.
UbvToFp(usize),
/// translate the (signed) bit-vector number represented by the argument to a floating-point
/// value of this width.
SbvToFp(usize),
// dest width
/// translate the number represented by the argument to a floating-point value of this width.
FpToFp(usize),
/// Prime-field unary operator
PfUnOp(PfUnOp),
/// Prime-field n-ary operator
PfNaryOp(PfNaryOp),
/// Unsigned bit-vector to prime-field
///
/// Takes the modulus.
UbvToPf(Arc<Integer>),
/// Binary operator, with arguments (array, index).
///
/// Gets the value at index in array.
Select,
/// Ternary operator, with arguments (array, index, value).
///
/// Makes an array equal to `array`, but with `value` at `index`.
Store,
/// Assemble n things into a tuple
Tuple,
/// Get the n'th element of a tuple
Field(usize),
/// Update (tuple, element)
Update(usize),
}
/// Boolean AND
pub const AND: Op = Op::BoolNaryOp(BoolNaryOp::And);
/// Boolean OR
pub const OR: Op = Op::BoolNaryOp(BoolNaryOp::Or);
/// Boolean XOR
pub const XOR: Op = Op::BoolNaryOp(BoolNaryOp::Xor);
/// Boolean NOT
pub const NOT: Op = Op::Not;
/// Equal to
pub const EQ: Op = Op::Eq;
/// If-then-else
pub const ITE: Op = Op::Ite;
/// Boolean implication
pub const IMPLIES: Op = Op::Implies;
/// Bit-vector AND
pub const BV_AND: Op = Op::BvNaryOp(BvNaryOp::And);
/// Bit-vector OR
pub const BV_OR: Op = Op::BvNaryOp(BvNaryOp::Or);
/// Bit-vector XOR
pub const BV_XOR: Op = Op::BvNaryOp(BvNaryOp::Xor);
/// Bit-vector multiplication
pub const BV_MUL: Op = Op::BvNaryOp(BvNaryOp::Mul);
/// Bit-vector addition
pub const BV_ADD: Op = Op::BvNaryOp(BvNaryOp::Add);
/// Bit-vector subtraction
pub const BV_SUB: Op = Op::BvBinOp(BvBinOp::Sub);
/// Bit-vector unsigned division
pub const BV_UDIV: Op = Op::BvBinOp(BvBinOp::Udiv);
/// Bit-vector unsigned remainder
pub const BV_UREM: Op = Op::BvBinOp(BvBinOp::Urem);
/// Bit-vector shift left
pub const BV_SHL: Op = Op::BvBinOp(BvBinOp::Shl);
/// Bit-vector logical shift right
pub const BV_LSHR: Op = Op::BvBinOp(BvBinOp::Lshr);
/// Bit-vector arithmetic shift right
pub const BV_ASHR: Op = Op::BvBinOp(BvBinOp::Ashr);
/// Bit-vector negation
pub const BV_NEG: Op = Op::BvUnOp(BvUnOp::Neg);
/// Bit-vector not
pub const BV_NOT: Op = Op::BvUnOp(BvUnOp::Not);
/// Bit-vector unsigned less than
pub const BV_ULT: Op = Op::BvBinPred(BvBinPred::Ult);
/// Bit-vector unsigned greater than
pub const BV_UGT: Op = Op::BvBinPred(BvBinPred::Ugt);
/// Bit-vector unsigned less than or equal
pub const BV_ULE: Op = Op::BvBinPred(BvBinPred::Ule);
/// Bit-vector unsigned greater than or equal
pub const BV_UGE: Op = Op::BvBinPred(BvBinPred::Uge);
/// Bit-vector signed less than
pub const BV_SLT: Op = Op::BvBinPred(BvBinPred::Slt);
/// Bit-vector signed greater than
pub const BV_SGT: Op = Op::BvBinPred(BvBinPred::Sgt);
/// Bit-vector signed less than or equal
pub const BV_SLE: Op = Op::BvBinPred(BvBinPred::Sle);
/// Bit-vector signed greater than or equal
pub const BV_SGE: Op = Op::BvBinPred(BvBinPred::Sge);
/// Bit-vector of length one, from boolean
pub const BOOL_TO_BV: Op = Op::BoolToBv;
/// Bit-vector concatenation (high || low). N-ary.
pub const BV_CONCAT: Op = Op::BvConcat;
/// prime-field negation
pub const PF_NEG: Op = Op::PfUnOp(PfUnOp::Neg);
/// prime-field reciprocal
pub const PF_RECIP: Op = Op::PfUnOp(PfUnOp::Recip);
/// prime-field addition
pub const PF_ADD: Op = Op::PfNaryOp(PfNaryOp::Add);
/// prime-field multiplication
pub const PF_MUL: Op = Op::PfNaryOp(PfNaryOp::Mul);
impl Op {
/// Number of arguments for this operator. `None` if n-ary.
pub fn arity(&self) -> Option<usize> {
match self {
Op::Ite => Some(3),
Op::Eq => Some(2),
Op::Var(_, _) => Some(0),
Op::Const(_) => Some(0),
Op::BvBinOp(_) => Some(2),
Op::BvBinPred(_) => Some(2),
Op::BvNaryOp(_) => None,
Op::BvUnOp(_) => Some(1),
Op::BoolToBv => Some(1),
Op::BvExtract(_, _) => Some(1),
Op::BvConcat => None,
Op::BvUext(_) => Some(1),
Op::BvSext(_) => Some(1),
Op::PfToBv(_) => Some(1),
Op::Implies => Some(2),
Op::BoolNaryOp(_) => None,
Op::Not => Some(1),
Op::BvBit(_) => Some(1),
Op::BoolMaj => Some(3),
Op::FpBinOp(_) => Some(2),
Op::FpBinPred(_) => Some(2),
Op::FpUnPred(_) => Some(1),
Op::FpUnOp(_) => Some(1),
Op::BvToFp => Some(1),
Op::UbvToFp(_) => Some(1),
Op::SbvToFp(_) => Some(1),
Op::FpToFp(_) => Some(1),
Op::PfUnOp(_) => Some(1),
Op::PfNaryOp(_) => None,
Op::UbvToPf(_) => Some(1),
Op::Select => Some(2),
Op::Store => Some(3),
Op::Tuple => None,
Op::Field(_) => Some(1),
Op::Update(_) => Some(2),
}
}
}
impl Display for Op {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Op::Ite => write!(f, "ite"),
Op::Eq => write!(f, "="),
Op::Var(n, _) => write!(f, "{}", n),
Op::Const(c) => write!(f, "{}", c),
Op::BvBinOp(a) => write!(f, "{}", a),
Op::BvBinPred(a) => write!(f, "{}", a),
Op::BvNaryOp(a) => write!(f, "{}", a),
Op::BvUnOp(a) => write!(f, "{}", a),
Op::BoolToBv => write!(f, "bool2bv"),
Op::BvExtract(a, b) => write!(f, "extract {} {}", a, b),
Op::BvConcat => write!(f, "concat"),
Op::BvUext(a) => write!(f, "uext {}", a),
Op::BvSext(a) => write!(f, "sext {}", a),
Op::PfToBv(a) => write!(f, "pf2bv {}", a),
Op::Implies => write!(f, "=>"),
Op::BoolNaryOp(a) => write!(f, "{}", a),
Op::Not => write!(f, "not"),
Op::BvBit(a) => write!(f, "bit {}", a),
Op::BoolMaj => write!(f, "maj"),
Op::FpBinOp(a) => write!(f, "{}", a),
Op::FpBinPred(a) => write!(f, "{}", a),
Op::FpUnPred(a) => write!(f, "{}", a),
Op::FpUnOp(a) => write!(f, "{}", a),
Op::BvToFp => write!(f, "bv2fp"),
Op::UbvToFp(a) => write!(f, "ubv2fp {}", a),
Op::SbvToFp(a) => write!(f, "sbv2fp {}", a),
Op::FpToFp(a) => write!(f, "fp2fp {}", a),
Op::PfUnOp(a) => write!(f, "{}", a),
Op::PfNaryOp(a) => write!(f, "{}", a),
Op::UbvToPf(a) => write!(f, "bv2pf {}", a),
Op::Select => write!(f, "select"),
Op::Store => write!(f, "store"),
Op::Tuple => write!(f, "tuple"),
Op::Field(i) => write!(f, "field{}", i),
Op::Update(i) => write!(f, "update{}", i),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Boolean n-ary operator
pub enum BoolNaryOp {
/// Boolean AND
And,
/// Boolean XOR
Xor,
/// Boolean OR
Or,
}
impl Display for BoolNaryOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
BoolNaryOp::And => write!(f, "and"),
BoolNaryOp::Or => write!(f, "or"),
BoolNaryOp::Xor => write!(f, "xor"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Bit-vector binary operator
pub enum BvBinOp {
/// Bit-vector (-)
Sub,
/// Bit-vector (/)
Udiv,
/// Bit-vector (%)
Urem,
/// Bit-vector (<<)
Shl,
/// Bit-vector arithmetic (sign extend) (>>)
Ashr,
/// Bit-vector logical (zero fill) (>>)
Lshr,
}
impl Display for BvBinOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
BvBinOp::Sub => write!(f, "bvsub"),
BvBinOp::Udiv => write!(f, "bvudiv"),
BvBinOp::Urem => write!(f, "bvurem"),
BvBinOp::Shl => write!(f, "bvshl"),
BvBinOp::Ashr => write!(f, "bvashr"),
BvBinOp::Lshr => write!(f, "bvlshr"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Bit-vector binary predicate
pub enum BvBinPred {
// TODO: add overflow predicates.
/// Bit-vector unsigned (<)
Ult,
/// Bit-vector unsigned (>)
Ugt,
/// Bit-vector unsigned (<=)
Ule,
/// Bit-vector unsigned (>=)
Uge,
/// Bit-vector signed (<)
Slt,
/// Bit-vector signed (>)
Sgt,
/// Bit-vector signed (<=)
Sle,
/// Bit-vector signed (>=)
Sge,
}
impl Display for BvBinPred {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
BvBinPred::Ult => write!(f, "bvult"),
BvBinPred::Ugt => write!(f, "bvugt"),
BvBinPred::Ule => write!(f, "bvule"),
BvBinPred::Uge => write!(f, "bvuge"),
BvBinPred::Slt => write!(f, "bvslt"),
BvBinPred::Sgt => write!(f, "bvsgt"),
BvBinPred::Sle => write!(f, "bvsle"),
BvBinPred::Sge => write!(f, "bvsge"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Bit-vector n-ary operator
pub enum BvNaryOp {
/// Bit-vector (+)
Add,
/// Bit-vector (*)
Mul,
/// Bit-vector bitwise OR
Or,
/// Bit-vector bitwise AND
And,
/// Bit-vector bitwise XOR
Xor,
}
impl Display for BvNaryOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
BvNaryOp::Add => write!(f, "bvadd"),
BvNaryOp::Mul => write!(f, "bvmul"),
BvNaryOp::Or => write!(f, "bvor"),
BvNaryOp::And => write!(f, "bvand"),
BvNaryOp::Xor => write!(f, "bvxor"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Bit-vector unary operator
pub enum BvUnOp {
/// Bit-vector bitwise not
Not,
/// Bit-vector two's complement negation
Neg,
}
impl Display for BvUnOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
BvUnOp::Not => write!(f, "bvnot"),
BvUnOp::Neg => write!(f, "bvneg"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Floating-point binary operator
pub enum FpBinOp {
/// Floating-point (+)
Add,
/// Floating-point (*)
Mul,
/// Floating-point (-)
Sub,
/// Floating-point (/)
Div,
/// Floating-point (%)
Rem,
/// Floating-point max
Max,
/// Floating-point min
Min,
}
impl Display for FpBinOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
FpBinOp::Add => write!(f, "fpadd"),
FpBinOp::Mul => write!(f, "fpmul"),
FpBinOp::Sub => write!(f, "fpsub"),
FpBinOp::Div => write!(f, "fpdiv"),
FpBinOp::Rem => write!(f, "fprem"),
FpBinOp::Max => write!(f, "fpmax"),
FpBinOp::Min => write!(f, "fpmin"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Floating-point unary operator
pub enum FpUnOp {
/// Floating-point unary negation
Neg,
/// Floating-point absolute value
Abs,
/// Floating-point square root
Sqrt,
/// Floating-point round
Round,
}
impl Display for FpUnOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
FpUnOp::Neg => write!(f, "fpneg"),
FpUnOp::Abs => write!(f, "fpabs"),
FpUnOp::Sqrt => write!(f, "fpsqrt"),
FpUnOp::Round => write!(f, "fpround"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Floating-point binary predicate
pub enum FpBinPred {
/// Floating-point (<=)
Le,
/// Floating-point (<)
Lt,
/// Floating-point (=)
Eq,
/// Floating-point (>=)
Ge,
/// Floating-point (>)
Gt,
}
impl Display for FpBinPred {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
FpBinPred::Le => write!(f, "fple"),
FpBinPred::Lt => write!(f, "fplt"),
FpBinPred::Eq => write!(f, "fpeq"),
FpBinPred::Ge => write!(f, "fpge"),
FpBinPred::Gt => write!(f, "fpgt"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Floating-point unary predicate
pub enum FpUnPred {
/// Is this normal?
Normal,
/// Is this subnormal?
Subnormal,
/// Is this zero (or negative zero)?
Zero,
/// Is this infinite?
Infinite,
/// Is this not-a-number?
Nan,
/// Is this negative?
Negative,
/// Is this positive?
Positive,
}
impl Display for FpUnPred {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
FpUnPred::Normal => write!(f, "fpnormal"),
FpUnPred::Subnormal => write!(f, "fpsubnormal"),
FpUnPred::Zero => write!(f, "fpzero"),
FpUnPred::Infinite => write!(f, "fpinfinite"),
FpUnPred::Nan => write!(f, "fpnan"),
FpUnPred::Negative => write!(f, "fpnegative"),
FpUnPred::Positive => write!(f, "fppositive"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Finite field n-ary operator
pub enum PfNaryOp {
/// Finite field (+)
Add,
/// Finite field (*)
Mul,
}
impl Display for PfNaryOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
PfNaryOp::Add => write!(f, "+"),
PfNaryOp::Mul => write!(f, "*"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// Finite field n-ary operator
pub enum PfUnOp {
/// Finite field negation
Neg,
/// Finite field reciprocal
Recip,
}
impl Display for PfUnOp {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
PfUnOp::Neg => write!(f, "-"),
PfUnOp::Recip => write!(f, "pfrecip"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
/// A term: an operator applied to arguements
pub struct TermData {
/// the operator
pub op: Op,
/// the arguments
pub cs: Vec<Term>,
}
impl Display for TermData {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.op.arity() == Some(0) {
write!(f, "{}", self.op)
} else {
write!(f, "({}", self.op)?;
for c in &self.cs {
write!(f, " {}", c)?;
}
write!(f, ")")
}
}
}
impl Debug for TermData {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
#[derive(Clone, PartialEq, Debug, PartialOrd)]
/// An IR value (aka literal)
pub enum Value {
/// Bit-vector
BitVector(BitVector),
/// f32
F32(f32),
/// f64
F64(f64),
/// Arbitrary-precision integer
Int(Integer),
/// Finite field element
Field(FieldElem),
/// Boolean
Bool(bool),
/// Array
Array(Array),
/// Tuple
Tuple(Vec<Value>),
}
#[derive(Clone, PartialEq, Debug, PartialOrd, Hash)]
/// An IR array value.
///
/// A sized, space array.
pub struct Array {
/// Key sort
pub key_sort: Sort,
/// Default (fill) value. What is stored when a key is missing from the next member
pub default: Box<Value>,
/// Key-> Value map
pub map: BTreeMap<Value, Value>,
/// Size of array. There are this many valid keys.
pub size: usize,
}
impl Array {
/// Create a new [Array] from components
pub fn new(
key_sort: Sort,
default: Box<Value>,
map: BTreeMap<Value, Value>,
size: usize,
) -> Self {
Self {
key_sort,
default,
map,
size,
}
}
/// Create a new, default-initialized [Array]
pub fn default(key_sort: Sort, val_sort: &Sort, size: usize) -> Self {
Self::new(
key_sort,
Box::new(val_sort.default_value()),
Default::default(),
size,
)
}
/// Store
pub fn store(mut self, idx: Value, val: Value) -> Self {
self.map.insert(idx, val);
self
}
/// Select
pub fn select(&self, idx: &Value) -> Value {
self.map.get(idx).unwrap_or(&*self.default).clone()
}
}
impl Display for Value {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Value::Bool(b) => write!(f, "{}", b),
Value::F32(b) => write!(f, "{}", b),
Value::F64(b) => write!(f, "{}", b),
Value::Int(b) => write!(f, "{}", b),
Value::Field(b) => write!(f, "{}", b),
Value::BitVector(b) => write!(f, "{}", b),
Value::Tuple(fields) => {
write!(f, "(tuple")?;
for field in fields {
write!(f, " {}", field)?;
}
write!(f, ")")
}
Value::Array(a) => write!(f, "{}", a),
}
}
}
impl Display for Array {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"(map default:{} size:{} {:?})",
self.default, self.size, self.map
)
}
}
impl std::cmp::Eq for Value {}
// We walk in danger here, intentionally. One day we may fix it.
// FP is the heart of the problem.
#[allow(clippy::derive_ord_xor_partial_ord)]
impl std::cmp::Ord for Value {
fn cmp(&self, o: &Self) -> std::cmp::Ordering {
self.partial_cmp(o).expect("broken Value cmp")
}
}
// We walk in danger here, intentionally. One day we may fix it.
// FP is the heart of the problem.
#[allow(clippy::derive_hash_xor_eq)]
impl std::hash::Hash for Value {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Value::BitVector(bv) => bv.hash(state),
Value::F32(bv) => bv.to_bits().hash(state),
Value::F64(bv) => bv.to_bits().hash(state),
Value::Int(bv) => bv.hash(state),
Value::Field(bv) => bv.hash(state),
Value::Bool(bv) => bv.hash(state),
Value::Array(a) => a.hash(state),
Value::Tuple(s) => {
s.hash(state);
}
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
/// The "type" of an IR term
pub enum Sort {
/// bit-vectors of this width
BitVector(usize),
/// f32s
F32,
/// f64s
F64,
/// arbitrary-precision integer
Int,
/// prime field, integers mod this modulus
Field(Arc<Integer>),
/// boolean
Bool,
/// Array from one sort to another, of fixed size.
///
/// size presumes an order, and a zero, for the key sort.
Array(Box<Sort>, Box<Sort>, usize),
/// A tuple
Tuple(Vec<Sort>),
}
impl Sort {
#[track_caller]
/// Unwrap the bitsize of this bit-vector, panicking otherwise.
pub fn as_bv(&self) -> usize {
if let Sort::BitVector(w) = self {
*w
} else {
panic!("{} is not a bit-vector", self)
}
}
#[track_caller]
/// Unwrap the modulus of this prime field, panicking otherwise.
pub fn as_pf(&self) -> Arc<Integer> {
if let Sort::Field(w) = self {
w.clone()
} else {
panic!("{} is not a field", self)
}
}
#[track_caller]
/// Unwrap the constituent sorts of this tuple, panicking otherwise.
pub fn as_tuple(&self) -> &Vec<Sort> {
if let Sort::Tuple(w) = self {
w
} else {
panic!("{} is not a tuple", self)
}
}
/// An iterator over the elements of this sort.
/// Only defined for booleans, bit-vectors, and field elements.
#[track_caller]
pub fn elems_iter(&self) -> Box<dyn Iterator<Item = Term>> {
match self {
Sort::Bool => Box::new(
vec![false, true]
.into_iter()
.map(|b| leaf_term(Op::Const(Value::Bool(b)))),
),
Sort::BitVector(w) => {
let w = *w;
let lim = Integer::from(1) << w as u32;
Box::new(
std::iter::successors(Some(Integer::from(0)), move |p| {
let q = p.clone() + 1;
if q < lim {
Some(q)
} else {
None
}
})
.map(move |i| bv_lit(i, w)),
)
}
Sort::Field(m) => {
let m = m.clone();
let m2 = m.clone();
Box::new(
std::iter::successors(Some(Integer::from(0)), move |p| {
let q = p.clone() + 1;
if q < *m {
Some(q)
} else {
None
}
})
.map(move |i| {
leaf_term(Op::Const(Value::Field(FieldElem::new(i, m2.clone()))))
}),
)
}
_ => panic!("Cannot iterate over {}", self),
}
}
/// Compute the default term for this sort.
///
/// * booleans: false
/// * bit-vectors: zero
/// * field elements: zero
/// * floats: zero
/// * tuples/arrays: recursively default
pub fn default_term(&self) -> Term {
leaf_term(Op::Const(self.default_value()))
}
/// Compute the default value for this sort.
///
/// * booleans: false
/// * bit-vectors: zero
/// * field elements: zero
/// * floats: zero
/// * tuples/arrays: recursively default
pub fn default_value(&self) -> Value {
match self {
Sort::Bool => Value::Bool(false),
Sort::BitVector(w) => Value::BitVector(BitVector::new(0.into(), *w)),
Sort::Field(m) => Value::Field(FieldElem::new(Integer::from(0), m.clone())),
Sort::Int => Value::Int(0.into()),
Sort::F32 => Value::F32(0.0f32),
Sort::F64 => Value::F64(0.0),
Sort::Tuple(t) => Value::Tuple(t.iter().map(Sort::default_value).collect()),
Sort::Array(k, v, n) => Value::Array(Array::default((**k).clone(), v, *n)),
}
}
}
impl Display for Sort {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Sort::Bool => write!(f, "bool"),
Sort::BitVector(n) => write!(f, "(bv {})", n),
Sort::Int => write!(f, "int"),
Sort::F32 => write!(f, "f32"),
Sort::F64 => write!(f, "f64"),
Sort::Field(i) => write!(f, "(mod {})", i),
Sort::Array(k, v, n) => write!(f, "(array {} {} {})", k, v, n),
Sort::Tuple(fields) => {
write!(f, "(tuple")?;
for field in fields {
write!(f, " {}", field)?;
}
write!(f, ")")
}
}
}
}
/// A (perfectly shared) pointer to a term
pub type Term = HConsed<TermData>;
// "Temporary" terms.
/// A weak (perfectly shared) pointer to a term
pub type TTerm = WHConsed<TermData>;
struct TermTable {
map: FxHashMap<TermData, TTerm>,
count: u64,
}
impl TermTable {
fn get(&self, key: &TermData) -> Option<Term> {
if let Some(old) = self.map.get(key) {
old.to_hconsed()
} else {
None
}
}
fn mk(&mut self, elm: TermData) -> Term {
// If the element is known and upgradable return it.
if let Some(hconsed) = self.get(&elm) {
//debug_assert!(*hconsed.elm == elm);
return hconsed;
}
// Otherwise build hconsed version.
let hconsed = HConsed {
elm: Arc::new(elm.clone()),
uid: self.count,
};
// Increment uid count.
self.count += 1;
// ...add weak version to the table...
self.map.insert(elm, hconsed.to_weak());
// ...and return consed version.
hconsed
}
fn collect(&mut self) {
let old_size = self.map.len();
let mut to_check: OnceQueue<Term> = OnceQueue::new();
self.map.retain(|key, val| {
if val.elm.upgrade().is_some() {
true
} else {
to_check.extend(key.cs.iter().cloned());
false
}
});
while let Some(t) = to_check.pop() {
let data: TermData = (*t).clone();
std::mem::drop(t);
if let std::collections::hash_map::Entry::Occupied(e) = self.map.entry(data) {
if e.get().elm.upgrade().is_none() {
let (key, _val) = e.remove_entry();
to_check.extend(key.cs.iter().cloned());
}
}
}
let new_size = self.map.len();
for (k, v) in self.map.iter() {
assert!(v.elm.upgrade().is_some(), "Can not upgrade: {:?}", k)
}
debug!(target: "ir::term::gc", "{} of {} terms collected", old_size - new_size, old_size);
}
}
lazy_static! {
static ref TERMS: RwLock<TermTable> = RwLock::new(TermTable {
map: FxHashMap::default(),
count: 0,
});
}
fn mk(elm: TermData) -> Term {
let mut slf = TERMS.write().unwrap();
slf.mk(elm)
}
/// Scans the term database and the type database and removes dead terms and types.
pub fn garbage_collect() {
collect_terms();
collect_types();
}
fn collect_terms() {
TERMS.write().unwrap().collect();
}
fn collect_types() {
let mut ty_map = ty::TERM_TYPES.write().unwrap();
let old_size = ty_map.len();
ty_map.retain(|term, _| term.to_hconsed().is_some());
let new_size = ty_map.len();
debug!(target: "ir::term::gc", "{} of {} types collected", old_size - new_size, old_size);
}
impl TermData {
/// Get the underlying boolean constant, if possible.
pub fn as_bool_opt(&self) -> Option<bool> {
if let Op::Const(Value::Bool(b)) = &self.op {
Some(*b)
} else {
None
}
}
/// Get the underlying bit-vector constant, if possible.
pub fn as_bv_opt(&self) -> Option<&BitVector> {
if let Op::Const(Value::BitVector(b)) = &self.op {
Some(b)