1use std::collections::{HashMap, HashSet};
2
3use super::writes::{count_writes_of, rebound_names, CalleeGlobals, WriteSet};
4use crate::arena::Arena;
5use crate::ast::stmt::{BinaryOpKind, Expr, Literal, MatchArm, Pattern, Stmt};
6use crate::intern::Symbol;
7
8fn elem_type_enabled() -> bool {
18 crate::optimize::active_config().is_on(crate::optimization::Opt::ElemType)
19}
20
21#[derive(Clone, Debug, PartialEq)]
22enum Bound {
23 NegInf,
24 Finite(i64),
25 PosInf,
26}
27
28impl Bound {
29 fn add(&self, other: &Bound) -> Bound {
30 match (self, other) {
31 (Bound::Finite(a), Bound::Finite(b)) => match a.checked_add(*b) {
32 Some(r) => Bound::Finite(r),
33 None => {
34 if *a > 0 {
35 Bound::PosInf
36 } else {
37 Bound::NegInf
38 }
39 }
40 },
41 (Bound::PosInf, Bound::NegInf) | (Bound::NegInf, Bound::PosInf) => Bound::NegInf,
42 (Bound::PosInf, _) | (_, Bound::PosInf) => Bound::PosInf,
43 (Bound::NegInf, _) | (_, Bound::NegInf) => Bound::NegInf,
44 }
45 }
46
47 fn sub(&self, other: &Bound) -> Bound {
48 match (self, other) {
49 (Bound::Finite(a), Bound::Finite(b)) => match a.checked_sub(*b) {
50 Some(r) => Bound::Finite(r),
51 None => {
52 if *a > 0 {
53 Bound::PosInf
54 } else {
55 Bound::NegInf
56 }
57 }
58 },
59 (Bound::PosInf, Bound::PosInf) | (Bound::NegInf, Bound::NegInf) => Bound::NegInf,
60 (Bound::PosInf, _) | (_, Bound::NegInf) => Bound::PosInf,
61 (Bound::NegInf, _) | (_, Bound::PosInf) => Bound::NegInf,
62 }
63 }
64
65 fn mul(&self, other: &Bound) -> Bound {
66 if matches!(self, Bound::Finite(0)) || matches!(other, Bound::Finite(0)) {
69 return Bound::Finite(0);
70 }
71 if let (Bound::Finite(a), Bound::Finite(b)) = (self, other) {
72 return match a.checked_mul(*b) {
73 Some(r) => Bound::Finite(r),
74 None => {
75 if (*a > 0) == (*b > 0) {
76 Bound::PosInf
77 } else {
78 Bound::NegInf
79 }
80 }
81 };
82 }
83 let positive = |x: &Bound| match x {
86 Bound::PosInf => true,
87 Bound::NegInf => false,
88 Bound::Finite(v) => *v > 0,
89 };
90 if positive(self) == positive(other) {
91 Bound::PosInf
92 } else {
93 Bound::NegInf
94 }
95 }
96
97 fn div_by(&self, k: i64) -> Bound {
101 match self {
102 Bound::Finite(a) => Bound::Finite(a / k),
103 Bound::NegInf => {
104 if k > 0 {
105 Bound::NegInf
106 } else {
107 Bound::PosInf
108 }
109 }
110 Bound::PosInf => {
111 if k > 0 {
112 Bound::PosInf
113 } else {
114 Bound::NegInf
115 }
116 }
117 }
118 }
119
120 fn shr_by(&self, k: u32) -> Bound {
124 match self {
125 Bound::Finite(a) => Bound::Finite(a >> k),
126 Bound::NegInf => Bound::NegInf,
127 Bound::PosInf => Bound::PosInf,
128 }
129 }
130
131 fn cmp_bound(&self, other: &Self) -> std::cmp::Ordering {
132 match (self, other) {
133 (Bound::NegInf, Bound::NegInf) => std::cmp::Ordering::Equal,
134 (Bound::NegInf, _) => std::cmp::Ordering::Less,
135 (_, Bound::NegInf) => std::cmp::Ordering::Greater,
136 (Bound::PosInf, Bound::PosInf) => std::cmp::Ordering::Equal,
137 (Bound::PosInf, _) => std::cmp::Ordering::Greater,
138 (_, Bound::PosInf) => std::cmp::Ordering::Less,
139 (Bound::Finite(a), Bound::Finite(b)) => a.cmp(b),
140 }
141 }
142
143 fn decided(&self, other: &Self) -> Option<std::cmp::Ordering> {
147 match (self, other) {
148 (Bound::PosInf, Bound::PosInf) | (Bound::NegInf, Bound::NegInf) => None,
149 _ => Some(self.cmp_bound(other)),
150 }
151 }
152
153 fn min_bound(a: &Bound, b: &Bound) -> Bound {
154 if a.cmp_bound(b) == std::cmp::Ordering::Less {
155 a.clone()
156 } else {
157 b.clone()
158 }
159 }
160
161 fn max_bound(a: &Bound, b: &Bound) -> Bound {
162 if a.cmp_bound(b) == std::cmp::Ordering::Greater {
163 a.clone()
164 } else {
165 b.clone()
166 }
167 }
168}
169
170trait AbstractDomain: Clone {
178 fn top() -> Self;
180 fn bottom() -> Self;
182 fn join(&self, other: &Self) -> Self;
184 fn meet(&self, other: &Self) -> Self;
186 fn widen(&self, other: &Self) -> Self;
188 fn leq(&self, other: &Self) -> bool;
190}
191
192#[derive(Clone, Debug)]
193struct Interval {
194 lo: Bound,
195 hi: Bound,
196}
197
198impl Interval {
199 fn exact(n: i64) -> Self {
200 Interval {
201 lo: Bound::Finite(n),
202 hi: Bound::Finite(n),
203 }
204 }
205
206 fn top() -> Self {
207 Interval {
208 lo: Bound::NegInf,
209 hi: Bound::PosInf,
210 }
211 }
212
213 fn non_negative() -> Self {
214 Interval {
215 lo: Bound::Finite(0),
216 hi: Bound::PosInf,
217 }
218 }
219
220 fn is_exact(&self) -> Option<i64> {
221 if let (Bound::Finite(a), Bound::Finite(b)) = (&self.lo, &self.hi) {
222 if a == b {
223 return Some(*a);
224 }
225 }
226 None
227 }
228
229 fn bottom() -> Self {
232 Interval {
233 lo: Bound::PosInf,
234 hi: Bound::NegInf,
235 }
236 }
237
238 fn is_bottom(&self) -> bool {
239 self.lo.cmp_bound(&self.hi) == std::cmp::Ordering::Greater
240 }
241
242 fn join(&self, other: &Interval) -> Interval {
243 if self.is_bottom() {
244 return other.clone();
245 }
246 if other.is_bottom() {
247 return self.clone();
248 }
249 Interval {
250 lo: Bound::min_bound(&self.lo, &other.lo),
251 hi: Bound::max_bound(&self.hi, &other.hi),
252 }
253 }
254
255 fn meet(&self, other: &Interval) -> Interval {
257 if self.is_bottom() || other.is_bottom() {
258 return Interval::bottom();
259 }
260 let r = Interval {
261 lo: Bound::max_bound(&self.lo, &other.lo),
262 hi: Bound::min_bound(&self.hi, &other.hi),
263 };
264 if r.is_bottom() {
265 Interval::bottom()
266 } else {
267 r
268 }
269 }
270
271 fn widen(&self, other: &Interval) -> Interval {
274 if self.is_bottom() {
275 return other.clone();
276 }
277 if other.is_bottom() {
278 return self.clone();
279 }
280 const WIDENING_THRESHOLDS: &[i64] = &[-1000, -100, -10, -1, 0, 1, 10, 100, 1000];
285 let lo = if other.lo.cmp_bound(&self.lo) == std::cmp::Ordering::Less {
286 match other.lo {
287 Bound::Finite(v) => WIDENING_THRESHOLDS
288 .iter()
289 .rev()
290 .find(|&&t| t <= v)
291 .map(|&t| Bound::Finite(t))
292 .unwrap_or(Bound::NegInf),
293 _ => Bound::NegInf,
294 }
295 } else {
296 self.lo.clone()
297 };
298 let hi = if other.hi.cmp_bound(&self.hi) == std::cmp::Ordering::Greater {
299 match other.hi {
300 Bound::Finite(v) => WIDENING_THRESHOLDS
301 .iter()
302 .find(|&&t| t >= v)
303 .map(|&t| Bound::Finite(t))
304 .unwrap_or(Bound::PosInf),
305 _ => Bound::PosInf,
306 }
307 } else {
308 self.hi.clone()
309 };
310 Interval { lo, hi }
311 }
312
313 fn narrow(&self, other: &Interval) -> Interval {
323 if self.is_bottom() || other.is_bottom() {
324 return self.clone();
325 }
326 let lo = match self.lo {
327 Bound::NegInf => other.lo.clone(),
328 _ => self.lo.clone(),
329 };
330 let hi = match self.hi {
331 Bound::PosInf => other.hi.clone(),
332 _ => self.hi.clone(),
333 };
334 Interval { lo, hi }
335 }
336
337 fn leq(&self, other: &Interval) -> bool {
339 if self.is_bottom() {
340 return true;
341 }
342 if other.is_bottom() {
343 return false;
344 }
345 other.lo.cmp_bound(&self.lo) != std::cmp::Ordering::Greater
346 && self.hi.cmp_bound(&other.hi) != std::cmp::Ordering::Greater
347 }
348
349 fn add(&self, other: &Interval) -> Interval {
350 Interval {
351 lo: self.lo.add(&other.lo),
352 hi: self.hi.add(&other.hi),
353 }
354 }
355
356 fn sub(&self, other: &Interval) -> Interval {
357 Interval {
358 lo: self.lo.sub(&other.hi),
359 hi: self.hi.sub(&other.lo),
360 }
361 }
362
363 fn mul(&self, other: &Interval) -> Interval {
364 let corners = [
369 self.lo.mul(&other.lo),
370 self.lo.mul(&other.hi),
371 self.hi.mul(&other.lo),
372 self.hi.mul(&other.hi),
373 ];
374 let mut lo = corners[0].clone();
375 let mut hi = corners[0].clone();
376 for c in &corners[1..] {
377 lo = Bound::min_bound(&lo, c);
378 hi = Bound::max_bound(&hi, c);
379 }
380 Interval { lo, hi }
381 }
382
383 fn div(&self, other: &Interval) -> Interval {
384 if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
385 if b != 0 {
386 return Interval::exact(a.wrapping_div(b));
389 }
390 }
391 if let Some(k) = other.is_exact() {
397 if k > 0 {
398 return Interval {
399 lo: self.lo.div_by(k),
400 hi: self.hi.div_by(k),
401 };
402 } else if k < 0 {
403 return Interval {
404 lo: self.hi.div_by(k),
405 hi: self.lo.div_by(k),
406 };
407 }
408 }
409 Interval::top()
410 }
411
412 fn modulo(&self, other: &Interval) -> Interval {
413 if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
414 if b != 0 {
415 return Interval::exact(a.wrapping_rem(b));
418 }
419 }
420 if let Some(k) = other.is_exact() {
427 if k != 0 {
428 let m = k.checked_abs().unwrap_or(i64::MAX).saturating_sub(1).max(0);
429 let nonneg = matches!(self.lo, Bound::Finite(v) if v >= 0);
430 let nonpos = matches!(self.hi, Bound::Finite(v) if v <= 0);
431 let lo = if nonneg {
432 Bound::Finite(0)
433 } else {
434 Bound::Finite(-m)
435 };
436 let hi = if nonpos {
437 Bound::Finite(0)
438 } else {
439 Bound::Finite(m)
440 };
441 return Interval { lo, hi };
442 }
443 }
444 let nonneg = matches!(self.lo, Bound::Finite(v) if v >= 0);
452 let nonpos = matches!(self.hi, Bound::Finite(v) if v <= 0);
453 if nonneg {
454 return Interval::non_negative();
455 }
456 if nonpos {
457 return Interval {
458 lo: Bound::NegInf,
459 hi: Bound::Finite(0),
460 };
461 }
462 Interval::top()
463 }
464
465 fn shr(&self, other: &Interval) -> Interval {
472 if let Some(k) = other.is_exact() {
473 if (0..64).contains(&k) {
474 let k = k as u32;
475 return Interval {
476 lo: self.lo.shr_by(k),
477 hi: self.hi.shr_by(k),
478 };
479 }
480 }
481 Interval::top()
482 }
483
484 fn natural(&self) -> Option<(i64, i64)> {
486 match (&self.lo, &self.hi) {
487 (Bound::Finite(lo), Bound::Finite(hi)) if *lo >= 0 && lo <= hi => Some((*lo, *hi)),
488 _ => None,
489 }
490 }
491
492 fn bitand(&self, other: &Interval) -> Interval {
496 if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
497 return Interval::exact(a & b);
498 }
499 let cap = |i: &Interval| match (&i.lo, &i.hi) {
500 (Bound::Finite(lo), hi) if *lo >= 0 => Some(hi.clone()),
501 _ => None,
502 };
503 match (cap(self), cap(other)) {
504 (Some(a), Some(b)) => Interval {
505 lo: Bound::Finite(0),
506 hi: Bound::min_bound(&a, &b),
507 },
508 (Some(hi), None) | (None, Some(hi)) => Interval {
509 lo: Bound::Finite(0),
510 hi,
511 },
512 (None, None) => Interval::top(),
513 }
514 }
515
516 fn bitor_or_xor(&self, other: &Interval, or: bool) -> Interval {
519 let (Some((al, ah)), Some((bl, bh))) = (self.natural(), other.natural()) else {
520 return Interval::top();
521 };
522 let width = 64 - (ah.max(bh) as u64).leading_zeros();
523 let ceiling = ((1u128 << width) - 1) as i64;
524 Interval {
525 lo: Bound::Finite(if or { al.max(bl) } else { 0 }),
526 hi: Bound::Finite(ceiling),
527 }
528 }
529
530 fn shl(&self, other: &Interval) -> Interval {
533 let (Some(s), Bound::Finite(lo), Bound::Finite(hi)) = (other.is_exact(), &self.lo, &self.hi) else {
534 return Interval::top();
535 };
536 let k = (s as u32) & 63;
537 let scale = |v: i64| i64::try_from((v as i128) << k).ok();
538 match (scale(*lo), scale(*hi)) {
539 (Some(lo), Some(hi)) => Interval {
540 lo: Bound::Finite(lo),
541 hi: Bound::Finite(hi),
542 },
543 _ => Interval::top(),
544 }
545 }
546
547 fn definitely_gt(&self, other: &Interval) -> Option<bool> {
548 use std::cmp::Ordering::{Equal, Greater, Less};
549 if self.lo.decided(&other.hi) == Some(Greater) {
550 return Some(true);
551 }
552 if matches!(self.hi.decided(&other.lo), Some(Less | Equal)) {
553 return Some(false);
554 }
555 None
556 }
557
558 fn definitely_lt(&self, other: &Interval) -> Option<bool> {
559 use std::cmp::Ordering::{Equal, Greater, Less};
560 if self.hi.decided(&other.lo) == Some(Less) {
561 return Some(true);
562 }
563 if matches!(self.lo.decided(&other.hi), Some(Greater | Equal)) {
564 return Some(false);
565 }
566 None
567 }
568
569 fn definitely_gteq(&self, other: &Interval) -> Option<bool> {
570 use std::cmp::Ordering::{Equal, Greater, Less};
571 if matches!(self.lo.decided(&other.hi), Some(Greater | Equal)) {
572 return Some(true);
573 }
574 if self.hi.decided(&other.lo) == Some(Less) {
575 return Some(false);
576 }
577 None
578 }
579
580 fn definitely_lteq(&self, other: &Interval) -> Option<bool> {
581 use std::cmp::Ordering::{Equal, Greater, Less};
582 if matches!(self.hi.decided(&other.lo), Some(Less | Equal)) {
583 return Some(true);
584 }
585 if self.lo.decided(&other.hi) == Some(Greater) {
586 return Some(false);
587 }
588 None
589 }
590
591 fn definitely_eq(&self, other: &Interval) -> Option<bool> {
592 if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
593 return Some(a == b);
594 }
595 None
596 }
597
598 fn definitely_neq(&self, other: &Interval) -> Option<bool> {
599 if self.hi.decided(&other.lo) == Some(std::cmp::Ordering::Less)
600 || self.lo.decided(&other.hi) == Some(std::cmp::Ordering::Greater)
601 {
602 return Some(true);
603 }
604 if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
605 return Some(a != b);
606 }
607 None
608 }
609}
610
611impl AbstractDomain for Interval {
612 fn top() -> Self {
613 Interval::top()
614 }
615 fn bottom() -> Self {
616 Interval::bottom()
617 }
618 fn join(&self, other: &Self) -> Self {
619 Interval::join(self, other)
620 }
621 fn meet(&self, other: &Self) -> Self {
622 Interval::meet(self, other)
623 }
624 fn widen(&self, other: &Self) -> Self {
625 Interval::widen(self, other)
626 }
627 fn leq(&self, other: &Self) -> bool {
628 Interval::leq(self, other)
629 }
630}
631
632#[derive(Clone, Debug, PartialEq, Eq, Hash)]
636enum TypeTag {
637 Int,
638 Float,
639 Bool,
640 Text,
641 Char,
642 Nothing,
643 Duration,
644 Date,
645 Moment,
646 Span,
647 Time,
648}
649
650#[derive(Clone, Debug)]
654enum TypeAbstraction {
655 Bottom,
656 Concrete(TypeTag),
657 Union(std::collections::HashSet<TypeTag>),
658 Top,
659}
660
661impl TypeAbstraction {
662 const UNION_CAP: usize = 6;
665
666 fn tag_set(&self) -> Option<std::collections::HashSet<TypeTag>> {
669 match self {
670 TypeAbstraction::Top => None,
671 TypeAbstraction::Bottom => Some(std::collections::HashSet::new()),
672 TypeAbstraction::Concrete(t) => {
673 let mut s = std::collections::HashSet::new();
674 s.insert(t.clone());
675 Some(s)
676 }
677 TypeAbstraction::Union(s) => Some(s.clone()),
678 }
679 }
680
681 fn from_tags(s: std::collections::HashSet<TypeTag>) -> Self {
682 if s.is_empty() {
683 TypeAbstraction::Bottom
684 } else if s.len() == 1 {
685 TypeAbstraction::Concrete(s.into_iter().next().unwrap())
686 } else if s.len() > Self::UNION_CAP {
687 TypeAbstraction::Top
688 } else {
689 TypeAbstraction::Union(s)
690 }
691 }
692}
693
694impl PartialEq for TypeAbstraction {
695 fn eq(&self, other: &Self) -> bool {
696 self.tag_set() == other.tag_set()
697 }
698}
699
700impl AbstractDomain for TypeAbstraction {
701 fn top() -> Self {
702 TypeAbstraction::Top
703 }
704 fn bottom() -> Self {
705 TypeAbstraction::Bottom
706 }
707
708 fn join(&self, other: &Self) -> Self {
709 match (self.tag_set(), other.tag_set()) {
710 (None, _) | (_, None) => TypeAbstraction::Top,
711 (Some(a), Some(b)) => TypeAbstraction::from_tags(a.union(&b).cloned().collect()),
712 }
713 }
714
715 fn meet(&self, other: &Self) -> Self {
716 match (self.tag_set(), other.tag_set()) {
717 (None, _) => other.clone(),
718 (_, None) => self.clone(),
719 (Some(a), Some(b)) => TypeAbstraction::from_tags(a.intersection(&b).cloned().collect()),
720 }
721 }
722
723 fn widen(&self, other: &Self) -> Self {
725 self.join(other)
726 }
727
728 fn leq(&self, other: &Self) -> bool {
729 match (self.tag_set(), other.tag_set()) {
730 (_, None) => true, (None, Some(_)) => false, (Some(a), Some(b)) => a.is_subset(&b),
733 }
734 }
735}
736
737fn literal_type(lit: &Literal) -> TypeTag {
738 match lit {
739 Literal::Number(_) => TypeTag::Int,
740 Literal::Float(_) => TypeTag::Float,
741 Literal::Text(_) => TypeTag::Text,
742 Literal::Boolean(_) => TypeTag::Bool,
743 Literal::Nothing => TypeTag::Nothing,
744 Literal::Char(_) => TypeTag::Char,
745 Literal::Duration(_) => TypeTag::Duration,
746 Literal::Date(_) => TypeTag::Date,
747 Literal::Moment(_) => TypeTag::Moment,
748 Literal::Span { .. } => TypeTag::Span,
749 Literal::Time(_) => TypeTag::Time,
750 }
751}
752
753fn binop_type(op: BinaryOpKind, l: &TypeAbstraction, r: &TypeAbstraction) -> TypeAbstraction {
754 use BinaryOpKind::*;
755 let conc = |t: TypeTag| TypeAbstraction::Concrete(t);
756 let is = |a: &TypeAbstraction, t: TypeTag| matches!(a, TypeAbstraction::Concrete(x) if *x == t);
757 match op {
758 Lt | Gt | LtEq | GtEq | Eq | NotEq | ApproxEq => conc(TypeTag::Bool),
760 BitAnd | BitOr => TypeAbstraction::Top,
763 Concat => conc(TypeTag::Text),
765 SeqConcat => TypeAbstraction::Top,
767 Add => {
768 if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
769 conc(TypeTag::Int)
770 } else if is(l, TypeTag::Float) && is(r, TypeTag::Float) {
771 conc(TypeTag::Float)
772 } else if is(l, TypeTag::Text) || is(r, TypeTag::Text) {
773 conc(TypeTag::Text)
774 } else {
775 TypeAbstraction::Top
776 }
777 }
778 ExactDivide | Pow => TypeAbstraction::Top,
782 Subtract | Multiply | Divide | FloorDivide | Modulo => {
783 if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
784 conc(TypeTag::Int)
785 } else if is(l, TypeTag::Float) && is(r, TypeTag::Float) {
786 conc(TypeTag::Float)
787 } else {
788 TypeAbstraction::Top
789 }
790 }
791 And | Or => {
792 if is(l, TypeTag::Bool) && is(r, TypeTag::Bool) {
793 conc(TypeTag::Bool)
794 } else if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
795 conc(TypeTag::Int)
796 } else {
797 TypeAbstraction::Top
798 }
799 }
800 BitXor | Shl | Shr => {
801 if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
802 conc(TypeTag::Int)
803 } else {
804 TypeAbstraction::Top
805 }
806 }
807 }
808}
809
810fn eval_type(
811 expr: &Expr,
812 types: &HashMap<Symbol, TypeAbstraction>,
813 fn_returns: &HashMap<Symbol, TypeTag>,
814 elem_type: &HashMap<Symbol, TypeAbstraction>,
815) -> TypeAbstraction {
816 match expr {
817 Expr::Literal(lit) => TypeAbstraction::Concrete(literal_type(lit)),
818 Expr::Identifier(sym) => types.get(sym).cloned().unwrap_or(TypeAbstraction::Top),
819 Expr::BinaryOp { op, left, right } => {
820 let l = eval_type(left, types, fn_returns, elem_type);
821 let r = eval_type(right, types, fn_returns, elem_type);
822 binop_type(*op, &l, &r)
823 }
824 Expr::Not { operand } => match eval_type(operand, types, fn_returns, elem_type) {
825 TypeAbstraction::Concrete(TypeTag::Bool) => TypeAbstraction::Concrete(TypeTag::Bool),
826 TypeAbstraction::Concrete(TypeTag::Int) => TypeAbstraction::Concrete(TypeTag::Int),
827 _ => TypeAbstraction::Top,
828 },
829 Expr::Length { .. } => TypeAbstraction::Concrete(TypeTag::Int),
830 Expr::Contains { .. } => TypeAbstraction::Concrete(TypeTag::Bool),
831 Expr::WithCapacity { value, .. } => eval_type(value, types, fn_returns, elem_type),
834 Expr::Call { function, .. } => fn_returns
837 .get(function)
838 .map(|t| TypeAbstraction::Concrete(t.clone()))
839 .unwrap_or(TypeAbstraction::Top),
840 Expr::Index {
845 collection: Expr::Identifier(sym),
846 ..
847 } if elem_type_enabled() => {
848 let t = elem_type.get(sym).cloned().unwrap_or(TypeAbstraction::Top);
849 if !matches!(t, TypeAbstraction::Top) {
850 crate::optimize::mark_fired(crate::optimization::Opt::ElemType);
851 }
852 t
853 }
854 _ => TypeAbstraction::Top,
855 }
856}
857
858#[derive(Clone, Debug)]
863enum CollectionShape {
864 Bottom,
866 Empty,
868 Singleton,
870 KnownSize(u64),
872 SizeRange(u64, u64),
874 NonEmpty,
876 Top,
878}
879
880impl CollectionShape {
881 fn empty_collection() -> Self {
883 CollectionShape::Empty
884 }
885
886 fn bounds(&self) -> Option<(u64, Option<u64>)> {
889 match self {
890 CollectionShape::Bottom => None,
891 CollectionShape::Empty => Some((0, Some(0))),
892 CollectionShape::Singleton => Some((1, Some(1))),
893 CollectionShape::KnownSize(n) => Some((*n, Some(*n))),
894 CollectionShape::SizeRange(lo, hi) => Some((*lo, Some(*hi))),
895 CollectionShape::NonEmpty => Some((1, None)),
896 CollectionShape::Top => Some((0, None)),
897 }
898 }
899
900 fn from_bounds(lo: u64, hi: Option<u64>) -> Self {
903 match hi {
904 Some(h) if lo > h => CollectionShape::Bottom,
905 Some(0) => CollectionShape::Empty,
906 Some(1) if lo == 1 => CollectionShape::Singleton,
907 Some(h) if lo == h => CollectionShape::KnownSize(h),
908 Some(h) => CollectionShape::SizeRange(lo, h),
909 None if lo == 0 => CollectionShape::Top,
910 None => CollectionShape::NonEmpty,
911 }
912 }
913
914 fn pushed(&self) -> Self {
916 match self.bounds() {
917 None => CollectionShape::Bottom,
918 Some((lo, hi)) => CollectionShape::from_bounds(lo + 1, hi.map(|h| h + 1)),
919 }
920 }
921
922 fn popped(&self) -> Self {
924 match self.bounds() {
925 None => CollectionShape::Bottom,
926 Some((lo, hi)) => {
927 CollectionShape::from_bounds(lo.saturating_sub(1), hi.map(|h| h.saturating_sub(1)))
928 }
929 }
930 }
931
932 fn is_definitely_nonempty(&self) -> bool {
933 matches!(self.bounds(), Some((lo, _)) if lo >= 1)
934 }
935
936 fn is_definitely_empty(&self) -> bool {
937 matches!(self.bounds(), Some((_, Some(0))))
938 }
939}
940
941impl PartialEq for CollectionShape {
942 fn eq(&self, other: &Self) -> bool {
943 self.bounds() == other.bounds()
944 }
945}
946
947impl AbstractDomain for CollectionShape {
948 fn top() -> Self {
949 CollectionShape::Top
950 }
951 fn bottom() -> Self {
952 CollectionShape::Bottom
953 }
954
955 fn join(&self, other: &Self) -> Self {
956 match (self.bounds(), other.bounds()) {
957 (None, _) => other.clone(),
958 (_, None) => self.clone(),
959 (Some((l1, h1)), Some((l2, h2))) => {
960 let lo = l1.min(l2);
961 let hi = match (h1, h2) {
962 (Some(a), Some(b)) => Some(a.max(b)),
963 _ => None,
964 };
965 CollectionShape::from_bounds(lo, hi)
966 }
967 }
968 }
969
970 fn meet(&self, other: &Self) -> Self {
971 match (self.bounds(), other.bounds()) {
972 (None, _) | (_, None) => CollectionShape::Bottom,
973 (Some((l1, h1)), Some((l2, h2))) => {
974 let lo = l1.max(l2);
975 let hi = match (h1, h2) {
976 (Some(a), Some(b)) => Some(a.min(b)),
977 (Some(a), None) => Some(a),
978 (None, Some(b)) => Some(b),
979 (None, None) => None,
980 };
981 CollectionShape::from_bounds(lo, hi)
982 }
983 }
984 }
985
986 fn widen(&self, other: &Self) -> Self {
987 match (self.bounds(), other.bounds()) {
988 (None, _) => other.clone(),
989 (_, None) => self.clone(),
990 (Some((l1, h1)), Some((l2, h2))) => {
991 let lo = if l2 < l1 { 0 } else { l1 };
992 let hi = match (h1, h2) {
993 (Some(a), Some(b)) if b <= a => Some(a),
994 _ => None,
995 };
996 CollectionShape::from_bounds(lo, hi)
997 }
998 }
999 }
1000
1001 fn leq(&self, other: &Self) -> bool {
1002 match (self.bounds(), other.bounds()) {
1003 (None, _) => true,
1004 (_, None) => false,
1005 (Some((l1, h1)), Some((l2, h2))) => {
1006 let lo_ok = l2 <= l1;
1007 let hi_ok = match (h1, h2) {
1008 (_, None) => true,
1009 (None, Some(_)) => false,
1010 (Some(a), Some(b)) => a <= b,
1011 };
1012 lo_ok && hi_ok
1013 }
1014 }
1015 }
1016}
1017
1018#[derive(Clone, Debug, PartialEq, Eq)]
1023enum Nullability {
1024 Bottom,
1026 Definite,
1028 Null,
1030 Maybe,
1032}
1033
1034impl Nullability {
1035 fn for_literal(lit: &Literal) -> Nullability {
1037 match lit {
1038 Literal::Nothing => Nullability::Null,
1039 _ => Nullability::Definite,
1040 }
1041 }
1042
1043 fn for_matched_variant() -> Nullability {
1046 Nullability::Definite
1047 }
1048}
1049
1050impl AbstractDomain for Nullability {
1051 fn top() -> Self {
1052 Nullability::Maybe
1053 }
1054 fn bottom() -> Self {
1055 Nullability::Bottom
1056 }
1057
1058 fn join(&self, other: &Self) -> Self {
1059 use Nullability::*;
1060 match (self, other) {
1061 (Bottom, x) | (x, Bottom) => x.clone(),
1062 (Maybe, _) | (_, Maybe) => Maybe,
1063 (Definite, Definite) => Definite,
1064 (Null, Null) => Null,
1065 (Definite, Null) | (Null, Definite) => Maybe,
1066 }
1067 }
1068
1069 fn meet(&self, other: &Self) -> Self {
1070 use Nullability::*;
1071 match (self, other) {
1072 (Maybe, x) | (x, Maybe) => x.clone(),
1073 (Bottom, _) | (_, Bottom) => Bottom,
1074 (Definite, Definite) => Definite,
1075 (Null, Null) => Null,
1076 (Definite, Null) | (Null, Definite) => Bottom,
1077 }
1078 }
1079
1080 fn widen(&self, other: &Self) -> Self {
1082 self.join(other)
1083 }
1084
1085 fn leq(&self, other: &Self) -> bool {
1086 *self == Nullability::Bottom || *other == Nullability::Maybe || self == other
1087 }
1088}
1089
1090#[derive(Clone, Debug)]
1095enum AliasInfo {
1096 Bottom,
1098 Unique,
1100 MayAlias(HashSet<Symbol>),
1102 Top,
1104}
1105
1106enum AliasReach {
1108 Bottom,
1109 Finite(HashSet<Symbol>),
1110 Anything,
1111}
1112
1113impl AliasInfo {
1114 fn reach(&self) -> AliasReach {
1115 match self {
1116 AliasInfo::Bottom => AliasReach::Bottom,
1117 AliasInfo::Unique => AliasReach::Finite(HashSet::new()),
1118 AliasInfo::MayAlias(s) => AliasReach::Finite(s.clone()),
1119 AliasInfo::Top => AliasReach::Anything,
1120 }
1121 }
1122
1123 fn from_reach(r: AliasReach) -> Self {
1124 match r {
1125 AliasReach::Bottom => AliasInfo::Bottom,
1126 AliasReach::Anything => AliasInfo::Top,
1127 AliasReach::Finite(s) => {
1128 if s.is_empty() {
1129 AliasInfo::Unique
1130 } else {
1131 AliasInfo::MayAlias(s)
1132 }
1133 }
1134 }
1135 }
1136}
1137
1138impl PartialEq for AliasInfo {
1139 fn eq(&self, other: &Self) -> bool {
1140 match (self.reach(), other.reach()) {
1141 (AliasReach::Bottom, AliasReach::Bottom) => true,
1142 (AliasReach::Anything, AliasReach::Anything) => true,
1143 (AliasReach::Finite(a), AliasReach::Finite(b)) => a == b,
1144 _ => false,
1145 }
1146 }
1147}
1148
1149impl AbstractDomain for AliasInfo {
1150 fn top() -> Self {
1151 AliasInfo::Top
1152 }
1153 fn bottom() -> Self {
1154 AliasInfo::Bottom
1155 }
1156
1157 fn join(&self, other: &Self) -> Self {
1158 match (self.reach(), other.reach()) {
1159 (AliasReach::Bottom, _) => other.clone(),
1160 (_, AliasReach::Bottom) => self.clone(),
1161 (AliasReach::Anything, _) | (_, AliasReach::Anything) => AliasInfo::Top,
1162 (AliasReach::Finite(a), AliasReach::Finite(b)) => {
1163 AliasInfo::from_reach(AliasReach::Finite(a.union(&b).cloned().collect()))
1164 }
1165 }
1166 }
1167
1168 fn meet(&self, other: &Self) -> Self {
1169 match (self.reach(), other.reach()) {
1170 (AliasReach::Bottom, _) | (_, AliasReach::Bottom) => AliasInfo::Bottom,
1171 (AliasReach::Anything, _) => other.clone(),
1172 (_, AliasReach::Anything) => self.clone(),
1173 (AliasReach::Finite(a), AliasReach::Finite(b)) => {
1174 AliasInfo::from_reach(AliasReach::Finite(a.intersection(&b).cloned().collect()))
1175 }
1176 }
1177 }
1178
1179 fn widen(&self, other: &Self) -> Self {
1181 self.join(other)
1182 }
1183
1184 fn leq(&self, other: &Self) -> bool {
1185 match (self.reach(), other.reach()) {
1186 (AliasReach::Bottom, _) => true,
1187 (_, AliasReach::Anything) => true,
1188 (AliasReach::Anything, _) => false,
1189 (_, AliasReach::Bottom) => false,
1190 (AliasReach::Finite(a), AliasReach::Finite(b)) => a.is_subset(&b),
1191 }
1192 }
1193}
1194
1195#[derive(Clone, Default)]
1206struct AliasGraph {
1207 edges: HashMap<Symbol, HashSet<Symbol>>,
1208 tainted: HashSet<Symbol>,
1209}
1210
1211impl AliasGraph {
1212 fn new() -> Self {
1213 AliasGraph::default()
1214 }
1215
1216 fn link(&mut self, a: Symbol, b: Symbol) {
1219 if a == b {
1220 return;
1221 }
1222 self.edges.entry(a).or_default().insert(b);
1223 self.edges.entry(b).or_default().insert(a);
1224 if self.tainted.contains(&a) {
1226 self.tainted.insert(b);
1227 }
1228 if self.tainted.contains(&b) {
1229 self.tainted.insert(a);
1230 }
1231 }
1232
1233 fn taint(&mut self, a: Symbol) {
1235 self.tainted.insert(a);
1236 }
1237
1238 fn union_from(&mut self, other: &AliasGraph) -> bool {
1240 let mut grew = false;
1241 for (k, ns) in &other.edges {
1242 let e = self.edges.entry(*k).or_default();
1243 for n in ns {
1244 if e.insert(*n) {
1245 grew = true;
1246 }
1247 }
1248 }
1249 for t in &other.tainted {
1250 if self.tainted.insert(*t) {
1251 grew = true;
1252 }
1253 }
1254 grew
1255 }
1256
1257 fn definitely_distinct(&self, a: Symbol, b: Symbol) -> bool {
1260 if a == b || self.tainted.contains(&a) || self.tainted.contains(&b) {
1261 return false;
1262 }
1263 !self.may_alias(a).contains(&b)
1264 }
1265
1266 fn may_alias(&self, v: Symbol) -> HashSet<Symbol> {
1268 let mut seen = HashSet::new();
1269 let mut stack = vec![v];
1270 while let Some(x) = stack.pop() {
1271 if seen.insert(x) {
1272 if let Some(ns) = self.edges.get(&x) {
1273 for &n in ns {
1274 if !seen.contains(&n) {
1275 stack.push(n);
1276 }
1277 }
1278 }
1279 }
1280 }
1281 seen
1282 }
1283
1284 fn invalidated_by_mutation(&self, v: Symbol) -> HashSet<Symbol> {
1286 self.may_alias(v)
1287 }
1288
1289 fn unlink(&mut self, a: Symbol) {
1292 if let Some(ns) = self.edges.remove(&a) {
1293 for n in ns {
1294 if let Some(s) = self.edges.get_mut(&n) {
1295 s.remove(&a);
1296 }
1297 }
1298 }
1299 self.tainted.remove(&a);
1300 }
1301}
1302
1303#[derive(Clone)]
1304struct AbstractState {
1305 globals: std::rc::Rc<CalleeGlobals>,
1307 vars: HashMap<Symbol, Interval>,
1308 lengths: HashMap<Symbol, Interval>,
1309 elem: HashMap<Symbol, Interval>,
1315}
1316
1317impl AbstractState {
1318 fn new() -> Self {
1319 AbstractState::with_globals(std::rc::Rc::default())
1320 }
1321
1322 fn with_globals(globals: std::rc::Rc<CalleeGlobals>) -> Self {
1323 AbstractState {
1324 globals,
1325 vars: HashMap::new(),
1326 lengths: HashMap::new(),
1327 elem: HashMap::new(),
1328 }
1329 }
1330
1331 fn effects_of(&self, stmt: &Stmt) -> WriteSet {
1333 WriteSet::of_stmt(stmt).with_callee_globals(&self.globals)
1334 }
1335
1336 fn effects_of_expr(&self, expr: &Expr) -> WriteSet {
1338 WriteSet::of_expr(expr).with_callee_globals(&self.globals)
1339 }
1340
1341 fn forget(&mut self, effects: &WriteSet) {
1344 if effects.is_opaque() {
1345 self.forget_all();
1346 return;
1347 }
1348 for sym in effects.symbols() {
1349 self.set_var(sym, Interval::top());
1350 self.set_length(sym, Interval::top());
1351 }
1352 }
1353
1354 fn forget_all(&mut self) {
1355 self.vars.clear();
1356 self.lengths.clear();
1357 self.elem.clear();
1358 }
1359
1360 fn get_var(&self, sym: &Symbol) -> Interval {
1361 self.vars.get(sym).cloned().unwrap_or(Interval::top())
1362 }
1363
1364 fn set_var(&mut self, sym: Symbol, range: Interval) {
1365 self.vars.insert(sym, range);
1366 }
1367
1368 fn get_length(&self, sym: &Symbol) -> Interval {
1369 self.lengths
1370 .get(sym)
1371 .cloned()
1372 .unwrap_or(Interval::non_negative())
1373 }
1374
1375 fn set_length(&mut self, sym: Symbol, range: Interval) {
1376 self.lengths.insert(sym, range);
1377 }
1378
1379 fn get_elem(&self, sym: &Symbol) -> Interval {
1381 self.elem.get(sym).cloned().unwrap_or(Interval::top())
1382 }
1383
1384 fn observe_elem(&mut self, sym: Symbol, range: Interval) {
1388 let joined = match self.elem.get(&sym) {
1389 Some(existing) => existing.join(&range),
1390 None => range,
1391 };
1392 self.elem.insert(sym, joined);
1393 }
1394
1395 fn clear_elem(&mut self, sym: &Symbol) {
1398 self.elem.remove(sym);
1399 }
1400}
1401
1402fn eval_expr(expr: &Expr, state: &AbstractState) -> Interval {
1403 match expr {
1404 Expr::Literal(Literal::Number(n)) => Interval::exact(*n),
1405 Expr::Literal(Literal::Boolean(_)) => Interval::top(),
1406 Expr::Literal(Literal::Float(_)) => Interval::top(),
1407 Expr::Identifier(sym) => state.get_var(sym),
1408 Expr::BinaryOp { op, left, right } => {
1409 let l = eval_expr(left, state);
1410 let r = eval_expr(right, state);
1411 match op {
1412 BinaryOpKind::Add => l.add(&r),
1413 BinaryOpKind::Subtract => l.sub(&r),
1414 BinaryOpKind::Multiply => l.mul(&r),
1415 BinaryOpKind::Divide => l.div(&r),
1416 BinaryOpKind::ExactDivide => Interval::top(),
1422 BinaryOpKind::Modulo => l.modulo(&r),
1423 BinaryOpKind::Shr => l.shr(&r),
1424 BinaryOpKind::Shl => l.shl(&r),
1425 BinaryOpKind::BitAnd => l.bitand(&r),
1426 BinaryOpKind::BitOr => l.bitor_or_xor(&r, true),
1427 BinaryOpKind::BitXor => l.bitor_or_xor(&r, false),
1428 _ => Interval::top(),
1429 }
1430 }
1431 Expr::Length { collection } => {
1432 if let Expr::Identifier(sym) = collection {
1433 state.get_length(sym)
1434 } else {
1435 Interval::non_negative()
1436 }
1437 }
1438 Expr::Index { collection, .. } => {
1443 if let Expr::Identifier(sym) = collection {
1444 state.get_elem(sym)
1445 } else {
1446 Interval::top()
1447 }
1448 }
1449 _ => Interval::top(),
1450 }
1451}
1452
1453fn eval_condition(cond: &Expr, state: &AbstractState) -> Option<bool> {
1454 match cond {
1455 Expr::Literal(Literal::Boolean(b)) => Some(*b),
1456 Expr::BinaryOp { op, left, right } => {
1457 let l = eval_expr(left, state);
1458 let r = eval_expr(right, state);
1459 match op {
1460 BinaryOpKind::Gt => l.definitely_gt(&r),
1461 BinaryOpKind::Lt => l.definitely_lt(&r),
1462 BinaryOpKind::GtEq => l.definitely_gteq(&r),
1463 BinaryOpKind::LtEq => l.definitely_lteq(&r),
1464 BinaryOpKind::Eq => l.definitely_eq(&r),
1465 BinaryOpKind::NotEq => l.definitely_neq(&r),
1466 _ => None,
1467 }
1468 }
1469 Expr::Not { operand } => eval_condition(operand, state).map(|b| !b),
1470 _ => None,
1471 }
1472}
1473
1474fn narrow_state(cond: &Expr, state: &mut AbstractState) {
1475 narrow_by_comparison(cond, state, false);
1476}
1477
1478fn narrow_state_negated(cond: &Expr, state: &mut AbstractState) {
1479 narrow_by_comparison(cond, state, true);
1480}
1481
1482fn narrow_by_comparison(cond: &Expr, state: &mut AbstractState, negated: bool) {
1489 let Expr::BinaryOp { op, left, right } = cond else {
1490 return;
1491 };
1492 let holds = match (op, negated) {
1493 (BinaryOpKind::Lt, false) | (BinaryOpKind::GtEq, true) => BinaryOpKind::Lt,
1494 (BinaryOpKind::LtEq, false) | (BinaryOpKind::Gt, true) => BinaryOpKind::LtEq,
1495 (BinaryOpKind::Gt, false) | (BinaryOpKind::LtEq, true) => BinaryOpKind::Gt,
1496 (BinaryOpKind::GtEq, false) | (BinaryOpKind::Lt, true) => BinaryOpKind::GtEq,
1497 (BinaryOpKind::Eq, false) | (BinaryOpKind::NotEq, true) => BinaryOpKind::Eq,
1498 _ => return,
1499 };
1500 let (l, r) = (eval_expr(left, state), eval_expr(right, state));
1501 let cap = |state: &mut AbstractState, e: &Expr, hi: &Bound| {
1502 if let Expr::Identifier(sym) = e {
1503 let cur = state.get_var(sym);
1504 state.set_var(
1505 *sym,
1506 Interval {
1507 lo: cur.lo.clone(),
1508 hi: Bound::min_bound(&cur.hi, hi),
1509 },
1510 );
1511 }
1512 };
1513 let floor = |state: &mut AbstractState, e: &Expr, lo: &Bound| {
1514 if let Expr::Identifier(sym) = e {
1515 let cur = state.get_var(sym);
1516 state.set_var(
1517 *sym,
1518 Interval {
1519 lo: Bound::max_bound(&cur.lo, lo),
1520 hi: cur.hi.clone(),
1521 },
1522 );
1523 }
1524 };
1525 let step = |b: &Bound, by: i64| -> Option<Bound> {
1527 match b {
1528 Bound::Finite(n) => n.checked_add(by).map(Bound::Finite),
1529 other => Some(other.clone()),
1530 }
1531 };
1532 let (small, big, small_iv, big_iv, strict) = match holds {
1533 BinaryOpKind::Lt => (left, right, &l, &r, true),
1534 BinaryOpKind::LtEq => (left, right, &l, &r, false),
1535 BinaryOpKind::Gt => (right, left, &r, &l, true),
1536 BinaryOpKind::GtEq => (right, left, &r, &l, false),
1537 _ => {
1538 cap(state, left, &r.hi);
1539 floor(state, left, &r.lo);
1540 cap(state, right, &l.hi);
1541 floor(state, right, &l.lo);
1542 return;
1543 }
1544 };
1545 let by = if strict { 1 } else { 0 };
1546 if let Some(hi) = step(&big_iv.hi, -by) {
1547 cap(state, small, &hi);
1548 }
1549 if let Some(lo) = step(&small_iv.lo, by) {
1550 floor(state, big, &lo);
1551 }
1552}
1553
1554pub fn abstract_interp_stmts<'a>(
1555 stmts: Vec<Stmt<'a>>,
1556 expr_arena: &'a Arena<Expr<'a>>,
1557 stmt_arena: &'a Arena<Stmt<'a>>,
1558) -> Vec<Stmt<'a>> {
1559 let mut state =
1560 AbstractState::with_globals(std::rc::Rc::new(CalleeGlobals::of_program(&stmts)));
1561 interp_block(stmts, &mut state, expr_arena, stmt_arena)
1562}
1563
1564fn interp_block<'a>(
1565 stmts: Vec<Stmt<'a>>,
1566 state: &mut AbstractState,
1567 expr_arena: &'a Arena<Expr<'a>>,
1568 stmt_arena: &'a Arena<Stmt<'a>>,
1569) -> Vec<Stmt<'a>> {
1570 let mut result = Vec::with_capacity(stmts.len());
1571
1572 for stmt in stmts {
1573 let effects = state.effects_of(&stmt);
1575 match stmt {
1576 Stmt::Let {
1577 var,
1578 ty,
1579 value,
1580 mutable,
1581 } => {
1582 let value_effects = state.effects_of_expr(value);
1584 state.forget(&value_effects);
1585 let range = eval_expr(value, state);
1586 state.set_var(var, range);
1587 if matches!(value, Expr::New { .. }) {
1588 state.set_length(var, Interval::exact(0));
1589 }
1590 result.push(Stmt::Let {
1591 var,
1592 ty,
1593 value,
1594 mutable,
1595 });
1596 }
1597
1598 Stmt::Set { target, value } => {
1599 let value_effects = state.effects_of_expr(value);
1600 state.forget(&value_effects);
1601 let range = eval_expr(value, state);
1602 state.set_var(target, range);
1603 result.push(Stmt::Set { target, value });
1604 }
1605
1606 Stmt::Push { value, collection } => {
1607 let value_effects = state.effects_of_expr(value);
1608 state.forget(&value_effects);
1609 if let Expr::Identifier(sym) = collection {
1610 let cur_len = state.get_length(sym);
1611 state.set_length(*sym, cur_len.add(&Interval::exact(1)));
1612 }
1613 result.push(Stmt::Push { value, collection });
1614 }
1615
1616 Stmt::If {
1617 cond,
1618 then_block,
1619 else_block,
1620 } => {
1621 let cond_effects = state.effects_of_expr(cond);
1622 state.forget(&cond_effects);
1623 if let Some(val) = eval_condition(cond, state) {
1624 let new_cond = expr_arena.alloc(Expr::Literal(Literal::Boolean(val)));
1625 if val {
1626 let mut then_state = state.clone();
1627 narrow_state(cond, &mut then_state);
1628 let new_then = interp_nested_block(
1629 then_block,
1630 &mut then_state,
1631 expr_arena,
1632 stmt_arena,
1633 );
1634 *state = then_state;
1635 result.push(Stmt::If {
1636 cond: new_cond,
1637 then_block: new_then,
1638 else_block: None,
1639 });
1640 } else {
1641 if let Some(eb) = else_block {
1642 let mut else_state = state.clone();
1643 narrow_state_negated(cond, &mut else_state);
1644 let new_else =
1645 interp_nested_block(eb, &mut else_state, expr_arena, stmt_arena);
1646 *state = else_state;
1647 result.push(Stmt::If {
1648 cond: new_cond,
1649 then_block: stmt_arena.alloc_slice(vec![]),
1650 else_block: Some(new_else),
1651 });
1652 } else {
1653 result.push(Stmt::If {
1654 cond: new_cond,
1655 then_block: stmt_arena.alloc_slice(vec![]),
1656 else_block: None,
1657 });
1658 }
1659 }
1660 } else {
1661 let mut then_state = state.clone();
1662 narrow_state(cond, &mut then_state);
1663 let new_then =
1664 interp_nested_block(then_block, &mut then_state, expr_arena, stmt_arena);
1665
1666 let (new_else, else_state) = if let Some(eb) = else_block {
1667 let mut es = state.clone();
1668 narrow_state_negated(cond, &mut es);
1669 let ne = interp_nested_block(eb, &mut es, expr_arena, stmt_arena);
1670 (Some(ne), Some(es))
1671 } else {
1672 (None, None)
1673 };
1674
1675 if let Some(es) = else_state {
1676 join_states(state, &then_state, &es);
1677 } else {
1678 let orig = state.clone();
1679 join_states(state, &then_state, &orig);
1680 }
1681
1682 result.push(Stmt::If {
1683 cond,
1684 then_block: new_then,
1685 else_block: new_else,
1686 });
1687 }
1688 }
1689
1690 Stmt::While {
1691 cond,
1692 body,
1693 decreasing,
1694 } => {
1695 let mut loop_state = state.clone();
1696
1697 loop_state.forget(&effects);
1703
1704 narrow_state(cond, &mut loop_state);
1709
1710 let new_body = interp_nested_block(body, &mut loop_state, expr_arena, stmt_arena);
1711
1712 state.forget(&effects);
1716 if !crate::loop_shape::leaves_by_break(body) {
1717 narrow_state_negated(cond, state);
1718 }
1719
1720 result.push(Stmt::While {
1721 cond,
1722 body: new_body,
1723 decreasing,
1724 });
1725 }
1726
1727 Stmt::Repeat {
1728 pattern,
1729 iterable,
1730 body,
1731 } => {
1732 let mut loop_state = state.clone();
1733
1734 if let Pattern::Identifier(var) = &pattern {
1735 loop_state.set_var(*var, Interval::top());
1736 }
1737
1738 loop_state.forget(&effects);
1739
1740 let new_body = interp_nested_block(body, &mut loop_state, expr_arena, stmt_arena);
1741
1742 state.forget(&effects);
1743
1744 result.push(Stmt::Repeat {
1745 pattern,
1746 iterable,
1747 body: new_body,
1748 });
1749 }
1750
1751 Stmt::FunctionDef {
1752 name,
1753 params,
1754 generics,
1755 body,
1756 return_type,
1757 is_native,
1758 native_path,
1759 is_exported,
1760 export_target,
1761 opt_flags,
1762 } => {
1763 let mut func_state = AbstractState::with_globals(state.globals.clone());
1764 let new_body = interp_nested_block(body, &mut func_state, expr_arena, stmt_arena);
1765 result.push(Stmt::FunctionDef {
1766 name,
1767 params,
1768 generics,
1769 body: new_body,
1770 return_type,
1771 is_native,
1772 native_path,
1773 is_exported,
1774 export_target,
1775 opt_flags,
1776 });
1777 }
1778
1779 Stmt::Inspect {
1780 target,
1781 arms,
1782 has_otherwise,
1783 } => {
1784 let new_arms: Vec<_> = arms
1785 .into_iter()
1786 .map(|arm| {
1787 let mut arm_state = state.clone();
1788 let new_body =
1789 interp_nested_block(arm.body, &mut arm_state, expr_arena, stmt_arena);
1790 crate::ast::stmt::MatchArm {
1791 enum_name: arm.enum_name,
1792 variant: arm.variant,
1793 bindings: arm.bindings,
1794 body: new_body,
1795 }
1796 })
1797 .collect();
1798 state.forget(&effects);
1800 result.push(Stmt::Inspect {
1801 target,
1802 arms: new_arms,
1803 has_otherwise,
1804 });
1805 }
1806
1807 Stmt::Zone { .. } => {
1808 state.forget(&effects);
1811 result.push(stmt);
1812 }
1813
1814 Stmt::Concurrent { tasks } => {
1815 let mut sub_state = state.clone();
1816 let new_tasks = interp_nested_block(tasks, &mut sub_state, expr_arena, stmt_arena);
1817 state.forget(&effects);
1818 result.push(Stmt::Concurrent { tasks: new_tasks });
1819 }
1820
1821 Stmt::Parallel { tasks } => {
1822 let mut sub_state = state.clone();
1823 let new_tasks = interp_nested_block(tasks, &mut sub_state, expr_arena, stmt_arena);
1824 state.forget(&effects);
1825 result.push(Stmt::Parallel { tasks: new_tasks });
1826 }
1827
1828 other => {
1830 state.forget(&effects);
1831 result.push(other);
1832 }
1833 }
1834 }
1835
1836 result
1837}
1838
1839fn interp_nested_block<'a>(
1840 block: &'a [Stmt<'a>],
1841 state: &mut AbstractState,
1842 expr_arena: &'a Arena<Expr<'a>>,
1843 stmt_arena: &'a Arena<Stmt<'a>>,
1844) -> &'a [Stmt<'a>] {
1845 let stmts: Vec<Stmt<'a>> = block.iter().cloned().collect();
1846 let result = interp_block(stmts, state, expr_arena, stmt_arena);
1847 stmt_arena.alloc_slice(result)
1848}
1849
1850fn join_states(out: &mut AbstractState, a: &AbstractState, b: &AbstractState) {
1851 let mut all_keys: std::collections::HashSet<Symbol> = a.vars.keys().cloned().collect();
1852 all_keys.extend(b.vars.keys().cloned());
1853
1854 for key in all_keys {
1855 let a_range = a.vars.get(&key).cloned().unwrap_or(Interval::top());
1856 let b_range = b.vars.get(&key).cloned().unwrap_or(Interval::top());
1857 out.set_var(key, a_range.join(&b_range));
1858 }
1859
1860 let mut len_keys: std::collections::HashSet<Symbol> = a.lengths.keys().cloned().collect();
1861 len_keys.extend(b.lengths.keys().cloned());
1862
1863 for key in len_keys {
1864 let a_len = a
1865 .lengths
1866 .get(&key)
1867 .cloned()
1868 .unwrap_or(Interval::non_negative());
1869 let b_len = b
1870 .lengths
1871 .get(&key)
1872 .cloned()
1873 .unwrap_or(Interval::non_negative());
1874 out.set_length(key, a_len.join(&b_len));
1875 }
1876
1877 let mut el_keys: std::collections::HashSet<Symbol> = a.elem.keys().cloned().collect();
1882 el_keys.extend(b.elem.keys().cloned());
1883 for key in el_keys {
1884 let a_el = a.get_elem(&key);
1885 let b_el = b.get_elem(&key);
1886 out.elem.insert(key, a_el.join(&b_el));
1887 }
1888}
1889
1890#[derive(Clone, Debug)]
1901pub(crate) struct AbstractValue {
1902 interval: Interval,
1903 ty: TypeAbstraction,
1904 shape: CollectionShape,
1905 nullability: Nullability,
1906 alias: AliasInfo,
1907}
1908
1909impl AbstractDomain for AbstractValue {
1910 fn top() -> Self {
1911 AbstractValue {
1912 interval: Interval::top(),
1913 ty: TypeAbstraction::Top,
1914 shape: CollectionShape::Top,
1915 nullability: Nullability::Maybe,
1916 alias: AliasInfo::Top,
1917 }
1918 }
1919
1920 fn bottom() -> Self {
1921 AbstractValue {
1922 interval: Interval::bottom(),
1923 ty: TypeAbstraction::Bottom,
1924 shape: CollectionShape::Bottom,
1925 nullability: Nullability::Bottom,
1926 alias: AliasInfo::Bottom,
1927 }
1928 }
1929
1930 fn join(&self, o: &Self) -> Self {
1931 AbstractValue {
1932 interval: self.interval.join(&o.interval),
1933 ty: self.ty.join(&o.ty),
1934 shape: self.shape.join(&o.shape),
1935 nullability: self.nullability.join(&o.nullability),
1936 alias: self.alias.join(&o.alias),
1937 }
1938 }
1939
1940 fn meet(&self, o: &Self) -> Self {
1941 AbstractValue {
1942 interval: self.interval.meet(&o.interval),
1943 ty: self.ty.meet(&o.ty),
1944 shape: self.shape.meet(&o.shape),
1945 nullability: self.nullability.meet(&o.nullability),
1946 alias: self.alias.meet(&o.alias),
1947 }
1948 }
1949
1950 fn widen(&self, o: &Self) -> Self {
1951 AbstractValue {
1952 interval: self.interval.widen(&o.interval),
1953 ty: self.ty.widen(&o.ty),
1954 shape: self.shape.widen(&o.shape),
1955 nullability: self.nullability.widen(&o.nullability),
1956 alias: self.alias.widen(&o.alias),
1957 }
1958 }
1959
1960 fn leq(&self, o: &Self) -> bool {
1961 self.interval.leq(&o.interval)
1962 && self.ty.leq(&o.ty)
1963 && self.shape.leq(&o.shape)
1964 && self.nullability.leq(&o.nullability)
1965 && self.alias.leq(&o.alias)
1966 }
1967}
1968
1969#[derive(Clone)]
1972pub(crate) struct RichAbstractState {
1973 intervals: AbstractState,
1974 types: HashMap<Symbol, TypeAbstraction>,
1975 shapes: HashMap<Symbol, CollectionShape>,
1976 nullability: HashMap<Symbol, Nullability>,
1977 aliases: AliasGraph,
1978 coll_vars: std::collections::HashSet<Symbol>,
1983 fn_returns: std::rc::Rc<HashMap<Symbol, TypeTag>>,
1985 callee_globals: std::rc::Rc<CalleeGlobals>,
1987 length_def: HashMap<Symbol, (Symbol, i64)>,
1995 param_colls: std::collections::HashSet<Symbol>,
2000 scalar_def: HashMap<Symbol, super::affine::LinExpr>,
2007 scalar_upper: HashMap<Symbol, super::affine::LinExpr>,
2015 elem_upper: HashMap<Symbol, super::affine::LinExpr>,
2022 elem_type: HashMap<Symbol, TypeAbstraction>,
2033 scalar_lower: HashMap<Symbol, super::affine::LinExpr>,
2041 aot_entry_guard: bool,
2050 entry_guard_lowers: Vec<(Symbol, i64)>,
2057 karr: super::karr::AffineSpace,
2059 seq_vars: std::collections::HashSet<Symbol>,
2063 seq_types: std::rc::Rc<std::collections::HashSet<Symbol>>,
2065 len_summaries: std::rc::Rc<HashMap<Symbol, usize>>,
2068}
2069
2070impl RichAbstractState {
2071 fn new() -> Self {
2072 RichAbstractState {
2073 intervals: AbstractState::new(),
2074 types: HashMap::new(),
2075 shapes: HashMap::new(),
2076 nullability: HashMap::new(),
2077 aliases: AliasGraph::new(),
2078 coll_vars: std::collections::HashSet::new(),
2079 fn_returns: std::rc::Rc::new(HashMap::new()),
2080 callee_globals: std::rc::Rc::new(CalleeGlobals::default()),
2081 length_def: HashMap::new(),
2082 param_colls: std::collections::HashSet::new(),
2083 scalar_def: HashMap::new(),
2084 scalar_upper: HashMap::new(),
2085 elem_upper: HashMap::new(),
2086 elem_type: HashMap::new(),
2087 scalar_lower: HashMap::new(),
2088 aot_entry_guard: false,
2089 entry_guard_lowers: Vec::new(),
2090 karr: super::karr::AffineSpace::top(),
2091 seq_vars: std::collections::HashSet::new(),
2092 seq_types: std::rc::Rc::new(std::collections::HashSet::new()),
2093 len_summaries: std::rc::Rc::new(HashMap::new()),
2094 }
2095 }
2096
2097 fn karr_forget(&mut self, sym: Symbol) {
2099 self.karr.forget(super::affine::var_index(sym));
2100 self.karr.forget(super::affine::len_index(sym));
2101 }
2102
2103 fn karr_resized(&mut self, c: Symbol) {
2107 let names = self.aliases.may_alias(c);
2108 let tainted = &self.aliases.tainted;
2109 let unknown = tainted.contains(&c);
2110 let stale: Vec<i64> = self
2111 .karr
2112 .tracked()
2113 .iter()
2114 .copied()
2115 .filter(|&d| {
2116 super::affine::len_owner(d).is_some_and(|a| {
2117 a != c && (names.contains(&a) || (unknown && tainted.contains(&a)))
2118 })
2119 })
2120 .collect();
2121 for d in stale {
2122 self.karr.forget(d);
2123 }
2124 }
2125
2126 fn karr_unknown(&mut self, sym: Symbol) {
2129 self.karr_resized(sym);
2130 self.karr_forget(sym);
2131 self.seq_vars.remove(&sym);
2132 }
2133
2134 pub(crate) fn value_of(&self, sym: Symbol) -> AbstractValue {
2136 let mut others = self.aliases.may_alias(sym);
2137 others.remove(&sym);
2138 let alias = if others.is_empty() {
2139 AliasInfo::Unique
2140 } else {
2141 AliasInfo::MayAlias(others)
2142 };
2143 AbstractValue {
2144 interval: self.intervals.get_var(&sym),
2145 ty: self
2146 .types
2147 .get(&sym)
2148 .cloned()
2149 .unwrap_or(TypeAbstraction::Top),
2150 shape: self
2151 .shapes
2152 .get(&sym)
2153 .cloned()
2154 .unwrap_or(CollectionShape::Top),
2155 nullability: self
2156 .nullability
2157 .get(&sym)
2158 .cloned()
2159 .unwrap_or(Nullability::Maybe),
2160 alias,
2161 }
2162 }
2163
2164 fn forget_callee_globals(&mut self) {
2170 let globals = self.callee_globals.clone();
2171 if globals.opaque {
2172 self.forget_everything();
2173 return;
2174 }
2175 for g in &globals.symbols {
2176 self.karr_unknown(*g);
2177 self.invalidate_var(*g);
2178 self.aliases.unlink(*g);
2179 self.intervals.set_length(*g, Interval::non_negative());
2180 self.length_def.remove(g);
2181 }
2182 }
2183
2184 fn forget_everything(&mut self) {
2187 self.intervals.forget_all();
2188 self.types.clear();
2189 self.shapes.clear();
2190 self.nullability.clear();
2191 self.aliases = AliasGraph::new();
2192 self.coll_vars.clear();
2193 self.length_def.clear();
2194 self.scalar_def.clear();
2195 self.scalar_upper.clear();
2196 self.elem_upper.clear();
2197 self.elem_type.clear();
2198 self.scalar_lower.clear();
2199 self.entry_guard_lowers.clear();
2200 self.karr = super::karr::AffineSpace::top();
2201 self.seq_vars.clear();
2202 }
2203
2204 fn forget_written(&mut self, written: &[Symbol]) {
2207 for &m in written {
2208 self.karr_unknown(m);
2209 self.invalidate_var(m);
2210 self.aliases.unlink(m);
2211 self.intervals.set_length(m, Interval::non_negative());
2212 self.length_def.remove(&m);
2213 let mi = m.index() as i64;
2214 self.scalar_def.remove(&m);
2215 self.scalar_def
2216 .retain(|_, e| !e.coefficients.contains_key(&mi));
2217 }
2218 }
2219
2220 fn invalidate_var(&mut self, sym: Symbol) {
2221 self.karr_forget(sym);
2222 self.seq_vars.remove(&sym);
2223 self.intervals.set_var(sym, Interval::top());
2224 self.types.insert(sym, TypeAbstraction::Top);
2225 self.shapes.insert(sym, CollectionShape::Top);
2226 self.nullability.insert(sym, Nullability::Maybe);
2227 self.coll_vars.remove(&sym);
2228 self.intervals.clear_elem(&sym);
2229 let si = sym.index() as i64;
2230 self.scalar_upper.remove(&sym);
2231 self.scalar_upper
2232 .retain(|_, e| !e.coefficients.contains_key(&si));
2233 self.elem_upper.remove(&sym);
2234 self.elem_upper
2235 .retain(|_, e| !e.coefficients.contains_key(&si));
2236 self.elem_type.remove(&sym);
2237 self.scalar_lower.remove(&sym);
2238 self.scalar_lower
2239 .retain(|_, e| !e.coefficients.contains_key(&si));
2240 }
2241}
2242
2243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2248pub enum ScalarKind {
2249 Int,
2250 Float,
2251 Bool,
2252 Text,
2253}
2254
2255#[derive(Clone, Debug, Default, PartialEq)]
2259pub struct VarProvenFacts {
2260 pub scalar: Option<ScalarKind>,
2262 pub int_range: Option<(i64, i64)>,
2264 pub nonneg: bool,
2266}
2267
2268#[derive(Default)]
2275pub struct OracleFacts {
2276 loop_depth: usize,
2279 exprs: HashMap<usize, AbstractValue>,
2280 lengths: HashMap<usize, Interval>,
2283 collections: std::collections::HashSet<usize>,
2286 loop_aliases: HashMap<usize, AliasGraph>,
2291 suppress_exprs: bool,
2298 relational_inbounds: std::collections::HashSet<usize>,
2305 speculative_inbounds: std::collections::HashSet<usize>,
2310 hoist_descs: HashMap<usize, Vec<HoistDesc>>,
2318 positivity_guards: HashMap<usize, Vec<Symbol>>,
2325 map_caps: HashMap<Symbol, super::affine::LinExpr>,
2332 dense_map_key_proven: HashMap<usize, Symbol>,
2337 map_insert_cover: HashMap<Symbol, (super::affine::LinExpr, super::affine::LinExpr)>,
2343 map_key_covered: HashMap<usize, Symbol>,
2347 karr_at: HashMap<usize, super::karr::AffineSpace>,
2350 return_probe: Option<Vec<(usize, Option<Symbol>, super::karr::AffineSpace)>>,
2353}
2354
2355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2358pub struct HoistDesc {
2359 pub array: Symbol,
2360 pub bound: Symbol,
2361 pub iv: Symbol,
2362 pub add_max: i32,
2363 pub add_min: i32,
2364}
2365
2366impl OracleFacts {
2367 pub fn hoist_descs_for(&self, loop_ptr: usize) -> &[HoistDesc] {
2371 self.hoist_descs
2372 .get(&loop_ptr)
2373 .map_or(&[], |v| v.as_slice())
2374 }
2375
2376 pub fn index_is_speculative(&self, index: &Expr) -> bool {
2380 self.speculative_inbounds
2381 .contains(&(index as *const Expr as usize))
2382 }
2383
2384 fn record(&mut self, e: &Expr, av: AbstractValue) {
2385 if self.suppress_exprs {
2386 return;
2387 }
2388 let key = e as *const Expr as usize;
2389 match self.exprs.get_mut(&key) {
2390 None => {
2391 self.exprs.insert(key, av);
2392 }
2393 Some(prev) => *prev = prev.join(&av),
2394 }
2395 }
2396
2397 fn record_length(&mut self, e: &Expr, len: Interval) {
2398 if self.suppress_exprs {
2399 return;
2400 }
2401 let key = e as *const Expr as usize;
2402 match self.lengths.get_mut(&key) {
2403 None => {
2404 self.lengths.insert(key, len);
2405 }
2406 Some(prev) => *prev = prev.join(&len),
2407 }
2408 }
2409
2410 pub fn expr_scalar(&self, e: &Expr) -> Option<ScalarKind> {
2412 let av = self.exprs.get(&(e as *const Expr as usize))?;
2413 match &av.ty {
2414 TypeAbstraction::Concrete(TypeTag::Int) => Some(ScalarKind::Int),
2415 TypeAbstraction::Concrete(TypeTag::Float) => Some(ScalarKind::Float),
2416 TypeAbstraction::Concrete(TypeTag::Bool) => Some(ScalarKind::Bool),
2417 TypeAbstraction::Concrete(TypeTag::Text) => Some(ScalarKind::Text),
2418 _ => None,
2419 }
2420 }
2421
2422 pub fn expr_int_range(&self, e: &Expr) -> Option<(i64, i64)> {
2425 self.expr_int_range_addr(e as *const Expr as usize)
2426 }
2427
2428 pub fn expr_proven_nonneg(&self, e: &Expr) -> bool {
2436 self.expr_proven_at_least(e, 0)
2437 }
2438
2439 pub fn expr_proven_at_least(&self, e: &Expr, k: i64) -> bool {
2442 match self.exprs.get(&(e as *const Expr as usize)) {
2443 Some(av) => matches!(av.interval.lo, Bound::Finite(v) if v >= k),
2444 None => false,
2445 }
2446 }
2447
2448 pub fn expr_int_range_addr(&self, addr: usize) -> Option<(i64, i64)> {
2451 let av = self.exprs.get(&addr)?;
2452 match (&av.interval.lo, &av.interval.hi) {
2453 (Bound::Finite(lo), Bound::Finite(hi)) if lo <= hi => Some((*lo, *hi)),
2454 _ => None,
2455 }
2456 }
2457
2458 pub fn summarize_variables(&self, stmts: &[Stmt]) -> Vec<(Symbol, VarProvenFacts)> {
2467 let mut by_sym: HashMap<Symbol, AbstractValue> = HashMap::new();
2468 collect_idents_block(stmts, &mut |sym, addr| {
2469 if let Some(av) = self.exprs.get(&addr) {
2470 match by_sym.get_mut(&sym) {
2471 None => {
2472 by_sym.insert(sym, av.clone());
2473 }
2474 Some(prev) => *prev = prev.join(av),
2475 }
2476 }
2477 });
2478 by_sym
2479 .into_iter()
2480 .map(|(sym, av)| {
2481 let int_range = match (&av.interval.lo, &av.interval.hi) {
2482 (Bound::Finite(lo), Bound::Finite(hi)) if lo <= hi => Some((*lo, *hi)),
2483 _ => None,
2484 };
2485 let scalar = match &av.ty {
2486 TypeAbstraction::Concrete(TypeTag::Int) => Some(ScalarKind::Int),
2487 TypeAbstraction::Concrete(TypeTag::Float) => Some(ScalarKind::Float),
2488 TypeAbstraction::Concrete(TypeTag::Bool) => Some(ScalarKind::Bool),
2489 TypeAbstraction::Concrete(TypeTag::Text) => Some(ScalarKind::Text),
2490 _ => None,
2491 };
2492 let nonneg = matches!(av.interval.lo, Bound::Finite(v) if v >= 0);
2493 (
2494 sym,
2495 VarProvenFacts {
2496 scalar,
2497 int_range,
2498 nonneg,
2499 },
2500 )
2501 })
2502 .collect()
2503 }
2504
2505 pub fn has_dense_map_capacity(&self, map: Symbol) -> bool {
2508 self.map_caps.contains_key(&map)
2509 }
2510
2511 pub fn map_cap_lin(&self, map: Symbol) -> Option<&super::affine::LinExpr> {
2515 self.map_caps.get(&map)
2516 }
2517
2518 pub fn dense_map_key_proven(&self, key: &Expr, map: Symbol) -> bool {
2521 self.dense_map_key_proven_addr(key as *const Expr as usize, map)
2522 }
2523
2524 pub fn dense_map_key_proven_addr(&self, key_addr: usize, map: Symbol) -> bool {
2527 self.dense_map_key_proven.get(&key_addr) == Some(&map)
2528 }
2529
2530 pub fn dense_map_has_full_coverage(&self, map: Symbol) -> bool {
2533 self.map_insert_cover.contains_key(&map)
2534 }
2535
2536 pub fn dense_key_covered_addr(&self, key_addr: usize, map: Symbol) -> bool {
2539 self.map_key_covered.get(&key_addr) == Some(&map)
2540 }
2541
2542 pub fn expr_is_tracked_collection(&self, e: &Expr) -> bool {
2546 self.collections.contains(&(e as *const Expr as usize))
2547 }
2548
2549 pub fn loop_handles_definitely_distinct(&self, loop_stmt: &Stmt, a: Symbol, b: Symbol) -> bool {
2557 let key = loop_stmt as *const Stmt as usize;
2558 match self.loop_aliases.get(&key) {
2559 Some(g) => g.definitely_distinct(a, b),
2560 None => false,
2561 }
2562 }
2563
2564 pub fn expr_len_range(&self, e: &Expr) -> Option<(i64, i64)> {
2566 let iv = self.lengths.get(&(e as *const Expr as usize))?;
2567 match (&iv.lo, &iv.hi) {
2568 (Bound::Finite(lo), Bound::Finite(hi)) if lo <= hi => Some((*lo, *hi)),
2569 _ => None,
2570 }
2571 }
2572
2573 pub fn index_proven_relational(&self, index: &Expr) -> bool {
2580 self.relational_inbounds
2581 .contains(&(index as *const Expr as usize))
2582 }
2583
2584 pub fn index_provably_in_bounds(&self, collection: &Expr, index: &Expr) -> bool {
2588 if self
2592 .relational_inbounds
2593 .contains(&(index as *const Expr as usize))
2594 {
2595 return true;
2596 }
2597 let Some(len) = self.lengths.get(&(collection as *const Expr as usize)) else {
2600 return false;
2601 };
2602 let Some((ilo, ihi)) = self.expr_int_range(index) else {
2603 return false;
2604 };
2605 let len_lo = match len.lo {
2606 Bound::Finite(v) => v,
2607 _ => return false,
2608 };
2609 ilo >= 1 && ihi <= len_lo
2610 }
2611
2612 pub fn index_positivity_guards(&self, index: &Expr) -> &[Symbol] {
2617 self.positivity_guards
2618 .get(&(index as *const Expr as usize))
2619 .map_or(&[], |v| v.as_slice())
2620 }
2621
2622 pub fn index_always_in_bounds(&self, collection: &Expr, index: &Expr) -> bool {
2627 super::facts::holds_expr(super::facts::Fact::InBounds, index)
2628 || (self.index_provably_in_bounds(collection, index)
2629 && self.index_positivity_guards(index).is_empty())
2630 }
2631}
2632
2633fn record_karr(index: &Expr, st: &RichAbstractState, facts: &mut OracleFacts) {
2636 if facts.suppress_exprs {
2637 return;
2638 }
2639 let key = index as *const Expr as usize;
2640 match facts.karr_at.entry(key) {
2641 std::collections::hash_map::Entry::Occupied(mut e) => {
2642 let joined = e.get().join(&st.karr);
2643 e.insert(joined);
2644 }
2645 std::collections::hash_map::Entry::Vacant(v) => {
2646 v.insert(st.karr.clone());
2647 }
2648 }
2649}
2650
2651fn record_expr(e: &Expr, st: &RichAbstractState, facts: &mut OracleFacts) {
2654 use crate::ast::stmt::StringPart;
2655 match e {
2656 Expr::BinaryOp { left, right, .. }
2657 | Expr::Union { left, right }
2658 | Expr::Intersection { left, right }
2659 | Expr::Range {
2660 start: left,
2661 end: right,
2662 } => {
2663 record_expr(left, st, facts);
2664 record_expr(right, st, facts);
2665 }
2666 Expr::Not { operand } => record_expr(operand, st, facts),
2667 Expr::Call { args, .. } => {
2668 for a in args {
2669 record_expr(a, st, facts);
2670 }
2671 }
2672 Expr::CallExpr { callee, args } => {
2673 record_expr(callee, st, facts);
2674 for a in args {
2675 record_expr(a, st, facts);
2676 }
2677 }
2678 Expr::Index { collection, index } => {
2679 record_expr(collection, st, facts);
2680 record_expr(index, st, facts);
2681 record_karr(index, st, facts);
2682 }
2683 Expr::Slice {
2684 collection,
2685 start,
2686 end,
2687 } => {
2688 record_expr(collection, st, facts);
2689 record_expr(start, st, facts);
2690 record_expr(end, st, facts);
2691 }
2692 Expr::Copy { expr } => record_expr(expr, st, facts),
2693 Expr::Give { value } => record_expr(value, st, facts),
2694 Expr::Length { collection } => record_expr(collection, st, facts),
2695 Expr::Contains { collection, value } => {
2696 record_expr(collection, st, facts);
2697 record_expr(value, st, facts);
2698 }
2699 Expr::List(items) | Expr::Tuple(items) => {
2700 for i in items {
2701 record_expr(i, st, facts);
2702 }
2703 }
2704 Expr::FieldAccess { object, .. } => record_expr(object, st, facts),
2705 Expr::New { init_fields, .. } => {
2706 for (_, fe) in init_fields {
2707 record_expr(fe, st, facts);
2708 }
2709 }
2710 Expr::NewVariant { fields, .. } => {
2711 for (_, fe) in fields {
2712 record_expr(fe, st, facts);
2713 }
2714 }
2715 Expr::OptionSome { value } => record_expr(value, st, facts),
2716 Expr::WithCapacity { value, capacity } => {
2717 record_expr(value, st, facts);
2718 record_expr(capacity, st, facts);
2719 }
2720 Expr::InterpolatedString(parts) => {
2721 for p in parts {
2722 if let StringPart::Expr { value, .. } = p {
2723 record_expr(value, st, facts);
2724 }
2725 }
2726 }
2727 _ => {}
2728 }
2729 let av = AbstractValue {
2730 interval: eval_expr(e, &st.intervals),
2731 ty: eval_type(e, &st.types, &st.fn_returns, &st.elem_type),
2732 shape: match e {
2733 Expr::Identifier(sym) => st.shapes.get(sym).cloned().unwrap_or(CollectionShape::Top),
2734 _ => CollectionShape::Top,
2735 },
2736 nullability: nullability_of_expr(e, st),
2737 alias: AliasInfo::top(),
2738 };
2739 facts.record(e, av);
2740 if let Expr::Identifier(sym) = e {
2741 facts.record_length(e, st.intervals.get_length(sym));
2742 if !facts.suppress_exprs && st.coll_vars.contains(sym) {
2743 facts.collections.insert(e as *const Expr as usize);
2744 }
2745 }
2746}
2747
2748fn collect_idents_block(stmts: &[Stmt], f: &mut dyn FnMut(Symbol, usize)) {
2754 for s in stmts {
2755 collect_idents_stmt(s, f);
2756 }
2757}
2758
2759fn collect_idents_stmt(stmt: &Stmt, f: &mut dyn FnMut(Symbol, usize)) {
2760 use crate::ast::stmt::ReadSource;
2761 match stmt {
2763 Stmt::Let { value, .. } | Stmt::Set { value, .. } => collect_idents_expr(value, f),
2764 Stmt::Return { value: Some(e) } => collect_idents_expr(e, f),
2765 Stmt::Call { args, .. } => {
2766 for a in args {
2767 collect_idents_expr(a, f);
2768 }
2769 }
2770 Stmt::If { cond, .. } | Stmt::While { cond, .. } => collect_idents_expr(cond, f),
2771 Stmt::Repeat { iterable, .. } => collect_idents_expr(iterable, f),
2772 Stmt::Show { object, .. } | Stmt::Give { object, .. } => collect_idents_expr(object, f),
2773 Stmt::Push { value, collection }
2774 | Stmt::Add { value, collection }
2775 | Stmt::Remove { value, collection } => {
2776 collect_idents_expr(value, f);
2777 collect_idents_expr(collection, f);
2778 }
2779 Stmt::SetIndex {
2780 collection,
2781 index,
2782 value,
2783 } => {
2784 collect_idents_expr(collection, f);
2785 collect_idents_expr(index, f);
2786 collect_idents_expr(value, f);
2787 }
2788 Stmt::SetField { object, value, .. } => {
2789 collect_idents_expr(object, f);
2790 collect_idents_expr(value, f);
2791 }
2792 Stmt::Inspect { target, .. } => collect_idents_expr(target, f),
2793 Stmt::RuntimeAssert { condition, .. } => collect_idents_expr(condition, f),
2794 Stmt::Sleep { milliseconds } => collect_idents_expr(milliseconds, f),
2795 Stmt::ReadFrom {
2796 source: ReadSource::File(p),
2797 ..
2798 } => collect_idents_expr(p, f),
2799 _ => {}
2800 }
2801 match stmt {
2803 Stmt::If {
2804 then_block,
2805 else_block,
2806 ..
2807 } => {
2808 collect_idents_block(then_block, f);
2809 if let Some(eb) = else_block {
2810 collect_idents_block(eb, f);
2811 }
2812 }
2813 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => collect_idents_block(body, f),
2814 Stmt::FunctionDef { body, .. } => collect_idents_block(body, f),
2815 Stmt::Inspect { arms, .. } => {
2816 for arm in arms {
2817 collect_idents_block(arm.body, f);
2818 }
2819 }
2820 Stmt::Zone { body, .. } => collect_idents_block(body, f),
2821 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => collect_idents_block(tasks, f),
2822 _ => {}
2823 }
2824}
2825
2826fn collect_idents_expr(e: &Expr, f: &mut dyn FnMut(Symbol, usize)) {
2827 use crate::ast::stmt::StringPart;
2828 if let Expr::Identifier(sym) = e {
2829 f(*sym, e as *const Expr as usize);
2830 }
2831 match e {
2832 Expr::BinaryOp { left, right, .. }
2833 | Expr::Union { left, right }
2834 | Expr::Intersection { left, right }
2835 | Expr::Range {
2836 start: left,
2837 end: right,
2838 } => {
2839 collect_idents_expr(left, f);
2840 collect_idents_expr(right, f);
2841 }
2842 Expr::Not { operand } => collect_idents_expr(operand, f),
2843 Expr::Call { args, .. } => {
2844 for a in args {
2845 collect_idents_expr(a, f);
2846 }
2847 }
2848 Expr::CallExpr { callee, args } => {
2849 collect_idents_expr(callee, f);
2850 for a in args {
2851 collect_idents_expr(a, f);
2852 }
2853 }
2854 Expr::Index { collection, index } => {
2855 collect_idents_expr(collection, f);
2856 collect_idents_expr(index, f);
2857 }
2858 Expr::Slice {
2859 collection,
2860 start,
2861 end,
2862 } => {
2863 collect_idents_expr(collection, f);
2864 collect_idents_expr(start, f);
2865 collect_idents_expr(end, f);
2866 }
2867 Expr::Copy { expr } => collect_idents_expr(expr, f),
2868 Expr::Give { value } => collect_idents_expr(value, f),
2869 Expr::Length { collection } => collect_idents_expr(collection, f),
2870 Expr::Contains { collection, value } => {
2871 collect_idents_expr(collection, f);
2872 collect_idents_expr(value, f);
2873 }
2874 Expr::List(items) | Expr::Tuple(items) => {
2875 for i in items {
2876 collect_idents_expr(i, f);
2877 }
2878 }
2879 Expr::FieldAccess { object, .. } => collect_idents_expr(object, f),
2880 Expr::New { init_fields, .. } => {
2881 for (_, fe) in init_fields {
2882 collect_idents_expr(fe, f);
2883 }
2884 }
2885 Expr::NewVariant { fields, .. } => {
2886 for (_, fe) in fields {
2887 collect_idents_expr(fe, f);
2888 }
2889 }
2890 Expr::OptionSome { value } => collect_idents_expr(value, f),
2891 Expr::WithCapacity { value, capacity } => {
2892 collect_idents_expr(value, f);
2893 collect_idents_expr(capacity, f);
2894 }
2895 Expr::InterpolatedString(parts) => {
2896 for p in parts {
2897 if let StringPart::Expr { value, .. } = p {
2898 collect_idents_expr(value, f);
2899 }
2900 }
2901 }
2902 _ => {}
2903 }
2904}
2905
2906enum IvBound {
2908 LenOf(Symbol),
2910 Var { var: Symbol, headroom: i64 },
2916}
2917
2918struct IvGuard {
2920 iv: Symbol,
2921 bound: IvBound,
2922 strict: bool,
2924 iv_lo: i64,
2926}
2927
2928fn record_loop_index_bounds(
2940 cond: &Expr,
2941 body: &[Stmt],
2942 state: &RichAbstractState,
2943 facts: &mut OracleFacts,
2944) {
2945 let mut guards: Vec<IvGuard> = Vec::new();
2946 collect_iv_guards(cond, state, &mut guards);
2947 if guards.is_empty() {
2948 return;
2949 }
2950 if !body_is_index_proof_safe(body) {
2955 return;
2956 }
2957 let mut clobbered: std::collections::HashSet<Symbol> = std::collections::HashSet::new();
2958 collect_resized_arrays(body, &mut clobbered);
2959 record_proven_reads(
2960 body,
2961 &guards,
2962 &state.length_def,
2963 &mut clobbered,
2964 facts,
2965 &state.callee_globals,
2966 );
2967}
2968
2969#[derive(Default, Clone)]
2991struct AffineFacts {
2992 constraints: Vec<super::affine::Constraint>,
2993 syms: Vec<Symbol>,
2994 lengths: std::rc::Rc<HashSet<Symbol>>,
2997 karr_pass: bool,
3001}
3002
3003fn record_affine_index_bounds(
3004 cond: &Expr,
3005 body: &[Stmt],
3006 state: &RichAbstractState,
3007 entry: &RichAbstractState,
3008 facts: &mut OracleFacts,
3009 karr_pass: bool,
3010) {
3011 if !body_is_index_proof_safe(body) {
3012 return;
3013 }
3014 let mut clobbered: std::collections::HashSet<Symbol> = std::collections::HashSet::new();
3015 collect_resized_arrays(body, &mut clobbered);
3016 let mutated: std::collections::HashSet<Symbol> =
3017 collect_mutations_in(body, &state.callee_globals)
3018 .into_iter()
3019 .collect();
3020 let state = {
3027 let mut st = state.clone();
3028 if st.entry_guard_lowers.is_empty() {
3032 st.entry_guard_lowers = entry.entry_guard_lowers.clone();
3033 }
3034 augment_body_scalar_defs(body, &mut st);
3035 st
3036 };
3037 let inits: HashMap<Symbol, i64> = HashMap::new();
3038 let mut amb = AffineFacts {
3039 lengths: std::rc::Rc::new(
3040 state
3041 .seq_vars
3042 .iter()
3043 .copied()
3044 .filter(|c| !clobbered.contains(c) && !mutated.contains(c))
3045 .collect(),
3046 ),
3047 karr_pass,
3048 ..AffineFacts::default()
3049 };
3050 affine_add_loop_guards(cond, body, &state, Some(entry), &inits, &mut amb);
3051 affine_walk(
3052 body, body, &state, &clobbered, &mutated, &amb, &inits, facts,
3053 );
3054}
3055
3056fn augment_body_scalar_defs(body: &[Stmt], st: &mut RichAbstractState) {
3063 let reassigned = reassigned_scalars(body, &st.callee_globals);
3066 let mut let_count: HashMap<Symbol, u32> = HashMap::new();
3068 for s in body {
3069 if let Stmt::Let { var, .. } = s {
3070 *let_count.entry(*var).or_insert(0) += 1;
3071 }
3072 }
3073 for s in body {
3074 if let Stmt::Let { var, value, .. } = s {
3075 if reassigned.contains(var)
3076 || let_count.get(var) != Some(&1)
3077 || st.scalar_def.contains_key(var)
3078 {
3079 continue;
3080 }
3081 if let Some(e) = super::affine::lin_of(value) {
3082 let rhs_stable = e.coefficients.keys().all(|&i| {
3088 let s = Symbol::from_index(i as usize);
3089 !reassigned.contains(&s) && let_count.get(&s).map_or(true, |&c| c <= 1)
3090 });
3091 if rhs_stable
3092 && !e.coefficients.is_empty()
3093 && !e.coefficients.contains_key(&(var.index() as i64))
3094 {
3095 st.scalar_def.insert(*var, e);
3096 }
3097 }
3098 }
3099 }
3100}
3101
3102fn reassigned_scalars(body: &[Stmt], globals: &CalleeGlobals) -> std::collections::HashSet<Symbol> {
3106 let writes = WriteSet::of_block(body).with_callee_globals(globals);
3107 if writes.is_opaque() {
3108 return collect_mutations_in(body, globals).into_iter().collect();
3109 }
3110 writes.assigned().clone()
3111}
3112
3113fn affine_cmp(
3116 op: BinaryOpKind,
3117 a: &Expr,
3118 b: &Expr,
3119 negate: bool,
3120 lengths: &HashSet<Symbol>,
3121) -> Option<super::affine::Constraint> {
3122 use super::affine::{ge, gt, le, lin_of_with_lengths, lt};
3123 let fixed = |c: Symbol| lengths.contains(&c);
3124 let (la, lb) = (
3125 lin_of_with_lengths(a, &fixed)?,
3126 lin_of_with_lengths(b, &fixed)?,
3127 );
3128 Some(match (op, negate) {
3129 (BinaryOpKind::Lt, false) | (BinaryOpKind::GtEq, true) => lt(&la, &lb),
3130 (BinaryOpKind::LtEq, false) | (BinaryOpKind::Gt, true) => le(&la, &lb),
3131 (BinaryOpKind::Gt, false) | (BinaryOpKind::LtEq, true) => gt(&la, &lb),
3132 (BinaryOpKind::GtEq, false) | (BinaryOpKind::Lt, true) => ge(&la, &lb),
3133 _ => return None,
3134 })
3135}
3136
3137fn affine_add_cmp(cond: &Expr, negate: bool, out: &mut AffineFacts) {
3141 match cond {
3142 Expr::BinaryOp {
3143 op: BinaryOpKind::And,
3144 left,
3145 right,
3146 } if !negate => {
3147 affine_add_cmp(left, false, out);
3148 affine_add_cmp(right, false, out);
3149 }
3150 Expr::BinaryOp {
3151 op: op @ (BinaryOpKind::Lt | BinaryOpKind::LtEq | BinaryOpKind::Gt | BinaryOpKind::GtEq),
3152 left,
3153 right,
3154 } => {
3155 if let Some(c) = affine_cmp(*op, left, right, negate, &out.lengths) {
3156 out.constraints.push(c);
3157 affine_collect_syms(left, &mut out.syms);
3158 affine_collect_syms(right, &mut out.syms);
3159 }
3160 }
3161 _ => {}
3162 }
3163}
3164
3165fn affine_collect_syms(e: &Expr, out: &mut Vec<Symbol>) {
3167 match e {
3168 Expr::Identifier(s) => {
3169 if !out.contains(s) {
3170 out.push(*s);
3171 }
3172 }
3173 Expr::BinaryOp { left, right, .. } => {
3174 affine_collect_syms(left, out);
3175 affine_collect_syms(right, out);
3176 }
3177 _ => {}
3178 }
3179}
3180
3181fn write_keeps_ge(
3187 value: &Expr,
3188 iv: Symbol,
3189 lo: i64,
3190 state: &RichAbstractState,
3191 mutated: &std::collections::HashSet<Symbol>,
3192) -> bool {
3193 match value {
3194 Expr::BinaryOp {
3195 op: BinaryOpKind::Add,
3196 left,
3197 right,
3198 } => {
3199 let is_iv = |e: &&Expr| matches!(e, Expr::Identifier(s) if *s == iv);
3200 let nonneg = |e: &&Expr| matches!(e, Expr::Literal(Literal::Number(n)) if *n >= 0);
3201 (is_iv(&left) && nonneg(&right)) || (nonneg(&left) && is_iv(&right))
3202 }
3203 Expr::Literal(Literal::Number(n)) => *n >= lo,
3204 Expr::Identifier(s) if !mutated.contains(s) => {
3205 matches!(state.intervals.get_var(s).lo, Bound::Finite(l) if l >= lo)
3206 }
3207 _ => false,
3208 }
3209}
3210
3211fn iv_lower_bound(
3220 iv: Symbol,
3221 body: &[Stmt],
3222 state: &RichAbstractState,
3223 mutated: &std::collections::HashSet<Symbol>,
3224 inits: &HashMap<Symbol, i64>,
3225) -> Option<i64> {
3226 let lo = match inits.get(&iv) {
3227 Some(c) => *c,
3228 None => match state.intervals.get_var(&iv).lo {
3229 Bound::Finite(l) => l,
3230 _ => return None,
3231 },
3232 };
3233 fn preserved(
3234 iv: Symbol,
3235 stmts: &[Stmt],
3236 lo: i64,
3237 state: &RichAbstractState,
3238 mutated: &std::collections::HashSet<Symbol>,
3239 ) -> bool {
3240 stmts.iter().all(|s| match s {
3241 Stmt::Set { target, value } if *target == iv => {
3242 write_keeps_ge(value, iv, lo, state, mutated)
3243 }
3244 Stmt::Let { var, value, .. } if *var == iv => {
3245 write_keeps_ge(value, iv, lo, state, mutated)
3246 }
3247 Stmt::If {
3248 then_block,
3249 else_block,
3250 ..
3251 } => {
3252 preserved(iv, then_block, lo, state, mutated)
3253 && else_block.map_or(true, |eb| preserved(iv, eb, lo, state, mutated))
3254 }
3255 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
3256 preserved(iv, body, lo, state, mutated)
3257 }
3258 _ => true,
3259 })
3260 }
3261 preserved(iv, body, lo, state, mutated).then_some(lo)
3262}
3263
3264pub(crate) fn self_increment(v: Symbol, value: &Expr) -> Option<i64> {
3270 if let Expr::BinaryOp {
3271 op: BinaryOpKind::Add,
3272 left,
3273 right,
3274 } = value
3275 {
3276 if let (Expr::Identifier(s), Expr::Literal(Literal::Number(c))) = (&**left, &**right) {
3277 if *s == v {
3278 return Some(*c);
3279 }
3280 }
3281 if let (Expr::Literal(Literal::Number(c)), Expr::Identifier(s)) = (&**left, &**right) {
3282 if *s == v {
3283 return Some(*c);
3284 }
3285 }
3286 }
3287 None
3288}
3289
3290pub(crate) fn self_decrement(v: Symbol, value: &Expr) -> Option<i64> {
3293 if let Expr::BinaryOp {
3294 op: BinaryOpKind::Subtract,
3295 left,
3296 right,
3297 } = value
3298 {
3299 if let (Expr::Identifier(s), Expr::Literal(Literal::Number(c))) = (&**left, &**right) {
3300 if *s == v && *c >= 0 {
3301 return Some(*c);
3302 }
3303 }
3304 }
3305 None
3306}
3307
3308fn top_level_unconditional_incs(body: &[Stmt], globals: &CalleeGlobals) -> Vec<(Symbol, i64)> {
3312 let mut out = Vec::new();
3313 for s in body {
3314 if let Stmt::Set { target, value } = s {
3315 if let Some(c) = self_increment(*target, value) {
3316 if c > 0 && count_writes_of(body, *target, globals) == 1 {
3317 out.push((*target, c));
3318 }
3319 }
3320 }
3321 }
3322 out
3323}
3324
3325fn monotone_inc_within(
3329 stmts: &[Stmt],
3330 v: Symbol,
3331 in_loop: bool,
3332 total: &mut i64,
3333 count: &mut usize,
3334) -> bool {
3335 for s in stmts {
3336 match s {
3337 Stmt::Set { target, value } if *target == v => match self_increment(v, value) {
3338 Some(c) if c >= 0 && !in_loop => {
3339 *total += c;
3340 *count += 1;
3341 }
3342 _ => return false,
3343 },
3344 Stmt::Let { var, .. } if *var == v => return false,
3345 Stmt::If {
3346 then_block,
3347 else_block,
3348 ..
3349 } => {
3350 if !monotone_inc_within(then_block, v, in_loop, total, count) {
3351 return false;
3352 }
3353 if let Some(eb) = else_block {
3354 if !monotone_inc_within(eb, v, in_loop, total, count) {
3355 return false;
3356 }
3357 }
3358 }
3359 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
3360 if !monotone_inc_within(body, v, true, total, count) {
3361 return false;
3362 }
3363 }
3364 _ => {}
3365 }
3366 }
3367 true
3368}
3369
3370fn monotone_inc_vars(body: &[Stmt], limit: i64) -> Vec<Symbol> {
3373 let mut cands: Vec<Symbol> = Vec::new();
3374 fn collect(stmts: &[Stmt], out: &mut Vec<Symbol>) {
3375 for s in stmts {
3376 match s {
3377 Stmt::Set { target, value } if self_increment(*target, value).is_some() => {
3378 if !out.contains(target) {
3379 out.push(*target);
3380 }
3381 }
3382 Stmt::If {
3383 then_block,
3384 else_block,
3385 ..
3386 } => {
3387 collect(then_block, out);
3388 if let Some(eb) = else_block {
3389 collect(eb, out);
3390 }
3391 }
3392 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => collect(body, out),
3393 _ => {}
3394 }
3395 }
3396 }
3397 collect(body, &mut cands);
3398 cands
3399 .into_iter()
3400 .filter(|v| {
3401 let (mut total, mut count) = (0, 0);
3402 monotone_inc_within(body, *v, false, &mut total, &mut count)
3403 && count >= 1
3404 && total <= limit
3405 })
3406 .collect()
3407}
3408
3409fn derive_iv_le_invariants(
3419 body: &[Stmt],
3420 entry: &RichAbstractState,
3421 state: &RichAbstractState,
3422 mutated: &std::collections::HashSet<Symbol>,
3423 inits: &HashMap<Symbol, i64>,
3424 amb: &mut AffineFacts,
3425) {
3426 use super::affine::{ge, konst, le, var};
3427 for (j, dj) in top_level_unconditional_incs(body, &entry.callee_globals) {
3428 for i in monotone_inc_vars(body, dj) {
3429 if i == j {
3430 continue;
3431 }
3432 let equal_start = match (entry.scalar_def.get(&i), entry.scalar_def.get(&j)) {
3435 (Some(a), Some(b)) => a == b,
3436 _ => false,
3437 };
3438 if !equal_start {
3439 continue;
3440 }
3441 amb.constraints.push(le(&var(i), &var(j)));
3442 if let Some(lo) = iv_lower_bound(i, body, state, mutated, inits) {
3445 amb.constraints.push(ge(&var(i), &konst(lo)));
3446 }
3447 if let Some(u) = entry.scalar_def.get(&i) {
3458 amb.constraints.push(ge(&var(i), u));
3459 amb.constraints.push(ge(&var(j), u));
3460 for &si in u.coefficients.keys() {
3461 let s = Symbol::from_index(si as usize);
3462 if !amb.syms.contains(&s) {
3463 amb.syms.push(s);
3464 }
3465 }
3466 }
3467 for s in [i, j] {
3468 if !amb.syms.contains(&s) {
3469 amb.syms.push(s);
3470 }
3471 }
3472 }
3473 }
3474}
3475
3476fn affine_add_loop_guards(
3477 cond: &Expr,
3478 body: &[Stmt],
3479 state: &RichAbstractState,
3480 entry: Option<&RichAbstractState>,
3481 inits: &HashMap<Symbol, i64>,
3482 amb: &mut AffineFacts,
3483) {
3484 affine_add_cmp(cond, false, amb);
3485 let mutated: std::collections::HashSet<Symbol> =
3486 collect_mutations_in(body, &state.callee_globals)
3487 .into_iter()
3488 .collect();
3489 let mut ivs: Vec<Symbol> = Vec::new();
3490 affine_collect_syms(cond, &mut ivs);
3491 for iv in ivs {
3492 if let Some(lo) = iv_lower_bound(iv, body, state, &mutated, inits) {
3493 amb.constraints.push(super::affine::ge(
3494 &super::affine::var(iv),
3495 &super::affine::konst(lo),
3496 ));
3497 if !amb.syms.contains(&iv) {
3498 amb.syms.push(iv);
3499 }
3500 }
3501 }
3502 if let Some(entry) = entry {
3506 derive_iv_le_invariants(body, entry, state, &mutated, inits, amb);
3507 derive_monotone_dec_invariants(body, entry, &mutated, amb);
3508 }
3509}
3510
3511fn derive_monotone_dec_invariants(
3521 body: &[Stmt],
3522 entry: &RichAbstractState,
3523 mutated: &std::collections::HashSet<Symbol>,
3524 amb: &mut AffineFacts,
3525) {
3526 use super::affine::{le, var};
3527 for s in body {
3528 if let Stmt::Set { target, value } = s {
3529 if self_decrement(*target, value).is_some()
3530 && count_writes_of(body, *target, &entry.callee_globals) == 1
3531 {
3532 if let Some(e0) = entry.scalar_def.get(target) {
3533 let e0_stable = e0
3534 .coefficients
3535 .keys()
3536 .all(|&si| !mutated.contains(&Symbol::from_index(si as usize)));
3537 if e0_stable {
3538 amb.constraints.push(le(&var(*target), e0));
3539 for &si in e0.coefficients.keys() {
3540 let sym = Symbol::from_index(si as usize);
3541 if !amb.syms.contains(&sym) {
3542 amb.syms.push(sym);
3543 }
3544 }
3545 if !amb.syms.contains(target) {
3546 amb.syms.push(*target);
3547 }
3548 }
3549 }
3550 }
3551 }
3552 }
3553}
3554
3555fn affine_drop_mentioning(amb: &mut AffineFacts, set: &std::collections::HashSet<Symbol>) {
3559 amb.constraints.retain(|c| {
3560 !set.iter()
3561 .any(|s| c.expr.coefficients.contains_key(&(s.index() as i64)))
3562 });
3563 amb.syms.retain(|s| !set.contains(s));
3564}
3565
3566fn affine_drop_one(amb: &mut AffineFacts, sym: Symbol) {
3567 let k = sym.index() as i64;
3568 amb.constraints
3569 .retain(|c| !c.expr.coefficients.contains_key(&k));
3570 amb.syms.retain(|s| *s != sym);
3571}
3572
3573fn affine_prove_in_expr(
3576 e: &Expr,
3577 body: &[Stmt],
3578 state: &RichAbstractState,
3579 clobbered: &std::collections::HashSet<Symbol>,
3580 mutated: &std::collections::HashSet<Symbol>,
3581 amb: &AffineFacts,
3582 facts: &mut OracleFacts,
3583) {
3584 if let Expr::Index { collection, index } = e {
3585 if amb.karr_pass {
3586 try_prove_affine_karr(collection, index, state, mutated, amb, facts);
3587 } else {
3588 if let Expr::Identifier(m) = collection {
3590 if facts.map_caps.contains_key(m) {
3591 try_prove_dense_key(*m, index, state, mutated, amb, facts);
3592 }
3593 }
3594 try_prove_affine(
3595 collection, index, body, state, clobbered, mutated, amb, facts,
3596 );
3597 }
3598 }
3599 if let (Expr::Contains { collection, value }, false) = (e, amb.karr_pass) {
3601 if let Expr::Identifier(m) = collection {
3602 if facts.map_caps.contains_key(m) {
3603 try_prove_dense_key(*m, value, state, mutated, amb, facts);
3604 }
3605 }
3606 }
3607 match e {
3608 Expr::BinaryOp { left, right, .. }
3609 | Expr::Union { left, right }
3610 | Expr::Intersection { left, right }
3611 | Expr::Range {
3612 start: left,
3613 end: right,
3614 } => {
3615 affine_prove_in_expr(left, body, state, clobbered, mutated, amb, facts);
3616 affine_prove_in_expr(right, body, state, clobbered, mutated, amb, facts);
3617 }
3618 Expr::Not { operand } => {
3619 affine_prove_in_expr(operand, body, state, clobbered, mutated, amb, facts)
3620 }
3621 Expr::Contains { collection, value } => {
3622 affine_prove_in_expr(collection, body, state, clobbered, mutated, amb, facts);
3623 affine_prove_in_expr(value, body, state, clobbered, mutated, amb, facts);
3624 }
3625 Expr::Index { collection, index } => {
3626 affine_prove_in_expr(collection, body, state, clobbered, mutated, amb, facts);
3627 affine_prove_in_expr(index, body, state, clobbered, mutated, amb, facts);
3628 }
3629 Expr::Call { args, .. } => {
3630 for a in args {
3631 affine_prove_in_expr(a, body, state, clobbered, mutated, amb, facts);
3632 }
3633 }
3634 Expr::Length { collection } => {
3635 affine_prove_in_expr(collection, body, state, clobbered, mutated, amb, facts)
3636 }
3637 _ => {}
3638 }
3639}
3640
3641fn affine_length_lb(
3644 arr: Symbol,
3645 state: &RichAbstractState,
3646) -> Option<(super::affine::LinExpr, Vec<Symbol>)> {
3647 use super::affine::{konst, var};
3648 if let Some((n, off)) = state.length_def.get(&arr) {
3649 return Some((var(*n).add(&konst(*off)), vec![*n]));
3650 }
3651 if let Bound::Finite(l) = state.intervals.get_length(&arr).lo {
3652 return Some((konst(l), vec![]));
3653 }
3654 None
3655}
3656
3657fn affine_walk(
3660 stmts: &[Stmt],
3661 full_body: &[Stmt],
3662 state: &RichAbstractState,
3663 clobbered: &std::collections::HashSet<Symbol>,
3664 mutated: &std::collections::HashSet<Symbol>,
3665 ambient: &AffineFacts,
3666 inits: &HashMap<Symbol, i64>,
3667 facts: &mut OracleFacts,
3668) {
3669 let mut local = ambient.clone();
3670 let mut inits = inits.clone();
3671 for stmt in stmts {
3672 for_each_direct_expr(stmt, &mut |e| {
3673 affine_prove_in_expr(e, full_body, state, clobbered, mutated, &local, facts);
3674 });
3675 if let Stmt::SetIndex {
3676 collection, index, ..
3677 } = stmt
3678 {
3679 if local.karr_pass {
3680 try_prove_affine_karr(collection, index, state, mutated, &local, facts);
3681 } else {
3682 if let Expr::Identifier(m) = collection {
3685 if facts.map_caps.contains_key(m) {
3686 try_prove_dense_key(*m, index, state, mutated, &local, facts);
3687 }
3688 }
3689 try_prove_affine(
3690 collection, index, full_body, state, clobbered, mutated, &local, facts,
3691 );
3692 }
3693 }
3694 match stmt {
3695 Stmt::If {
3696 cond,
3697 then_block,
3698 else_block,
3699 } => {
3700 let mut then_facts = local.clone();
3701 affine_add_cmp(cond, false, &mut then_facts);
3702 affine_walk(
3703 then_block,
3704 full_body,
3705 state,
3706 clobbered,
3707 mutated,
3708 &then_facts,
3709 &inits,
3710 facts,
3711 );
3712 if let Some(eb) = else_block {
3713 let mut else_facts = local.clone();
3714 affine_add_cmp(cond, true, &mut else_facts);
3715 affine_walk(
3716 eb,
3717 full_body,
3718 state,
3719 clobbered,
3720 mutated,
3721 &else_facts,
3722 &inits,
3723 facts,
3724 );
3725 }
3726 }
3727 Stmt::While { cond, body, .. } => {
3728 let nested: std::collections::HashSet<Symbol> =
3732 collect_mutations_in(body, &state.callee_globals)
3733 .into_iter()
3734 .collect();
3735 let mut inner = local.clone();
3736 affine_drop_mentioning(&mut inner, &nested);
3737 affine_add_loop_guards(cond, body, state, None, &inits, &mut inner);
3738 affine_walk(
3739 body, full_body, state, clobbered, mutated, &inner, &inits, facts,
3740 );
3741 }
3742 Stmt::Repeat { body, .. } => {
3743 affine_walk(
3744 body, full_body, state, clobbered, mutated, &local, &inits, facts,
3745 );
3746 }
3747 _ => {}
3748 }
3749 match stmt {
3753 Stmt::Set { target, value } => {
3754 if let Expr::Literal(Literal::Number(n)) = value {
3755 inits.insert(*target, *n);
3756 } else {
3757 inits.remove(target);
3758 }
3759 affine_drop_one(&mut local, *target);
3760 }
3761 Stmt::Let { var, value, .. } => {
3762 if let Expr::Literal(Literal::Number(n)) = value {
3763 inits.insert(*var, *n);
3764 } else {
3765 inits.remove(var);
3766 }
3767 affine_drop_one(&mut local, *var);
3768 }
3769 _ => {}
3770 }
3771 }
3772}
3773
3774fn prove_toplevel_accesses(
3783 stmt: &Stmt,
3784 body: &[Stmt],
3785 st: &RichAbstractState,
3786 clobbered: &std::collections::HashSet<Symbol>,
3787 mutated: &std::collections::HashSet<Symbol>,
3788 facts: &mut OracleFacts,
3789) {
3790 let amb = AffineFacts::default();
3791 for_each_direct_expr(stmt, &mut |e| {
3792 affine_prove_in_expr(e, body, st, clobbered, mutated, &amb, facts);
3793 });
3794 if let Stmt::SetIndex {
3795 collection, index, ..
3796 } = stmt
3797 {
3798 try_prove_affine(collection, index, body, st, clobbered, mutated, &amb, facts);
3799 }
3800}
3801
3802fn value_ge_lo(
3815 value: &Expr,
3816 lo: i64,
3817 body: &[Stmt],
3818 state: &RichAbstractState,
3819 mutated: &std::collections::HashSet<Symbol>,
3820 assumed: &std::collections::HashSet<Symbol>,
3821 fuel: u32,
3822) -> bool {
3823 if fuel == 0 {
3824 return false;
3825 }
3826 match value {
3827 Expr::Literal(Literal::Number(n)) => *n >= lo,
3828 Expr::Identifier(s) => {
3829 if assumed.contains(s) {
3830 return true;
3831 }
3832 if !mutated.contains(s) {
3833 if matches!(state.intervals.get_var(s).lo, Bound::Finite(l) if l >= lo) {
3834 return true;
3835 }
3836 }
3837 if state
3838 .entry_guard_lowers
3839 .iter()
3840 .any(|(g, l)| g == s && *l >= lo)
3841 {
3842 return true;
3843 }
3844 let mut a2 = assumed.clone();
3845 a2.insert(*s);
3846 sym_ge_lo(*s, lo, body, state, mutated, &a2, fuel - 1)
3847 }
3848 Expr::BinaryOp {
3849 op: BinaryOpKind::Add,
3850 left,
3851 right,
3852 } => {
3853 (value_ge_lo(left, lo, body, state, mutated, assumed, fuel - 1)
3854 && value_ge_lo(right, 0, body, state, mutated, assumed, fuel - 1))
3855 || (value_ge_lo(left, 0, body, state, mutated, assumed, fuel - 1)
3856 && value_ge_lo(right, lo, body, state, mutated, assumed, fuel - 1))
3857 }
3858 Expr::BinaryOp {
3860 op: BinaryOpKind::Multiply,
3861 left,
3862 right,
3863 } => {
3864 lo <= 0
3865 && value_ge_lo(left, 0, body, state, mutated, assumed, fuel - 1)
3866 && value_ge_lo(right, 0, body, state, mutated, assumed, fuel - 1)
3867 }
3868 _ => false,
3869 }
3870}
3871
3872fn sym_ge_lo(
3875 sym: Symbol,
3876 lo: i64,
3877 body: &[Stmt],
3878 state: &RichAbstractState,
3879 mutated: &std::collections::HashSet<Symbol>,
3880 assumed: &std::collections::HashSet<Symbol>,
3881 fuel: u32,
3882) -> bool {
3883 if fuel == 0 {
3884 return false;
3885 }
3886 fn walk(
3887 sym: Symbol,
3888 stmts: &[Stmt],
3889 lo: i64,
3890 body: &[Stmt],
3891 state: &RichAbstractState,
3892 mutated: &std::collections::HashSet<Symbol>,
3893 assumed: &std::collections::HashSet<Symbol>,
3894 fuel: u32,
3895 seen: &mut bool,
3896 ) -> bool {
3897 stmts.iter().all(|s| match s {
3898 Stmt::Set { target, value } if *target == sym => {
3899 *seen = true;
3900 value_ge_lo(value, lo, body, state, mutated, assumed, fuel)
3901 }
3902 Stmt::Let { var, value, .. } if *var == sym => {
3903 *seen = true;
3904 value_ge_lo(value, lo, body, state, mutated, assumed, fuel)
3905 }
3906 Stmt::If {
3907 then_block,
3908 else_block,
3909 ..
3910 } => {
3911 walk(
3912 sym, then_block, lo, body, state, mutated, assumed, fuel, seen,
3913 ) && else_block.map_or(true, |eb| {
3914 walk(sym, eb, lo, body, state, mutated, assumed, fuel, seen)
3915 })
3916 }
3917 Stmt::While { body: b, .. } | Stmt::Repeat { body: b, .. } => {
3918 walk(sym, b, lo, body, state, mutated, assumed, fuel, seen)
3919 }
3920 _ => true,
3921 })
3922 }
3923 let mut seen = false;
3924 let ok = walk(
3925 sym, body, lo, body, state, mutated, assumed, fuel, &mut seen,
3926 );
3927 ok && seen
3928}
3929
3930fn prove_le_bound(
3936 value: &Expr,
3937 bound_sym: Symbol,
3938 base: &[super::affine::Constraint],
3939 path: &[(&Expr, bool)],
3940 state: &RichAbstractState,
3941 local_defs: &HashMap<Symbol, super::affine::LinExpr>,
3942) -> bool {
3943 use super::affine::{consistent, le, lin_of, prove, var};
3944 let Some(v_lin) = lin_of(value) else {
3945 return false;
3946 };
3947 let mut facts = AffineFacts {
3948 constraints: base.to_vec(),
3949 ..AffineFacts::default()
3950 };
3951 for &(c, neg) in path {
3952 affine_add_cmp(c, neg, &mut facts);
3953 }
3954 let mut vsyms = Vec::new();
3955 affine_collect_syms(value, &mut vsyms);
3956 for s in vsyms {
3957 if let Some(def) = state.scalar_def.get(&s).or_else(|| local_defs.get(&s)) {
3964 facts.constraints.push(le(&var(s), def));
3965 facts.constraints.push(le(def, &var(s)));
3966 }
3967 }
3968 consistent(&facts.constraints) && prove(&facts.constraints, &var(bound_sym).sub(&v_lin))
3969}
3970
3971fn collect_local_affine_defs(
3976 body: &[Stmt],
3977 globals: &CalleeGlobals,
3978) -> HashMap<Symbol, super::affine::LinExpr> {
3979 let set_targets = reassigned_scalars(body, globals);
3980 let mut let_count: HashMap<Symbol, u32> = HashMap::new();
3981 fn count(stmts: &[Stmt], lc: &mut HashMap<Symbol, u32>) {
3982 for s in stmts {
3983 match s {
3984 Stmt::Let { var, .. } => *lc.entry(*var).or_insert(0) += 1,
3985 Stmt::If {
3986 then_block,
3987 else_block,
3988 ..
3989 } => {
3990 count(then_block, lc);
3991 if let Some(e) = else_block {
3992 count(e, lc);
3993 }
3994 }
3995 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => count(body, lc),
3996 _ => {}
3997 }
3998 }
3999 }
4000 count(body, &mut let_count);
4001 let mut defs: HashMap<Symbol, super::affine::LinExpr> = HashMap::new();
4002 fn walk(
4003 stmts: &[Stmt],
4004 set_targets: &std::collections::HashSet<Symbol>,
4005 let_count: &HashMap<Symbol, u32>,
4006 defs: &mut HashMap<Symbol, super::affine::LinExpr>,
4007 ) {
4008 for s in stmts {
4009 match s {
4010 Stmt::Let { var, value, .. }
4011 if !set_targets.contains(var) && let_count.get(var) == Some(&1) =>
4012 {
4013 if let Some(e) = super::affine::lin_of(value) {
4014 if !e.coefficients.is_empty()
4015 && !e.coefficients.contains_key(&(var.index() as i64))
4016 {
4017 defs.insert(*var, e);
4018 }
4019 }
4020 }
4021 Stmt::If {
4022 then_block,
4023 else_block,
4024 ..
4025 } => {
4026 walk(then_block, set_targets, let_count, defs);
4027 if let Some(e) = else_block {
4028 walk(e, set_targets, let_count, defs);
4029 }
4030 }
4031 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
4032 walk(body, set_targets, let_count, defs)
4033 }
4034 _ => {}
4035 }
4036 }
4037 }
4038 walk(body, &set_targets, &let_count, &mut defs);
4039 defs
4040}
4041
4042fn sym_le_sym(
4048 s: Symbol,
4049 bound_sym: Symbol,
4050 body: &[Stmt],
4051 base: &[super::affine::Constraint],
4052 state: &RichAbstractState,
4053) -> bool {
4054 #[allow(clippy::too_many_arguments)]
4055 fn walk<'a>(
4056 s: Symbol,
4057 stmts: &'a [Stmt<'a>],
4058 bound_sym: Symbol,
4059 base: &[super::affine::Constraint],
4060 state: &RichAbstractState,
4061 local_defs: &HashMap<Symbol, super::affine::LinExpr>,
4062 path: &mut Vec<(&'a Expr<'a>, bool)>,
4063 seen: &mut bool,
4064 fuel: &mut u32,
4065 ) -> bool {
4066 if *fuel == 0 {
4067 return false;
4068 }
4069 *fuel -= 1;
4070 stmts.iter().all(|stmt| match stmt {
4071 Stmt::Set { target, value } if *target == s => {
4072 *seen = true;
4073 prove_le_bound(value, bound_sym, base, path, state, local_defs)
4074 }
4075 Stmt::Let { var, value, .. } if *var == s => {
4076 *seen = true;
4077 prove_le_bound(value, bound_sym, base, path, state, local_defs)
4078 }
4079 Stmt::If {
4080 cond,
4081 then_block,
4082 else_block,
4083 } => {
4084 path.push((cond, false));
4085 let ok_t = walk(
4086 s, then_block, bound_sym, base, state, local_defs, path, seen, fuel,
4087 );
4088 path.pop();
4089 let ok_e = else_block.map_or(true, |eb| {
4090 path.push((cond, true));
4091 let r = walk(s, eb, bound_sym, base, state, local_defs, path, seen, fuel);
4092 path.pop();
4093 r
4094 });
4095 ok_t && ok_e
4096 }
4097 Stmt::While { body: b, .. } | Stmt::Repeat { body: b, .. } => {
4098 walk(s, b, bound_sym, base, state, local_defs, path, seen, fuel)
4099 }
4100 _ => true,
4101 })
4102 }
4103 let local_defs = collect_local_affine_defs(body, &state.callee_globals);
4104 let mut path: Vec<(&Expr, bool)> = Vec::new();
4105 let mut seen = false;
4106 let mut fuel = 400u32;
4107 let ok = walk(
4108 s,
4109 body,
4110 bound_sym,
4111 base,
4112 state,
4113 &local_defs,
4114 &mut path,
4115 &mut seen,
4116 &mut fuel,
4117 );
4118 ok && seen
4119}
4120
4121fn try_prove_affine_karr(
4134 collection: &Expr,
4135 index: &Expr,
4136 state: &RichAbstractState,
4137 mutated: &HashSet<Symbol>,
4138 amb: &AffineFacts,
4139 facts: &mut OracleFacts,
4140) {
4141 use super::affine::{
4142 consistent, konst, le, len_index, len_var, lin_of, prove, var, Constraint, LinExpr,
4143 };
4144 let Expr::Identifier(arr) = collection else {
4145 return;
4146 };
4147 let key = index as *const Expr as usize;
4148 if facts.relational_inbounds.contains(&key) {
4149 return;
4150 }
4151 let Some(karr) = facts.karr_at.get(&key) else {
4152 return;
4153 };
4154 if !karr.tracked().contains(&len_index(*arr)) {
4155 return;
4156 }
4157 let Some(e) = lin_of(index) else { return };
4158
4159 let mut system: Vec<Constraint> = amb.constraints.clone();
4161 let mut mentioned: std::collections::BTreeSet<i64> = e.coefficients.keys().copied().collect();
4162 mentioned.insert(len_index(*arr));
4163 for c in &system {
4164 mentioned.extend(c.expr.coefficients.keys().copied());
4165 }
4166 let solved = karr.solved();
4167 for (_, v) in &solved {
4168 mentioned.extend(v.coefficients.keys().copied());
4169 }
4170 for &(d, _) in &solved {
4171 mentioned.insert(d);
4172 }
4173 for &k in &mentioned {
4174 if k < 0 {
4175 system.push(le(&konst(0), &LinExpr::var(k)));
4176 continue;
4177 }
4178 let s = Symbol::from_index(k as usize);
4179 if !mutated.contains(&s) {
4180 let iv = state.intervals.get_var(&s);
4181 if let Bound::Finite(lo) = iv.lo {
4182 system.push(le(&konst(lo), &var(s)));
4183 }
4184 if let Bound::Finite(hi) = iv.hi {
4185 system.push(le(&var(s), &konst(hi)));
4186 }
4187 }
4188 if let Some(l) = state.scalar_lower.get(&s) {
4189 system.push(le(l, &var(s)));
4190 }
4191 }
4192 for &(s, lb) in &state.entry_guard_lowers {
4193 system.push(le(&konst(lb), &var(s)));
4194 }
4195
4196 let substitute = |x: &LinExpr| -> LinExpr {
4198 let mut out = x.clone();
4199 for (d, v) in &solved {
4200 if let Some(c) = out.coefficients.remove(d) {
4201 out = out.add(&v.scale(&c));
4202 }
4203 }
4204 out
4205 };
4206 let low = substitute(&e.add(&konst(-1)));
4207 let high = substitute(&len_var(*arr).sub(&e));
4208 let system: Vec<Constraint> = system
4209 .iter()
4210 .map(|c| Constraint {
4211 expr: substitute(&c.expr),
4212 strict: c.strict,
4213 })
4214 .filter(|c| !c.expr.coefficients.is_empty() || !c.is_satisfied_constant())
4215 .collect();
4216
4217 let mut reach: std::collections::BTreeSet<i64> = low.coefficients.keys().copied().collect();
4219 reach.extend(high.coefficients.keys().copied());
4220 let mut kept = vec![false; system.len()];
4221 loop {
4222 let mut grew = false;
4223 for (k, c) in system.iter().enumerate() {
4224 if kept[k] {
4225 continue;
4226 }
4227 if c.expr.coefficients.is_empty()
4228 || c.expr.coefficients.keys().any(|v| reach.contains(v))
4229 {
4230 kept[k] = true;
4231 reach.extend(c.expr.coefficients.keys().copied());
4232 grew = true;
4233 }
4234 }
4235 if !grew {
4236 break;
4237 }
4238 }
4239 let relevant: Vec<Constraint> = system
4240 .into_iter()
4241 .zip(kept)
4242 .filter_map(|(c, k)| k.then_some(c))
4243 .collect();
4244 if relevant.len() > KARR_MAX_CONSTRAINTS || reach.len() > KARR_MAX_VARS {
4245 return;
4246 }
4247 if consistent(&relevant) && prove(&relevant, &low) && prove(&relevant, &high) {
4248 facts.relational_inbounds.insert(key);
4249 }
4250}
4251
4252const KARR_MAX_CONSTRAINTS: usize = 48;
4254
4255const KARR_MAX_VARS: usize = 12;
4257
4258fn try_prove_affine(
4261 collection: &Expr,
4262 index: &Expr,
4263 body: &[Stmt],
4264 state: &RichAbstractState,
4265 clobbered: &std::collections::HashSet<Symbol>,
4266 mutated: &std::collections::HashSet<Symbol>,
4267 amb: &AffineFacts,
4268 facts: &mut OracleFacts,
4269) {
4270 use super::affine::{ge, konst, le, lin_of, prove, var};
4271 let Expr::Identifier(arr) = collection else {
4272 return;
4273 };
4274 if clobbered.contains(arr) {
4275 return;
4276 }
4277 let key = index as *const Expr as usize;
4278 if facts.relational_inbounds.contains(&key) {
4279 return; }
4281 let Some(e_lin) = lin_of(index) else { return };
4282 let Some((len_lb, len_syms)) = affine_length_lb(*arr, state) else {
4283 return;
4284 };
4285
4286 let mut system = amb.constraints.clone();
4287 let mut syms = amb.syms.clone();
4288 affine_collect_syms(index, &mut syms);
4289 for s in len_syms {
4290 if !syms.contains(&s) {
4291 syms.push(s);
4292 }
4293 }
4294 for &s in &syms {
4295 if let Some(def) = state.scalar_def.get(&s) {
4298 let sv = var(s);
4299 system.push(le(&sv, def));
4300 system.push(le(def, &sv));
4301 }
4302 if !mutated.contains(&s) {
4307 let iv = state.intervals.get_var(&s);
4308 if let Bound::Finite(lo) = iv.lo {
4309 system.push(le(&konst(lo), &var(s)));
4310 }
4311 if let Bound::Finite(hi) = iv.hi {
4312 system.push(le(&var(s), &konst(hi)));
4313 }
4314 }
4315 if let Some(l) = state.scalar_lower.get(&s) {
4328 system.push(le(l, &var(s)));
4329 }
4330 }
4331
4332 for &(s, lb) in &state.entry_guard_lowers {
4338 system.push(le(&konst(lb), &var(s)));
4339 }
4340
4341 let base_system = system.clone();
4349 let bound_sym = state.length_def.get(arr).map(|(b, _)| *b);
4350 for &s in &syms {
4351 if !mutated.contains(&s) || state.scalar_def.contains_key(&s) {
4352 continue;
4353 }
4354 let assumed = std::collections::HashSet::new();
4355 if sym_ge_lo(s, 0, body, state, mutated, &assumed, 64) {
4356 system.push(ge(&var(s), &konst(0)));
4357 }
4358 if let Some(b) = bound_sym {
4359 if s != b && sym_le_sym(s, b, body, &base_system, state) {
4360 system.push(le(&var(s), &var(b)));
4361 }
4362 }
4363 }
4364
4365 if !super::affine::consistent(&system) {
4368 return;
4369 }
4370 let lower = e_lin.add(&konst(-1));
4372 let upper = len_lb.sub(&e_lin);
4373 if !prove(&system, &lower) {
4374 return;
4375 }
4376 if prove(&system, &upper) {
4378 facts.relational_inbounds.insert(key);
4379 return;
4380 }
4381 let mut mod_divisors: Vec<Symbol> = Vec::new();
4387 for &s in &syms {
4388 if let Some(u) = state.scalar_upper.get(&s) {
4389 system.push(le(&var(s), u));
4390 if let Some(m) = mod_upper_divisor(u) {
4391 mod_divisors.push(m);
4392 }
4393 }
4394 }
4395 if super::affine::consistent(&system) && prove(&system, &upper) {
4396 facts.relational_inbounds.insert(key);
4397 if !mod_divisors.is_empty() {
4398 facts
4399 .positivity_guards
4400 .entry(key)
4401 .or_default()
4402 .extend(mod_divisors);
4403 }
4404 }
4405}
4406
4407fn try_prove_dense_key(
4415 map: Symbol,
4416 key: &Expr,
4417 state: &RichAbstractState,
4418 mutated: &std::collections::HashSet<Symbol>,
4419 amb: &AffineFacts,
4420 facts: &mut OracleFacts,
4421) {
4422 use super::affine::{consistent, konst, le, lin_of, prove, var};
4423 let key_addr = key as *const Expr as usize;
4424 if facts.dense_map_key_proven.contains_key(&key_addr) {
4425 return;
4426 }
4427 let Some(cap) = facts.map_caps.get(&map).cloned() else {
4428 return;
4429 };
4430 let Some(k_lin) = lin_of(key) else { return };
4431
4432 let mut system = amb.constraints.clone();
4440 let mut syms = amb.syms.clone();
4441 affine_collect_syms(key, &mut syms);
4442 let mut reached: std::collections::HashSet<Symbol> = syms.iter().copied().collect();
4443 let mut w = 0;
4444 while w < syms.len() {
4445 let s = syms[w];
4446 w += 1;
4447 for chained in [
4448 state.scalar_def.get(&s),
4449 state.scalar_upper.get(&s),
4450 state.scalar_lower.get(&s),
4451 ] {
4452 if let Some(e) = chained {
4453 for &idx in e.coefficients.keys() {
4454 let t = Symbol::from_index(idx as usize);
4455 if reached.insert(t) {
4456 syms.push(t);
4457 }
4458 }
4459 }
4460 }
4461 }
4462 for &s in &syms {
4463 if let Some(def) = state.scalar_def.get(&s) {
4464 let sv = var(s);
4465 system.push(le(&sv, def));
4466 system.push(le(def, &sv));
4467 }
4468 if !mutated.contains(&s) {
4469 let iv = state.intervals.get_var(&s);
4470 if let Bound::Finite(lo) = iv.lo {
4471 system.push(le(&konst(lo), &var(s)));
4472 }
4473 if let Bound::Finite(hi) = iv.hi {
4474 system.push(le(&var(s), &konst(hi)));
4475 }
4476 }
4477 if let Some(l) = state.scalar_lower.get(&s) {
4478 system.push(le(l, &var(s)));
4479 }
4480 if let Some(u) = state.scalar_upper.get(&s) {
4481 system.push(le(&var(s), u));
4482 }
4483 }
4484
4485 if !consistent(&system) {
4487 return;
4488 }
4489 if prove(&system, &k_lin) && prove(&system, &cap.sub(&k_lin)) {
4491 facts.dense_map_key_proven.insert(key_addr, map);
4492 if let Some((a, b)) = facts.map_insert_cover.get(&map).cloned() {
4496 if prove(&system, &k_lin.sub(&a)) && prove(&system, &b.sub(&k_lin)) {
4497 facts.map_key_covered.insert(key_addr, map);
4498 }
4499 }
4500 }
4501}
4502
4503fn collect_iv_guards(cond: &Expr, state: &RichAbstractState, out: &mut Vec<IvGuard>) {
4508 match cond {
4509 Expr::BinaryOp {
4510 op: BinaryOpKind::And,
4511 left,
4512 right,
4513 } => {
4514 collect_iv_guards(left, state, out);
4515 collect_iv_guards(right, state, out);
4516 }
4517 Expr::BinaryOp { op, left, right } => {
4518 let (iv_e, bnd_e, strict): (&Expr, &Expr, bool) = match op {
4519 BinaryOpKind::Lt => (*left, *right, true),
4520 BinaryOpKind::LtEq => (*left, *right, false),
4521 BinaryOpKind::Gt => (*right, *left, true),
4522 BinaryOpKind::GtEq => (*right, *left, false),
4523 _ => return,
4524 };
4525 let Expr::Identifier(iv) = iv_e else { return };
4526 let iv_lo = match state.intervals.get_var(iv).lo {
4531 Bound::Finite(lo) => lo,
4532 _ => i64::MIN,
4533 };
4534 let bound = match bnd_e {
4535 Expr::Length { collection } => match &**collection {
4536 Expr::Identifier(arr) => IvBound::LenOf(*arr),
4537 _ => return,
4538 },
4539 Expr::Identifier(v) => IvBound::Var {
4540 var: *v,
4541 headroom: 0,
4542 },
4543 _ => match var_minus_bound(bnd_e, state) {
4545 Some((v, headroom)) => IvBound::Var { var: v, headroom },
4546 None => return,
4547 },
4548 };
4549 out.push(IvGuard {
4550 iv: *iv,
4551 bound,
4552 strict,
4553 iv_lo,
4554 });
4555 }
4556 _ => {}
4557 }
4558}
4559
4560fn var_minus_bound(b: &Expr, state: &RichAbstractState) -> Option<(Symbol, i64)> {
4565 match b {
4566 Expr::Identifier(v) => Some((*v, 0)),
4567 Expr::BinaryOp {
4568 op: BinaryOpKind::Subtract,
4569 left,
4570 right,
4571 } => {
4572 let (v, head) = var_minus_bound(left, state)?;
4573 let r_lo = match eval_expr(right, &state.intervals).lo {
4576 Bound::Finite(lo) => lo,
4577 _ => return None,
4578 };
4579 if r_lo < 0 {
4580 return None;
4581 }
4582 Some((v, head.saturating_add(r_lo)))
4583 }
4584 _ => None,
4585 }
4586}
4587
4588fn affine_of(e: &Expr) -> Option<(Symbol, i64)> {
4591 match e {
4592 Expr::Identifier(s) => Some((*s, 0)),
4593 Expr::BinaryOp {
4594 op: BinaryOpKind::Add,
4595 left,
4596 right,
4597 } => match (&**left, &**right) {
4598 (Expr::Identifier(s), Expr::Literal(Literal::Number(k))) => Some((*s, *k)),
4599 (Expr::Literal(Literal::Number(k)), Expr::Identifier(s)) => Some((*s, *k)),
4600 _ => None,
4601 },
4602 Expr::BinaryOp {
4603 op: BinaryOpKind::Subtract,
4604 left,
4605 right,
4606 } => match (&**left, &**right) {
4607 (Expr::Identifier(s), Expr::Literal(Literal::Number(k))) => Some((*s, -*k)),
4608 _ => None,
4609 },
4610 _ => None,
4611 }
4612}
4613
4614fn try_record_index(
4619 collection: &Expr,
4620 index: &Expr,
4621 guards: &[IvGuard],
4622 length_def: &HashMap<Symbol, (Symbol, i64)>,
4623 clobbered: &std::collections::HashSet<Symbol>,
4624 facts: &mut OracleFacts,
4625) {
4626 let Expr::Identifier(arr) = collection else {
4627 return;
4628 };
4629 if clobbered.contains(arr) {
4630 return;
4631 }
4632 let Some((iv, k)) = affine_of(index) else {
4633 return;
4634 };
4635 let proven = guards
4636 .iter()
4637 .any(|g| g.iv == iv && !clobbered.contains(&g.iv) && guard_proves(g, *arr, k, length_def));
4638 if proven {
4639 facts
4640 .relational_inbounds
4641 .insert(index as *const Expr as usize);
4642 }
4643}
4644
4645fn guard_proves(
4648 g: &IvGuard,
4649 arr: Symbol,
4650 k: i64,
4651 length_def: &HashMap<Symbol, (Symbol, i64)>,
4652) -> bool {
4653 if g.iv_lo.saturating_add(k) < 1 {
4655 return false;
4656 }
4657 let slack = if g.strict { 1 } else { 0 };
4659 match &g.bound {
4660 IvBound::LenOf(g_arr) => *g_arr == arr && k - slack <= 0,
4662 IvBound::Var { var, headroom } => match length_def.get(&arr) {
4666 Some((n, off)) => *n == *var && k - slack - headroom <= *off,
4667 None => false,
4668 },
4669 }
4670}
4671
4672fn var_rebound_in(sym: Symbol, body: &[Stmt]) -> bool {
4674 body.iter().any(|s| match s {
4675 Stmt::Set { target, .. } => *target == sym,
4676 Stmt::Let { var, .. } => *var == sym,
4677 Stmt::If {
4678 then_block,
4679 else_block,
4680 ..
4681 } => {
4682 var_rebound_in(sym, then_block)
4683 || matches!(else_block, Some(eb) if var_rebound_in(sym, eb))
4684 }
4685 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => var_rebound_in(sym, body),
4686 _ => false,
4687 })
4688}
4689
4690fn is_positive_increment(value: &Expr, iv: Symbol) -> bool {
4692 if let Expr::BinaryOp {
4693 op: BinaryOpKind::Add,
4694 left,
4695 right,
4696 } = value
4697 {
4698 let is_iv = |e: &Expr| matches!(e, Expr::Identifier(s) if *s == iv);
4699 let amt = match (&**left, &**right) {
4700 (l, Expr::Literal(Literal::Number(c))) if is_iv(l) => Some(*c),
4701 (Expr::Literal(Literal::Number(c)), r) if is_iv(r) => Some(*c),
4702 _ => None,
4703 };
4704 return amt.is_some_and(|c| c >= 1);
4705 }
4706 false
4707}
4708
4709fn iv_increment_is_last(iv: Symbol, body: &[Stmt]) -> bool {
4714 let Some((last, rest)) = body.split_last() else {
4715 return false;
4716 };
4717 let last_is_inc = matches!(last, Stmt::Set { target, value }
4718 if *target == iv && is_positive_increment(value, iv));
4719 last_is_inc && !var_rebound_in(iv, rest)
4720}
4721
4722fn consider_hoist_access(
4725 collection: &Expr,
4726 index: &Expr,
4727 iv: Symbol,
4728 state: &RichAbstractState,
4729 body: &[Stmt],
4730 facts: &mut OracleFacts,
4731 per_array: &mut HashMap<Symbol, (i64, i64)>,
4732) {
4733 let Expr::Identifier(arr) = collection else {
4734 return;
4735 };
4736 if !state.coll_vars.contains(arr) || var_rebound_in(*arr, body) || array_resized_in(*arr, body)
4740 {
4741 return;
4742 }
4743 if !state.param_colls.contains(arr) {
4748 return;
4749 }
4750 let Some((aiv, k)) = affine_of(index) else {
4751 return;
4752 };
4753 if aiv != iv {
4754 return;
4755 }
4756 let key = index as *const Expr as usize;
4757 if facts.relational_inbounds.contains(&key) {
4758 return; }
4760 facts.speculative_inbounds.insert(key);
4761 let entry = per_array.entry(*arr).or_insert((k, k));
4762 entry.0 = entry.0.min(k);
4763 entry.1 = entry.1.max(k);
4764}
4765
4766fn walk_hoist_accesses(
4768 stmts: &[Stmt],
4769 iv: Symbol,
4770 state: &RichAbstractState,
4771 body: &[Stmt],
4772 facts: &mut OracleFacts,
4773 per_array: &mut HashMap<Symbol, (i64, i64)>,
4774) {
4775 for s in stmts {
4776 for_each_direct_expr(s, &mut |e| {
4777 walk_hoist_in_expr(e, iv, state, body, facts, per_array)
4778 });
4779 if let Stmt::SetIndex {
4780 collection, index, ..
4781 } = s
4782 {
4783 consider_hoist_access(collection, index, iv, state, body, facts, per_array);
4784 }
4785 match s {
4786 Stmt::If {
4787 then_block,
4788 else_block,
4789 ..
4790 } => {
4791 walk_hoist_accesses(then_block, iv, state, body, facts, per_array);
4792 if let Some(eb) = else_block {
4793 walk_hoist_accesses(eb, iv, state, body, facts, per_array);
4794 }
4795 }
4796 Stmt::While { body: b, .. } | Stmt::Repeat { body: b, .. } => {
4797 walk_hoist_accesses(b, iv, state, body, facts, per_array);
4798 }
4799 _ => {}
4800 }
4801 }
4802}
4803
4804fn walk_hoist_in_expr(
4806 e: &Expr,
4807 iv: Symbol,
4808 state: &RichAbstractState,
4809 body: &[Stmt],
4810 facts: &mut OracleFacts,
4811 per_array: &mut HashMap<Symbol, (i64, i64)>,
4812) {
4813 use crate::ast::stmt::StringPart;
4814 if let Expr::Index { collection, index } = e {
4815 consider_hoist_access(collection, index, iv, state, body, facts, per_array);
4816 }
4817 let mut go = |x: &Expr| walk_hoist_in_expr(x, iv, state, body, facts, per_array);
4818 match e {
4819 Expr::BinaryOp { left, right, .. }
4820 | Expr::Union { left, right }
4821 | Expr::Intersection { left, right }
4822 | Expr::Range {
4823 start: left,
4824 end: right,
4825 } => {
4826 go(left);
4827 go(right);
4828 }
4829 Expr::Not { operand } => go(operand),
4830 Expr::Call { args, .. } => args.iter().for_each(|a| go(a)),
4831 Expr::CallExpr { callee, args } => {
4832 go(callee);
4833 args.iter().for_each(|a| go(a));
4834 }
4835 Expr::Index { collection, index } => {
4836 go(collection);
4837 go(index);
4838 }
4839 Expr::Slice {
4840 collection,
4841 start,
4842 end,
4843 } => {
4844 go(collection);
4845 go(start);
4846 go(end);
4847 }
4848 Expr::Copy { expr } => go(expr),
4849 Expr::Give { value } => go(value),
4850 Expr::Length { collection } => go(collection),
4851 Expr::Contains { collection, value } => {
4852 go(collection);
4853 go(value);
4854 }
4855 Expr::List(items) | Expr::Tuple(items) => items.iter().for_each(|i| go(i)),
4856 Expr::FieldAccess { object, .. } => go(object),
4857 Expr::New { init_fields, .. } => init_fields.iter().for_each(|(_, fe)| go(fe)),
4858 Expr::NewVariant { fields, .. } => fields.iter().for_each(|(_, fe)| go(fe)),
4859 Expr::OptionSome { value } => go(value),
4860 Expr::WithCapacity { value, capacity } => {
4861 go(value);
4862 go(capacity);
4863 }
4864 Expr::InterpolatedString(parts) => {
4865 for p in parts {
4866 if let StringPart::Expr { value, .. } = p {
4867 go(value);
4868 }
4869 }
4870 }
4871 _ => {}
4872 }
4873}
4874
4875fn hoist_descs(
4879 per_array: impl IntoIterator<Item = (Symbol, (i64, i64))>,
4880 bound: Symbol,
4881 iv: Symbol,
4882 strict: i64,
4883) -> Vec<HoistDesc> {
4884 let mut descs: Vec<HoistDesc> = per_array
4885 .into_iter()
4886 .filter_map(|(array, (kmin, kmax))| {
4887 Some(HoistDesc {
4888 array,
4889 bound,
4890 iv,
4891 add_max: i32::try_from(kmax - strict).ok()?,
4892 add_min: i32::try_from(kmin).ok()?,
4893 })
4894 })
4895 .collect();
4896 descs.sort_by_key(|d| d.array);
4897 descs
4898}
4899
4900fn record_hoist_speculation(
4908 cond: &Expr,
4909 body: &[Stmt],
4910 state: &RichAbstractState,
4911 facts: &mut OracleFacts,
4912 loop_key: usize,
4913) {
4914 if !body_is_index_proof_safe(body) {
4917 return;
4918 }
4919 let mut guards: Vec<IvGuard> = Vec::new();
4920 collect_iv_guards(cond, state, &mut guards);
4921 let Some(g) = guards.iter().find(|g| {
4924 matches!(g.bound, IvBound::Var { headroom: 0, var } if !var_rebound_in(var, body))
4925 && iv_increment_is_last(g.iv, body)
4926 }) else {
4927 return;
4928 };
4929 let IvBound::Var { var: bound, .. } = g.bound else {
4930 return;
4931 };
4932 if bound == g.iv {
4933 return;
4934 }
4935 let mut per_array: HashMap<Symbol, (i64, i64)> = HashMap::new();
4936 walk_hoist_accesses(body, g.iv, state, body, facts, &mut per_array);
4937 if per_array.is_empty() {
4938 return;
4939 }
4940 let strict = if g.strict { 1 } else { 0 };
4941 let descs = hoist_descs(per_array, bound, g.iv, strict);
4942 if !descs.is_empty() {
4943 facts.hoist_descs.entry(loop_key).or_default().extend(descs);
4944 }
4945}
4946
4947enum BuildLength {
4949 Symbolic(Symbol, Symbol, i64),
4951 Concrete(Symbol, Interval),
4954}
4955
4956fn infer_build_length(cond: &Expr, body: &[Stmt], entry: &RichAbstractState) -> Vec<BuildLength> {
4966 let (c_e, b_e, strict) = match cond {
4967 Expr::BinaryOp { op, left, right } => {
4968 let (l, r) = (&**left, &**right);
4969 match op {
4970 BinaryOpKind::Lt => (l, r, true),
4971 BinaryOpKind::LtEq => (l, r, false),
4972 _ => return Vec::new(),
4973 }
4974 }
4975 _ => return Vec::new(),
4976 };
4977 let Expr::Identifier(c) = c_e else {
4978 return Vec::new();
4979 };
4980 let c = *c;
4981 let bound_var = match b_e {
4983 Expr::Identifier(n) => Some(*n),
4984 Expr::Literal(Literal::Number(_)) => None,
4985 _ => return Vec::new(),
4986 };
4987 if bound_var == Some(c) {
4988 return Vec::new();
4989 }
4990 let iv = entry.intervals.get_var(&c);
4992 let c0 = match (iv.lo, iv.hi) {
4993 (Bound::Finite(lo), Bound::Finite(hi)) if lo == hi => lo,
4994 _ => return Vec::new(),
4995 };
4996 let mut push_counts: HashMap<Symbol, u32> = HashMap::new();
5003 let mut increments = 0;
5004 for s in body {
5005 match s {
5006 Stmt::Push { collection, .. } => {
5007 let Expr::Identifier(a) = &**collection else {
5008 return Vec::new();
5009 };
5010 *push_counts.entry(*a).or_insert(0) += 1;
5011 }
5012 Stmt::Set { target, value } => {
5013 if *target == c {
5014 if !is_increment_by_one(value, c) {
5015 return Vec::new();
5016 }
5017 increments += 1;
5018 } else if bound_var == Some(*target) {
5019 return Vec::new(); }
5021 }
5022 Stmt::Let { var, .. } => {
5023 if *var == c || bound_var == Some(*var) {
5024 return Vec::new();
5025 }
5026 }
5027 Stmt::Show { .. }
5030 | Stmt::RuntimeAssert { .. }
5031 | Stmt::Assert { .. }
5032 | Stmt::Trust { .. } => {}
5033 _ => return Vec::new(),
5034 }
5035 }
5036 if increments != 1 {
5037 return Vec::new();
5038 }
5039 let off = if strict { -c0 } else { -c0 + 1 };
5041 let mut arrays: Vec<(Symbol, u32)> = push_counts.into_iter().collect();
5043 arrays.sort_by_key(|(a, _)| a.index());
5044 let mut out = Vec::new();
5045 for (arr, count) in arrays {
5046 if count != 1 || arr == c || bound_var == Some(arr) {
5047 continue;
5048 }
5049 let entry_len = entry.intervals.get_length(&arr);
5054 let Bound::Finite(seed) = entry_len.lo else {
5055 continue;
5056 };
5057 match (bound_var, b_e) {
5058 (Some(n), _) => {
5059 if let Some(total) = off.checked_add(seed) {
5060 out.push(BuildLength::Symbolic(arr, n, total));
5061 }
5062 }
5063 (None, Expr::Literal(Literal::Number(bn))) => {
5064 if let Some(trips) = bn.checked_add(off) {
5065 let filled = Interval::exact(trips.max(0)).add(&entry_len);
5066 out.push(BuildLength::Concrete(arr, filled));
5067 }
5068 }
5069 _ => {}
5070 }
5071 }
5072 out
5073}
5074
5075fn is_increment_by_one(value: &Expr, c: Symbol) -> bool {
5077 if let Expr::BinaryOp {
5078 op: BinaryOpKind::Add,
5079 left,
5080 right,
5081 } = value
5082 {
5083 let is_c = |e: &Expr| matches!(e, Expr::Identifier(s) if *s == c);
5084 let is_one = |e: &Expr| matches!(e, Expr::Literal(Literal::Number(1)));
5085 return (is_c(&**left) && is_one(&**right)) || (is_one(&**left) && is_c(&**right));
5086 }
5087 false
5088}
5089
5090fn body_is_index_proof_safe(body: &[Stmt]) -> bool {
5097 body.iter().all(|s| match s {
5098 Stmt::Let { .. }
5099 | Stmt::Set { .. }
5100 | Stmt::SetIndex { .. }
5101 | Stmt::Push { .. }
5102 | Stmt::Pop { .. }
5103 | Stmt::Add { .. }
5104 | Stmt::Remove { .. }
5105 | Stmt::Show { .. }
5106 | Stmt::Return { .. }
5107 | Stmt::Break
5108 | Stmt::RuntimeAssert { .. }
5109 | Stmt::Assert { .. }
5110 | Stmt::Trust { .. } => true,
5111 Stmt::If {
5112 then_block,
5113 else_block,
5114 ..
5115 } => {
5116 body_is_index_proof_safe(then_block)
5117 && match else_block {
5118 Some(eb) => body_is_index_proof_safe(eb),
5119 None => true,
5120 }
5121 }
5122 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => body_is_index_proof_safe(body),
5123 _ => false,
5124 })
5125}
5126
5127fn collect_resized_arrays(body: &[Stmt], out: &mut std::collections::HashSet<Symbol>) {
5137 for s in body {
5138 match s {
5139 Stmt::Push { .. } | Stmt::Add { .. } => {}
5143 Stmt::Remove { collection, .. } => {
5145 if let Expr::Identifier(c) = &**collection {
5146 out.insert(*c);
5147 }
5148 }
5149 Stmt::Pop { collection, into } => {
5150 if let Expr::Identifier(c) = &**collection {
5151 out.insert(*c);
5152 }
5153 if let Some(v) = into {
5154 out.insert(*v);
5155 }
5156 }
5157 Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
5161 if let Expr::Identifier(src) = &**value {
5162 out.insert(*src);
5163 }
5164 }
5165 Stmt::If {
5166 then_block,
5167 else_block,
5168 ..
5169 } => {
5170 collect_resized_arrays(then_block, out);
5171 if let Some(eb) = else_block {
5172 collect_resized_arrays(eb, out);
5173 }
5174 }
5175 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
5176 collect_resized_arrays(body, out);
5177 }
5178 _ => {}
5179 }
5180 }
5181}
5182
5183fn array_resized_in(sym: Symbol, body: &[Stmt]) -> bool {
5186 let hits = |c: &Expr| matches!(c, Expr::Identifier(s) if *s == sym);
5187 body.iter().any(|s| match s {
5188 Stmt::Push { collection, .. }
5189 | Stmt::Add { collection, .. }
5190 | Stmt::Remove { collection, .. } => hits(collection),
5191 Stmt::Pop { collection, into } => hits(collection) || matches!(into, Some(v) if *v == sym),
5192 Stmt::If {
5193 then_block,
5194 else_block,
5195 ..
5196 } => {
5197 array_resized_in(sym, then_block)
5198 || matches!(else_block, Some(eb) if array_resized_in(sym, eb))
5199 }
5200 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => array_resized_in(sym, body),
5201 _ => false,
5202 })
5203}
5204
5205fn record_proven_reads(
5211 stmts: &[Stmt],
5212 guards: &[IvGuard],
5213 length_def: &HashMap<Symbol, (Symbol, i64)>,
5214 clobbered: &mut std::collections::HashSet<Symbol>,
5215 facts: &mut OracleFacts,
5216 globals: &CalleeGlobals,
5217) {
5218 for stmt in stmts {
5219 for_each_direct_expr(stmt, &mut |e| {
5220 record_index_reads(e, guards, length_def, clobbered, facts)
5221 });
5222 if let Stmt::SetIndex {
5225 collection, index, ..
5226 } = stmt
5227 {
5228 try_record_index(collection, index, guards, length_def, clobbered, facts);
5229 }
5230 match stmt {
5231 Stmt::If {
5232 then_block,
5233 else_block,
5234 ..
5235 } => {
5236 let mut c_then = clobbered.clone();
5237 record_proven_reads(then_block, guards, length_def, &mut c_then, facts, globals);
5238 let mut c_else = clobbered.clone();
5239 if let Some(eb) = else_block {
5240 record_proven_reads(eb, guards, length_def, &mut c_else, facts, globals);
5241 }
5242 clobbered.extend(c_then);
5243 clobbered.extend(c_else);
5244 }
5245 Stmt::While { body, .. } => {
5246 let mut inner = clobbered.clone();
5247 for m in collect_mutations_in(body, globals) {
5248 inner.insert(m);
5249 }
5250 record_proven_reads(body, guards, length_def, &mut inner.clone(), facts, globals);
5251 *clobbered = inner;
5252 }
5253 Stmt::Repeat { pattern, body, .. } => {
5254 if let Some(v) = pattern_loop_var(pattern) {
5255 clobbered.insert(v);
5256 }
5257 for m in collect_mutations_in(body, globals) {
5258 clobbered.insert(m);
5259 }
5260 }
5261 _ => {}
5262 }
5263 match stmt {
5266 Stmt::Set { target, .. } => {
5267 clobbered.insert(*target);
5268 }
5269 Stmt::Let { var, .. } => {
5270 clobbered.insert(*var);
5271 }
5272 _ => {}
5273 }
5274 }
5275}
5276
5277fn for_each_direct_expr(stmt: &Stmt, f: &mut impl FnMut(&Expr)) {
5280 match stmt {
5281 Stmt::Let { value, .. } | Stmt::Set { value, .. } => f(value),
5282 Stmt::SetIndex {
5283 collection,
5284 index,
5285 value,
5286 } => {
5287 f(collection);
5288 f(index);
5289 f(value);
5290 }
5291 Stmt::Show { object, .. } => f(object),
5292 Stmt::Push { value, .. } | Stmt::Add { value, .. } | Stmt::Remove { value, .. } => f(value),
5295 Stmt::Return { value: Some(v) } => f(v),
5296 Stmt::RuntimeAssert { condition, .. } => f(condition),
5297 Stmt::If { cond, .. } => f(cond),
5298 Stmt::While {
5299 cond, decreasing, ..
5300 } => {
5301 f(cond);
5302 if let Some(d) = decreasing {
5303 f(d);
5304 }
5305 }
5306 Stmt::Repeat { iterable, .. } => f(iterable),
5307 _ => {}
5308 }
5309}
5310
5311fn record_index_reads(
5315 e: &Expr,
5316 guards: &[IvGuard],
5317 length_def: &HashMap<Symbol, (Symbol, i64)>,
5318 clobbered: &std::collections::HashSet<Symbol>,
5319 facts: &mut OracleFacts,
5320) {
5321 use crate::ast::stmt::StringPart;
5322 if let Expr::Index { collection, index } = e {
5323 try_record_index(collection, index, guards, length_def, clobbered, facts);
5324 }
5325 match e {
5326 Expr::BinaryOp { left, right, .. }
5327 | Expr::Union { left, right }
5328 | Expr::Intersection { left, right }
5329 | Expr::Range {
5330 start: left,
5331 end: right,
5332 } => {
5333 record_index_reads(left, guards, length_def, clobbered, facts);
5334 record_index_reads(right, guards, length_def, clobbered, facts);
5335 }
5336 Expr::Not { operand } => record_index_reads(operand, guards, length_def, clobbered, facts),
5337 Expr::Call { args, .. } => {
5338 for a in args {
5339 record_index_reads(a, guards, length_def, clobbered, facts);
5340 }
5341 }
5342 Expr::CallExpr { callee, args } => {
5343 record_index_reads(callee, guards, length_def, clobbered, facts);
5344 for a in args {
5345 record_index_reads(a, guards, length_def, clobbered, facts);
5346 }
5347 }
5348 Expr::Index { collection, index } => {
5349 record_index_reads(collection, guards, length_def, clobbered, facts);
5350 record_index_reads(index, guards, length_def, clobbered, facts);
5351 }
5352 Expr::Slice {
5353 collection,
5354 start,
5355 end,
5356 } => {
5357 record_index_reads(collection, guards, length_def, clobbered, facts);
5358 record_index_reads(start, guards, length_def, clobbered, facts);
5359 record_index_reads(end, guards, length_def, clobbered, facts);
5360 }
5361 Expr::Copy { expr } => record_index_reads(expr, guards, length_def, clobbered, facts),
5362 Expr::Give { value } => record_index_reads(value, guards, length_def, clobbered, facts),
5363 Expr::Length { collection } => {
5364 record_index_reads(collection, guards, length_def, clobbered, facts)
5365 }
5366 Expr::Contains { collection, value } => {
5367 record_index_reads(collection, guards, length_def, clobbered, facts);
5368 record_index_reads(value, guards, length_def, clobbered, facts);
5369 }
5370 Expr::List(items) | Expr::Tuple(items) => {
5371 for it in items {
5372 record_index_reads(it, guards, length_def, clobbered, facts);
5373 }
5374 }
5375 Expr::FieldAccess { object, .. } => {
5376 record_index_reads(object, guards, length_def, clobbered, facts)
5377 }
5378 Expr::New { init_fields, .. } => {
5379 for (_, fe) in init_fields {
5380 record_index_reads(fe, guards, length_def, clobbered, facts);
5381 }
5382 }
5383 Expr::NewVariant { fields, .. } => {
5384 for (_, fe) in fields {
5385 record_index_reads(fe, guards, length_def, clobbered, facts);
5386 }
5387 }
5388 Expr::OptionSome { value } => {
5389 record_index_reads(value, guards, length_def, clobbered, facts)
5390 }
5391 Expr::WithCapacity { value, capacity } => {
5392 record_index_reads(value, guards, length_def, clobbered, facts);
5393 record_index_reads(capacity, guards, length_def, clobbered, facts);
5394 }
5395 Expr::InterpolatedString(parts) => {
5396 for p in parts {
5397 if let StringPart::Expr { value, .. } = p {
5398 record_index_reads(value, guards, length_def, clobbered, facts);
5399 }
5400 }
5401 }
5402 _ => {}
5403 }
5404}
5405
5406fn each_child_block(s: &Stmt, f: &mut impl FnMut(&[Stmt])) {
5412 match s {
5413 Stmt::If {
5414 then_block,
5415 else_block,
5416 ..
5417 } => {
5418 f(then_block);
5419 if let Some(eb) = else_block {
5420 f(eb);
5421 }
5422 }
5423 Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => f(body),
5424 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => f(tasks),
5425 Stmt::Inspect { arms, .. } => {
5426 for a in arms {
5427 f(a.body);
5428 }
5429 }
5430 Stmt::FunctionDef { body, .. } => f(body),
5431 _ => {}
5432 }
5433}
5434
5435fn gather_map_caps(
5443 stmts: &[Stmt],
5444 interner: &crate::intern::Interner,
5445 reassigned: &std::collections::HashSet<Symbol>,
5446 out: &mut HashMap<Symbol, super::affine::LinExpr>,
5447 poisoned: &mut std::collections::HashSet<Symbol>,
5448) {
5449 for s in stmts {
5450 if let Stmt::Let { var, value, .. } = s {
5451 if let Expr::WithCapacity {
5452 value: inner,
5453 capacity,
5454 } = value
5455 {
5456 if let Expr::New { type_name, .. } = inner {
5457 if matches!(interner.resolve(*type_name), "Map" | "HashMap") {
5458 if let Some(cap_lin) = super::affine::lin_of(capacity) {
5459 let mut cap_syms = Vec::new();
5460 affine_collect_syms(capacity, &mut cap_syms);
5461 let invariant = cap_syms.iter().all(|s| !reassigned.contains(s));
5462 if poisoned.contains(var) {
5463 } else if !invariant {
5465 out.remove(var);
5466 poisoned.insert(*var);
5467 } else if out.insert(*var, cap_lin).is_some() {
5468 out.remove(var);
5470 poisoned.insert(*var);
5471 }
5472 }
5473 }
5474 }
5475 }
5476 }
5477 each_child_block(s, &mut |b| {
5478 gather_map_caps(b, interner, reassigned, out, poisoned)
5479 });
5480 }
5481}
5482
5483fn counted_loop_bound<'a>(cond: &'a Expr<'a>) -> Option<&'a Expr<'a>> {
5487 let Expr::BinaryOp { op, left, right } = cond else {
5488 return None;
5489 };
5490 if !matches!(op, BinaryOpKind::Lt | BinaryOpKind::LtEq) {
5491 return None;
5492 }
5493 let Expr::Identifier(_) = *left else {
5494 return None;
5495 };
5496 Some(*right)
5497}
5498
5499fn collect_bare_new_maps(
5503 stmts: &[Stmt],
5504 interner: &crate::intern::Interner,
5505 out: &mut std::collections::HashSet<Symbol>,
5506) {
5507 for s in stmts {
5508 if let Stmt::Let { var, value, .. } = s {
5509 if let Expr::New { type_name, .. } = value {
5510 if matches!(interner.resolve(*type_name), "Map" | "HashMap") {
5511 out.insert(*var);
5512 }
5513 }
5514 }
5515 each_child_block(s, &mut |b| collect_bare_new_maps(b, interner, out));
5516 }
5517}
5518
5519fn collect_loop_inserted_maps(
5522 stmts: &[Stmt],
5523 candidates: &std::collections::HashSet<Symbol>,
5524 out: &mut Vec<Symbol>,
5525) {
5526 for s in stmts {
5527 if let Stmt::SetIndex {
5528 collection: Expr::Identifier(m),
5529 ..
5530 } = s
5531 {
5532 if candidates.contains(m) {
5533 out.push(*m);
5534 }
5535 }
5536 each_child_block(s, &mut |b| collect_loop_inserted_maps(b, candidates, out));
5537 }
5538}
5539
5540fn gather_implicit_map_caps(
5551 stmts: &[Stmt],
5552 interner: &crate::intern::Interner,
5553 reassigned: &std::collections::HashSet<Symbol>,
5554 poisoned: &std::collections::HashSet<Symbol>,
5555 out: &mut HashMap<Symbol, super::affine::LinExpr>,
5556) {
5557 let mut bare = std::collections::HashSet::new();
5558 collect_bare_new_maps(stmts, interner, &mut bare);
5559 if bare.is_empty() {
5560 return;
5561 }
5562 fn walk(
5563 stmts: &[Stmt],
5564 bare: &std::collections::HashSet<Symbol>,
5565 reassigned: &std::collections::HashSet<Symbol>,
5566 poisoned: &std::collections::HashSet<Symbol>,
5567 out: &mut HashMap<Symbol, super::affine::LinExpr>,
5568 ) {
5569 for s in stmts {
5570 if let Stmt::While { cond, body, .. } = s {
5571 if let Some(bound) = counted_loop_bound(cond) {
5572 if let Some(b_lin) = super::affine::lin_of(bound) {
5573 let mut syms = Vec::new();
5574 affine_collect_syms(bound, &mut syms);
5575 if syms.iter().all(|x| !reassigned.contains(x)) {
5576 let mut inserted = Vec::new();
5577 collect_loop_inserted_maps(body, bare, &mut inserted);
5578 for m in inserted {
5579 if !poisoned.contains(&m) && !out.contains_key(&m) {
5580 out.insert(m, b_lin.clone());
5581 }
5582 }
5583 }
5584 }
5585 }
5586 }
5587 each_child_block(s, &mut |b| walk(b, bare, reassigned, poisoned, out));
5588 }
5589 }
5590 walk(stmts, &bare, reassigned, poisoned, out);
5591}
5592
5593pub fn lin_to_rust(
5599 e: &super::affine::LinExpr,
5600 interner: &crate::intern::Interner,
5601) -> Option<String> {
5602 let mut coeffs: Vec<(i64, i64)> = Vec::new();
5603 for (idx, c) in e.coefficients.iter() {
5604 let ci = c.to_i64()?;
5605 if ci != 0 {
5606 coeffs.push((*idx, ci));
5607 }
5608 }
5609 coeffs.sort_by_key(|&(idx, _)| idx);
5610 let mut terms: Vec<String> = Vec::new();
5611 for (idx, ci) in coeffs {
5612 let name = interner.resolve(Symbol::from_index(idx as usize));
5613 terms.push(if ci == 1 {
5614 name.to_string()
5615 } else {
5616 format!("{} * {}", ci, name)
5617 });
5618 }
5619 let k = e.constant.to_i64()?;
5620 if k != 0 || terms.is_empty() {
5621 terms.push(k.to_string());
5622 }
5623 Some(terms.join(" + "))
5624}
5625
5626fn count_insert_sites(stmts: &[Stmt], out: &mut HashMap<Symbol, u32>) {
5630 for s in stmts {
5631 if let Stmt::SetIndex {
5632 collection: Expr::Identifier(m),
5633 ..
5634 } = s
5635 {
5636 *out.entry(*m).or_insert(0) += 1;
5637 }
5638 each_child_block(s, &mut |b| count_insert_sites(b, out));
5639 }
5640}
5641
5642fn match_insert_loop(
5651 cond: &Expr,
5652 body: &[Stmt],
5653 map_caps: &HashMap<Symbol, super::affine::LinExpr>,
5654) -> Option<(Symbol, Symbol, super::affine::LinExpr)> {
5655 use super::affine::{konst, lin_of};
5656 let Expr::BinaryOp { op, left, right } = cond else {
5658 return None;
5659 };
5660 let Expr::Identifier(iv) = left else {
5661 return None;
5662 };
5663 let b_lin = match op {
5664 BinaryOpKind::Lt => lin_of(right)?.sub(&konst(1)),
5665 BinaryOpKind::LtEq => lin_of(right)?,
5666 _ => return None,
5667 };
5668 if body.len() != 2 {
5669 return None;
5670 }
5671 let mut found_map: Option<Symbol> = None;
5672 let mut found_incr = false;
5673 for s in body {
5674 match s {
5675 Stmt::SetIndex {
5677 collection: Expr::Identifier(m),
5678 index: Expr::Identifier(ix),
5679 ..
5680 } if ix == iv && map_caps.contains_key(m) => {
5681 if found_map.is_some() {
5682 return None;
5683 }
5684 found_map = Some(*m);
5685 }
5686 Stmt::Set {
5688 target,
5689 value:
5690 Expr::BinaryOp {
5691 op: BinaryOpKind::Add,
5692 left: l,
5693 right: r,
5694 },
5695 } if target == iv => {
5696 let iv_plus_one = matches!((l, r),
5697 (Expr::Identifier(a), Expr::Literal(Literal::Number(1))) if a == iv)
5698 || matches!((l, r),
5699 (Expr::Literal(Literal::Number(1)), Expr::Identifier(a)) if a == iv);
5700 if !iv_plus_one {
5701 return None;
5702 }
5703 found_incr = true;
5704 }
5705 _ => return None,
5706 }
5707 }
5708 match (found_map, found_incr) {
5709 (Some(m), true) => Some((m, *iv, b_lin)),
5710 _ => None,
5711 }
5712}
5713
5714fn gather_insert_coverage(
5720 stmts: &[Stmt],
5721 map_caps: &HashMap<Symbol, super::affine::LinExpr>,
5722 insert_counts: &HashMap<Symbol, u32>,
5723 inits: &mut HashMap<Symbol, i64>,
5724 out: &mut HashMap<Symbol, (super::affine::LinExpr, super::affine::LinExpr)>,
5725) {
5726 use super::affine::konst;
5727 for s in stmts {
5728 if let Stmt::While { cond, body, .. } = s {
5729 if let Some((m, iv, b_lin)) = match_insert_loop(cond, body, map_caps) {
5730 if insert_counts.get(&m) == Some(&1) {
5731 if let Some(&a) = inits.get(&iv) {
5732 out.entry(m).or_insert((konst(a), b_lin));
5733 }
5734 }
5735 }
5736 }
5737 each_child_block(s, &mut |b| {
5738 gather_insert_coverage(b, map_caps, insert_counts, &mut inits.clone(), out)
5739 });
5740 match s {
5743 Stmt::Let {
5744 var,
5745 value: Expr::Literal(Literal::Number(n)),
5746 ..
5747 } => {
5748 inits.insert(*var, *n);
5749 }
5750 Stmt::Let { var, .. } => {
5751 inits.remove(var);
5752 }
5753 Stmt::Set {
5754 target,
5755 value: Expr::Literal(Literal::Number(n)),
5756 } => {
5757 inits.insert(*target, *n);
5758 }
5759 Stmt::Set { target, .. } => {
5760 inits.remove(target);
5761 }
5762 _ => {}
5763 }
5764 }
5765}
5766
5767pub fn oracle_analyze(stmts: &[Stmt]) -> OracleFacts {
5768 let mut facts = OracleFacts::default();
5769 let callee_globals = std::rc::Rc::new(CalleeGlobals::of_program(stmts));
5770 let mut st = RichAbstractState::new();
5771 st.callee_globals = callee_globals.clone();
5772 rich_walk_block(stmts, &mut st, &mut facts);
5773 for s in stmts {
5775 if let Stmt::FunctionDef { params, body, .. } = s {
5776 let mut fst = RichAbstractState::new();
5777 fst.callee_globals = callee_globals.clone();
5778 for (psym, ty) in params.iter() {
5779 if let crate::ast::stmt::TypeExpr::Primitive(t) = ty {
5780 fst.types.insert(*psym, type_tag_for_name(*t));
5783 }
5784 fst.aliases.taint(*psym);
5787 }
5788 rich_walk_block(body, &mut fst, &mut facts);
5789 }
5790 }
5791 strip_concurrent_loop_snapshots(stmts, &mut facts, false);
5792 facts
5793}
5794
5795fn type_tag_for_name(_name: Symbol) -> TypeAbstraction {
5800 TypeAbstraction::Top
5803}
5804
5805pub fn oracle_analyze_with(stmts: &[Stmt], interner: &crate::intern::Interner) -> OracleFacts {
5811 oracle_analyze_with_opts(stmts, interner, false)
5812}
5813
5814pub fn oracle_analyze_with_entry_guards(
5820 stmts: &[Stmt],
5821 interner: &crate::intern::Interner,
5822) -> OracleFacts {
5823 oracle_analyze_with_opts(stmts, interner, true)
5824}
5825
5826fn length_preserving_functions(
5834 stmts: &[Stmt],
5835 fn_returns: &std::rc::Rc<HashMap<Symbol, TypeTag>>,
5836 callee_globals: &std::rc::Rc<CalleeGlobals>,
5837 seq_types: &std::rc::Rc<HashSet<Symbol>>,
5838) -> HashMap<Symbol, usize> {
5839 use super::affine::{entry_len_index, len_index, len_var, LinExpr};
5840 use crate::ast::stmt::TypeExpr;
5841 let is_seq =
5842 |ty: &TypeExpr| matches!(ty, TypeExpr::Generic { base, .. } if seq_types.contains(base));
5843 let mut defs = Vec::new();
5844 let mut candidates: HashMap<Symbol, Vec<usize>> = HashMap::new();
5845 for s in stmts {
5846 let Stmt::FunctionDef {
5847 name,
5848 params,
5849 body,
5850 return_type: Some(ret),
5851 ..
5852 } = s
5853 else {
5854 continue;
5855 };
5856 let mut sites = Vec::new();
5857 if !is_seq(ret) || !return_sites(body, &mut sites) || sites.is_empty() {
5858 continue;
5859 }
5860 let positions: Vec<usize> = (0..params.len()).filter(|&i| is_seq(params[i].1)).collect();
5861 if !positions.is_empty() {
5862 candidates.insert(*name, positions);
5863 defs.push((*name, params, *body, sites));
5864 }
5865 }
5866 loop {
5867 let assumed: std::rc::Rc<HashMap<Symbol, usize>> = std::rc::Rc::new(
5868 candidates
5869 .iter()
5870 .filter_map(|(f, ps)| ps.first().map(|p| (*f, *p)))
5871 .collect(),
5872 );
5873 let mut refuted = false;
5874 for (name, params, body, sites) in &defs {
5875 let positions = candidates[name].clone();
5876 if positions.is_empty() {
5877 continue;
5878 }
5879 let mut fst = RichAbstractState::new();
5880 fst.fn_returns = fn_returns.clone();
5881 fst.callee_globals = callee_globals.clone();
5882 fst.seq_types = seq_types.clone();
5883 fst.len_summaries = assumed.clone();
5884 for (i, (p, ty)) in params.iter().enumerate() {
5885 fst.aliases.taint(*p);
5886 if is_seq(ty) {
5887 fst.seq_vars.insert(*p);
5888 fst.coll_vars.insert(*p);
5889 fst.karr
5890 .assign(len_index(*p), Some(&LinExpr::var(entry_len_index(i))));
5891 }
5892 }
5893 let mut facts = OracleFacts {
5894 return_probe: Some(Vec::new()),
5895 ..OracleFacts::default()
5896 };
5897 rich_walk_block(body, &mut fst, &mut facts);
5898 let returns = facts.return_probe.take().unwrap_or_default();
5899 let kept: Vec<usize> = positions
5900 .iter()
5901 .copied()
5902 .filter(|&p| {
5903 let entry = LinExpr::var(entry_len_index(p));
5904 sites.iter().all(|&site| {
5905 let mut at = returns.iter().filter(|(a, _, _)| *a == site).peekable();
5906 at.peek().is_some()
5907 && at.all(|(_, named, karr)| {
5908 named.is_some_and(|c| karr.entails_zero(&len_var(c).sub(&entry)))
5909 })
5910 })
5911 })
5912 .collect();
5913 if kept.len() != positions.len() {
5914 refuted = true;
5915 candidates.insert(*name, kept);
5916 }
5917 }
5918 if !refuted {
5919 break;
5920 }
5921 }
5922 candidates
5923 .into_iter()
5924 .filter_map(|(f, ps)| ps.first().map(|p| (f, *p)))
5925 .collect()
5926}
5927
5928fn return_sites(block: &[Stmt], out: &mut Vec<usize>) -> bool {
5932 block.iter().all(|s| match s {
5933 Stmt::Return { value: Some(_) } => {
5934 out.push(s as *const Stmt as usize);
5935 true
5936 }
5937 Stmt::If {
5938 then_block,
5939 else_block,
5940 ..
5941 } => return_sites(then_block, out) && else_block.map_or(true, |eb| return_sites(eb, out)),
5942 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => return_sites(body, out),
5943 Stmt::Inspect { arms, .. } => arms.iter().all(|a| return_sites(a.body, out)),
5944 Stmt::Let { .. }
5945 | Stmt::Set { .. }
5946 | Stmt::SetIndex { .. }
5947 | Stmt::SetField { .. }
5948 | Stmt::Push { .. }
5949 | Stmt::Pop { .. }
5950 | Stmt::Add { .. }
5951 | Stmt::Remove { .. }
5952 | Stmt::Swap { .. }
5953 | Stmt::Show { .. }
5954 | Stmt::Call { .. }
5955 | Stmt::Break
5956 | Stmt::RuntimeAssert { .. } => true,
5957 _ => false,
5958 })
5959}
5960
5961fn oracle_analyze_with_opts(
5964 stmts: &[Stmt],
5965 interner: &crate::intern::Interner,
5966 aot_entry_guard: bool,
5967) -> OracleFacts {
5968 let mut facts = OracleFacts::default();
5969 let callee_globals = std::rc::Rc::new(CalleeGlobals::of_program(stmts));
5970 {
5974 let reassigned = rebound_names(stmts, &callee_globals);
5975 let mut poisoned = std::collections::HashSet::new();
5976 gather_map_caps(
5977 stmts,
5978 interner,
5979 &reassigned,
5980 &mut facts.map_caps,
5981 &mut poisoned,
5982 );
5983 gather_implicit_map_caps(stmts, interner, &reassigned, &poisoned, &mut facts.map_caps);
5988 let mut insert_counts = HashMap::new();
5991 count_insert_sites(stmts, &mut insert_counts);
5992 let mut inits = HashMap::new();
5993 gather_insert_coverage(
5994 stmts,
5995 &facts.map_caps,
5996 &insert_counts,
5997 &mut inits,
5998 &mut facts.map_insert_cover,
5999 );
6000 }
6001 let mut fn_returns: HashMap<Symbol, TypeTag> = HashMap::new();
6005 for s in stmts {
6006 if let Stmt::FunctionDef {
6007 name,
6008 return_type: Some(ty),
6009 ..
6010 } = s
6011 {
6012 if let crate::ast::stmt::TypeExpr::Primitive(t) | crate::ast::stmt::TypeExpr::Named(t) =
6013 ty
6014 {
6015 let tag = match interner.resolve(*t) {
6016 "Int" | "Element" | "Event" | "View" => Some(TypeTag::Int),
6017 "Float" => Some(TypeTag::Float),
6018 "Bool" => Some(TypeTag::Bool),
6019 "Text" => Some(TypeTag::Text),
6020 _ => None,
6021 };
6022 if let Some(tag) = tag {
6023 fn_returns.insert(*name, tag);
6024 }
6025 }
6026 }
6027 }
6028 let fn_returns = std::rc::Rc::new(fn_returns);
6029 let seq_types: std::rc::Rc<HashSet<Symbol>> = std::rc::Rc::new(
6030 ["Seq", "List"]
6031 .iter()
6032 .filter_map(|n| interner.lookup(n))
6033 .collect(),
6034 );
6035 let len_summaries = std::rc::Rc::new(length_preserving_functions(
6036 stmts,
6037 &fn_returns,
6038 &callee_globals,
6039 &seq_types,
6040 ));
6041 let mut st = RichAbstractState::new();
6042 st.fn_returns = fn_returns.clone();
6043 st.callee_globals = callee_globals.clone();
6044 st.seq_types = seq_types.clone();
6045 st.len_summaries = len_summaries.clone();
6046 rich_walk_block(stmts, &mut st, &mut facts);
6047 for s in stmts {
6048 if let Stmt::FunctionDef { params, body, .. } = s {
6049 let mut fst = RichAbstractState::new();
6050 fst.fn_returns = fn_returns.clone();
6051 fst.callee_globals = callee_globals.clone();
6052 fst.seq_types = seq_types.clone();
6053 fst.len_summaries = len_summaries.clone();
6054 fst.aot_entry_guard = aot_entry_guard;
6055 for (psym, ty) in params.iter() {
6056 match ty {
6057 crate::ast::stmt::TypeExpr::Primitive(t) => {
6058 let tag = match interner.resolve(*t) {
6059 "Int" | "Element" | "Event" | "View" => {
6060 TypeAbstraction::Concrete(TypeTag::Int)
6061 }
6062 "Float" => TypeAbstraction::Concrete(TypeTag::Float),
6063 "Bool" => TypeAbstraction::Concrete(TypeTag::Bool),
6064 "Text" => TypeAbstraction::Concrete(TypeTag::Text),
6065 _ => TypeAbstraction::Top,
6066 };
6067 fst.types.insert(*psym, tag);
6068 }
6069 crate::ast::stmt::TypeExpr::Generic { base, .. }
6073 if matches!(interner.resolve(*base), "Seq" | "List" | "Array") =>
6074 {
6075 fst.coll_vars.insert(*psym);
6076 fst.param_colls.insert(*psym);
6077 if seq_types.contains(base) {
6078 fst.seq_vars.insert(*psym);
6079 }
6080 }
6081 _ => {}
6082 }
6083 fst.aliases.taint(*psym);
6086 }
6087 let mut partition_guarded = false;
6099 if aot_entry_guard {
6100 if let Some(g) =
6101 crate::codegen::entry_guard::detect_entry_guard(params, body, interner)
6102 {
6103 fst.intervals.set_var(
6104 g.lo,
6105 Interval {
6106 lo: Bound::Finite(1),
6107 hi: Bound::PosInf,
6108 },
6109 );
6110 fst.intervals.set_var(
6111 g.hi,
6112 Interval {
6113 lo: Bound::Finite(1),
6114 hi: Bound::PosInf,
6115 },
6116 );
6117 fst.length_def.insert(g.arr, (g.hi, 0));
6118 fst.entry_guard_lowers = vec![(g.lo, 1), (g.hi, 1)];
6123 partition_guarded = true;
6124 } else if let Some(g) =
6125 crate::codegen::entry_guard::detect_heap_sift_guard(params, body, interner)
6126 {
6127 fst.intervals.set_var(
6135 g.start,
6136 Interval {
6137 lo: Bound::Finite(0),
6138 hi: Bound::PosInf,
6139 },
6140 );
6141 fst.intervals.set_var(
6142 g.end,
6143 Interval {
6144 lo: Bound::Finite(0),
6145 hi: Bound::PosInf,
6146 },
6147 );
6148 fst.length_def.insert(g.arr, (g.end, 1));
6149 fst.entry_guard_lowers = vec![(g.start, 0), (g.end, 0)];
6150 let mutated: std::collections::HashSet<Symbol> =
6151 collect_mutations_in(body, &callee_globals)
6152 .into_iter()
6153 .collect();
6154 let assumed = std::collections::HashSet::new();
6155 if sym_ge_lo(g.counter, 0, body, &fst, &mutated, &assumed, 64) {
6156 fst.entry_guard_lowers.push((g.counter, 0));
6157 }
6158 }
6159 }
6160 if partition_guarded {
6161 let tl_mutated: std::collections::HashSet<Symbol> =
6173 collect_mutations_in(body, &callee_globals)
6174 .into_iter()
6175 .collect();
6176 let mut tl_clobbered: std::collections::HashSet<Symbol> =
6177 std::collections::HashSet::new();
6178 collect_resized_arrays(body, &mut tl_clobbered);
6179 for stmt in body.iter() {
6180 record_stmt_exprs(stmt, &fst, &mut facts);
6181 prove_toplevel_accesses(
6182 stmt,
6183 body,
6184 &fst,
6185 &tl_clobbered,
6186 &tl_mutated,
6187 &mut facts,
6188 );
6189 rich_walk_stmt(stmt, &mut fst, &mut facts);
6190 }
6191 } else {
6192 rich_walk_block(body, &mut fst, &mut facts);
6193 }
6194 }
6195 }
6196 strip_concurrent_loop_snapshots(stmts, &mut facts, false);
6197 facts
6198}
6199
6200fn strip_concurrent_loop_snapshots(stmts: &[Stmt], facts: &mut OracleFacts, in_concurrent: bool) {
6204 for stmt in stmts {
6205 match stmt {
6206 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
6207 if in_concurrent {
6208 facts.loop_aliases.remove(&(stmt as *const Stmt as usize));
6209 }
6210 strip_concurrent_loop_snapshots(body, facts, in_concurrent);
6211 }
6212 Stmt::If {
6213 then_block,
6214 else_block,
6215 ..
6216 } => {
6217 strip_concurrent_loop_snapshots(then_block, facts, in_concurrent);
6218 if let Some(eb) = else_block {
6219 strip_concurrent_loop_snapshots(eb, facts, in_concurrent);
6220 }
6221 }
6222 Stmt::Zone { body, .. } => {
6223 strip_concurrent_loop_snapshots(body, facts, in_concurrent);
6224 }
6225 Stmt::FunctionDef { body, .. } => {
6226 strip_concurrent_loop_snapshots(body, facts, in_concurrent);
6227 }
6228 Stmt::Inspect { arms, .. } => {
6229 for arm in arms {
6230 strip_concurrent_loop_snapshots(arm.body, facts, in_concurrent);
6231 }
6232 }
6233 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
6234 strip_concurrent_loop_snapshots(tasks, facts, true);
6235 }
6236 _ => {}
6237 }
6238 }
6239}
6240
6241pub(crate) fn rich_abstract_interp_stmts<'a>(
6242 stmts: Vec<Stmt<'a>>,
6243 _expr_arena: &'a Arena<Expr<'a>>,
6244 _stmt_arena: &'a Arena<Stmt<'a>>,
6245) -> (Vec<Stmt<'a>>, RichAbstractState) {
6246 let mut st = RichAbstractState::new();
6247 st.callee_globals = std::rc::Rc::new(CalleeGlobals::of_program(&stmts));
6248 let mut facts = OracleFacts::default();
6249 rich_walk_block(&stmts, &mut st, &mut facts);
6250 (stmts, st)
6251}
6252
6253fn rich_walk_block(block: &[Stmt], st: &mut RichAbstractState, facts: &mut OracleFacts) {
6254 for stmt in block {
6255 record_stmt_exprs(stmt, st, facts);
6256 rich_walk_stmt(stmt, st, facts);
6257 }
6258}
6259
6260fn record_stmt_exprs(stmt: &Stmt, st: &RichAbstractState, facts: &mut OracleFacts) {
6263 use crate::ast::stmt::ReadSource;
6264 match stmt {
6265 Stmt::Let { value, .. } | Stmt::Set { value, .. } => record_expr(value, st, facts),
6266 Stmt::Return { value: Some(e) } => {
6267 record_expr(e, st, facts);
6268 if let Some(probe) = &mut facts.return_probe {
6269 let named = match e {
6270 Expr::Identifier(s) if st.seq_vars.contains(s) => Some(*s),
6271 _ => None,
6272 };
6273 probe.push((stmt as *const Stmt as usize, named, st.karr.clone()));
6274 }
6275 }
6276 Stmt::Call { args, .. } => {
6277 for a in args {
6278 record_expr(a, st, facts);
6279 }
6280 }
6281 Stmt::If { cond, .. } | Stmt::While { cond, .. } => record_expr(cond, st, facts),
6282 Stmt::Repeat { iterable, .. } => record_expr(iterable, st, facts),
6283 Stmt::Show { object, .. } | Stmt::Give { object, .. } => record_expr(object, st, facts),
6284 Stmt::Push { value, collection }
6285 | Stmt::Add { value, collection }
6286 | Stmt::Remove { value, collection } => {
6287 record_expr(value, st, facts);
6288 record_expr(collection, st, facts);
6289 }
6290 Stmt::SetIndex {
6291 collection,
6292 index,
6293 value,
6294 } => {
6295 record_expr(collection, st, facts);
6296 record_expr(index, st, facts);
6297 record_expr(value, st, facts);
6298 record_karr(index, st, facts);
6299 }
6300 Stmt::SetField { object, value, .. } => {
6301 record_expr(object, st, facts);
6302 record_expr(value, st, facts);
6303 }
6304 Stmt::Inspect { target, .. } => record_expr(target, st, facts),
6305 Stmt::RuntimeAssert { condition, .. } => record_expr(condition, st, facts),
6306 Stmt::Sleep { milliseconds } => record_expr(milliseconds, st, facts),
6307 Stmt::ReadFrom {
6308 source: ReadSource::File(p),
6309 ..
6310 } => record_expr(p, st, facts),
6311 _ => {}
6312 }
6313}
6314
6315fn rich_walk_stmt(stmt: &Stmt, st: &mut RichAbstractState, facts: &mut OracleFacts) {
6316 let own = WriteSet::of_stmt_shallow(stmt).with_callee_globals(&st.callee_globals);
6319 if own.is_opaque() {
6320 st.forget_everything();
6321 return;
6322 }
6323 if own.has_calls() {
6324 st.forget_callee_globals();
6325 }
6326 karr_step(stmt, &own, st);
6327 match stmt {
6328 Stmt::Let { var, value, .. } => rich_bind(*var, value, st),
6329 Stmt::Swap { a, b } => {
6330 for sym in [*a, *b] {
6331 st.invalidate_var(sym);
6332 st.aliases.unlink(sym);
6333 }
6334 }
6335 Stmt::Set { target, value } => rich_bind(*target, value, st),
6336 Stmt::Push { collection, value } | Stmt::Add { collection, value } => {
6337 rich_grow(collection, st);
6338 observe_written_elem(collection, value, st);
6339 }
6340 Stmt::Pop { collection, into } => {
6341 rich_shrink(collection, st);
6342 if let Some(v) = into {
6343 st.invalidate_var(*v);
6344 st.aliases.unlink(*v);
6345 st.aliases.taint(*v);
6348 }
6349 }
6350 Stmt::Remove { collection, .. } => rich_shrink(collection, st),
6351 Stmt::SetIndex {
6355 collection, value, ..
6356 } => observe_written_elem(collection, value, st),
6357 Stmt::SetField { object, .. } => {
6358 if let Expr::Identifier(s) = *object {
6359 for a in st.aliases.may_alias(*s) {
6360 st.shapes.insert(a, CollectionShape::Top);
6361 }
6362 }
6363 }
6364 Stmt::If {
6365 cond,
6366 then_block,
6367 else_block,
6368 } => {
6369 rich_walk_if(cond, then_block, *else_block, st, facts);
6370 }
6371 Stmt::While { cond, body, .. } => {
6372 let key = stmt as *const Stmt as usize;
6373 rich_walk_loop(Some(cond), body, st, None, facts, Some(key));
6374 }
6375 Stmt::Repeat { pattern, body, .. } => {
6376 let key = stmt as *const Stmt as usize;
6377 rich_walk_loop(None, body, st, pattern_loop_var(pattern), facts, Some(key));
6378 }
6379 Stmt::Inspect { target, arms, .. } => rich_walk_inspect(target, arms, st, facts),
6380 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
6381 st.karr = super::karr::AffineSpace::top();
6383 rich_walk_block(tasks, st, facts);
6384 st.karr = super::karr::AffineSpace::top();
6385 }
6386 Stmt::Zone { body, .. } => {
6387 let prev = facts.suppress_exprs;
6394 facts.suppress_exprs = true;
6395 rich_walk_block(body, st, facts);
6396 facts.suppress_exprs = prev;
6397 }
6398 Stmt::Call { args, .. } => {
6399 for arg in args {
6401 if let Expr::Identifier(s) = *arg {
6402 for a in st.aliases.may_alias(*s) {
6403 st.shapes.insert(a, CollectionShape::Top);
6404 st.intervals.set_length(a, Interval::non_negative());
6405 }
6406 }
6407 }
6408 }
6409 Stmt::Give { object, .. } => {
6410 if let Expr::Identifier(s) = *object {
6411 st.invalidate_var(*s);
6412 st.aliases.unlink(*s);
6413 }
6414 }
6415 Stmt::ReadFrom { var, .. } => {
6416 st.invalidate_var(*var);
6417 st.aliases.unlink(*var);
6418 }
6419 _ => {
6423 let effects = WriteSet::of_stmt(stmt).with_callee_globals(&st.callee_globals);
6424 if effects.is_opaque() {
6425 st.forget_everything();
6426 return;
6427 }
6428 if effects.has_calls() {
6429 st.forget_callee_globals();
6430 }
6431 for sym in effects.symbols() {
6432 st.invalidate_var(sym);
6433 st.aliases.unlink(sym);
6434 }
6435 }
6436 }
6437}
6438
6439fn karr_counted_exit(
6445 cond: &Expr,
6446 body: &[Stmt],
6447 entry: &RichAbstractState,
6448 after: &mut RichAbstractState,
6449) {
6450 use super::affine::{konst, lin_of_with_lengths, var};
6451 let Expr::BinaryOp { op, left, right } = cond else {
6452 return;
6453 };
6454 let Expr::Identifier(x) = left else { return };
6455 let past = match op {
6456 BinaryOpKind::LtEq => 1,
6457 BinaryOpKind::Lt => 0,
6458 _ => return,
6459 };
6460 let writes = WriteSet::of_block(body).with_callee_globals(&entry.callee_globals);
6461 if writes.is_opaque()
6462 || !top_level_unconditional_incs(body, &entry.callee_globals)
6463 .iter()
6464 .any(|(v, d)| v == x && *d == 1)
6465 {
6466 return;
6467 }
6468 let mut resized = HashSet::new();
6469 collect_resized_arrays(body, &mut resized);
6470 let fixed =
6471 |c: Symbol| entry.seq_vars.contains(&c) && !resized.contains(&c) && !writes.may_write(c);
6472 let Some(bound) = lin_of_with_lengths(right, &fixed) else {
6473 return;
6474 };
6475 let int = |s: Symbol| {
6476 matches!(
6477 entry.types.get(&s),
6478 Some(TypeAbstraction::Concrete(TypeTag::Int))
6479 )
6480 };
6481 let names = bound
6482 .coefficients
6483 .keys()
6484 .filter(|&&k| k >= 0)
6485 .map(|&k| Symbol::from_index(k as usize));
6486 let names_ok = names.clone().all(|s| int(s) && !writes.may_write(s));
6487 if !int(*x) || !names_ok || !entry_proves(entry, &bound.add(&konst(past)).sub(&var(*x))) {
6488 return;
6489 }
6490 after.karr.meet_eq(&var(*x).sub(&bound).sub(&konst(past)));
6491}
6492
6493fn entry_proves(st: &RichAbstractState, goal: &super::affine::LinExpr) -> bool {
6496 use super::affine::{consistent, konst, le, prove, var};
6497 let mut system = Vec::new();
6498 for eq in st.karr.equalities() {
6499 system.push(le(&eq, &konst(0)));
6500 system.push(le(&konst(0), &eq));
6501 }
6502 let mut mentioned: std::collections::BTreeSet<i64> =
6503 goal.coefficients.keys().copied().collect();
6504 for c in &system {
6505 mentioned.extend(c.expr.coefficients.keys().copied());
6506 }
6507 for &k in &mentioned {
6508 if k < 0 {
6509 system.push(le(&konst(0), &super::affine::LinExpr::var(k)));
6510 continue;
6511 }
6512 let s = Symbol::from_index(k as usize);
6513 let iv = st.intervals.get_var(&s);
6514 if let Bound::Finite(lo) = iv.lo {
6515 system.push(le(&konst(lo), &var(s)));
6516 }
6517 if let Bound::Finite(hi) = iv.hi {
6518 system.push(le(&var(s), &konst(hi)));
6519 }
6520 if let Some(u) = st.scalar_upper.get(&s) {
6521 system.push(le(&var(s), u));
6522 }
6523 if let Some(l) = st.scalar_lower.get(&s) {
6524 system.push(le(l, &var(s)));
6525 }
6526 }
6527 consistent(&system) && prove(&system, goal)
6528}
6529
6530fn karr_step(stmt: &Stmt, own: &WriteSet, st: &mut RichAbstractState) {
6535 use super::affine::{konst, len_index, len_var};
6536 let named = |e: &Expr| match e {
6537 Expr::Identifier(s) => Some(*s),
6538 _ => None,
6539 };
6540 let moved: Option<(Symbol, i64)> = match stmt {
6541 Stmt::Let { .. } | Stmt::Set { .. } => return,
6542 Stmt::Push { collection, .. } => named(collection).map(|c| (c, 1)),
6543 Stmt::Pop { collection, .. } => named(collection).map(|c| (c, -1)),
6544 _ => None,
6545 };
6546 let kept = match stmt {
6547 Stmt::SetIndex { collection, .. } => named(collection).filter(|c| st.seq_vars.contains(c)),
6548 _ => None,
6549 };
6550 let unknown: Vec<Symbol> = own
6551 .symbols()
6552 .filter(|s| Some(*s) != moved.map(|(c, _)| c) && Some(*s) != kept)
6553 .collect();
6554 for name in unknown {
6555 st.karr_unknown(name);
6556 }
6557 if let Some((c, by)) = moved {
6558 st.karr_resized(c);
6559 let next = st.seq_vars.contains(&c).then(|| len_var(c).add(&konst(by)));
6560 st.karr.assign(len_index(c), next.as_ref());
6561 }
6562}
6563
6564fn value_upper(value: &Expr, st: &RichAbstractState) -> Option<super::affine::LinExpr> {
6578 use super::affine::{konst, var};
6579 match value {
6580 Expr::Literal(Literal::Number(k)) => Some(konst(*k)),
6581 Expr::Identifier(s) => st.scalar_upper.get(s).cloned(),
6582 Expr::Index { collection, .. } => match collection {
6583 Expr::Identifier(arr) => st.elem_upper.get(arr).cloned(),
6584 _ => None,
6585 },
6586 Expr::BinaryOp {
6587 op: BinaryOpKind::Modulo,
6588 right,
6589 ..
6590 } => match right {
6591 Expr::Identifier(n) => Some(var(*n).sub(&konst(1))),
6592 _ => None,
6593 },
6594 Expr::BinaryOp {
6596 op: BinaryOpKind::Divide,
6597 left,
6598 right,
6599 } if divides_nonnegative(left, right, st) => super::affine::lin_of(left),
6600 _ => None,
6601 }
6602}
6603
6604fn divides_nonnegative(left: &Expr, right: &Expr, st: &RichAbstractState) -> bool {
6607 matches!(right, Expr::Literal(Literal::Number(k)) if *k >= 1)
6608 && matches!(eval_expr(left, &st.intervals).lo, Bound::Finite(lo) if lo >= 0)
6609}
6610
6611fn value_lower(value: &Expr, st: &RichAbstractState) -> Option<super::affine::LinExpr> {
6617 use super::affine::konst;
6618 match value {
6619 Expr::Literal(Literal::Number(k)) => Some(konst(*k)),
6620 Expr::Identifier(s) => st.scalar_lower.get(s).cloned(),
6621 Expr::Index { collection, .. } => match collection {
6622 Expr::Identifier(arr) => match st.intervals.get_elem(arr).lo {
6623 Bound::Finite(lo) => Some(konst(lo)),
6624 _ => None,
6625 },
6626 _ => None,
6627 },
6628 Expr::BinaryOp {
6629 op: BinaryOpKind::Divide,
6630 left,
6631 right,
6632 } if divides_nonnegative(left, right, st) => Some(konst(0)),
6633 _ => None,
6634 }
6635}
6636
6637fn join_sym_upper(
6643 a: &super::affine::LinExpr,
6644 b: &super::affine::LinExpr,
6645 st: &RichAbstractState,
6646) -> Option<super::affine::LinExpr> {
6647 if a == b {
6648 return Some(a.clone());
6649 }
6650 if lin_ge_zero(&b.sub(a), st) {
6651 return Some(b.clone()); }
6653 if lin_ge_zero(&a.sub(b), st) {
6654 return Some(a.clone());
6655 }
6656 if is_nonpos_const(a) && mod_upper_divisor(b).is_some() {
6664 return Some(b.clone());
6665 }
6666 if is_nonpos_const(b) && mod_upper_divisor(a).is_some() {
6667 return Some(a.clone());
6668 }
6669 None
6670}
6671
6672fn mod_upper_divisor(e: &super::affine::LinExpr) -> Option<Symbol> {
6677 if e.coefficients.len() != 1 || e.constant.to_i64() != Some(-1) {
6678 return None;
6679 }
6680 let (&idx, coeff) = e.coefficients.iter().next()?;
6681 (coeff.to_i64() == Some(1)).then(|| Symbol::from_index(idx as usize))
6682}
6683
6684fn is_nonpos_const(e: &super::affine::LinExpr) -> bool {
6686 e.coefficients.is_empty() && !e.constant.is_positive()
6687}
6688
6689fn lin_ge_zero(e: &super::affine::LinExpr, st: &RichAbstractState) -> bool {
6694 let Some(k) = e.constant.to_i64() else {
6695 return false;
6696 };
6697 let mut acc = Interval::exact(k);
6698 for (idx, coeff) in &e.coefficients {
6699 let Some(c) = coeff.to_i64() else {
6700 return false;
6701 };
6702 let sym = Symbol::from_index(*idx as usize);
6703 acc = acc.add(&Interval::exact(c).mul(&st.intervals.get_var(&sym)));
6704 }
6705 matches!(acc.lo, Bound::Finite(v) if v >= 0)
6706}
6707
6708fn observe_written_elem(collection: &Expr, value: &Expr, st: &mut RichAbstractState) {
6709 if let Expr::Identifier(sym) = collection {
6710 let v = eval_expr(value, &st.intervals);
6711 let sym_up = value_upper(value, st);
6714 let sym_ty = eval_type(value, &st.types, &st.fn_returns, &st.elem_type);
6717 for a in st.aliases.may_alias(*sym) {
6718 let was_fresh = st.intervals.get_elem(&a).is_bottom();
6721 st.intervals.observe_elem(a, v.clone());
6722 if was_fresh {
6727 st.elem_type.insert(a, sym_ty.clone());
6728 } else {
6729 let joined = match st.elem_type.get(&a) {
6730 Some(existing) => existing.join(&sym_ty),
6731 None => TypeAbstraction::Top,
6732 };
6733 st.elem_type.insert(a, joined);
6734 }
6735 match &sym_up {
6736 None => {
6739 st.elem_upper.remove(&a);
6740 }
6741 Some(nb) => {
6742 if was_fresh {
6743 st.elem_upper.insert(a, nb.clone());
6744 } else if let Some(existing) = st.elem_upper.get(&a).cloned() {
6745 match join_sym_upper(&existing, nb, st) {
6746 Some(m) => {
6747 st.elem_upper.insert(a, m);
6748 }
6749 None => {
6750 st.elem_upper.remove(&a);
6751 }
6752 }
6753 }
6754 }
6757 }
6758 }
6759 }
6760}
6761
6762fn rich_bind(var: Symbol, value: &Expr, st: &mut RichAbstractState) {
6763 let karr = karr_after_bind(var, value, st);
6764 let is_seq = sequence_length(value, st).is_some();
6765 rich_bind_facts(var, value, st);
6766 st.karr = karr;
6767 if is_seq {
6768 st.seq_vars.insert(var);
6769 } else {
6770 st.seq_vars.remove(&var);
6771 }
6772}
6773
6774fn karr_after_bind(var: Symbol, value: &Expr, st: &RichAbstractState) -> super::karr::AffineSpace {
6778 let int_valued = matches!(
6779 eval_type(value, &st.types, &st.fn_returns, &st.elem_type),
6780 TypeAbstraction::Concrete(TypeTag::Int)
6781 );
6782 let lent: Vec<Symbol> = WriteSet::of_expr(value).symbols().collect();
6783 if lent.is_empty() {
6784 return karr_assigned(var, value, int_valued, st.karr.clone(), st);
6785 }
6786 let mut probe = RichAbstractState {
6787 karr: st.karr.clone(),
6788 aliases: st.aliases.clone(),
6789 seq_vars: st.seq_vars.clone(),
6790 seq_types: st.seq_types.clone(),
6791 len_summaries: st.len_summaries.clone(),
6792 ..RichAbstractState::new()
6793 };
6794 for name in lent {
6795 probe.karr_unknown(name);
6796 }
6797 let karr = std::mem::replace(&mut probe.karr, super::karr::AffineSpace::top());
6798 karr_assigned(var, value, int_valued, karr, &probe)
6799}
6800
6801fn karr_assigned(
6803 var: Symbol,
6804 value: &Expr,
6805 int_valued: bool,
6806 mut karr: super::karr::AffineSpace,
6807 lengths: &RichAbstractState,
6808) -> super::karr::AffineSpace {
6809 use super::affine::{len_index, lin_of_with_lengths, var_index};
6810 let scalar = if int_valued {
6811 lin_of_with_lengths(value, &|c| lengths.seq_vars.contains(&c))
6812 } else {
6813 None
6814 };
6815 let length = sequence_length(value, lengths);
6816 karr.assign(var_index(var), scalar.as_ref());
6817 karr.assign(len_index(var), length.as_ref());
6818 karr
6819}
6820
6821fn sequence_length(value: &Expr, st: &RichAbstractState) -> Option<super::affine::LinExpr> {
6825 use super::affine::{konst, len_var};
6826 let tracked = |e: &Expr| match e {
6827 Expr::Identifier(s) if st.seq_vars.contains(s) => Some(len_var(*s)),
6828 _ => None,
6829 };
6830 match value {
6831 Expr::New { type_name, .. } if st.seq_types.contains(type_name) => Some(konst(0)),
6832 Expr::List(items) => Some(konst(items.len() as i64)),
6833 Expr::Identifier(_) => tracked(value),
6834 Expr::Copy { expr } => tracked(expr),
6835 Expr::WithCapacity { value, .. } => sequence_length(value, st),
6836 Expr::Call { function, args } => tracked(args.get(*st.len_summaries.get(function)?)?),
6837 _ => None,
6838 }
6839}
6840
6841fn rich_bind_facts(var: Symbol, value: &Expr, st: &mut RichAbstractState) {
6842 if let Expr::WithCapacity { value, .. } = value {
6848 rich_bind_facts(var, value, st);
6849 return;
6850 }
6851 st.aliases.unlink(var);
6852 st.length_def.remove(&var);
6856 st.length_def.retain(|_, (n, _)| *n != var);
6857 st.scalar_def.remove(&var);
6860 let vi = var.index() as i64;
6861 st.scalar_def
6862 .retain(|_, e| !e.coefficients.contains_key(&vi));
6863 st.scalar_upper.remove(&var);
6867 st.scalar_upper
6868 .retain(|_, e| !e.coefficients.contains_key(&vi));
6869 st.elem_upper.remove(&var);
6870 st.elem_upper
6871 .retain(|_, e| !e.coefficients.contains_key(&vi));
6872 st.elem_type.remove(&var);
6876 st.scalar_lower.remove(&var);
6877 st.scalar_lower
6878 .retain(|_, e| !e.coefficients.contains_key(&vi));
6879 st.param_colls.remove(&var);
6882
6883 let iv = eval_expr(value, &st.intervals);
6884 st.intervals.set_var(var, iv);
6885 let value_ty = eval_type(value, &st.types, &st.fn_returns, &st.elem_type);
6886 st.types.insert(var, value_ty);
6887 st.nullability.insert(var, nullability_of_expr(value, st));
6888 st.intervals.clear_elem(&var);
6891 if let Some(e) = super::affine::lin_of(value) {
6898 if !e.coefficients.is_empty() && !e.coefficients.contains_key(&(var.index() as i64)) {
6899 st.scalar_def.insert(var, e);
6900 }
6901 }
6902 if let Some(u) = value_upper(value, st) {
6907 if !u.coefficients.contains_key(&(var.index() as i64)) {
6908 st.scalar_upper.insert(var, u);
6909 }
6910 }
6911 if let Some(l) = value_lower(value, st) {
6912 if !l.coefficients.contains_key(&(var.index() as i64)) {
6913 st.scalar_lower.insert(var, l);
6914 }
6915 }
6916 if let Expr::Length { collection } = value {
6924 if let Expr::Identifier(a) = &**collection {
6925 if *a != var {
6926 st.length_def.insert(*a, (var, 0));
6927 }
6928 }
6929 }
6930
6931 match value {
6932 Expr::New { .. } => {
6933 st.shapes.insert(var, CollectionShape::Empty);
6934 st.intervals.set_length(var, Interval::exact(0));
6935 st.coll_vars.insert(var);
6936 st.intervals.observe_elem(var, Interval::bottom());
6940 }
6941 Expr::List(items) | Expr::Tuple(items) => {
6942 let n = items.len() as u64;
6943 st.shapes
6944 .insert(var, CollectionShape::from_bounds(n, Some(n)));
6945 st.intervals
6946 .set_length(var, Interval::exact(items.len() as i64));
6947 st.coll_vars.insert(var);
6948 let mut el = Interval::bottom();
6950 for it in items.iter() {
6951 el = el.join(&eval_expr(it, &st.intervals));
6952 }
6953 st.intervals.observe_elem(var, el);
6954 let mut item_iter = items.iter();
6957 if let Some(first) = item_iter.next() {
6958 let mut ty = eval_type(first, &st.types, &st.fn_returns, &st.elem_type);
6959 for it in item_iter {
6960 ty = ty.join(&eval_type(it, &st.types, &st.fn_returns, &st.elem_type));
6961 }
6962 st.elem_type.insert(var, ty);
6963 }
6964 }
6965 Expr::Identifier(src) => {
6966 st.aliases.link(var, *src);
6968 let shape = st.shapes.get(src).cloned().unwrap_or(CollectionShape::Top);
6969 st.shapes.insert(var, shape);
6970 let len = st.intervals.get_length(src);
6971 st.intervals.set_length(var, len);
6972 if st.intervals.elem.contains_key(src) {
6974 let e = st.intervals.get_elem(src);
6975 st.intervals.observe_elem(var, e);
6976 }
6977 if let Some(t) = st.elem_type.get(src).cloned() {
6979 st.elem_type.insert(var, t);
6980 }
6981 if st.coll_vars.contains(src) {
6982 st.coll_vars.insert(var);
6983 if st.param_colls.contains(src) {
6985 st.param_colls.insert(var);
6986 }
6987 } else {
6988 st.coll_vars.remove(&var);
6989 }
6990 if st.aot_entry_guard {
6998 if let Some(&(n, off)) = st.length_def.get(src) {
6999 if n != var {
7000 st.length_def.insert(var, (n, off));
7001 }
7002 }
7003 }
7004 }
7005 Expr::Copy { expr } => {
7006 st.shapes.insert(var, CollectionShape::Top);
7008 let from_coll =
7009 matches!(
7010 expr,
7011 Expr::Identifier(s) if st.coll_vars.contains(s)
7012 ) || matches!(expr, Expr::New { .. } | Expr::List(_) | Expr::Slice { .. });
7013 if from_coll {
7014 st.coll_vars.insert(var);
7015 } else {
7016 st.coll_vars.remove(&var);
7017 }
7018 }
7019 Expr::Slice { .. } => {
7020 st.shapes.insert(var, CollectionShape::Top);
7022 st.coll_vars.insert(var);
7023 }
7024 _ => {
7025 st.shapes.insert(var, CollectionShape::Top);
7027 st.coll_vars.remove(&var);
7028 match value {
7033 Expr::Literal(_)
7034 | Expr::BinaryOp { .. }
7035 | Expr::Not { .. }
7036 | Expr::Length { .. }
7037 | Expr::Contains { .. }
7038 | Expr::Range { .. }
7039 | Expr::Union { .. }
7040 | Expr::Intersection { .. }
7041 | Expr::InterpolatedString(_)
7042 | Expr::OptionNone => {}
7043 _ => st.aliases.taint(var),
7044 }
7045 }
7046 }
7047}
7048
7049fn rich_grow(collection: &Expr, st: &mut RichAbstractState) {
7052 if let Expr::Identifier(sym) = collection {
7053 let new_shape = st
7054 .shapes
7055 .get(sym)
7056 .cloned()
7057 .unwrap_or(CollectionShape::Top)
7058 .pushed();
7059 let new_len = st.intervals.get_length(sym).add(&Interval::exact(1));
7060 for a in st.aliases.may_alias(*sym) {
7061 st.shapes.insert(a, new_shape.clone());
7062 st.intervals.set_length(a, new_len.clone());
7063 st.length_def.remove(&a);
7066 }
7067 }
7068}
7069
7070fn rich_shrink(collection: &Expr, st: &mut RichAbstractState) {
7072 if let Expr::Identifier(sym) = collection {
7073 let new_shape = st
7074 .shapes
7075 .get(sym)
7076 .cloned()
7077 .unwrap_or(CollectionShape::Top)
7078 .popped();
7079 let new_len = st.intervals.get_length(sym).sub(&Interval::exact(1));
7080 for a in st.aliases.may_alias(*sym) {
7081 st.shapes.insert(a, new_shape.clone());
7082 st.intervals.set_length(a, new_len.clone());
7083 st.length_def.remove(&a);
7085 }
7086 }
7087}
7088
7089fn nullability_of_expr(expr: &Expr, st: &RichAbstractState) -> Nullability {
7090 match expr {
7091 Expr::Literal(lit) => Nullability::for_literal(lit),
7092 Expr::Identifier(s) => st.nullability.get(s).cloned().unwrap_or(Nullability::Maybe),
7093 Expr::New { .. }
7094 | Expr::NewVariant { .. }
7095 | Expr::List(_)
7096 | Expr::Tuple(_)
7097 | Expr::Range { .. }
7098 | Expr::BinaryOp { .. }
7099 | Expr::Not { .. }
7100 | Expr::Length { .. }
7101 | Expr::Contains { .. } => Nullability::Definite,
7102 _ => Nullability::Maybe,
7104 }
7105}
7106
7107fn pattern_loop_var(p: &Pattern) -> Option<Symbol> {
7108 match p {
7109 Pattern::Identifier(s) => Some(*s),
7110 _ => None,
7111 }
7112}
7113
7114fn rich_walk_if(
7115 cond: &Expr,
7116 then_block: &[Stmt],
7117 else_block: Option<&[Stmt]>,
7118 st: &mut RichAbstractState,
7119 facts: &mut OracleFacts,
7120) {
7121 match eval_condition(cond, &st.intervals) {
7122 Some(true) => {
7123 narrow_state(cond, &mut st.intervals);
7124 rich_walk_block(then_block, st, facts);
7125 }
7126 Some(false) => {
7127 if let Some(eb) = else_block {
7128 narrow_state_negated(cond, &mut st.intervals);
7129 rich_walk_block(eb, st, facts);
7130 }
7131 }
7132 None => {
7133 let mut then_st = st.clone();
7134 narrow_state(cond, &mut then_st.intervals);
7135 rich_walk_block(then_block, &mut then_st, facts);
7136
7137 let mut else_st = st.clone();
7138 narrow_state_negated(cond, &mut else_st.intervals);
7139 if let Some(eb) = else_block {
7140 rich_walk_block(eb, &mut else_st, facts);
7141 }
7142
7143 *st = rich_join(&then_st, &else_st);
7144 }
7145 }
7146}
7147
7148fn refine_invariant_bound_from_guard(
7154 cond: &Expr,
7155 pre: &RichAbstractState,
7156 mutated: &[Symbol],
7157 out: &mut AbstractState,
7158) {
7159 if let Expr::BinaryOp {
7160 op: BinaryOpKind::And,
7161 left,
7162 right,
7163 } = cond
7164 {
7165 refine_invariant_bound_from_guard(left, pre, mutated, out);
7166 refine_invariant_bound_from_guard(right, pre, mutated, out);
7167 return;
7168 }
7169 let Expr::BinaryOp { op, left, right } = cond else {
7170 return;
7171 };
7172 let (iv_e, bnd_e, strict) = match op {
7173 BinaryOpKind::Lt => (left, right, true),
7174 BinaryOpKind::LtEq => (left, right, false),
7175 BinaryOpKind::Gt => (right, left, true),
7176 BinaryOpKind::GtEq => (right, left, false),
7177 _ => return,
7178 };
7179 let (Expr::Identifier(iv), Expr::Identifier(bnd)) = (iv_e, bnd_e) else {
7180 return;
7181 };
7182 if mutated.contains(bnd) {
7183 return; }
7185 let Bound::Finite(i0) = pre.intervals.get_var(iv).lo else {
7186 return;
7187 };
7188 let Some(new_lo) = (if strict { i0.checked_add(1) } else { Some(i0) }) else {
7189 return;
7190 };
7191 let cur = out.get_var(bnd);
7192 out.set_var(
7193 *bnd,
7194 Interval {
7195 lo: Bound::max_bound(&cur.lo, &Bound::Finite(new_lo)),
7196 hi: cur.hi,
7197 },
7198 );
7199}
7200
7201const MAX_FIXPOINT_NESTING: usize = 4;
7213
7214fn rich_walk_loop(
7215 cond: Option<&Expr>,
7216 body: &[Stmt],
7217 st: &mut RichAbstractState,
7218 loop_var: Option<Symbol>,
7219 facts: &mut OracleFacts,
7220 loop_key: Option<usize>,
7221) {
7222 let body_writes = WriteSet::of_block(body).with_callee_globals(&st.callee_globals);
7223 if body_writes.is_opaque() {
7224 st.forget_everything();
7226 return;
7227 }
7228 let mut mutated: Vec<Symbol> = body_writes.symbols().collect();
7229 if let Some(lv) = loop_var {
7230 if !mutated.contains(&lv) {
7231 mutated.push(lv);
7232 }
7233 }
7234 let breaks = crate::loop_shape::leaves_by_break(body);
7237 if facts.loop_depth >= MAX_FIXPOINT_NESTING {
7238 rich_walk_loop_widened(cond, body, st, &mutated, breaks, facts, loop_key);
7239 return;
7240 }
7241 facts.loop_depth += 1;
7242 rich_walk_loop_fixpoint(cond, body, st, loop_var, &mutated, breaks, facts, loop_key);
7243 facts.loop_depth -= 1;
7244}
7245
7246fn rich_walk_loop_widened(
7250 cond: Option<&Expr>,
7251 body: &[Stmt],
7252 st: &mut RichAbstractState,
7253 mutated: &[Symbol],
7254 breaks: bool,
7255 facts: &mut OracleFacts,
7256 loop_key: Option<usize>,
7257) {
7258 for &m in mutated {
7259 st.karr_unknown(m);
7260 st.invalidate_var(m);
7261 st.aliases.unlink(m);
7262 st.intervals.set_length(m, Interval::non_negative());
7263 st.length_def.remove(&m);
7264 }
7265 let mut record_state = st.clone();
7266 if let Some(c) = cond {
7267 narrow_state(c, &mut record_state.intervals);
7268 }
7269 if let Some(key) = loop_key {
7277 match facts.loop_aliases.entry(key) {
7278 std::collections::hash_map::Entry::Occupied(mut e) => {
7279 e.get_mut().union_from(&record_state.aliases);
7280 }
7281 std::collections::hash_map::Entry::Vacant(v) => {
7282 v.insert(record_state.aliases.clone());
7283 }
7284 }
7285 }
7286 let header = record_state.clone();
7287 if let Some(c) = cond {
7288 record_loop_index_bounds(c, body, &record_state, facts);
7289 record_affine_index_bounds(c, body, &record_state, st, facts, false);
7290 if let Some(key) = loop_key {
7291 record_hoist_speculation(c, body, &record_state, facts, key);
7292 }
7293 }
7294 rich_walk_block(body, &mut record_state, facts);
7295 if let Some(c) = cond {
7296 record_expr(c, &record_state, facts);
7297 record_affine_index_bounds(c, body, &header, st, facts, true);
7298 }
7299 if let Some(c) = cond.filter(|_| !breaks) {
7300 narrow_state_negated(c, &mut st.intervals);
7301 }
7302}
7303
7304fn rich_walk_loop_fixpoint(
7305 cond: Option<&Expr>,
7306 body: &[Stmt],
7307 st: &mut RichAbstractState,
7308 loop_var: Option<Symbol>,
7309 mutated: &[Symbol],
7310 breaks: bool,
7311 facts: &mut OracleFacts,
7312 loop_key: Option<usize>,
7313) {
7314 let mutated: Vec<Symbol> = mutated.to_vec();
7315 let mut inside = st.clone();
7318 if let Some(lv) = loop_var {
7319 inside.invalidate_var(lv);
7320 inside.aliases.unlink(lv);
7321 inside.aliases.taint(lv);
7322 }
7323 if let Some(c) = cond {
7324 narrow_state(c, &mut inside.intervals);
7325 refine_invariant_bound_from_guard(c, st, &mutated, &mut inside.intervals);
7331 }
7332
7333 let mut sink = OracleFacts::default();
7336 sink.loop_depth = facts.loop_depth;
7337 let mut converged = false;
7338 for pass in 0..12 {
7339 let mut next = inside.clone();
7340 rich_walk_block(body, &mut next, &mut sink);
7341 if let Some(c) = cond {
7342 narrow_state(c, &mut next.intervals);
7343 }
7344 let mut stable = true;
7347 for &m in &mutated {
7348 let inside_fresh_elem = inside.intervals.get_elem(&m).is_bottom();
7351 let cur_iv = inside.intervals.get_var(&m);
7352 let nxt_iv = next.intervals.get_var(&m);
7353 let wid = cur_iv.widen(&nxt_iv);
7354 if !wid.leq(&cur_iv) || !cur_iv.leq(&wid) {
7355 stable = false;
7356 }
7357 inside.intervals.set_var(m, wid);
7358 let cur_len = inside.intervals.get_length(&m);
7361 let nxt_len = next.intervals.get_length(&m);
7362 let wid_len = cur_len.widen(&nxt_len);
7363 if !wid_len.leq(&cur_len) || !cur_len.leq(&wid_len) {
7364 stable = false;
7365 }
7366 inside.intervals.set_length(m, wid_len);
7367
7368 if inside.intervals.elem.contains_key(&m) || next.intervals.elem.contains_key(&m) {
7377 let cur_el = inside.intervals.get_elem(&m);
7378 let nxt_el = next.intervals.get_elem(&m);
7379 let merged = if pass < 3 {
7380 cur_el.join(&nxt_el)
7381 } else {
7382 cur_el.widen(&nxt_el)
7383 };
7384 if !(merged.leq(&cur_el) && cur_el.leq(&merged)) {
7385 stable = false;
7386 }
7387 inside.intervals.elem.insert(m, merged);
7388 }
7389
7390 let merged_sym = if inside_fresh_elem {
7395 next.elem_upper.get(&m).cloned()
7396 } else {
7397 match (
7398 inside.elem_upper.get(&m).cloned(),
7399 next.elem_upper.get(&m).cloned(),
7400 ) {
7401 (Some(e), Some(n)) => join_sym_upper(&e, &n, &next),
7402 _ => None,
7403 }
7404 };
7405 if inside.elem_upper.get(&m) != merged_sym.as_ref() {
7406 stable = false;
7407 }
7408 match merged_sym {
7409 Some(l) => {
7410 inside.elem_upper.insert(m, l);
7411 }
7412 None => {
7413 inside.elem_upper.remove(&m);
7414 }
7415 }
7416 let merged_et = if inside_fresh_elem {
7423 next.elem_type.get(&m).cloned()
7424 } else {
7425 match (
7426 inside.elem_type.get(&m).cloned(),
7427 next.elem_type.get(&m).cloned(),
7428 ) {
7429 (Some(e), Some(n)) => Some(e.join(&n)),
7430 _ => None,
7431 }
7432 };
7433 if inside.elem_type.get(&m) != merged_et.as_ref() {
7434 stable = false;
7435 }
7436 match merged_et {
7437 Some(t) => {
7438 inside.elem_type.insert(m, t);
7439 }
7440 None => {
7441 inside.elem_type.remove(&m);
7442 }
7443 }
7444 let merged_su = match (
7450 inside.scalar_upper.get(&m).cloned(),
7451 next.scalar_upper.get(&m).cloned(),
7452 ) {
7453 (Some(a), Some(b)) if a == b => Some(a),
7454 (None, Some(b)) => Some(b),
7455 _ => None,
7456 };
7457 if inside.scalar_upper.get(&m) != merged_su.as_ref() {
7458 stable = false;
7459 }
7460 match merged_su {
7461 Some(l) => {
7462 inside.scalar_upper.insert(m, l);
7463 }
7464 None => {
7465 inside.scalar_upper.remove(&m);
7466 }
7467 }
7468 let merged_sl = match (
7469 inside.scalar_lower.get(&m).cloned(),
7470 next.scalar_lower.get(&m).cloned(),
7471 ) {
7472 (Some(a), Some(b)) if a == b => Some(a),
7473 (None, Some(b)) => Some(b),
7474 _ => None,
7475 };
7476 if inside.scalar_lower.get(&m) != merged_sl.as_ref() {
7477 stable = false;
7478 }
7479 match merged_sl {
7480 Some(l) => {
7481 inside.scalar_lower.insert(m, l);
7482 }
7483 None => {
7484 inside.scalar_lower.remove(&m);
7485 }
7486 }
7487
7488 let cur_ty = inside
7489 .types
7490 .get(&m)
7491 .cloned()
7492 .unwrap_or(TypeAbstraction::Top);
7493 let nxt_ty = next.types.get(&m).cloned().unwrap_or(TypeAbstraction::Top);
7494 let j = cur_ty.join(&nxt_ty);
7495 if !(j.leq(&cur_ty) && cur_ty.leq(&j)) {
7496 stable = false;
7497 }
7498 inside.types.insert(m, j);
7499
7500 let cur_sh = inside
7501 .shapes
7502 .get(&m)
7503 .cloned()
7504 .unwrap_or(CollectionShape::Top);
7505 let nxt_sh = next.shapes.get(&m).cloned().unwrap_or(CollectionShape::Top);
7506 inside.shapes.insert(m, cur_sh.widen(&nxt_sh));
7507
7508 if !next.coll_vars.contains(&m) {
7511 inside.coll_vars.remove(&m);
7512 }
7513
7514 let cur_n = inside
7515 .nullability
7516 .get(&m)
7517 .cloned()
7518 .unwrap_or(Nullability::Maybe);
7519 let nxt_n = next
7520 .nullability
7521 .get(&m)
7522 .cloned()
7523 .unwrap_or(Nullability::Maybe);
7524 inside.nullability.insert(m, cur_n.join(&nxt_n));
7525 }
7526 if inside.aliases.union_from(&next.aliases) {
7531 stable = false;
7532 }
7533 let hull = inside.karr.join(&next.karr);
7536 if !hull.leq(&inside.karr) {
7537 stable = false;
7538 }
7539 inside.karr = hull;
7540 let seqs_before = inside.seq_vars.len();
7541 inside.seq_vars.retain(|s| next.seq_vars.contains(s));
7542 if inside.seq_vars.len() != seqs_before {
7543 stable = false;
7544 }
7545 if stable {
7546 converged = true;
7547 break;
7548 }
7549 }
7550
7551 if converged {
7552 if let Some(key) = loop_key {
7556 match facts.loop_aliases.entry(key) {
7557 std::collections::hash_map::Entry::Occupied(mut e) => {
7558 e.get_mut().union_from(&inside.aliases);
7559 }
7560 std::collections::hash_map::Entry::Vacant(v) => {
7561 v.insert(inside.aliases.clone());
7562 }
7563 }
7564 }
7565 const NARROW_PASSES: usize = 4;
7578 for _ in 0..NARROW_PASSES {
7579 let mut probe = inside.clone();
7580 let mut narrow_sink = OracleFacts::default();
7581 narrow_sink.loop_depth = facts.loop_depth;
7582 rich_walk_block(body, &mut probe, &mut narrow_sink);
7583 if let Some(c) = cond {
7584 narrow_state(c, &mut probe.intervals);
7585 }
7586 let mut tightened = false;
7587 for &m in &mutated {
7588 let cur = inside.intervals.get_var(&m);
7589 let narrowed = cur.narrow(&probe.intervals.get_var(&m));
7590 if !(narrowed.leq(&cur) && cur.leq(&narrowed)) {
7591 tightened = true;
7592 }
7593 inside.intervals.set_var(m, narrowed);
7594 }
7595 if !tightened {
7596 break;
7597 }
7598 }
7599
7600 let mut record_state = inside.clone();
7605 if let Some(c) = cond {
7606 narrow_state(c, &mut record_state.intervals);
7607 }
7608 let header = record_state.clone();
7614 if let Some(c) = cond {
7615 record_loop_index_bounds(c, body, &record_state, facts);
7616 record_affine_index_bounds(c, body, &record_state, st, facts, false);
7622 if let Some(key) = loop_key {
7623 record_hoist_speculation(c, body, &record_state, facts, key);
7624 }
7625 }
7626 rich_walk_block(body, &mut record_state, facts);
7627 if let Some(c) = cond {
7630 record_expr(c, &record_state, facts);
7631 }
7632 if let Some(c) = cond {
7634 record_affine_index_bounds(c, body, &header, st, facts, true);
7635 }
7636 let mut after = rich_join(st, &inside);
7637 if breaks {
7638 after.forget_written(&mutated);
7639 } else if let Some(c) = cond {
7640 narrow_state_negated(c, &mut after.intervals);
7641 karr_counted_exit(c, body, st, &mut after);
7642 for bl in infer_build_length(c, body, st) {
7649 match bl {
7650 BuildLength::Symbolic(arr, n, off) => {
7651 after.length_def.insert(arr, (n, off));
7652 }
7653 BuildLength::Concrete(arr, len) => {
7654 after.intervals.set_length(arr, len);
7655 }
7656 }
7657 }
7658 }
7659 if !breaks && !st.entry_guard_lowers.is_empty() {
7671 if let Some(Expr::BinaryOp {
7672 op: BinaryOpKind::Lt,
7673 left: Expr::Identifier(j),
7674 right: Expr::Identifier(hi),
7675 }) = cond
7676 {
7677 if top_level_unconditional_incs(body, &st.callee_globals)
7678 .iter()
7679 .any(|(v, d)| v == j && *d == 1)
7680 {
7681 for i in monotone_inc_vars(body, 1) {
7682 if i != *j {
7683 if let (Some(di), Some(dj)) =
7684 (st.scalar_def.get(&i), st.scalar_def.get(j))
7685 {
7686 if di == dj {
7687 let lo_def = di.clone();
7688 after.scalar_lower.entry(i).or_insert(lo_def);
7689 after
7690 .scalar_upper
7691 .entry(i)
7692 .or_insert_with(|| super::affine::var(*hi));
7693 }
7694 }
7695 }
7696 }
7697 }
7698 }
7699 }
7700 *st = after;
7701 } else {
7702 if let Some(c) = cond.filter(|_| !breaks) {
7704 narrow_state_negated(c, &mut st.intervals);
7705 }
7706 for m in mutated {
7707 st.karr_unknown(m);
7708 st.intervals.set_var(m, Interval::top());
7709 st.intervals.set_length(m, Interval::non_negative());
7710 st.types.insert(m, TypeAbstraction::Top);
7711 st.shapes.insert(m, CollectionShape::Top);
7712 st.nullability.insert(m, Nullability::Maybe);
7713 st.coll_vars.remove(&m);
7714 }
7715 }
7716}
7717
7718fn rich_walk_inspect(
7719 target: &Expr,
7720 arms: &[MatchArm],
7721 st: &mut RichAbstractState,
7722 facts: &mut OracleFacts,
7723) {
7724 if arms.is_empty() {
7725 return;
7726 }
7727 let mut acc: Option<RichAbstractState> = None;
7728 for arm in arms {
7729 let mut arm_st = st.clone();
7730 if arm.variant.is_some() {
7733 if let Expr::Identifier(sym) = target {
7734 arm_st.nullability.insert(*sym, Nullability::Definite);
7735 }
7736 for (_field, binding) in &arm.bindings {
7737 arm_st.nullability.insert(*binding, Nullability::Definite);
7738 }
7739 }
7740 for (_field, binding) in &arm.bindings {
7743 arm_st.aliases.unlink(*binding);
7744 arm_st.aliases.taint(*binding);
7745 }
7746 rich_walk_block(arm.body, &mut arm_st, facts);
7747 acc = Some(match acc {
7748 None => arm_st,
7749 Some(prev) => rich_join(&prev, &arm_st),
7750 });
7751 }
7752 if let Some(joined) = acc {
7753 *st = joined;
7754 }
7755}
7756
7757fn rich_join(a: &RichAbstractState, b: &RichAbstractState) -> RichAbstractState {
7758 let mut intervals = AbstractState::new();
7759 join_states(&mut intervals, &a.intervals, &b.intervals);
7760 RichAbstractState {
7761 intervals,
7762 types: join_maps(&a.types, &b.types),
7763 shapes: join_maps(&a.shapes, &b.shapes),
7764 nullability: join_maps(&a.nullability, &b.nullability),
7765 aliases: alias_union(&a.aliases, &b.aliases),
7766 coll_vars: a.coll_vars.intersection(&b.coll_vars).cloned().collect(),
7768 fn_returns: a.fn_returns.clone(),
7769 callee_globals: a.callee_globals.clone(),
7770 length_def: a
7772 .length_def
7773 .iter()
7774 .filter(|(k, v)| b.length_def.get(k) == Some(v))
7775 .map(|(k, v)| (*k, *v))
7776 .collect(),
7777 param_colls: a.param_colls.union(&b.param_colls).copied().collect(),
7779 scalar_def: a
7782 .scalar_def
7783 .iter()
7784 .filter(|(k, v)| b.scalar_def.get(*k) == Some(*v))
7785 .map(|(k, v)| (*k, v.clone()))
7786 .collect(),
7787 scalar_upper: a
7791 .scalar_upper
7792 .iter()
7793 .filter(|(k, v)| b.scalar_upper.get(*k) == Some(*v))
7794 .map(|(k, v)| (*k, v.clone()))
7795 .collect(),
7796 elem_upper: join_elem_upper_maps(a, b),
7797 elem_type: join_elem_type_maps(a, b),
7798 scalar_lower: a
7799 .scalar_lower
7800 .iter()
7801 .filter(|(k, v)| b.scalar_lower.get(*k) == Some(*v))
7802 .map(|(k, v)| (*k, v.clone()))
7803 .collect(),
7804 aot_entry_guard: a.aot_entry_guard || b.aot_entry_guard,
7807 entry_guard_lowers: if a.entry_guard_lowers.is_empty() {
7808 b.entry_guard_lowers.clone()
7809 } else {
7810 a.entry_guard_lowers.clone()
7811 },
7812 karr: a.karr.join(&b.karr),
7813 seq_vars: a.seq_vars.intersection(&b.seq_vars).copied().collect(),
7814 seq_types: a.seq_types.clone(),
7815 len_summaries: a.len_summaries.clone(),
7816 }
7817}
7818
7819fn join_elem_upper_maps(
7826 a: &RichAbstractState,
7827 b: &RichAbstractState,
7828) -> HashMap<Symbol, super::affine::LinExpr> {
7829 let mut out = HashMap::new();
7830 let keys: HashSet<Symbol> = a
7831 .elem_upper
7832 .keys()
7833 .chain(b.elem_upper.keys())
7834 .cloned()
7835 .collect();
7836 for key in keys {
7837 let a_bot = a.intervals.get_elem(&key).is_bottom();
7838 let b_bot = b.intervals.get_elem(&key).is_bottom();
7839 let v = if a_bot {
7840 b.elem_upper.get(&key).cloned()
7841 } else if b_bot {
7842 a.elem_upper.get(&key).cloned()
7843 } else {
7844 match (a.elem_upper.get(&key), b.elem_upper.get(&key)) {
7845 (Some(x), Some(y)) => join_sym_upper(x, y, b),
7846 _ => None,
7847 }
7848 };
7849 if let Some(l) = v {
7850 out.insert(key, l);
7851 }
7852 }
7853 out
7854}
7855
7856fn join_elem_type_maps(
7862 a: &RichAbstractState,
7863 b: &RichAbstractState,
7864) -> HashMap<Symbol, TypeAbstraction> {
7865 let mut out = HashMap::new();
7866 let keys: HashSet<Symbol> = a
7867 .elem_type
7868 .keys()
7869 .chain(b.elem_type.keys())
7870 .cloned()
7871 .collect();
7872 for key in keys {
7873 let a_bot = a.intervals.get_elem(&key).is_bottom();
7874 let b_bot = b.intervals.get_elem(&key).is_bottom();
7875 let v = if a_bot {
7876 b.elem_type.get(&key).cloned()
7877 } else if b_bot {
7878 a.elem_type.get(&key).cloned()
7879 } else {
7880 match (a.elem_type.get(&key), b.elem_type.get(&key)) {
7881 (Some(x), Some(y)) => Some(x.join(y)),
7882 _ => None,
7883 }
7884 };
7885 if let Some(t) = v {
7886 out.insert(key, t);
7887 }
7888 }
7889 out
7890}
7891
7892fn join_maps<V: AbstractDomain>(
7893 a: &HashMap<Symbol, V>,
7894 b: &HashMap<Symbol, V>,
7895) -> HashMap<Symbol, V> {
7896 let mut out = HashMap::new();
7897 let keys: HashSet<Symbol> = a.keys().chain(b.keys()).cloned().collect();
7898 for k in keys {
7899 let top = V::top();
7900 let va = a.get(&k).unwrap_or(&top);
7901 let vb = b.get(&k).unwrap_or(&top);
7902 out.insert(k, va.join(vb));
7903 }
7904 out
7905}
7906
7907fn alias_union(a: &AliasGraph, b: &AliasGraph) -> AliasGraph {
7908 let mut out = a.clone();
7909 out.union_from(b);
7910 out
7911}
7912
7913fn collect_mutations(block: &[Stmt]) -> Vec<Symbol> {
7916 collect_mutations_in(block, &CalleeGlobals::default())
7917}
7918
7919fn collect_mutations_in(block: &[Stmt], globals: &CalleeGlobals) -> Vec<Symbol> {
7922 let writes = WriteSet::of_block(block).with_callee_globals(globals);
7923 let mut out: Vec<Symbol> = writes.symbols().collect();
7924 if writes.is_opaque() {
7925 for s in block {
7926 collect_idents_stmt(s, &mut |sym, _| {
7927 if !out.contains(&sym) {
7928 out.push(sym);
7929 }
7930 });
7931 }
7932 }
7933 out
7934}
7935
7936#[cfg(test)]
7937#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/domain_tests.rs"]
7938mod domain_tests;
7939
7940#[cfg(test)]
7941#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/type_domain_tests.rs"]
7942mod type_domain_tests;
7943
7944#[cfg(test)]
7945#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/shape_domain_tests.rs"]
7946mod shape_domain_tests;
7947
7948#[cfg(test)]
7949#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/nullability_domain_tests.rs"]
7950mod nullability_domain_tests;
7951
7952#[cfg(test)]
7953#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/alias_domain_tests.rs"]
7954mod alias_domain_tests;
7955
7956#[cfg(test)]
7957#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/product_lattice_tests.rs"]
7958mod product_lattice_tests;
7959
7960#[cfg(test)]
7961#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/rich_walk_tests.rs"]
7962mod rich_walk_tests;
7963
7964#[cfg(test)]
7965#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/hoist_order_tests.rs"]
7966mod hoist_order_tests;