xref: /llvm-project/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp (revision a1580d7b59b65b17f2ce7fdb95f46379e7df4089)
1 //== RangeConstraintManager.cpp - Manage range constraints.------*- C++ -*--==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines RangeConstraintManager, a class that tracks simple
10 //  equality and inequality constraints on symbolic values of ProgramState.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/JsonSupport.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/ImmutableSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <iterator>
29 #include <optional>
30 
31 using namespace clang;
32 using namespace ento;
33 
34 // This class can be extended with other tables which will help to reason
35 // about ranges more precisely.
36 class OperatorRelationsTable {
37   static_assert(BO_LT < BO_GT && BO_GT < BO_LE && BO_LE < BO_GE &&
38                     BO_GE < BO_EQ && BO_EQ < BO_NE,
39                 "This class relies on operators order. Rework it otherwise.");
40 
41 public:
42   enum TriStateKind {
43     False = 0,
44     True,
45     Unknown,
46   };
47 
48 private:
49   // CmpOpTable holds states which represent the corresponding range for
50   // branching an exploded graph. We can reason about the branch if there is
51   // a previously known fact of the existence of a comparison expression with
52   // operands used in the current expression.
53   // E.g. assuming (x < y) is true that means (x != y) is surely true.
54   // if (x previous_operation y)  // <    | !=      | >
55   //   if (x operation y)         // !=   | >       | <
56   //     tristate                 // True | Unknown | False
57   //
58   // CmpOpTable represents next:
59   // __|< |> |<=|>=|==|!=|UnknownX2|
60   // < |1 |0 |* |0 |0 |* |1        |
61   // > |0 |1 |0 |* |0 |* |1        |
62   // <=|1 |0 |1 |* |1 |* |0        |
63   // >=|0 |1 |* |1 |1 |* |0        |
64   // ==|0 |0 |* |* |1 |0 |1        |
65   // !=|1 |1 |* |* |0 |1 |0        |
66   //
67   // Columns stands for a previous operator.
68   // Rows stands for a current operator.
69   // Each row has exactly two `Unknown` cases.
70   // UnknownX2 means that both `Unknown` previous operators are met in code,
71   // and there is a special column for that, for example:
72   // if (x >= y)
73   //   if (x != y)
74   //     if (x <= y)
75   //       False only
76   static constexpr size_t CmpOpCount = BO_NE - BO_LT + 1;
77   const TriStateKind CmpOpTable[CmpOpCount][CmpOpCount + 1] = {
78       // <      >      <=     >=     ==     !=    UnknownX2
79       {True, False, Unknown, False, False, Unknown, True}, // <
80       {False, True, False, Unknown, False, Unknown, True}, // >
81       {True, False, True, Unknown, True, Unknown, False},  // <=
82       {False, True, Unknown, True, True, Unknown, False},  // >=
83       {False, False, Unknown, Unknown, True, False, True}, // ==
84       {True, True, Unknown, Unknown, False, True, False},  // !=
85   };
86 
87   static size_t getIndexFromOp(BinaryOperatorKind OP) {
88     return static_cast<size_t>(OP - BO_LT);
89   }
90 
91 public:
92   constexpr size_t getCmpOpCount() const { return CmpOpCount; }
93 
94   static BinaryOperatorKind getOpFromIndex(size_t Index) {
95     return static_cast<BinaryOperatorKind>(Index + BO_LT);
96   }
97 
98   TriStateKind getCmpOpState(BinaryOperatorKind CurrentOP,
99                              BinaryOperatorKind QueriedOP) const {
100     return CmpOpTable[getIndexFromOp(CurrentOP)][getIndexFromOp(QueriedOP)];
101   }
102 
103   TriStateKind getCmpOpStateForUnknownX2(BinaryOperatorKind CurrentOP) const {
104     return CmpOpTable[getIndexFromOp(CurrentOP)][CmpOpCount];
105   }
106 };
107 
108 //===----------------------------------------------------------------------===//
109 //                           RangeSet implementation
110 //===----------------------------------------------------------------------===//
111 
112 RangeSet::ContainerType RangeSet::Factory::EmptySet{};
113 
114 RangeSet RangeSet::Factory::add(RangeSet LHS, RangeSet RHS) {
115   ContainerType Result;
116   Result.reserve(LHS.size() + RHS.size());
117   std::merge(LHS.begin(), LHS.end(), RHS.begin(), RHS.end(),
118              std::back_inserter(Result));
119   return makePersistent(std::move(Result));
120 }
121 
122 RangeSet RangeSet::Factory::add(RangeSet Original, Range Element) {
123   ContainerType Result;
124   Result.reserve(Original.size() + 1);
125 
126   const_iterator Lower = llvm::lower_bound(Original, Element);
127   Result.insert(Result.end(), Original.begin(), Lower);
128   Result.push_back(Element);
129   Result.insert(Result.end(), Lower, Original.end());
130 
131   return makePersistent(std::move(Result));
132 }
133 
134 RangeSet RangeSet::Factory::add(RangeSet Original, const llvm::APSInt &Point) {
135   return add(Original, Range(Point));
136 }
137 
138 RangeSet RangeSet::Factory::unite(RangeSet LHS, RangeSet RHS) {
139   ContainerType Result = unite(*LHS.Impl, *RHS.Impl);
140   return makePersistent(std::move(Result));
141 }
142 
143 RangeSet RangeSet::Factory::unite(RangeSet Original, Range R) {
144   ContainerType Result;
145   Result.push_back(R);
146   Result = unite(*Original.Impl, Result);
147   return makePersistent(std::move(Result));
148 }
149 
150 RangeSet RangeSet::Factory::unite(RangeSet Original, llvm::APSInt Point) {
151   return unite(Original, Range(ValueFactory.getValue(Point)));
152 }
153 
154 RangeSet RangeSet::Factory::unite(RangeSet Original, llvm::APSInt From,
155                                   llvm::APSInt To) {
156   return unite(Original,
157                Range(ValueFactory.getValue(From), ValueFactory.getValue(To)));
158 }
159 
160 template <typename T>
161 void swapIterators(T &First, T &FirstEnd, T &Second, T &SecondEnd) {
162   std::swap(First, Second);
163   std::swap(FirstEnd, SecondEnd);
164 }
165 
166 RangeSet::ContainerType RangeSet::Factory::unite(const ContainerType &LHS,
167                                                  const ContainerType &RHS) {
168   if (LHS.empty())
169     return RHS;
170   if (RHS.empty())
171     return LHS;
172 
173   using llvm::APSInt;
174   using iterator = ContainerType::const_iterator;
175 
176   iterator First = LHS.begin();
177   iterator FirstEnd = LHS.end();
178   iterator Second = RHS.begin();
179   iterator SecondEnd = RHS.end();
180   APSIntType Ty = APSIntType(First->From());
181   const APSInt Min = Ty.getMinValue();
182 
183   // Handle a corner case first when both range sets start from MIN.
184   // This helps to avoid complicated conditions below. Specifically, this
185   // particular check for `MIN` is not needed in the loop below every time
186   // when we do `Second->From() - One` operation.
187   if (Min == First->From() && Min == Second->From()) {
188     if (First->To() > Second->To()) {
189       //    [ First    ]--->
190       //    [ Second ]----->
191       // MIN^
192       // The Second range is entirely inside the First one.
193 
194       // Check if Second is the last in its RangeSet.
195       if (++Second == SecondEnd)
196         //    [ First     ]--[ First + 1 ]--->
197         //    [ Second ]--------------------->
198         // MIN^
199         // The Union is equal to First's RangeSet.
200         return LHS;
201     } else {
202       // case 1: [ First ]----->
203       // case 2: [ First   ]--->
204       //         [ Second  ]--->
205       //      MIN^
206       // The First range is entirely inside or equal to the Second one.
207 
208       // Check if First is the last in its RangeSet.
209       if (++First == FirstEnd)
210         //    [ First ]----------------------->
211         //    [ Second  ]--[ Second + 1 ]---->
212         // MIN^
213         // The Union is equal to Second's RangeSet.
214         return RHS;
215     }
216   }
217 
218   const APSInt One = Ty.getValue(1);
219   ContainerType Result;
220 
221   // This is called when there are no ranges left in one of the ranges.
222   // Append the rest of the ranges from another range set to the Result
223   // and return with that.
224   const auto AppendTheRest = [&Result](iterator I, iterator E) {
225     Result.append(I, E);
226     return Result;
227   };
228 
229   while (true) {
230     // We want to keep the following invariant at all times:
231     // ---[ First ------>
232     // -----[ Second --->
233     if (First->From() > Second->From())
234       swapIterators(First, FirstEnd, Second, SecondEnd);
235 
236     // The Union definitely starts with First->From().
237     // ----------[ First ------>
238     // ------------[ Second --->
239     // ----------[ Union ------>
240     // UnionStart^
241     const llvm::APSInt &UnionStart = First->From();
242 
243     // Loop where the invariant holds.
244     while (true) {
245       // Skip all enclosed ranges.
246       // ---[                  First                     ]--->
247       // -----[ Second ]--[ Second + 1 ]--[ Second + N ]----->
248       while (First->To() >= Second->To()) {
249         // Check if Second is the last in its RangeSet.
250         if (++Second == SecondEnd) {
251           // Append the Union.
252           // ---[ Union      ]--->
253           // -----[ Second ]----->
254           // --------[ First ]--->
255           //         UnionEnd^
256           Result.emplace_back(UnionStart, First->To());
257           // ---[ Union ]----------------->
258           // --------------[ First + 1]--->
259           // Append all remaining ranges from the First's RangeSet.
260           return AppendTheRest(++First, FirstEnd);
261         }
262       }
263 
264       // Check if First and Second are disjoint. It means that we find
265       // the end of the Union. Exit the loop and append the Union.
266       // ---[ First ]=------------->
267       // ------------=[ Second ]--->
268       // ----MinusOne^
269       if (First->To() < Second->From() - One)
270         break;
271 
272       // First is entirely inside the Union. Go next.
273       // ---[ Union ----------->
274       // ---- [ First ]-------->
275       // -------[ Second ]----->
276       // Check if First is the last in its RangeSet.
277       if (++First == FirstEnd) {
278         // Append the Union.
279         // ---[ Union       ]--->
280         // -----[ First ]------->
281         // --------[ Second ]--->
282         //          UnionEnd^
283         Result.emplace_back(UnionStart, Second->To());
284         // ---[ Union ]------------------>
285         // --------------[ Second + 1]--->
286         // Append all remaining ranges from the Second's RangeSet.
287         return AppendTheRest(++Second, SecondEnd);
288       }
289 
290       // We know that we are at one of the two cases:
291       // case 1: --[ First ]--------->
292       // case 2: ----[ First ]------->
293       // --------[ Second ]---------->
294       // In both cases First starts after Second->From().
295       // Make sure that the loop invariant holds.
296       swapIterators(First, FirstEnd, Second, SecondEnd);
297     }
298 
299     // Here First and Second are disjoint.
300     // Append the Union.
301     // ---[ Union    ]--------------->
302     // -----------------[ Second ]--->
303     // ------[ First ]--------------->
304     //       UnionEnd^
305     Result.emplace_back(UnionStart, First->To());
306 
307     // Check if First is the last in its RangeSet.
308     if (++First == FirstEnd)
309       // ---[ Union ]--------------->
310       // --------------[ Second ]--->
311       // Append all remaining ranges from the Second's RangeSet.
312       return AppendTheRest(Second, SecondEnd);
313   }
314 
315   llvm_unreachable("Normally, we should not reach here");
316 }
317 
318 RangeSet RangeSet::Factory::getRangeSet(Range From) {
319   ContainerType Result;
320   Result.push_back(From);
321   return makePersistent(std::move(Result));
322 }
323 
324 RangeSet RangeSet::Factory::makePersistent(ContainerType &&From) {
325   llvm::FoldingSetNodeID ID;
326   void *InsertPos;
327 
328   From.Profile(ID);
329   ContainerType *Result = Cache.FindNodeOrInsertPos(ID, InsertPos);
330 
331   if (!Result) {
332     // It is cheaper to fully construct the resulting range on stack
333     // and move it to the freshly allocated buffer if we don't have
334     // a set like this already.
335     Result = construct(std::move(From));
336     Cache.InsertNode(Result, InsertPos);
337   }
338 
339   return Result;
340 }
341 
342 RangeSet::ContainerType *RangeSet::Factory::construct(ContainerType &&From) {
343   void *Buffer = Arena.Allocate();
344   return new (Buffer) ContainerType(std::move(From));
345 }
346 
347 const llvm::APSInt &RangeSet::getMinValue() const {
348   assert(!isEmpty());
349   return begin()->From();
350 }
351 
352 const llvm::APSInt &RangeSet::getMaxValue() const {
353   assert(!isEmpty());
354   return std::prev(end())->To();
355 }
356 
357 bool clang::ento::RangeSet::isUnsigned() const {
358   assert(!isEmpty());
359   return begin()->From().isUnsigned();
360 }
361 
362 uint32_t clang::ento::RangeSet::getBitWidth() const {
363   assert(!isEmpty());
364   return begin()->From().getBitWidth();
365 }
366 
367 APSIntType clang::ento::RangeSet::getAPSIntType() const {
368   assert(!isEmpty());
369   return APSIntType(begin()->From());
370 }
371 
372 bool RangeSet::containsImpl(llvm::APSInt &Point) const {
373   if (isEmpty() || !pin(Point))
374     return false;
375 
376   Range Dummy(Point);
377   const_iterator It = llvm::upper_bound(*this, Dummy);
378   if (It == begin())
379     return false;
380 
381   return std::prev(It)->Includes(Point);
382 }
383 
384 bool RangeSet::pin(llvm::APSInt &Point) const {
385   APSIntType Type(getMinValue());
386   if (Type.testInRange(Point, true) != APSIntType::RTR_Within)
387     return false;
388 
389   Type.apply(Point);
390   return true;
391 }
392 
393 bool RangeSet::pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
394   // This function has nine cases, the cartesian product of range-testing
395   // both the upper and lower bounds against the symbol's type.
396   // Each case requires a different pinning operation.
397   // The function returns false if the described range is entirely outside
398   // the range of values for the associated symbol.
399   APSIntType Type(getMinValue());
400   APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower, true);
401   APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper, true);
402 
403   switch (LowerTest) {
404   case APSIntType::RTR_Below:
405     switch (UpperTest) {
406     case APSIntType::RTR_Below:
407       // The entire range is outside the symbol's set of possible values.
408       // If this is a conventionally-ordered range, the state is infeasible.
409       if (Lower <= Upper)
410         return false;
411 
412       // However, if the range wraps around, it spans all possible values.
413       Lower = Type.getMinValue();
414       Upper = Type.getMaxValue();
415       break;
416     case APSIntType::RTR_Within:
417       // The range starts below what's possible but ends within it. Pin.
418       Lower = Type.getMinValue();
419       Type.apply(Upper);
420       break;
421     case APSIntType::RTR_Above:
422       // The range spans all possible values for the symbol. Pin.
423       Lower = Type.getMinValue();
424       Upper = Type.getMaxValue();
425       break;
426     }
427     break;
428   case APSIntType::RTR_Within:
429     switch (UpperTest) {
430     case APSIntType::RTR_Below:
431       // The range wraps around, but all lower values are not possible.
432       Type.apply(Lower);
433       Upper = Type.getMaxValue();
434       break;
435     case APSIntType::RTR_Within:
436       // The range may or may not wrap around, but both limits are valid.
437       Type.apply(Lower);
438       Type.apply(Upper);
439       break;
440     case APSIntType::RTR_Above:
441       // The range starts within what's possible but ends above it. Pin.
442       Type.apply(Lower);
443       Upper = Type.getMaxValue();
444       break;
445     }
446     break;
447   case APSIntType::RTR_Above:
448     switch (UpperTest) {
449     case APSIntType::RTR_Below:
450       // The range wraps but is outside the symbol's set of possible values.
451       return false;
452     case APSIntType::RTR_Within:
453       // The range starts above what's possible but ends within it (wrap).
454       Lower = Type.getMinValue();
455       Type.apply(Upper);
456       break;
457     case APSIntType::RTR_Above:
458       // The entire range is outside the symbol's set of possible values.
459       // If this is a conventionally-ordered range, the state is infeasible.
460       if (Lower <= Upper)
461         return false;
462 
463       // However, if the range wraps around, it spans all possible values.
464       Lower = Type.getMinValue();
465       Upper = Type.getMaxValue();
466       break;
467     }
468     break;
469   }
470 
471   return true;
472 }
473 
474 RangeSet RangeSet::Factory::intersect(RangeSet What, llvm::APSInt Lower,
475                                       llvm::APSInt Upper) {
476   if (What.isEmpty() || !What.pin(Lower, Upper))
477     return getEmptySet();
478 
479   ContainerType DummyContainer;
480 
481   if (Lower <= Upper) {
482     // [Lower, Upper] is a regular range.
483     //
484     // Shortcut: check that there is even a possibility of the intersection
485     //           by checking the two following situations:
486     //
487     //               <---[  What  ]---[------]------>
488     //                              Lower  Upper
489     //                            -or-
490     //               <----[------]----[  What  ]---->
491     //                  Lower  Upper
492     if (What.getMaxValue() < Lower || Upper < What.getMinValue())
493       return getEmptySet();
494 
495     DummyContainer.push_back(
496         Range(ValueFactory.getValue(Lower), ValueFactory.getValue(Upper)));
497   } else {
498     // [Lower, Upper] is an inverted range, i.e. [MIN, Upper] U [Lower, MAX]
499     //
500     // Shortcut: check that there is even a possibility of the intersection
501     //           by checking the following situation:
502     //
503     //               <------]---[  What  ]---[------>
504     //                    Upper             Lower
505     if (What.getMaxValue() < Lower && Upper < What.getMinValue())
506       return getEmptySet();
507 
508     DummyContainer.push_back(
509         Range(ValueFactory.getMinValue(Upper), ValueFactory.getValue(Upper)));
510     DummyContainer.push_back(
511         Range(ValueFactory.getValue(Lower), ValueFactory.getMaxValue(Lower)));
512   }
513 
514   return intersect(*What.Impl, DummyContainer);
515 }
516 
517 RangeSet RangeSet::Factory::intersect(const RangeSet::ContainerType &LHS,
518                                       const RangeSet::ContainerType &RHS) {
519   ContainerType Result;
520   Result.reserve(std::max(LHS.size(), RHS.size()));
521 
522   const_iterator First = LHS.begin(), Second = RHS.begin(),
523                  FirstEnd = LHS.end(), SecondEnd = RHS.end();
524 
525   // If we ran out of ranges in one set, but not in the other,
526   // it means that those elements are definitely not in the
527   // intersection.
528   while (First != FirstEnd && Second != SecondEnd) {
529     // We want to keep the following invariant at all times:
530     //
531     //    ----[ First ---------------------->
532     //    --------[ Second ----------------->
533     if (Second->From() < First->From())
534       swapIterators(First, FirstEnd, Second, SecondEnd);
535 
536     // Loop where the invariant holds:
537     do {
538       // Check for the following situation:
539       //
540       //    ----[ First ]--------------------->
541       //    ---------------[ Second ]--------->
542       //
543       // which means that...
544       if (Second->From() > First->To()) {
545         // ...First is not in the intersection.
546         //
547         // We should move on to the next range after First and break out of the
548         // loop because the invariant might not be true.
549         ++First;
550         break;
551       }
552 
553       // We have a guaranteed intersection at this point!
554       // And this is the current situation:
555       //
556       //    ----[   First   ]----------------->
557       //    -------[ Second ------------------>
558       //
559       // Additionally, it definitely starts with Second->From().
560       const llvm::APSInt &IntersectionStart = Second->From();
561 
562       // It is important to know which of the two ranges' ends
563       // is greater.  That "longer" range might have some other
564       // intersections, while the "shorter" range might not.
565       if (Second->To() > First->To()) {
566         // Here we make a decision to keep First as the "longer"
567         // range.
568         swapIterators(First, FirstEnd, Second, SecondEnd);
569       }
570 
571       // At this point, we have the following situation:
572       //
573       //    ---- First      ]-------------------->
574       //    ---- Second ]--[  Second+1 ---------->
575       //
576       // We don't know the relationship between First->From and
577       // Second->From and we don't know whether Second+1 intersects
578       // with First.
579       //
580       // However, we know that [IntersectionStart, Second->To] is
581       // a part of the intersection...
582       Result.push_back(Range(IntersectionStart, Second->To()));
583       ++Second;
584       // ...and that the invariant will hold for a valid Second+1
585       // because First->From <= Second->To < (Second+1)->From.
586     } while (Second != SecondEnd);
587   }
588 
589   if (Result.empty())
590     return getEmptySet();
591 
592   return makePersistent(std::move(Result));
593 }
594 
595 RangeSet RangeSet::Factory::intersect(RangeSet LHS, RangeSet RHS) {
596   // Shortcut: let's see if the intersection is even possible.
597   if (LHS.isEmpty() || RHS.isEmpty() || LHS.getMaxValue() < RHS.getMinValue() ||
598       RHS.getMaxValue() < LHS.getMinValue())
599     return getEmptySet();
600 
601   return intersect(*LHS.Impl, *RHS.Impl);
602 }
603 
604 RangeSet RangeSet::Factory::intersect(RangeSet LHS, llvm::APSInt Point) {
605   if (LHS.containsImpl(Point))
606     return getRangeSet(ValueFactory.getValue(Point));
607 
608   return getEmptySet();
609 }
610 
611 RangeSet RangeSet::Factory::negate(RangeSet What) {
612   if (What.isEmpty())
613     return getEmptySet();
614 
615   const llvm::APSInt SampleValue = What.getMinValue();
616   const llvm::APSInt &MIN = ValueFactory.getMinValue(SampleValue);
617   const llvm::APSInt &MAX = ValueFactory.getMaxValue(SampleValue);
618 
619   ContainerType Result;
620   Result.reserve(What.size() + (SampleValue == MIN));
621 
622   // Handle a special case for MIN value.
623   const_iterator It = What.begin();
624   const_iterator End = What.end();
625 
626   const llvm::APSInt &From = It->From();
627   const llvm::APSInt &To = It->To();
628 
629   if (From == MIN) {
630     // If the range [From, To] is [MIN, MAX], then result is also [MIN, MAX].
631     if (To == MAX) {
632       return What;
633     }
634 
635     const_iterator Last = std::prev(End);
636 
637     // Try to find and unite the following ranges:
638     // [MIN, MIN] & [MIN + 1, N] => [MIN, N].
639     if (Last->To() == MAX) {
640       // It means that in the original range we have ranges
641       //   [MIN, A], ... , [B, MAX]
642       // And the result should be [MIN, -B], ..., [-A, MAX]
643       Result.emplace_back(MIN, ValueFactory.getValue(-Last->From()));
644       // We already negated Last, so we can skip it.
645       End = Last;
646     } else {
647       // Add a separate range for the lowest value.
648       Result.emplace_back(MIN, MIN);
649     }
650 
651     // Skip adding the second range in case when [From, To] are [MIN, MIN].
652     if (To != MIN) {
653       Result.emplace_back(ValueFactory.getValue(-To), MAX);
654     }
655 
656     // Skip the first range in the loop.
657     ++It;
658   }
659 
660   // Negate all other ranges.
661   for (; It != End; ++It) {
662     // Negate int values.
663     const llvm::APSInt &NewFrom = ValueFactory.getValue(-It->To());
664     const llvm::APSInt &NewTo = ValueFactory.getValue(-It->From());
665 
666     // Add a negated range.
667     Result.emplace_back(NewFrom, NewTo);
668   }
669 
670   llvm::sort(Result);
671   return makePersistent(std::move(Result));
672 }
673 
674 // Convert range set to the given integral type using truncation and promotion.
675 // This works similar to APSIntType::apply function but for the range set.
676 RangeSet RangeSet::Factory::castTo(RangeSet What, APSIntType Ty) {
677   // Set is empty or NOOP (aka cast to the same type).
678   if (What.isEmpty() || What.getAPSIntType() == Ty)
679     return What;
680 
681   const bool IsConversion = What.isUnsigned() != Ty.isUnsigned();
682   const bool IsTruncation = What.getBitWidth() > Ty.getBitWidth();
683   const bool IsPromotion = What.getBitWidth() < Ty.getBitWidth();
684 
685   if (IsTruncation)
686     return makePersistent(truncateTo(What, Ty));
687 
688   // Here we handle 2 cases:
689   // - IsConversion && !IsPromotion.
690   //   In this case we handle changing a sign with same bitwidth: char -> uchar,
691   //   uint -> int. Here we convert negatives to positives and positives which
692   //   is out of range to negatives. We use convertTo function for that.
693   // - IsConversion && IsPromotion && !What.isUnsigned().
694   //   In this case we handle changing a sign from signeds to unsigneds with
695   //   higher bitwidth: char -> uint, int-> uint64. The point is that we also
696   //   need convert negatives to positives and use convertTo function as well.
697   //   For example, we don't need such a convertion when converting unsigned to
698   //   signed with higher bitwidth, because all the values of unsigned is valid
699   //   for the such signed.
700   if (IsConversion && (!IsPromotion || !What.isUnsigned()))
701     return makePersistent(convertTo(What, Ty));
702 
703   assert(IsPromotion && "Only promotion operation from unsigneds left.");
704   return makePersistent(promoteTo(What, Ty));
705 }
706 
707 RangeSet RangeSet::Factory::castTo(RangeSet What, QualType T) {
708   assert(T->isIntegralOrEnumerationType() && "T shall be an integral type.");
709   return castTo(What, ValueFactory.getAPSIntType(T));
710 }
711 
712 RangeSet::ContainerType RangeSet::Factory::truncateTo(RangeSet What,
713                                                       APSIntType Ty) {
714   using llvm::APInt;
715   using llvm::APSInt;
716   ContainerType Result;
717   ContainerType Dummy;
718   // CastRangeSize is an amount of all possible values of cast type.
719   // Example: `char` has 256 values; `short` has 65536 values.
720   // But in fact we use `amount of values` - 1, because
721   // we can't keep `amount of values of UINT64` inside uint64_t.
722   // E.g. 256 is an amount of all possible values of `char` and we can't keep
723   // it inside `char`.
724   // And it's OK, it's enough to do correct calculations.
725   uint64_t CastRangeSize = APInt::getMaxValue(Ty.getBitWidth()).getZExtValue();
726   for (const Range &R : What) {
727     // Get bounds of the given range.
728     APSInt FromInt = R.From();
729     APSInt ToInt = R.To();
730     // CurrentRangeSize is an amount of all possible values of the current
731     // range minus one.
732     uint64_t CurrentRangeSize = (ToInt - FromInt).getZExtValue();
733     // This is an optimization for a specific case when this Range covers
734     // the whole range of the target type.
735     Dummy.clear();
736     if (CurrentRangeSize >= CastRangeSize) {
737       Dummy.emplace_back(ValueFactory.getMinValue(Ty),
738                          ValueFactory.getMaxValue(Ty));
739       Result = std::move(Dummy);
740       break;
741     }
742     // Cast the bounds.
743     Ty.apply(FromInt);
744     Ty.apply(ToInt);
745     const APSInt &PersistentFrom = ValueFactory.getValue(FromInt);
746     const APSInt &PersistentTo = ValueFactory.getValue(ToInt);
747     if (FromInt > ToInt) {
748       Dummy.emplace_back(ValueFactory.getMinValue(Ty), PersistentTo);
749       Dummy.emplace_back(PersistentFrom, ValueFactory.getMaxValue(Ty));
750     } else
751       Dummy.emplace_back(PersistentFrom, PersistentTo);
752     // Every range retrieved after truncation potentialy has garbage values.
753     // So, we have to unite every next range with the previouses.
754     Result = unite(Result, Dummy);
755   }
756 
757   return Result;
758 }
759 
760 // Divide the convertion into two phases (presented as loops here).
761 // First phase(loop) works when casted values go in ascending order.
762 // E.g. char{1,3,5,127} -> uint{1,3,5,127}
763 // Interrupt the first phase and go to second one when casted values start
764 // go in descending order. That means that we crossed over the middle of
765 // the type value set (aka 0 for signeds and MAX/2+1 for unsigneds).
766 // For instance:
767 // 1: uchar{1,3,5,128,255} -> char{1,3,5,-128,-1}
768 //    Here we put {1,3,5} to one array and {-128, -1} to another
769 // 2: char{-128,-127,-1,0,1,2} -> uchar{128,129,255,0,1,3}
770 //    Here we put {128,129,255} to one array and {0,1,3} to another.
771 // After that we unite both arrays.
772 // NOTE: We don't just concatenate the arrays, because they may have
773 // adjacent ranges, e.g.:
774 // 1: char(-128, 127) -> uchar -> arr1(128, 255), arr2(0, 127) ->
775 //    unite -> uchar(0, 255)
776 // 2: uchar(0, 1)U(254, 255) -> char -> arr1(0, 1), arr2(-2, -1) ->
777 //    unite -> uchar(-2, 1)
778 RangeSet::ContainerType RangeSet::Factory::convertTo(RangeSet What,
779                                                      APSIntType Ty) {
780   using llvm::APInt;
781   using llvm::APSInt;
782   using Bounds = std::pair<const APSInt &, const APSInt &>;
783   ContainerType AscendArray;
784   ContainerType DescendArray;
785   auto CastRange = [Ty, &VF = ValueFactory](const Range &R) -> Bounds {
786     // Get bounds of the given range.
787     APSInt FromInt = R.From();
788     APSInt ToInt = R.To();
789     // Cast the bounds.
790     Ty.apply(FromInt);
791     Ty.apply(ToInt);
792     return {VF.getValue(FromInt), VF.getValue(ToInt)};
793   };
794   // Phase 1. Fill the first array.
795   APSInt LastConvertedInt = Ty.getMinValue();
796   const auto *It = What.begin();
797   const auto *E = What.end();
798   while (It != E) {
799     Bounds NewBounds = CastRange(*(It++));
800     // If values stop going acsending order, go to the second phase(loop).
801     if (NewBounds.first < LastConvertedInt) {
802       DescendArray.emplace_back(NewBounds.first, NewBounds.second);
803       break;
804     }
805     // If the range contains a midpoint, then split the range.
806     // E.g. char(-5, 5) -> uchar(251, 5)
807     // Here we shall add a range (251, 255) to the first array and (0, 5) to the
808     // second one.
809     if (NewBounds.first > NewBounds.second) {
810       DescendArray.emplace_back(ValueFactory.getMinValue(Ty), NewBounds.second);
811       AscendArray.emplace_back(NewBounds.first, ValueFactory.getMaxValue(Ty));
812     } else
813       // Values are going acsending order.
814       AscendArray.emplace_back(NewBounds.first, NewBounds.second);
815     LastConvertedInt = NewBounds.first;
816   }
817   // Phase 2. Fill the second array.
818   while (It != E) {
819     Bounds NewBounds = CastRange(*(It++));
820     DescendArray.emplace_back(NewBounds.first, NewBounds.second);
821   }
822   // Unite both arrays.
823   return unite(AscendArray, DescendArray);
824 }
825 
826 /// Promotion from unsigneds to signeds/unsigneds left.
827 RangeSet::ContainerType RangeSet::Factory::promoteTo(RangeSet What,
828                                                      APSIntType Ty) {
829   ContainerType Result;
830   // We definitely know the size of the result set.
831   Result.reserve(What.size());
832 
833   // Each unsigned value fits every larger type without any changes,
834   // whether the larger type is signed or unsigned. So just promote and push
835   // back each range one by one.
836   for (const Range &R : What) {
837     // Get bounds of the given range.
838     llvm::APSInt FromInt = R.From();
839     llvm::APSInt ToInt = R.To();
840     // Cast the bounds.
841     Ty.apply(FromInt);
842     Ty.apply(ToInt);
843     Result.emplace_back(ValueFactory.getValue(FromInt),
844                         ValueFactory.getValue(ToInt));
845   }
846   return Result;
847 }
848 
849 RangeSet RangeSet::Factory::deletePoint(RangeSet From,
850                                         const llvm::APSInt &Point) {
851   if (!From.contains(Point))
852     return From;
853 
854   llvm::APSInt Upper = Point;
855   llvm::APSInt Lower = Point;
856 
857   ++Upper;
858   --Lower;
859 
860   // Notice that the lower bound is greater than the upper bound.
861   return intersect(From, Upper, Lower);
862 }
863 
864 LLVM_DUMP_METHOD void Range::dump(raw_ostream &OS) const {
865   OS << '[' << toString(From(), 10) << ", " << toString(To(), 10) << ']';
866 }
867 LLVM_DUMP_METHOD void Range::dump() const { dump(llvm::errs()); }
868 
869 LLVM_DUMP_METHOD void RangeSet::dump(raw_ostream &OS) const {
870   OS << "{ ";
871   llvm::interleaveComma(*this, OS, [&OS](const Range &R) { R.dump(OS); });
872   OS << " }";
873 }
874 LLVM_DUMP_METHOD void RangeSet::dump() const { dump(llvm::errs()); }
875 
876 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet, SymbolRef)
877 
878 namespace {
879 class EquivalenceClass;
880 } // end anonymous namespace
881 
882 REGISTER_MAP_WITH_PROGRAMSTATE(ClassMap, SymbolRef, EquivalenceClass)
883 REGISTER_MAP_WITH_PROGRAMSTATE(ClassMembers, EquivalenceClass, SymbolSet)
884 REGISTER_MAP_WITH_PROGRAMSTATE(ConstraintRange, EquivalenceClass, RangeSet)
885 
886 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ClassSet, EquivalenceClass)
887 REGISTER_MAP_WITH_PROGRAMSTATE(DisequalityMap, EquivalenceClass, ClassSet)
888 
889 namespace {
890 /// This class encapsulates a set of symbols equal to each other.
891 ///
892 /// The main idea of the approach requiring such classes is in narrowing
893 /// and sharing constraints between symbols within the class.  Also we can
894 /// conclude that there is no practical need in storing constraints for
895 /// every member of the class separately.
896 ///
897 /// Main terminology:
898 ///
899 ///   * "Equivalence class" is an object of this class, which can be efficiently
900 ///     compared to other classes.  It represents the whole class without
901 ///     storing the actual in it.  The members of the class however can be
902 ///     retrieved from the state.
903 ///
904 ///   * "Class members" are the symbols corresponding to the class.  This means
905 ///     that A == B for every member symbols A and B from the class.  Members of
906 ///     each class are stored in the state.
907 ///
908 ///   * "Trivial class" is a class that has and ever had only one same symbol.
909 ///
910 ///   * "Merge operation" merges two classes into one.  It is the main operation
911 ///     to produce non-trivial classes.
912 ///     If, at some point, we can assume that two symbols from two distinct
913 ///     classes are equal, we can merge these classes.
914 class EquivalenceClass : public llvm::FoldingSetNode {
915 public:
916   /// Find equivalence class for the given symbol in the given state.
917   [[nodiscard]] static inline EquivalenceClass find(ProgramStateRef State,
918                                                     SymbolRef Sym);
919 
920   /// Merge classes for the given symbols and return a new state.
921   [[nodiscard]] static inline ProgramStateRef merge(RangeSet::Factory &F,
922                                                     ProgramStateRef State,
923                                                     SymbolRef First,
924                                                     SymbolRef Second);
925   // Merge this class with the given class and return a new state.
926   [[nodiscard]] inline ProgramStateRef
927   merge(RangeSet::Factory &F, ProgramStateRef State, EquivalenceClass Other);
928 
929   /// Return a set of class members for the given state.
930   [[nodiscard]] inline SymbolSet getClassMembers(ProgramStateRef State) const;
931 
932   /// Return true if the current class is trivial in the given state.
933   /// A class is trivial if and only if there is not any member relations stored
934   /// to it in State/ClassMembers.
935   /// An equivalence class with one member might seem as it does not hold any
936   /// meaningful information, i.e. that is a tautology. However, during the
937   /// removal of dead symbols we do not remove classes with one member for
938   /// resource and performance reasons. Consequently, a class with one member is
939   /// not necessarily trivial. It could happen that we have a class with two
940   /// members and then during the removal of dead symbols we remove one of its
941   /// members. In this case, the class is still non-trivial (it still has the
942   /// mappings in ClassMembers), even though it has only one member.
943   [[nodiscard]] inline bool isTrivial(ProgramStateRef State) const;
944 
945   /// Return true if the current class is trivial and its only member is dead.
946   [[nodiscard]] inline bool isTriviallyDead(ProgramStateRef State,
947                                             SymbolReaper &Reaper) const;
948 
949   [[nodiscard]] static inline ProgramStateRef
950   markDisequal(RangeSet::Factory &F, ProgramStateRef State, SymbolRef First,
951                SymbolRef Second);
952   [[nodiscard]] static inline ProgramStateRef
953   markDisequal(RangeSet::Factory &F, ProgramStateRef State,
954                EquivalenceClass First, EquivalenceClass Second);
955   [[nodiscard]] inline ProgramStateRef
956   markDisequal(RangeSet::Factory &F, ProgramStateRef State,
957                EquivalenceClass Other) const;
958   [[nodiscard]] static inline ClassSet getDisequalClasses(ProgramStateRef State,
959                                                           SymbolRef Sym);
960   [[nodiscard]] inline ClassSet getDisequalClasses(ProgramStateRef State) const;
961   [[nodiscard]] inline ClassSet
962   getDisequalClasses(DisequalityMapTy Map, ClassSet::Factory &Factory) const;
963 
964   [[nodiscard]] static inline Optional<bool> areEqual(ProgramStateRef State,
965                                                       EquivalenceClass First,
966                                                       EquivalenceClass Second);
967   [[nodiscard]] static inline Optional<bool>
968   areEqual(ProgramStateRef State, SymbolRef First, SymbolRef Second);
969 
970   /// Remove one member from the class.
971   [[nodiscard]] ProgramStateRef removeMember(ProgramStateRef State,
972                                              const SymbolRef Old);
973 
974   /// Iterate over all symbols and try to simplify them.
975   [[nodiscard]] static inline ProgramStateRef simplify(SValBuilder &SVB,
976                                                        RangeSet::Factory &F,
977                                                        ProgramStateRef State,
978                                                        EquivalenceClass Class);
979 
980   void dumpToStream(ProgramStateRef State, raw_ostream &os) const;
981   LLVM_DUMP_METHOD void dump(ProgramStateRef State) const {
982     dumpToStream(State, llvm::errs());
983   }
984 
985   /// Check equivalence data for consistency.
986   [[nodiscard]] LLVM_ATTRIBUTE_UNUSED static bool
987   isClassDataConsistent(ProgramStateRef State);
988 
989   [[nodiscard]] QualType getType() const {
990     return getRepresentativeSymbol()->getType();
991   }
992 
993   EquivalenceClass() = delete;
994   EquivalenceClass(const EquivalenceClass &) = default;
995   EquivalenceClass &operator=(const EquivalenceClass &) = delete;
996   EquivalenceClass(EquivalenceClass &&) = default;
997   EquivalenceClass &operator=(EquivalenceClass &&) = delete;
998 
999   bool operator==(const EquivalenceClass &Other) const {
1000     return ID == Other.ID;
1001   }
1002   bool operator<(const EquivalenceClass &Other) const { return ID < Other.ID; }
1003   bool operator!=(const EquivalenceClass &Other) const {
1004     return !operator==(Other);
1005   }
1006 
1007   static void Profile(llvm::FoldingSetNodeID &ID, uintptr_t CID) {
1008     ID.AddInteger(CID);
1009   }
1010 
1011   void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, this->ID); }
1012 
1013 private:
1014   /* implicit */ EquivalenceClass(SymbolRef Sym)
1015       : ID(reinterpret_cast<uintptr_t>(Sym)) {}
1016 
1017   /// This function is intended to be used ONLY within the class.
1018   /// The fact that ID is a pointer to a symbol is an implementation detail
1019   /// and should stay that way.
1020   /// In the current implementation, we use it to retrieve the only member
1021   /// of the trivial class.
1022   SymbolRef getRepresentativeSymbol() const {
1023     return reinterpret_cast<SymbolRef>(ID);
1024   }
1025   static inline SymbolSet::Factory &getMembersFactory(ProgramStateRef State);
1026 
1027   inline ProgramStateRef mergeImpl(RangeSet::Factory &F, ProgramStateRef State,
1028                                    SymbolSet Members, EquivalenceClass Other,
1029                                    SymbolSet OtherMembers);
1030 
1031   static inline bool
1032   addToDisequalityInfo(DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
1033                        RangeSet::Factory &F, ProgramStateRef State,
1034                        EquivalenceClass First, EquivalenceClass Second);
1035 
1036   /// This is a unique identifier of the class.
1037   uintptr_t ID;
1038 };
1039 
1040 //===----------------------------------------------------------------------===//
1041 //                             Constraint functions
1042 //===----------------------------------------------------------------------===//
1043 
1044 [[nodiscard]] LLVM_ATTRIBUTE_UNUSED bool
1045 areFeasible(ConstraintRangeTy Constraints) {
1046   return llvm::none_of(
1047       Constraints,
1048       [](const std::pair<EquivalenceClass, RangeSet> &ClassConstraint) {
1049         return ClassConstraint.second.isEmpty();
1050       });
1051 }
1052 
1053 [[nodiscard]] inline const RangeSet *getConstraint(ProgramStateRef State,
1054                                                    EquivalenceClass Class) {
1055   return State->get<ConstraintRange>(Class);
1056 }
1057 
1058 [[nodiscard]] inline const RangeSet *getConstraint(ProgramStateRef State,
1059                                                    SymbolRef Sym) {
1060   return getConstraint(State, EquivalenceClass::find(State, Sym));
1061 }
1062 
1063 [[nodiscard]] ProgramStateRef setConstraint(ProgramStateRef State,
1064                                             EquivalenceClass Class,
1065                                             RangeSet Constraint) {
1066   return State->set<ConstraintRange>(Class, Constraint);
1067 }
1068 
1069 [[nodiscard]] ProgramStateRef setConstraints(ProgramStateRef State,
1070                                              ConstraintRangeTy Constraints) {
1071   return State->set<ConstraintRange>(Constraints);
1072 }
1073 
1074 //===----------------------------------------------------------------------===//
1075 //                       Equality/diseqiality abstraction
1076 //===----------------------------------------------------------------------===//
1077 
1078 /// A small helper function for detecting symbolic (dis)equality.
1079 ///
1080 /// Equality check can have different forms (like a == b or a - b) and this
1081 /// class encapsulates those away if the only thing the user wants to check -
1082 /// whether it's equality/diseqiality or not.
1083 ///
1084 /// \returns true if assuming this Sym to be true means equality of operands
1085 ///          false if it means disequality of operands
1086 ///          None otherwise
1087 Optional<bool> meansEquality(const SymSymExpr *Sym) {
1088   switch (Sym->getOpcode()) {
1089   case BO_Sub:
1090     // This case is: A - B != 0 -> disequality check.
1091     return false;
1092   case BO_EQ:
1093     // This case is: A == B != 0 -> equality check.
1094     return true;
1095   case BO_NE:
1096     // This case is: A != B != 0 -> diseqiality check.
1097     return false;
1098   default:
1099     return std::nullopt;
1100   }
1101 }
1102 
1103 //===----------------------------------------------------------------------===//
1104 //                            Intersection functions
1105 //===----------------------------------------------------------------------===//
1106 
1107 template <class SecondTy, class... RestTy>
1108 [[nodiscard]] inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
1109                                         SecondTy Second, RestTy... Tail);
1110 
1111 template <class... RangeTy> struct IntersectionTraits;
1112 
1113 template <class... TailTy> struct IntersectionTraits<RangeSet, TailTy...> {
1114   // Found RangeSet, no need to check any further
1115   using Type = RangeSet;
1116 };
1117 
1118 template <> struct IntersectionTraits<> {
1119   // We ran out of types, and we didn't find any RangeSet, so the result should
1120   // be optional.
1121   using Type = Optional<RangeSet>;
1122 };
1123 
1124 template <class OptionalOrPointer, class... TailTy>
1125 struct IntersectionTraits<OptionalOrPointer, TailTy...> {
1126   // If current type is Optional or a raw pointer, we should keep looking.
1127   using Type = typename IntersectionTraits<TailTy...>::Type;
1128 };
1129 
1130 template <class EndTy>
1131 [[nodiscard]] inline EndTy intersect(RangeSet::Factory &F, EndTy End) {
1132   // If the list contains only RangeSet or Optional<RangeSet>, simply return
1133   // that range set.
1134   return End;
1135 }
1136 
1137 [[nodiscard]] LLVM_ATTRIBUTE_UNUSED inline Optional<RangeSet>
1138 intersect(RangeSet::Factory &F, const RangeSet *End) {
1139   // This is an extraneous conversion from a raw pointer into Optional<RangeSet>
1140   if (End) {
1141     return *End;
1142   }
1143   return std::nullopt;
1144 }
1145 
1146 template <class... RestTy>
1147 [[nodiscard]] inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
1148                                         RangeSet Second, RestTy... Tail) {
1149   // Here we call either the <RangeSet,RangeSet,...> or <RangeSet,...> version
1150   // of the function and can be sure that the result is RangeSet.
1151   return intersect(F, F.intersect(Head, Second), Tail...);
1152 }
1153 
1154 template <class SecondTy, class... RestTy>
1155 [[nodiscard]] inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
1156                                         SecondTy Second, RestTy... Tail) {
1157   if (Second) {
1158     // Here we call the <RangeSet,RangeSet,...> version of the function...
1159     return intersect(F, Head, *Second, Tail...);
1160   }
1161   // ...and here it is either <RangeSet,RangeSet,...> or <RangeSet,...>, which
1162   // means that the result is definitely RangeSet.
1163   return intersect(F, Head, Tail...);
1164 }
1165 
1166 /// Main generic intersect function.
1167 /// It intersects all of the given range sets.  If some of the given arguments
1168 /// don't hold a range set (nullptr or std::nullopt), the function will skip
1169 /// them.
1170 ///
1171 /// Available representations for the arguments are:
1172 ///   * RangeSet
1173 ///   * Optional<RangeSet>
1174 ///   * RangeSet *
1175 /// Pointer to a RangeSet is automatically assumed to be nullable and will get
1176 /// checked as well as the optional version.  If this behaviour is undesired,
1177 /// please dereference the pointer in the call.
1178 ///
1179 /// Return type depends on the arguments' types.  If we can be sure in compile
1180 /// time that there will be a range set as a result, the returning type is
1181 /// simply RangeSet, in other cases we have to back off to Optional<RangeSet>.
1182 ///
1183 /// Please, prefer optional range sets to raw pointers.  If the last argument is
1184 /// a raw pointer and all previous arguments are std::nullopt, it will cost one
1185 /// additional check to convert RangeSet * into Optional<RangeSet>.
1186 template <class HeadTy, class SecondTy, class... RestTy>
1187 [[nodiscard]] inline
1188     typename IntersectionTraits<HeadTy, SecondTy, RestTy...>::Type
1189     intersect(RangeSet::Factory &F, HeadTy Head, SecondTy Second,
1190               RestTy... Tail) {
1191   if (Head) {
1192     return intersect(F, *Head, Second, Tail...);
1193   }
1194   return intersect(F, Second, Tail...);
1195 }
1196 
1197 //===----------------------------------------------------------------------===//
1198 //                           Symbolic reasoning logic
1199 //===----------------------------------------------------------------------===//
1200 
1201 /// A little component aggregating all of the reasoning we have about
1202 /// the ranges of symbolic expressions.
1203 ///
1204 /// Even when we don't know the exact values of the operands, we still
1205 /// can get a pretty good estimate of the result's range.
1206 class SymbolicRangeInferrer
1207     : public SymExprVisitor<SymbolicRangeInferrer, RangeSet> {
1208 public:
1209   template <class SourceType>
1210   static RangeSet inferRange(RangeSet::Factory &F, ProgramStateRef State,
1211                              SourceType Origin) {
1212     SymbolicRangeInferrer Inferrer(F, State);
1213     return Inferrer.infer(Origin);
1214   }
1215 
1216   RangeSet VisitSymExpr(SymbolRef Sym) {
1217     if (Optional<RangeSet> RS = getRangeForNegatedSym(Sym))
1218       return *RS;
1219     // If we've reached this line, the actual type of the symbolic
1220     // expression is not supported for advanced inference.
1221     // In this case, we simply backoff to the default "let's simply
1222     // infer the range from the expression's type".
1223     return infer(Sym->getType());
1224   }
1225 
1226   RangeSet VisitUnarySymExpr(const UnarySymExpr *USE) {
1227     if (Optional<RangeSet> RS = getRangeForNegatedUnarySym(USE))
1228       return *RS;
1229     return infer(USE->getType());
1230   }
1231 
1232   RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
1233     return VisitBinaryOperator(Sym);
1234   }
1235 
1236   RangeSet VisitIntSymExpr(const IntSymExpr *Sym) {
1237     return VisitBinaryOperator(Sym);
1238   }
1239 
1240   RangeSet VisitSymSymExpr(const SymSymExpr *SSE) {
1241     return intersect(
1242         RangeFactory,
1243         // If Sym is a difference of symbols A - B, then maybe we have range
1244         // set stored for B - A.
1245         //
1246         // If we have range set stored for both A - B and B - A then
1247         // calculate the effective range set by intersecting the range set
1248         // for A - B and the negated range set of B - A.
1249         getRangeForNegatedSymSym(SSE),
1250         // If Sym is a comparison expression (except <=>),
1251         // find any other comparisons with the same operands.
1252         // See function description.
1253         getRangeForComparisonSymbol(SSE),
1254         // If Sym is (dis)equality, we might have some information
1255         // on that in our equality classes data structure.
1256         getRangeForEqualities(SSE),
1257         // And we should always check what we can get from the operands.
1258         VisitBinaryOperator(SSE));
1259   }
1260 
1261 private:
1262   SymbolicRangeInferrer(RangeSet::Factory &F, ProgramStateRef S)
1263       : ValueFactory(F.getValueFactory()), RangeFactory(F), State(S) {}
1264 
1265   /// Infer range information from the given integer constant.
1266   ///
1267   /// It's not a real "inference", but is here for operating with
1268   /// sub-expressions in a more polymorphic manner.
1269   RangeSet inferAs(const llvm::APSInt &Val, QualType) {
1270     return {RangeFactory, Val};
1271   }
1272 
1273   /// Infer range information from symbol in the context of the given type.
1274   RangeSet inferAs(SymbolRef Sym, QualType DestType) {
1275     QualType ActualType = Sym->getType();
1276     // Check that we can reason about the symbol at all.
1277     if (ActualType->isIntegralOrEnumerationType() ||
1278         Loc::isLocType(ActualType)) {
1279       return infer(Sym);
1280     }
1281     // Otherwise, let's simply infer from the destination type.
1282     // We couldn't figure out nothing else about that expression.
1283     return infer(DestType);
1284   }
1285 
1286   RangeSet infer(SymbolRef Sym) {
1287     return intersect(RangeFactory,
1288                      // Of course, we should take the constraint directly
1289                      // associated with this symbol into consideration.
1290                      getConstraint(State, Sym),
1291                      // Apart from the Sym itself, we can infer quite a lot if
1292                      // we look into subexpressions of Sym.
1293                      Visit(Sym));
1294   }
1295 
1296   RangeSet infer(EquivalenceClass Class) {
1297     if (const RangeSet *AssociatedConstraint = getConstraint(State, Class))
1298       return *AssociatedConstraint;
1299 
1300     return infer(Class.getType());
1301   }
1302 
1303   /// Infer range information solely from the type.
1304   RangeSet infer(QualType T) {
1305     // Lazily generate a new RangeSet representing all possible values for the
1306     // given symbol type.
1307     RangeSet Result(RangeFactory, ValueFactory.getMinValue(T),
1308                     ValueFactory.getMaxValue(T));
1309 
1310     // References are known to be non-zero.
1311     if (T->isReferenceType())
1312       return assumeNonZero(Result, T);
1313 
1314     return Result;
1315   }
1316 
1317   template <class BinarySymExprTy>
1318   RangeSet VisitBinaryOperator(const BinarySymExprTy *Sym) {
1319     // TODO #1: VisitBinaryOperator implementation might not make a good
1320     // use of the inferred ranges.  In this case, we might be calculating
1321     // everything for nothing.  This being said, we should introduce some
1322     // sort of laziness mechanism here.
1323     //
1324     // TODO #2: We didn't go into the nested expressions before, so it
1325     // might cause us spending much more time doing the inference.
1326     // This can be a problem for deeply nested expressions that are
1327     // involved in conditions and get tested continuously.  We definitely
1328     // need to address this issue and introduce some sort of caching
1329     // in here.
1330     QualType ResultType = Sym->getType();
1331     return VisitBinaryOperator(inferAs(Sym->getLHS(), ResultType),
1332                                Sym->getOpcode(),
1333                                inferAs(Sym->getRHS(), ResultType), ResultType);
1334   }
1335 
1336   RangeSet VisitBinaryOperator(RangeSet LHS, BinaryOperator::Opcode Op,
1337                                RangeSet RHS, QualType T);
1338 
1339   //===----------------------------------------------------------------------===//
1340   //                         Ranges and operators
1341   //===----------------------------------------------------------------------===//
1342 
1343   /// Return a rough approximation of the given range set.
1344   ///
1345   /// For the range set:
1346   ///   { [x_0, y_0], [x_1, y_1], ... , [x_N, y_N] }
1347   /// it will return the range [x_0, y_N].
1348   static Range fillGaps(RangeSet Origin) {
1349     assert(!Origin.isEmpty());
1350     return {Origin.getMinValue(), Origin.getMaxValue()};
1351   }
1352 
1353   /// Try to convert given range into the given type.
1354   ///
1355   /// It will return std::nullopt only when the trivial conversion is possible.
1356   llvm::Optional<Range> convert(const Range &Origin, APSIntType To) {
1357     if (To.testInRange(Origin.From(), false) != APSIntType::RTR_Within ||
1358         To.testInRange(Origin.To(), false) != APSIntType::RTR_Within) {
1359       return std::nullopt;
1360     }
1361     return Range(ValueFactory.Convert(To, Origin.From()),
1362                  ValueFactory.Convert(To, Origin.To()));
1363   }
1364 
1365   template <BinaryOperator::Opcode Op>
1366   RangeSet VisitBinaryOperator(RangeSet LHS, RangeSet RHS, QualType T) {
1367     assert(!LHS.isEmpty() && !RHS.isEmpty());
1368 
1369     Range CoarseLHS = fillGaps(LHS);
1370     Range CoarseRHS = fillGaps(RHS);
1371 
1372     APSIntType ResultType = ValueFactory.getAPSIntType(T);
1373 
1374     // We need to convert ranges to the resulting type, so we can compare values
1375     // and combine them in a meaningful (in terms of the given operation) way.
1376     auto ConvertedCoarseLHS = convert(CoarseLHS, ResultType);
1377     auto ConvertedCoarseRHS = convert(CoarseRHS, ResultType);
1378 
1379     // It is hard to reason about ranges when conversion changes
1380     // borders of the ranges.
1381     if (!ConvertedCoarseLHS || !ConvertedCoarseRHS) {
1382       return infer(T);
1383     }
1384 
1385     return VisitBinaryOperator<Op>(*ConvertedCoarseLHS, *ConvertedCoarseRHS, T);
1386   }
1387 
1388   template <BinaryOperator::Opcode Op>
1389   RangeSet VisitBinaryOperator(Range LHS, Range RHS, QualType T) {
1390     return infer(T);
1391   }
1392 
1393   /// Return a symmetrical range for the given range and type.
1394   ///
1395   /// If T is signed, return the smallest range [-x..x] that covers the original
1396   /// range, or [-min(T), max(T)] if the aforementioned symmetric range doesn't
1397   /// exist due to original range covering min(T)).
1398   ///
1399   /// If T is unsigned, return the smallest range [0..x] that covers the
1400   /// original range.
1401   Range getSymmetricalRange(Range Origin, QualType T) {
1402     APSIntType RangeType = ValueFactory.getAPSIntType(T);
1403 
1404     if (RangeType.isUnsigned()) {
1405       return Range(ValueFactory.getMinValue(RangeType), Origin.To());
1406     }
1407 
1408     if (Origin.From().isMinSignedValue()) {
1409       // If mini is a minimal signed value, absolute value of it is greater
1410       // than the maximal signed value.  In order to avoid these
1411       // complications, we simply return the whole range.
1412       return {ValueFactory.getMinValue(RangeType),
1413               ValueFactory.getMaxValue(RangeType)};
1414     }
1415 
1416     // At this point, we are sure that the type is signed and we can safely
1417     // use unary - operator.
1418     //
1419     // While calculating absolute maximum, we can use the following formula
1420     // because of these reasons:
1421     //   * If From >= 0 then To >= From and To >= -From.
1422     //     AbsMax == To == max(To, -From)
1423     //   * If To <= 0 then -From >= -To and -From >= From.
1424     //     AbsMax == -From == max(-From, To)
1425     //   * Otherwise, From <= 0, To >= 0, and
1426     //     AbsMax == max(abs(From), abs(To))
1427     llvm::APSInt AbsMax = std::max(-Origin.From(), Origin.To());
1428 
1429     // Intersection is guaranteed to be non-empty.
1430     return {ValueFactory.getValue(-AbsMax), ValueFactory.getValue(AbsMax)};
1431   }
1432 
1433   /// Return a range set subtracting zero from \p Domain.
1434   RangeSet assumeNonZero(RangeSet Domain, QualType T) {
1435     APSIntType IntType = ValueFactory.getAPSIntType(T);
1436     return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
1437   }
1438 
1439   template <typename ProduceNegatedSymFunc>
1440   Optional<RangeSet> getRangeForNegatedExpr(ProduceNegatedSymFunc F,
1441                                             QualType T) {
1442     // Do not negate if the type cannot be meaningfully negated.
1443     if (!T->isUnsignedIntegerOrEnumerationType() &&
1444         !T->isSignedIntegerOrEnumerationType())
1445       return std::nullopt;
1446 
1447     if (SymbolRef NegatedSym = F())
1448       if (const RangeSet *NegatedRange = getConstraint(State, NegatedSym))
1449         return RangeFactory.negate(*NegatedRange);
1450 
1451     return std::nullopt;
1452   }
1453 
1454   Optional<RangeSet> getRangeForNegatedUnarySym(const UnarySymExpr *USE) {
1455     // Just get the operand when we negate a symbol that is already negated.
1456     // -(-a) == a
1457     return getRangeForNegatedExpr(
1458         [USE]() -> SymbolRef {
1459           if (USE->getOpcode() == UO_Minus)
1460             return USE->getOperand();
1461           return nullptr;
1462         },
1463         USE->getType());
1464   }
1465 
1466   Optional<RangeSet> getRangeForNegatedSymSym(const SymSymExpr *SSE) {
1467     return getRangeForNegatedExpr(
1468         [SSE, State = this->State]() -> SymbolRef {
1469           if (SSE->getOpcode() == BO_Sub)
1470             return State->getSymbolManager().getSymSymExpr(
1471                 SSE->getRHS(), BO_Sub, SSE->getLHS(), SSE->getType());
1472           return nullptr;
1473         },
1474         SSE->getType());
1475   }
1476 
1477   Optional<RangeSet> getRangeForNegatedSym(SymbolRef Sym) {
1478     return getRangeForNegatedExpr(
1479         [Sym, State = this->State]() {
1480           return State->getSymbolManager().getUnarySymExpr(Sym, UO_Minus,
1481                                                            Sym->getType());
1482         },
1483         Sym->getType());
1484   }
1485 
1486   // Returns ranges only for binary comparison operators (except <=>)
1487   // when left and right operands are symbolic values.
1488   // Finds any other comparisons with the same operands.
1489   // Then do logical calculations and refuse impossible branches.
1490   // E.g. (x < y) and (x > y) at the same time are impossible.
1491   // E.g. (x >= y) and (x != y) at the same time makes (x > y) true only.
1492   // E.g. (x == y) and (y == x) are just reversed but the same.
1493   // It covers all possible combinations (see CmpOpTable description).
1494   // Note that `x` and `y` can also stand for subexpressions,
1495   // not only for actual symbols.
1496   Optional<RangeSet> getRangeForComparisonSymbol(const SymSymExpr *SSE) {
1497     const BinaryOperatorKind CurrentOP = SSE->getOpcode();
1498 
1499     // We currently do not support <=> (C++20).
1500     if (!BinaryOperator::isComparisonOp(CurrentOP) || (CurrentOP == BO_Cmp))
1501       return std::nullopt;
1502 
1503     static const OperatorRelationsTable CmpOpTable{};
1504 
1505     const SymExpr *LHS = SSE->getLHS();
1506     const SymExpr *RHS = SSE->getRHS();
1507     QualType T = SSE->getType();
1508 
1509     SymbolManager &SymMgr = State->getSymbolManager();
1510 
1511     // We use this variable to store the last queried operator (`QueriedOP`)
1512     // for which the `getCmpOpState` returned with `Unknown`. If there are two
1513     // different OPs that returned `Unknown` then we have to query the special
1514     // `UnknownX2` column. We assume that `getCmpOpState(CurrentOP, CurrentOP)`
1515     // never returns `Unknown`, so `CurrentOP` is a good initial value.
1516     BinaryOperatorKind LastQueriedOpToUnknown = CurrentOP;
1517 
1518     // Loop goes through all of the columns exept the last one ('UnknownX2').
1519     // We treat `UnknownX2` column separately at the end of the loop body.
1520     for (size_t i = 0; i < CmpOpTable.getCmpOpCount(); ++i) {
1521 
1522       // Let's find an expression e.g. (x < y).
1523       BinaryOperatorKind QueriedOP = OperatorRelationsTable::getOpFromIndex(i);
1524       const SymSymExpr *SymSym = SymMgr.getSymSymExpr(LHS, QueriedOP, RHS, T);
1525       const RangeSet *QueriedRangeSet = getConstraint(State, SymSym);
1526 
1527       // If ranges were not previously found,
1528       // try to find a reversed expression (y > x).
1529       if (!QueriedRangeSet) {
1530         const BinaryOperatorKind ROP =
1531             BinaryOperator::reverseComparisonOp(QueriedOP);
1532         SymSym = SymMgr.getSymSymExpr(RHS, ROP, LHS, T);
1533         QueriedRangeSet = getConstraint(State, SymSym);
1534       }
1535 
1536       if (!QueriedRangeSet || QueriedRangeSet->isEmpty())
1537         continue;
1538 
1539       const llvm::APSInt *ConcreteValue = QueriedRangeSet->getConcreteValue();
1540       const bool isInFalseBranch =
1541           ConcreteValue ? (*ConcreteValue == 0) : false;
1542 
1543       // If it is a false branch, we shall be guided by opposite operator,
1544       // because the table is made assuming we are in the true branch.
1545       // E.g. when (x <= y) is false, then (x > y) is true.
1546       if (isInFalseBranch)
1547         QueriedOP = BinaryOperator::negateComparisonOp(QueriedOP);
1548 
1549       OperatorRelationsTable::TriStateKind BranchState =
1550           CmpOpTable.getCmpOpState(CurrentOP, QueriedOP);
1551 
1552       if (BranchState == OperatorRelationsTable::Unknown) {
1553         if (LastQueriedOpToUnknown != CurrentOP &&
1554             LastQueriedOpToUnknown != QueriedOP) {
1555           // If we got the Unknown state for both different operators.
1556           // if (x <= y)    // assume true
1557           //   if (x != y)  // assume true
1558           //     if (x < y) // would be also true
1559           // Get a state from `UnknownX2` column.
1560           BranchState = CmpOpTable.getCmpOpStateForUnknownX2(CurrentOP);
1561         } else {
1562           LastQueriedOpToUnknown = QueriedOP;
1563           continue;
1564         }
1565       }
1566 
1567       return (BranchState == OperatorRelationsTable::True) ? getTrueRange(T)
1568                                                            : getFalseRange(T);
1569     }
1570 
1571     return std::nullopt;
1572   }
1573 
1574   Optional<RangeSet> getRangeForEqualities(const SymSymExpr *Sym) {
1575     Optional<bool> Equality = meansEquality(Sym);
1576 
1577     if (!Equality)
1578       return std::nullopt;
1579 
1580     if (Optional<bool> AreEqual =
1581             EquivalenceClass::areEqual(State, Sym->getLHS(), Sym->getRHS())) {
1582       // Here we cover two cases at once:
1583       //   * if Sym is equality and its operands are known to be equal -> true
1584       //   * if Sym is disequality and its operands are disequal -> true
1585       if (*AreEqual == *Equality) {
1586         return getTrueRange(Sym->getType());
1587       }
1588       // Opposite combinations result in false.
1589       return getFalseRange(Sym->getType());
1590     }
1591 
1592     return std::nullopt;
1593   }
1594 
1595   RangeSet getTrueRange(QualType T) {
1596     RangeSet TypeRange = infer(T);
1597     return assumeNonZero(TypeRange, T);
1598   }
1599 
1600   RangeSet getFalseRange(QualType T) {
1601     const llvm::APSInt &Zero = ValueFactory.getValue(0, T);
1602     return RangeSet(RangeFactory, Zero);
1603   }
1604 
1605   BasicValueFactory &ValueFactory;
1606   RangeSet::Factory &RangeFactory;
1607   ProgramStateRef State;
1608 };
1609 
1610 //===----------------------------------------------------------------------===//
1611 //               Range-based reasoning about symbolic operations
1612 //===----------------------------------------------------------------------===//
1613 
1614 template <>
1615 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_NE>(RangeSet LHS,
1616                                                            RangeSet RHS,
1617                                                            QualType T) {
1618   assert(!LHS.isEmpty() && !RHS.isEmpty());
1619 
1620   if (LHS.getAPSIntType() == RHS.getAPSIntType()) {
1621     if (intersect(RangeFactory, LHS, RHS).isEmpty())
1622       return getTrueRange(T);
1623   } else {
1624     // Both RangeSets should be casted to bigger unsigned type.
1625     APSIntType CastingType(std::max(LHS.getBitWidth(), RHS.getBitWidth()),
1626                            LHS.isUnsigned() || RHS.isUnsigned());
1627 
1628     RangeSet CastedLHS = RangeFactory.castTo(LHS, CastingType);
1629     RangeSet CastedRHS = RangeFactory.castTo(RHS, CastingType);
1630 
1631     if (intersect(RangeFactory, CastedLHS, CastedRHS).isEmpty())
1632       return getTrueRange(T);
1633   }
1634 
1635   // In all other cases, the resulting range cannot be deduced.
1636   return infer(T);
1637 }
1638 
1639 template <>
1640 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Or>(Range LHS, Range RHS,
1641                                                            QualType T) {
1642   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1643   llvm::APSInt Zero = ResultType.getZeroValue();
1644 
1645   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1646   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1647 
1648   bool IsLHSNegative = LHS.To() < Zero;
1649   bool IsRHSNegative = RHS.To() < Zero;
1650 
1651   // Check if both ranges have the same sign.
1652   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1653       (IsLHSNegative && IsRHSNegative)) {
1654     // The result is definitely greater or equal than any of the operands.
1655     const llvm::APSInt &Min = std::max(LHS.From(), RHS.From());
1656 
1657     // We estimate maximal value for positives as the maximal value for the
1658     // given type.  For negatives, we estimate it with -1 (e.g. 0x11111111).
1659     //
1660     // TODO: We basically, limit the resulting range from below, but don't do
1661     //       anything with the upper bound.
1662     //
1663     //       For positive operands, it can be done as follows: for the upper
1664     //       bound of LHS and RHS we calculate the most significant bit set.
1665     //       Let's call it the N-th bit.  Then we can estimate the maximal
1666     //       number to be 2^(N+1)-1, i.e. the number with all the bits up to
1667     //       the N-th bit set.
1668     const llvm::APSInt &Max = IsLHSNegative
1669                                   ? ValueFactory.getValue(--Zero)
1670                                   : ValueFactory.getMaxValue(ResultType);
1671 
1672     return {RangeFactory, ValueFactory.getValue(Min), Max};
1673   }
1674 
1675   // Otherwise, let's check if at least one of the operands is negative.
1676   if (IsLHSNegative || IsRHSNegative) {
1677     // This means that the result is definitely negative as well.
1678     return {RangeFactory, ValueFactory.getMinValue(ResultType),
1679             ValueFactory.getValue(--Zero)};
1680   }
1681 
1682   RangeSet DefaultRange = infer(T);
1683 
1684   // It is pretty hard to reason about operands with different signs
1685   // (and especially with possibly different signs).  We simply check if it
1686   // can be zero.  In order to conclude that the result could not be zero,
1687   // at least one of the operands should be definitely not zero itself.
1688   if (!LHS.Includes(Zero) || !RHS.Includes(Zero)) {
1689     return assumeNonZero(DefaultRange, T);
1690   }
1691 
1692   // Nothing much else to do here.
1693   return DefaultRange;
1694 }
1695 
1696 template <>
1697 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_And>(Range LHS,
1698                                                             Range RHS,
1699                                                             QualType T) {
1700   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1701   llvm::APSInt Zero = ResultType.getZeroValue();
1702 
1703   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1704   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1705 
1706   bool IsLHSNegative = LHS.To() < Zero;
1707   bool IsRHSNegative = RHS.To() < Zero;
1708 
1709   // Check if both ranges have the same sign.
1710   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1711       (IsLHSNegative && IsRHSNegative)) {
1712     // The result is definitely less or equal than any of the operands.
1713     const llvm::APSInt &Max = std::min(LHS.To(), RHS.To());
1714 
1715     // We conservatively estimate lower bound to be the smallest positive
1716     // or negative value corresponding to the sign of the operands.
1717     const llvm::APSInt &Min = IsLHSNegative
1718                                   ? ValueFactory.getMinValue(ResultType)
1719                                   : ValueFactory.getValue(Zero);
1720 
1721     return {RangeFactory, Min, Max};
1722   }
1723 
1724   // Otherwise, let's check if at least one of the operands is positive.
1725   if (IsLHSPositiveOrZero || IsRHSPositiveOrZero) {
1726     // This makes result definitely positive.
1727     //
1728     // We can also reason about a maximal value by finding the maximal
1729     // value of the positive operand.
1730     const llvm::APSInt &Max = IsLHSPositiveOrZero ? LHS.To() : RHS.To();
1731 
1732     // The minimal value on the other hand is much harder to reason about.
1733     // The only thing we know for sure is that the result is positive.
1734     return {RangeFactory, ValueFactory.getValue(Zero),
1735             ValueFactory.getValue(Max)};
1736   }
1737 
1738   // Nothing much else to do here.
1739   return infer(T);
1740 }
1741 
1742 template <>
1743 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Rem>(Range LHS,
1744                                                             Range RHS,
1745                                                             QualType T) {
1746   llvm::APSInt Zero = ValueFactory.getAPSIntType(T).getZeroValue();
1747 
1748   Range ConservativeRange = getSymmetricalRange(RHS, T);
1749 
1750   llvm::APSInt Max = ConservativeRange.To();
1751   llvm::APSInt Min = ConservativeRange.From();
1752 
1753   if (Max == Zero) {
1754     // It's an undefined behaviour to divide by 0 and it seems like we know
1755     // for sure that RHS is 0.  Let's say that the resulting range is
1756     // simply infeasible for that matter.
1757     return RangeFactory.getEmptySet();
1758   }
1759 
1760   // At this point, our conservative range is closed.  The result, however,
1761   // couldn't be greater than the RHS' maximal absolute value.  Because of
1762   // this reason, we turn the range into open (or half-open in case of
1763   // unsigned integers).
1764   //
1765   // While we operate on integer values, an open interval (a, b) can be easily
1766   // represented by the closed interval [a + 1, b - 1].  And this is exactly
1767   // what we do next.
1768   //
1769   // If we are dealing with unsigned case, we shouldn't move the lower bound.
1770   if (Min.isSigned()) {
1771     ++Min;
1772   }
1773   --Max;
1774 
1775   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1776   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1777 
1778   // Remainder operator results with negative operands is implementation
1779   // defined.  Positive cases are much easier to reason about though.
1780   if (IsLHSPositiveOrZero && IsRHSPositiveOrZero) {
1781     // If maximal value of LHS is less than maximal value of RHS,
1782     // the result won't get greater than LHS.To().
1783     Max = std::min(LHS.To(), Max);
1784     // We want to check if it is a situation similar to the following:
1785     //
1786     // <------------|---[  LHS  ]--------[  RHS  ]----->
1787     //  -INF        0                              +INF
1788     //
1789     // In this situation, we can conclude that (LHS / RHS) == 0 and
1790     // (LHS % RHS) == LHS.
1791     Min = LHS.To() < RHS.From() ? LHS.From() : Zero;
1792   }
1793 
1794   // Nevertheless, the symmetrical range for RHS is a conservative estimate
1795   // for any sign of either LHS, or RHS.
1796   return {RangeFactory, ValueFactory.getValue(Min), ValueFactory.getValue(Max)};
1797 }
1798 
1799 RangeSet SymbolicRangeInferrer::VisitBinaryOperator(RangeSet LHS,
1800                                                     BinaryOperator::Opcode Op,
1801                                                     RangeSet RHS, QualType T) {
1802   // We should propagate information about unfeasbility of one of the
1803   // operands to the resulting range.
1804   if (LHS.isEmpty() || RHS.isEmpty()) {
1805     return RangeFactory.getEmptySet();
1806   }
1807 
1808   switch (Op) {
1809   case BO_NE:
1810     return VisitBinaryOperator<BO_NE>(LHS, RHS, T);
1811   case BO_Or:
1812     return VisitBinaryOperator<BO_Or>(LHS, RHS, T);
1813   case BO_And:
1814     return VisitBinaryOperator<BO_And>(LHS, RHS, T);
1815   case BO_Rem:
1816     return VisitBinaryOperator<BO_Rem>(LHS, RHS, T);
1817   default:
1818     return infer(T);
1819   }
1820 }
1821 
1822 //===----------------------------------------------------------------------===//
1823 //                  Constraint manager implementation details
1824 //===----------------------------------------------------------------------===//
1825 
1826 class RangeConstraintManager : public RangedConstraintManager {
1827 public:
1828   RangeConstraintManager(ExprEngine *EE, SValBuilder &SVB)
1829       : RangedConstraintManager(EE, SVB), F(getBasicVals()) {}
1830 
1831   //===------------------------------------------------------------------===//
1832   // Implementation for interface from ConstraintManager.
1833   //===------------------------------------------------------------------===//
1834 
1835   bool haveEqualConstraints(ProgramStateRef S1,
1836                             ProgramStateRef S2) const override {
1837     // NOTE: ClassMembers are as simple as back pointers for ClassMap,
1838     //       so comparing constraint ranges and class maps should be
1839     //       sufficient.
1840     return S1->get<ConstraintRange>() == S2->get<ConstraintRange>() &&
1841            S1->get<ClassMap>() == S2->get<ClassMap>();
1842   }
1843 
1844   bool canReasonAbout(SVal X) const override;
1845 
1846   ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override;
1847 
1848   const llvm::APSInt *getSymVal(ProgramStateRef State,
1849                                 SymbolRef Sym) const override;
1850 
1851   ProgramStateRef removeDeadBindings(ProgramStateRef State,
1852                                      SymbolReaper &SymReaper) override;
1853 
1854   void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
1855                  unsigned int Space = 0, bool IsDot = false) const override;
1856   void printValue(raw_ostream &Out, ProgramStateRef State,
1857                   SymbolRef Sym) override;
1858   void printConstraints(raw_ostream &Out, ProgramStateRef State,
1859                         const char *NL = "\n", unsigned int Space = 0,
1860                         bool IsDot = false) const;
1861   void printEquivalenceClasses(raw_ostream &Out, ProgramStateRef State,
1862                                const char *NL = "\n", unsigned int Space = 0,
1863                                bool IsDot = false) const;
1864   void printDisequalities(raw_ostream &Out, ProgramStateRef State,
1865                           const char *NL = "\n", unsigned int Space = 0,
1866                           bool IsDot = false) const;
1867 
1868   //===------------------------------------------------------------------===//
1869   // Implementation for interface from RangedConstraintManager.
1870   //===------------------------------------------------------------------===//
1871 
1872   ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym,
1873                               const llvm::APSInt &V,
1874                               const llvm::APSInt &Adjustment) override;
1875 
1876   ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym,
1877                               const llvm::APSInt &V,
1878                               const llvm::APSInt &Adjustment) override;
1879 
1880   ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym,
1881                               const llvm::APSInt &V,
1882                               const llvm::APSInt &Adjustment) override;
1883 
1884   ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym,
1885                               const llvm::APSInt &V,
1886                               const llvm::APSInt &Adjustment) override;
1887 
1888   ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym,
1889                               const llvm::APSInt &V,
1890                               const llvm::APSInt &Adjustment) override;
1891 
1892   ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym,
1893                               const llvm::APSInt &V,
1894                               const llvm::APSInt &Adjustment) override;
1895 
1896   ProgramStateRef assumeSymWithinInclusiveRange(
1897       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1898       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1899 
1900   ProgramStateRef assumeSymOutsideInclusiveRange(
1901       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1902       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1903 
1904 private:
1905   RangeSet::Factory F;
1906 
1907   RangeSet getRange(ProgramStateRef State, SymbolRef Sym);
1908   RangeSet getRange(ProgramStateRef State, EquivalenceClass Class);
1909   ProgramStateRef setRange(ProgramStateRef State, SymbolRef Sym,
1910                            RangeSet Range);
1911   ProgramStateRef setRange(ProgramStateRef State, EquivalenceClass Class,
1912                            RangeSet Range);
1913 
1914   RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym,
1915                          const llvm::APSInt &Int,
1916                          const llvm::APSInt &Adjustment);
1917   RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym,
1918                          const llvm::APSInt &Int,
1919                          const llvm::APSInt &Adjustment);
1920   RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym,
1921                          const llvm::APSInt &Int,
1922                          const llvm::APSInt &Adjustment);
1923   RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS,
1924                          const llvm::APSInt &Int,
1925                          const llvm::APSInt &Adjustment);
1926   RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym,
1927                          const llvm::APSInt &Int,
1928                          const llvm::APSInt &Adjustment);
1929 };
1930 
1931 //===----------------------------------------------------------------------===//
1932 //                         Constraint assignment logic
1933 //===----------------------------------------------------------------------===//
1934 
1935 /// ConstraintAssignorBase is a small utility class that unifies visitor
1936 /// for ranges with a visitor for constraints (rangeset/range/constant).
1937 ///
1938 /// It is designed to have one derived class, but generally it can have more.
1939 /// Derived class can control which types we handle by defining methods of the
1940 /// following form:
1941 ///
1942 ///   bool handle${SYMBOL}To${CONSTRAINT}(const SYMBOL *Sym,
1943 ///                                       CONSTRAINT Constraint);
1944 ///
1945 /// where SYMBOL is the type of the symbol (e.g. SymSymExpr, SymbolCast, etc.)
1946 ///       CONSTRAINT is the type of constraint (RangeSet/Range/Const)
1947 ///       return value signifies whether we should try other handle methods
1948 ///          (i.e. false would mean to stop right after calling this method)
1949 template <class Derived> class ConstraintAssignorBase {
1950 public:
1951   using Const = const llvm::APSInt &;
1952 
1953 #define DISPATCH(CLASS) return assign##CLASS##Impl(cast<CLASS>(Sym), Constraint)
1954 
1955 #define ASSIGN(CLASS, TO, SYM, CONSTRAINT)                                     \
1956   if (!static_cast<Derived *>(this)->assign##CLASS##To##TO(SYM, CONSTRAINT))   \
1957   return false
1958 
1959   void assign(SymbolRef Sym, RangeSet Constraint) {
1960     assignImpl(Sym, Constraint);
1961   }
1962 
1963   bool assignImpl(SymbolRef Sym, RangeSet Constraint) {
1964     switch (Sym->getKind()) {
1965 #define SYMBOL(Id, Parent)                                                     \
1966   case SymExpr::Id##Kind:                                                      \
1967     DISPATCH(Id);
1968 #include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
1969     }
1970     llvm_unreachable("Unknown SymExpr kind!");
1971   }
1972 
1973 #define DEFAULT_ASSIGN(Id)                                                     \
1974   bool assign##Id##To##RangeSet(const Id *Sym, RangeSet Constraint) {          \
1975     return true;                                                               \
1976   }                                                                            \
1977   bool assign##Id##To##Range(const Id *Sym, Range Constraint) { return true; } \
1978   bool assign##Id##To##Const(const Id *Sym, Const Constraint) { return true; }
1979 
1980   // When we dispatch for constraint types, we first try to check
1981   // if the new constraint is the constant and try the corresponding
1982   // assignor methods.  If it didn't interrupt, we can proceed to the
1983   // range, and finally to the range set.
1984 #define CONSTRAINT_DISPATCH(Id)                                                \
1985   if (const llvm::APSInt *Const = Constraint.getConcreteValue()) {             \
1986     ASSIGN(Id, Const, Sym, *Const);                                            \
1987   }                                                                            \
1988   if (Constraint.size() == 1) {                                                \
1989     ASSIGN(Id, Range, Sym, *Constraint.begin());                               \
1990   }                                                                            \
1991   ASSIGN(Id, RangeSet, Sym, Constraint)
1992 
1993   // Our internal assign method first tries to call assignor methods for all
1994   // constraint types that apply.  And if not interrupted, continues with its
1995   // parent class.
1996 #define SYMBOL(Id, Parent)                                                     \
1997   bool assign##Id##Impl(const Id *Sym, RangeSet Constraint) {                  \
1998     CONSTRAINT_DISPATCH(Id);                                                   \
1999     DISPATCH(Parent);                                                          \
2000   }                                                                            \
2001   DEFAULT_ASSIGN(Id)
2002 #define ABSTRACT_SYMBOL(Id, Parent) SYMBOL(Id, Parent)
2003 #include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
2004 
2005   // Default implementations for the top class that doesn't have parents.
2006   bool assignSymExprImpl(const SymExpr *Sym, RangeSet Constraint) {
2007     CONSTRAINT_DISPATCH(SymExpr);
2008     return true;
2009   }
2010   DEFAULT_ASSIGN(SymExpr);
2011 
2012 #undef DISPATCH
2013 #undef CONSTRAINT_DISPATCH
2014 #undef DEFAULT_ASSIGN
2015 #undef ASSIGN
2016 };
2017 
2018 /// A little component aggregating all of the reasoning we have about
2019 /// assigning new constraints to symbols.
2020 ///
2021 /// The main purpose of this class is to associate constraints to symbols,
2022 /// and impose additional constraints on other symbols, when we can imply
2023 /// them.
2024 ///
2025 /// It has a nice symmetry with SymbolicRangeInferrer.  When the latter
2026 /// can provide more precise ranges by looking into the operands of the
2027 /// expression in question, ConstraintAssignor looks into the operands
2028 /// to see if we can imply more from the new constraint.
2029 class ConstraintAssignor : public ConstraintAssignorBase<ConstraintAssignor> {
2030 public:
2031   template <class ClassOrSymbol>
2032   [[nodiscard]] static ProgramStateRef
2033   assign(ProgramStateRef State, SValBuilder &Builder, RangeSet::Factory &F,
2034          ClassOrSymbol CoS, RangeSet NewConstraint) {
2035     if (!State || NewConstraint.isEmpty())
2036       return nullptr;
2037 
2038     ConstraintAssignor Assignor{State, Builder, F};
2039     return Assignor.assign(CoS, NewConstraint);
2040   }
2041 
2042   /// Handle expressions like: a % b != 0.
2043   template <typename SymT>
2044   bool handleRemainderOp(const SymT *Sym, RangeSet Constraint) {
2045     if (Sym->getOpcode() != BO_Rem)
2046       return true;
2047     // a % b != 0 implies that a != 0.
2048     if (!Constraint.containsZero()) {
2049       SVal SymSVal = Builder.makeSymbolVal(Sym->getLHS());
2050       if (auto NonLocSymSVal = SymSVal.getAs<nonloc::SymbolVal>()) {
2051         State = State->assume(*NonLocSymSVal, true);
2052         if (!State)
2053           return false;
2054       }
2055     }
2056     return true;
2057   }
2058 
2059   inline bool assignSymExprToConst(const SymExpr *Sym, Const Constraint);
2060   inline bool assignSymIntExprToRangeSet(const SymIntExpr *Sym,
2061                                          RangeSet Constraint) {
2062     return handleRemainderOp(Sym, Constraint);
2063   }
2064   inline bool assignSymSymExprToRangeSet(const SymSymExpr *Sym,
2065                                          RangeSet Constraint);
2066 
2067 private:
2068   ConstraintAssignor(ProgramStateRef State, SValBuilder &Builder,
2069                      RangeSet::Factory &F)
2070       : State(State), Builder(Builder), RangeFactory(F) {}
2071   using Base = ConstraintAssignorBase<ConstraintAssignor>;
2072 
2073   /// Base method for handling new constraints for symbols.
2074   [[nodiscard]] ProgramStateRef assign(SymbolRef Sym, RangeSet NewConstraint) {
2075     // All constraints are actually associated with equivalence classes, and
2076     // that's what we are going to do first.
2077     State = assign(EquivalenceClass::find(State, Sym), NewConstraint);
2078     if (!State)
2079       return nullptr;
2080 
2081     // And after that we can check what other things we can get from this
2082     // constraint.
2083     Base::assign(Sym, NewConstraint);
2084     return State;
2085   }
2086 
2087   /// Base method for handling new constraints for classes.
2088   [[nodiscard]] ProgramStateRef assign(EquivalenceClass Class,
2089                                        RangeSet NewConstraint) {
2090     // There is a chance that we might need to update constraints for the
2091     // classes that are known to be disequal to Class.
2092     //
2093     // In order for this to be even possible, the new constraint should
2094     // be simply a constant because we can't reason about range disequalities.
2095     if (const llvm::APSInt *Point = NewConstraint.getConcreteValue()) {
2096 
2097       ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2098       ConstraintRangeTy::Factory &CF = State->get_context<ConstraintRange>();
2099 
2100       // Add new constraint.
2101       Constraints = CF.add(Constraints, Class, NewConstraint);
2102 
2103       for (EquivalenceClass DisequalClass : Class.getDisequalClasses(State)) {
2104         RangeSet UpdatedConstraint = SymbolicRangeInferrer::inferRange(
2105             RangeFactory, State, DisequalClass);
2106 
2107         UpdatedConstraint = RangeFactory.deletePoint(UpdatedConstraint, *Point);
2108 
2109         // If we end up with at least one of the disequal classes to be
2110         // constrained with an empty range-set, the state is infeasible.
2111         if (UpdatedConstraint.isEmpty())
2112           return nullptr;
2113 
2114         Constraints = CF.add(Constraints, DisequalClass, UpdatedConstraint);
2115       }
2116       assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
2117                                          "a state with infeasible constraints");
2118 
2119       return setConstraints(State, Constraints);
2120     }
2121 
2122     return setConstraint(State, Class, NewConstraint);
2123   }
2124 
2125   ProgramStateRef trackDisequality(ProgramStateRef State, SymbolRef LHS,
2126                                    SymbolRef RHS) {
2127     return EquivalenceClass::markDisequal(RangeFactory, State, LHS, RHS);
2128   }
2129 
2130   ProgramStateRef trackEquality(ProgramStateRef State, SymbolRef LHS,
2131                                 SymbolRef RHS) {
2132     return EquivalenceClass::merge(RangeFactory, State, LHS, RHS);
2133   }
2134 
2135   [[nodiscard]] Optional<bool> interpreteAsBool(RangeSet Constraint) {
2136     assert(!Constraint.isEmpty() && "Empty ranges shouldn't get here");
2137 
2138     if (Constraint.getConcreteValue())
2139       return !Constraint.getConcreteValue()->isZero();
2140 
2141     if (!Constraint.containsZero())
2142       return true;
2143 
2144     return std::nullopt;
2145   }
2146 
2147   ProgramStateRef State;
2148   SValBuilder &Builder;
2149   RangeSet::Factory &RangeFactory;
2150 };
2151 
2152 
2153 bool ConstraintAssignor::assignSymExprToConst(const SymExpr *Sym,
2154                                               const llvm::APSInt &Constraint) {
2155   llvm::SmallSet<EquivalenceClass, 4> SimplifiedClasses;
2156   // Iterate over all equivalence classes and try to simplify them.
2157   ClassMembersTy Members = State->get<ClassMembers>();
2158   for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members) {
2159     EquivalenceClass Class = ClassToSymbolSet.first;
2160     State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
2161     if (!State)
2162       return false;
2163     SimplifiedClasses.insert(Class);
2164   }
2165 
2166   // Trivial equivalence classes (those that have only one symbol member) are
2167   // not stored in the State. Thus, we must skim through the constraints as
2168   // well. And we try to simplify symbols in the constraints.
2169   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2170   for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
2171     EquivalenceClass Class = ClassConstraint.first;
2172     if (SimplifiedClasses.count(Class)) // Already simplified.
2173       continue;
2174     State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
2175     if (!State)
2176       return false;
2177   }
2178 
2179   // We may have trivial equivalence classes in the disequality info as
2180   // well, and we need to simplify them.
2181   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
2182   for (std::pair<EquivalenceClass, ClassSet> DisequalityEntry :
2183        DisequalityInfo) {
2184     EquivalenceClass Class = DisequalityEntry.first;
2185     ClassSet DisequalClasses = DisequalityEntry.second;
2186     State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
2187     if (!State)
2188       return false;
2189   }
2190 
2191   return true;
2192 }
2193 
2194 bool ConstraintAssignor::assignSymSymExprToRangeSet(const SymSymExpr *Sym,
2195                                                     RangeSet Constraint) {
2196   if (!handleRemainderOp(Sym, Constraint))
2197     return false;
2198 
2199   Optional<bool> ConstraintAsBool = interpreteAsBool(Constraint);
2200 
2201   if (!ConstraintAsBool)
2202     return true;
2203 
2204   if (Optional<bool> Equality = meansEquality(Sym)) {
2205     // Here we cover two cases:
2206     //   * if Sym is equality and the new constraint is true -> Sym's operands
2207     //     should be marked as equal
2208     //   * if Sym is disequality and the new constraint is false -> Sym's
2209     //     operands should be also marked as equal
2210     if (*Equality == *ConstraintAsBool) {
2211       State = trackEquality(State, Sym->getLHS(), Sym->getRHS());
2212     } else {
2213       // Other combinations leave as with disequal operands.
2214       State = trackDisequality(State, Sym->getLHS(), Sym->getRHS());
2215     }
2216 
2217     if (!State)
2218       return false;
2219   }
2220 
2221   return true;
2222 }
2223 
2224 } // end anonymous namespace
2225 
2226 std::unique_ptr<ConstraintManager>
2227 ento::CreateRangeConstraintManager(ProgramStateManager &StMgr,
2228                                    ExprEngine *Eng) {
2229   return std::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder());
2230 }
2231 
2232 ConstraintMap ento::getConstraintMap(ProgramStateRef State) {
2233   ConstraintMap::Factory &F = State->get_context<ConstraintMap>();
2234   ConstraintMap Result = F.getEmptyMap();
2235 
2236   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2237   for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
2238     EquivalenceClass Class = ClassConstraint.first;
2239     SymbolSet ClassMembers = Class.getClassMembers(State);
2240     assert(!ClassMembers.isEmpty() &&
2241            "Class must always have at least one member!");
2242 
2243     SymbolRef Representative = *ClassMembers.begin();
2244     Result = F.add(Result, Representative, ClassConstraint.second);
2245   }
2246 
2247   return Result;
2248 }
2249 
2250 //===----------------------------------------------------------------------===//
2251 //                     EqualityClass implementation details
2252 //===----------------------------------------------------------------------===//
2253 
2254 LLVM_DUMP_METHOD void EquivalenceClass::dumpToStream(ProgramStateRef State,
2255                                                      raw_ostream &os) const {
2256   SymbolSet ClassMembers = getClassMembers(State);
2257   for (const SymbolRef &MemberSym : ClassMembers) {
2258     MemberSym->dump();
2259     os << "\n";
2260   }
2261 }
2262 
2263 inline EquivalenceClass EquivalenceClass::find(ProgramStateRef State,
2264                                                SymbolRef Sym) {
2265   assert(State && "State should not be null");
2266   assert(Sym && "Symbol should not be null");
2267   // We store far from all Symbol -> Class mappings
2268   if (const EquivalenceClass *NontrivialClass = State->get<ClassMap>(Sym))
2269     return *NontrivialClass;
2270 
2271   // This is a trivial class of Sym.
2272   return Sym;
2273 }
2274 
2275 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
2276                                                ProgramStateRef State,
2277                                                SymbolRef First,
2278                                                SymbolRef Second) {
2279   EquivalenceClass FirstClass = find(State, First);
2280   EquivalenceClass SecondClass = find(State, Second);
2281 
2282   return FirstClass.merge(F, State, SecondClass);
2283 }
2284 
2285 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
2286                                                ProgramStateRef State,
2287                                                EquivalenceClass Other) {
2288   // It is already the same class.
2289   if (*this == Other)
2290     return State;
2291 
2292   // FIXME: As of now, we support only equivalence classes of the same type.
2293   //        This limitation is connected to the lack of explicit casts in
2294   //        our symbolic expression model.
2295   //
2296   //        That means that for `int x` and `char y` we don't distinguish
2297   //        between these two very different cases:
2298   //          * `x == y`
2299   //          * `(char)x == y`
2300   //
2301   //        The moment we introduce symbolic casts, this restriction can be
2302   //        lifted.
2303   if (getType() != Other.getType())
2304     return State;
2305 
2306   SymbolSet Members = getClassMembers(State);
2307   SymbolSet OtherMembers = Other.getClassMembers(State);
2308 
2309   // We estimate the size of the class by the height of tree containing
2310   // its members.  Merging is not a trivial operation, so it's easier to
2311   // merge the smaller class into the bigger one.
2312   if (Members.getHeight() >= OtherMembers.getHeight()) {
2313     return mergeImpl(F, State, Members, Other, OtherMembers);
2314   } else {
2315     return Other.mergeImpl(F, State, OtherMembers, *this, Members);
2316   }
2317 }
2318 
2319 inline ProgramStateRef
2320 EquivalenceClass::mergeImpl(RangeSet::Factory &RangeFactory,
2321                             ProgramStateRef State, SymbolSet MyMembers,
2322                             EquivalenceClass Other, SymbolSet OtherMembers) {
2323   // Essentially what we try to recreate here is some kind of union-find
2324   // data structure.  It does have certain limitations due to persistence
2325   // and the need to remove elements from classes.
2326   //
2327   // In this setting, EquialityClass object is the representative of the class
2328   // or the parent element.  ClassMap is a mapping of class members to their
2329   // parent. Unlike the union-find structure, they all point directly to the
2330   // class representative because we don't have an opportunity to actually do
2331   // path compression when dealing with immutability.  This means that we
2332   // compress paths every time we do merges.  It also means that we lose
2333   // the main amortized complexity benefit from the original data structure.
2334   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2335   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
2336 
2337   // 1. If the merged classes have any constraints associated with them, we
2338   //    need to transfer them to the class we have left.
2339   //
2340   // Intersection here makes perfect sense because both of these constraints
2341   // must hold for the whole new class.
2342   if (Optional<RangeSet> NewClassConstraint =
2343           intersect(RangeFactory, getConstraint(State, *this),
2344                     getConstraint(State, Other))) {
2345     // NOTE: Essentially, NewClassConstraint should NEVER be infeasible because
2346     //       range inferrer shouldn't generate ranges incompatible with
2347     //       equivalence classes. However, at the moment, due to imperfections
2348     //       in the solver, it is possible and the merge function can also
2349     //       return infeasible states aka null states.
2350     if (NewClassConstraint->isEmpty())
2351       // Infeasible state
2352       return nullptr;
2353 
2354     // No need in tracking constraints of a now-dissolved class.
2355     Constraints = CRF.remove(Constraints, Other);
2356     // Assign new constraints for this class.
2357     Constraints = CRF.add(Constraints, *this, *NewClassConstraint);
2358 
2359     assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
2360                                        "a state with infeasible constraints");
2361 
2362     State = State->set<ConstraintRange>(Constraints);
2363   }
2364 
2365   // 2. Get ALL equivalence-related maps
2366   ClassMapTy Classes = State->get<ClassMap>();
2367   ClassMapTy::Factory &CMF = State->get_context<ClassMap>();
2368 
2369   ClassMembersTy Members = State->get<ClassMembers>();
2370   ClassMembersTy::Factory &MF = State->get_context<ClassMembers>();
2371 
2372   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
2373   DisequalityMapTy::Factory &DF = State->get_context<DisequalityMap>();
2374 
2375   ClassSet::Factory &CF = State->get_context<ClassSet>();
2376   SymbolSet::Factory &F = getMembersFactory(State);
2377 
2378   // 2. Merge members of the Other class into the current class.
2379   SymbolSet NewClassMembers = MyMembers;
2380   for (SymbolRef Sym : OtherMembers) {
2381     NewClassMembers = F.add(NewClassMembers, Sym);
2382     // *this is now the class for all these new symbols.
2383     Classes = CMF.add(Classes, Sym, *this);
2384   }
2385 
2386   // 3. Adjust member mapping.
2387   //
2388   // No need in tracking members of a now-dissolved class.
2389   Members = MF.remove(Members, Other);
2390   // Now only the current class is mapped to all the symbols.
2391   Members = MF.add(Members, *this, NewClassMembers);
2392 
2393   // 4. Update disequality relations
2394   ClassSet DisequalToOther = Other.getDisequalClasses(DisequalityInfo, CF);
2395   // We are about to merge two classes but they are already known to be
2396   // non-equal. This is a contradiction.
2397   if (DisequalToOther.contains(*this))
2398     return nullptr;
2399 
2400   if (!DisequalToOther.isEmpty()) {
2401     ClassSet DisequalToThis = getDisequalClasses(DisequalityInfo, CF);
2402     DisequalityInfo = DF.remove(DisequalityInfo, Other);
2403 
2404     for (EquivalenceClass DisequalClass : DisequalToOther) {
2405       DisequalToThis = CF.add(DisequalToThis, DisequalClass);
2406 
2407       // Disequality is a symmetric relation meaning that if
2408       // DisequalToOther not null then the set for DisequalClass is not
2409       // empty and has at least Other.
2410       ClassSet OriginalSetLinkedToOther =
2411           *DisequalityInfo.lookup(DisequalClass);
2412 
2413       // Other will be eliminated and we should replace it with the bigger
2414       // united class.
2415       ClassSet NewSet = CF.remove(OriginalSetLinkedToOther, Other);
2416       NewSet = CF.add(NewSet, *this);
2417 
2418       DisequalityInfo = DF.add(DisequalityInfo, DisequalClass, NewSet);
2419     }
2420 
2421     DisequalityInfo = DF.add(DisequalityInfo, *this, DisequalToThis);
2422     State = State->set<DisequalityMap>(DisequalityInfo);
2423   }
2424 
2425   // 5. Update the state
2426   State = State->set<ClassMap>(Classes);
2427   State = State->set<ClassMembers>(Members);
2428 
2429   return State;
2430 }
2431 
2432 inline SymbolSet::Factory &
2433 EquivalenceClass::getMembersFactory(ProgramStateRef State) {
2434   return State->get_context<SymbolSet>();
2435 }
2436 
2437 SymbolSet EquivalenceClass::getClassMembers(ProgramStateRef State) const {
2438   if (const SymbolSet *Members = State->get<ClassMembers>(*this))
2439     return *Members;
2440 
2441   // This class is trivial, so we need to construct a set
2442   // with just that one symbol from the class.
2443   SymbolSet::Factory &F = getMembersFactory(State);
2444   return F.add(F.getEmptySet(), getRepresentativeSymbol());
2445 }
2446 
2447 bool EquivalenceClass::isTrivial(ProgramStateRef State) const {
2448   return State->get<ClassMembers>(*this) == nullptr;
2449 }
2450 
2451 bool EquivalenceClass::isTriviallyDead(ProgramStateRef State,
2452                                        SymbolReaper &Reaper) const {
2453   return isTrivial(State) && Reaper.isDead(getRepresentativeSymbol());
2454 }
2455 
2456 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
2457                                                       ProgramStateRef State,
2458                                                       SymbolRef First,
2459                                                       SymbolRef Second) {
2460   return markDisequal(RF, State, find(State, First), find(State, Second));
2461 }
2462 
2463 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
2464                                                       ProgramStateRef State,
2465                                                       EquivalenceClass First,
2466                                                       EquivalenceClass Second) {
2467   return First.markDisequal(RF, State, Second);
2468 }
2469 
2470 inline ProgramStateRef
2471 EquivalenceClass::markDisequal(RangeSet::Factory &RF, ProgramStateRef State,
2472                                EquivalenceClass Other) const {
2473   // If we know that two classes are equal, we can only produce an infeasible
2474   // state.
2475   if (*this == Other) {
2476     return nullptr;
2477   }
2478 
2479   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
2480   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2481 
2482   // Disequality is a symmetric relation, so if we mark A as disequal to B,
2483   // we should also mark B as disequalt to A.
2484   if (!addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, *this,
2485                             Other) ||
2486       !addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, Other,
2487                             *this))
2488     return nullptr;
2489 
2490   assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
2491                                      "a state with infeasible constraints");
2492 
2493   State = State->set<DisequalityMap>(DisequalityInfo);
2494   State = State->set<ConstraintRange>(Constraints);
2495 
2496   return State;
2497 }
2498 
2499 inline bool EquivalenceClass::addToDisequalityInfo(
2500     DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
2501     RangeSet::Factory &RF, ProgramStateRef State, EquivalenceClass First,
2502     EquivalenceClass Second) {
2503 
2504   // 1. Get all of the required factories.
2505   DisequalityMapTy::Factory &F = State->get_context<DisequalityMap>();
2506   ClassSet::Factory &CF = State->get_context<ClassSet>();
2507   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
2508 
2509   // 2. Add Second to the set of classes disequal to First.
2510   const ClassSet *CurrentSet = Info.lookup(First);
2511   ClassSet NewSet = CurrentSet ? *CurrentSet : CF.getEmptySet();
2512   NewSet = CF.add(NewSet, Second);
2513 
2514   Info = F.add(Info, First, NewSet);
2515 
2516   // 3. If Second is known to be a constant, we can delete this point
2517   //    from the constraint asociated with First.
2518   //
2519   //    So, if Second == 10, it means that First != 10.
2520   //    At the same time, the same logic does not apply to ranges.
2521   if (const RangeSet *SecondConstraint = Constraints.lookup(Second))
2522     if (const llvm::APSInt *Point = SecondConstraint->getConcreteValue()) {
2523 
2524       RangeSet FirstConstraint = SymbolicRangeInferrer::inferRange(
2525           RF, State, First.getRepresentativeSymbol());
2526 
2527       FirstConstraint = RF.deletePoint(FirstConstraint, *Point);
2528 
2529       // If the First class is about to be constrained with an empty
2530       // range-set, the state is infeasible.
2531       if (FirstConstraint.isEmpty())
2532         return false;
2533 
2534       Constraints = CRF.add(Constraints, First, FirstConstraint);
2535     }
2536 
2537   return true;
2538 }
2539 
2540 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2541                                                  SymbolRef FirstSym,
2542                                                  SymbolRef SecondSym) {
2543   return EquivalenceClass::areEqual(State, find(State, FirstSym),
2544                                     find(State, SecondSym));
2545 }
2546 
2547 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2548                                                  EquivalenceClass First,
2549                                                  EquivalenceClass Second) {
2550   // The same equivalence class => symbols are equal.
2551   if (First == Second)
2552     return true;
2553 
2554   // Let's check if we know anything about these two classes being not equal to
2555   // each other.
2556   ClassSet DisequalToFirst = First.getDisequalClasses(State);
2557   if (DisequalToFirst.contains(Second))
2558     return false;
2559 
2560   // It is not clear.
2561   return std::nullopt;
2562 }
2563 
2564 [[nodiscard]] ProgramStateRef
2565 EquivalenceClass::removeMember(ProgramStateRef State, const SymbolRef Old) {
2566 
2567   SymbolSet ClsMembers = getClassMembers(State);
2568   assert(ClsMembers.contains(Old));
2569 
2570   // Remove `Old`'s Class->Sym relation.
2571   SymbolSet::Factory &F = getMembersFactory(State);
2572   ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>();
2573   ClsMembers = F.remove(ClsMembers, Old);
2574   // Ensure another precondition of the removeMember function (we can check
2575   // this only with isEmpty, thus we have to do the remove first).
2576   assert(!ClsMembers.isEmpty() &&
2577          "Class should have had at least two members before member removal");
2578   // Overwrite the existing members assigned to this class.
2579   ClassMembersTy ClassMembersMap = State->get<ClassMembers>();
2580   ClassMembersMap = EMFactory.add(ClassMembersMap, *this, ClsMembers);
2581   State = State->set<ClassMembers>(ClassMembersMap);
2582 
2583   // Remove `Old`'s Sym->Class relation.
2584   ClassMapTy Classes = State->get<ClassMap>();
2585   ClassMapTy::Factory &CMF = State->get_context<ClassMap>();
2586   Classes = CMF.remove(Classes, Old);
2587   State = State->set<ClassMap>(Classes);
2588 
2589   return State;
2590 }
2591 
2592 // Re-evaluate an SVal with top-level `State->assume` logic.
2593 [[nodiscard]] ProgramStateRef
2594 reAssume(ProgramStateRef State, const RangeSet *Constraint, SVal TheValue) {
2595   if (!Constraint)
2596     return State;
2597 
2598   const auto DefinedVal = TheValue.castAs<DefinedSVal>();
2599 
2600   // If the SVal is 0, we can simply interpret that as `false`.
2601   if (Constraint->encodesFalseRange())
2602     return State->assume(DefinedVal, false);
2603 
2604   // If the constraint does not encode 0 then we can interpret that as `true`
2605   // AND as a Range(Set).
2606   if (Constraint->encodesTrueRange()) {
2607     State = State->assume(DefinedVal, true);
2608     if (!State)
2609       return nullptr;
2610     // Fall through, re-assume based on the range values as well.
2611   }
2612   // Overestimate the individual Ranges with the RangeSet' lowest and
2613   // highest values.
2614   return State->assumeInclusiveRange(DefinedVal, Constraint->getMinValue(),
2615                                      Constraint->getMaxValue(), true);
2616 }
2617 
2618 // Iterate over all symbols and try to simplify them. Once a symbol is
2619 // simplified then we check if we can merge the simplified symbol's equivalence
2620 // class to this class. This way, we simplify not just the symbols but the
2621 // classes as well: we strive to keep the number of the classes to be the
2622 // absolute minimum.
2623 [[nodiscard]] ProgramStateRef
2624 EquivalenceClass::simplify(SValBuilder &SVB, RangeSet::Factory &F,
2625                            ProgramStateRef State, EquivalenceClass Class) {
2626   SymbolSet ClassMembers = Class.getClassMembers(State);
2627   for (const SymbolRef &MemberSym : ClassMembers) {
2628 
2629     const SVal SimplifiedMemberVal = simplifyToSVal(State, MemberSym);
2630     const SymbolRef SimplifiedMemberSym = SimplifiedMemberVal.getAsSymbol();
2631 
2632     // The symbol is collapsed to a constant, check if the current State is
2633     // still feasible.
2634     if (const auto CI = SimplifiedMemberVal.getAs<nonloc::ConcreteInt>()) {
2635       const llvm::APSInt &SV = CI->getValue();
2636       const RangeSet *ClassConstraint = getConstraint(State, Class);
2637       // We have found a contradiction.
2638       if (ClassConstraint && !ClassConstraint->contains(SV))
2639         return nullptr;
2640     }
2641 
2642     if (SimplifiedMemberSym && MemberSym != SimplifiedMemberSym) {
2643       // The simplified symbol should be the member of the original Class,
2644       // however, it might be in another existing class at the moment. We
2645       // have to merge these classes.
2646       ProgramStateRef OldState = State;
2647       State = merge(F, State, MemberSym, SimplifiedMemberSym);
2648       if (!State)
2649         return nullptr;
2650       // No state change, no merge happened actually.
2651       if (OldState == State)
2652         continue;
2653 
2654       assert(find(State, MemberSym) == find(State, SimplifiedMemberSym));
2655       // Remove the old and more complex symbol.
2656       State = find(State, MemberSym).removeMember(State, MemberSym);
2657 
2658       // Query the class constraint again b/c that may have changed during the
2659       // merge above.
2660       const RangeSet *ClassConstraint = getConstraint(State, Class);
2661 
2662       // Re-evaluate an SVal with top-level `State->assume`, this ignites
2663       // a RECURSIVE algorithm that will reach a FIXPOINT.
2664       //
2665       // About performance and complexity: Let us assume that in a State we
2666       // have N non-trivial equivalence classes and that all constraints and
2667       // disequality info is related to non-trivial classes. In the worst case,
2668       // we can simplify only one symbol of one class in each iteration. The
2669       // number of symbols in one class cannot grow b/c we replace the old
2670       // symbol with the simplified one. Also, the number of the equivalence
2671       // classes can decrease only, b/c the algorithm does a merge operation
2672       // optionally. We need N iterations in this case to reach the fixpoint.
2673       // Thus, the steps needed to be done in the worst case is proportional to
2674       // N*N.
2675       //
2676       // This worst case scenario can be extended to that case when we have
2677       // trivial classes in the constraints and in the disequality map. This
2678       // case can be reduced to the case with a State where there are only
2679       // non-trivial classes. This is because a merge operation on two trivial
2680       // classes results in one non-trivial class.
2681       State = reAssume(State, ClassConstraint, SimplifiedMemberVal);
2682       if (!State)
2683         return nullptr;
2684     }
2685   }
2686   return State;
2687 }
2688 
2689 inline ClassSet EquivalenceClass::getDisequalClasses(ProgramStateRef State,
2690                                                      SymbolRef Sym) {
2691   return find(State, Sym).getDisequalClasses(State);
2692 }
2693 
2694 inline ClassSet
2695 EquivalenceClass::getDisequalClasses(ProgramStateRef State) const {
2696   return getDisequalClasses(State->get<DisequalityMap>(),
2697                             State->get_context<ClassSet>());
2698 }
2699 
2700 inline ClassSet
2701 EquivalenceClass::getDisequalClasses(DisequalityMapTy Map,
2702                                      ClassSet::Factory &Factory) const {
2703   if (const ClassSet *DisequalClasses = Map.lookup(*this))
2704     return *DisequalClasses;
2705 
2706   return Factory.getEmptySet();
2707 }
2708 
2709 bool EquivalenceClass::isClassDataConsistent(ProgramStateRef State) {
2710   ClassMembersTy Members = State->get<ClassMembers>();
2711 
2712   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair : Members) {
2713     for (SymbolRef Member : ClassMembersPair.second) {
2714       // Every member of the class should have a mapping back to the class.
2715       if (find(State, Member) == ClassMembersPair.first) {
2716         continue;
2717       }
2718 
2719       return false;
2720     }
2721   }
2722 
2723   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2724   for (std::pair<EquivalenceClass, ClassSet> DisequalityInfo : Disequalities) {
2725     EquivalenceClass Class = DisequalityInfo.first;
2726     ClassSet DisequalClasses = DisequalityInfo.second;
2727 
2728     // There is no use in keeping empty sets in the map.
2729     if (DisequalClasses.isEmpty())
2730       return false;
2731 
2732     // Disequality is symmetrical, i.e. for every Class A and B that A != B,
2733     // B != A should also be true.
2734     for (EquivalenceClass DisequalClass : DisequalClasses) {
2735       const ClassSet *DisequalToDisequalClasses =
2736           Disequalities.lookup(DisequalClass);
2737 
2738       // It should be a set of at least one element: Class
2739       if (!DisequalToDisequalClasses ||
2740           !DisequalToDisequalClasses->contains(Class))
2741         return false;
2742     }
2743   }
2744 
2745   return true;
2746 }
2747 
2748 //===----------------------------------------------------------------------===//
2749 //                    RangeConstraintManager implementation
2750 //===----------------------------------------------------------------------===//
2751 
2752 bool RangeConstraintManager::canReasonAbout(SVal X) const {
2753   Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
2754   if (SymVal && SymVal->isExpression()) {
2755     const SymExpr *SE = SymVal->getSymbol();
2756 
2757     if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
2758       switch (SIE->getOpcode()) {
2759       // We don't reason yet about bitwise-constraints on symbolic values.
2760       case BO_And:
2761       case BO_Or:
2762       case BO_Xor:
2763         return false;
2764       // We don't reason yet about these arithmetic constraints on
2765       // symbolic values.
2766       case BO_Mul:
2767       case BO_Div:
2768       case BO_Rem:
2769       case BO_Shl:
2770       case BO_Shr:
2771         return false;
2772       // All other cases.
2773       default:
2774         return true;
2775       }
2776     }
2777 
2778     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
2779       // FIXME: Handle <=> here.
2780       if (BinaryOperator::isEqualityOp(SSE->getOpcode()) ||
2781           BinaryOperator::isRelationalOp(SSE->getOpcode())) {
2782         // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
2783         // We've recently started producing Loc <> NonLoc comparisons (that
2784         // result from casts of one of the operands between eg. intptr_t and
2785         // void *), but we can't reason about them yet.
2786         if (Loc::isLocType(SSE->getLHS()->getType())) {
2787           return Loc::isLocType(SSE->getRHS()->getType());
2788         }
2789       }
2790     }
2791 
2792     return false;
2793   }
2794 
2795   return true;
2796 }
2797 
2798 ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
2799                                                     SymbolRef Sym) {
2800   const RangeSet *Ranges = getConstraint(State, Sym);
2801 
2802   // If we don't have any information about this symbol, it's underconstrained.
2803   if (!Ranges)
2804     return ConditionTruthVal();
2805 
2806   // If we have a concrete value, see if it's zero.
2807   if (const llvm::APSInt *Value = Ranges->getConcreteValue())
2808     return *Value == 0;
2809 
2810   BasicValueFactory &BV = getBasicVals();
2811   APSIntType IntType = BV.getAPSIntType(Sym->getType());
2812   llvm::APSInt Zero = IntType.getZeroValue();
2813 
2814   // Check if zero is in the set of possible values.
2815   if (!Ranges->contains(Zero))
2816     return false;
2817 
2818   // Zero is a possible value, but it is not the /only/ possible value.
2819   return ConditionTruthVal();
2820 }
2821 
2822 const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St,
2823                                                       SymbolRef Sym) const {
2824   const RangeSet *T = getConstraint(St, Sym);
2825   return T ? T->getConcreteValue() : nullptr;
2826 }
2827 
2828 //===----------------------------------------------------------------------===//
2829 //                Remove dead symbols from existing constraints
2830 //===----------------------------------------------------------------------===//
2831 
2832 /// Scan all symbols referenced by the constraints. If the symbol is not alive
2833 /// as marked in LSymbols, mark it as dead in DSymbols.
2834 ProgramStateRef
2835 RangeConstraintManager::removeDeadBindings(ProgramStateRef State,
2836                                            SymbolReaper &SymReaper) {
2837   ClassMembersTy ClassMembersMap = State->get<ClassMembers>();
2838   ClassMembersTy NewClassMembersMap = ClassMembersMap;
2839   ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>();
2840   SymbolSet::Factory &SetFactory = State->get_context<SymbolSet>();
2841 
2842   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2843   ConstraintRangeTy NewConstraints = Constraints;
2844   ConstraintRangeTy::Factory &ConstraintFactory =
2845       State->get_context<ConstraintRange>();
2846 
2847   ClassMapTy Map = State->get<ClassMap>();
2848   ClassMapTy NewMap = Map;
2849   ClassMapTy::Factory &ClassFactory = State->get_context<ClassMap>();
2850 
2851   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2852   DisequalityMapTy::Factory &DisequalityFactory =
2853       State->get_context<DisequalityMap>();
2854   ClassSet::Factory &ClassSetFactory = State->get_context<ClassSet>();
2855 
2856   bool ClassMapChanged = false;
2857   bool MembersMapChanged = false;
2858   bool ConstraintMapChanged = false;
2859   bool DisequalitiesChanged = false;
2860 
2861   auto removeDeadClass = [&](EquivalenceClass Class) {
2862     // Remove associated constraint ranges.
2863     Constraints = ConstraintFactory.remove(Constraints, Class);
2864     ConstraintMapChanged = true;
2865 
2866     // Update disequality information to not hold any information on the
2867     // removed class.
2868     ClassSet DisequalClasses =
2869         Class.getDisequalClasses(Disequalities, ClassSetFactory);
2870     if (!DisequalClasses.isEmpty()) {
2871       for (EquivalenceClass DisequalClass : DisequalClasses) {
2872         ClassSet DisequalToDisequalSet =
2873             DisequalClass.getDisequalClasses(Disequalities, ClassSetFactory);
2874         // DisequalToDisequalSet is guaranteed to be non-empty for consistent
2875         // disequality info.
2876         assert(!DisequalToDisequalSet.isEmpty());
2877         ClassSet NewSet = ClassSetFactory.remove(DisequalToDisequalSet, Class);
2878 
2879         // No need in keeping an empty set.
2880         if (NewSet.isEmpty()) {
2881           Disequalities =
2882               DisequalityFactory.remove(Disequalities, DisequalClass);
2883         } else {
2884           Disequalities =
2885               DisequalityFactory.add(Disequalities, DisequalClass, NewSet);
2886         }
2887       }
2888       // Remove the data for the class
2889       Disequalities = DisequalityFactory.remove(Disequalities, Class);
2890       DisequalitiesChanged = true;
2891     }
2892   };
2893 
2894   // 1. Let's see if dead symbols are trivial and have associated constraints.
2895   for (std::pair<EquivalenceClass, RangeSet> ClassConstraintPair :
2896        Constraints) {
2897     EquivalenceClass Class = ClassConstraintPair.first;
2898     if (Class.isTriviallyDead(State, SymReaper)) {
2899       // If this class is trivial, we can remove its constraints right away.
2900       removeDeadClass(Class);
2901     }
2902   }
2903 
2904   // 2. We don't need to track classes for dead symbols.
2905   for (std::pair<SymbolRef, EquivalenceClass> SymbolClassPair : Map) {
2906     SymbolRef Sym = SymbolClassPair.first;
2907 
2908     if (SymReaper.isDead(Sym)) {
2909       ClassMapChanged = true;
2910       NewMap = ClassFactory.remove(NewMap, Sym);
2911     }
2912   }
2913 
2914   // 3. Remove dead members from classes and remove dead non-trivial classes
2915   //    and their constraints.
2916   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair :
2917        ClassMembersMap) {
2918     EquivalenceClass Class = ClassMembersPair.first;
2919     SymbolSet LiveMembers = ClassMembersPair.second;
2920     bool MembersChanged = false;
2921 
2922     for (SymbolRef Member : ClassMembersPair.second) {
2923       if (SymReaper.isDead(Member)) {
2924         MembersChanged = true;
2925         LiveMembers = SetFactory.remove(LiveMembers, Member);
2926       }
2927     }
2928 
2929     // Check if the class changed.
2930     if (!MembersChanged)
2931       continue;
2932 
2933     MembersMapChanged = true;
2934 
2935     if (LiveMembers.isEmpty()) {
2936       // The class is dead now, we need to wipe it out of the members map...
2937       NewClassMembersMap = EMFactory.remove(NewClassMembersMap, Class);
2938 
2939       // ...and remove all of its constraints.
2940       removeDeadClass(Class);
2941     } else {
2942       // We need to change the members associated with the class.
2943       NewClassMembersMap =
2944           EMFactory.add(NewClassMembersMap, Class, LiveMembers);
2945     }
2946   }
2947 
2948   // 4. Update the state with new maps.
2949   //
2950   // Here we try to be humble and update a map only if it really changed.
2951   if (ClassMapChanged)
2952     State = State->set<ClassMap>(NewMap);
2953 
2954   if (MembersMapChanged)
2955     State = State->set<ClassMembers>(NewClassMembersMap);
2956 
2957   if (ConstraintMapChanged)
2958     State = State->set<ConstraintRange>(Constraints);
2959 
2960   if (DisequalitiesChanged)
2961     State = State->set<DisequalityMap>(Disequalities);
2962 
2963   assert(EquivalenceClass::isClassDataConsistent(State));
2964 
2965   return State;
2966 }
2967 
2968 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
2969                                           SymbolRef Sym) {
2970   return SymbolicRangeInferrer::inferRange(F, State, Sym);
2971 }
2972 
2973 ProgramStateRef RangeConstraintManager::setRange(ProgramStateRef State,
2974                                                  SymbolRef Sym,
2975                                                  RangeSet Range) {
2976   return ConstraintAssignor::assign(State, getSValBuilder(), F, Sym, Range);
2977 }
2978 
2979 //===------------------------------------------------------------------------===
2980 // assumeSymX methods: protected interface for RangeConstraintManager.
2981 //===------------------------------------------------------------------------===/
2982 
2983 // The syntax for ranges below is mathematical, using [x, y] for closed ranges
2984 // and (x, y) for open ranges. These ranges are modular, corresponding with
2985 // a common treatment of C integer overflow. This means that these methods
2986 // do not have to worry about overflow; RangeSet::Intersect can handle such a
2987 // "wraparound" range.
2988 // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
2989 // UINT_MAX, 0, 1, and 2.
2990 
2991 ProgramStateRef
2992 RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
2993                                     const llvm::APSInt &Int,
2994                                     const llvm::APSInt &Adjustment) {
2995   // Before we do any real work, see if the value can even show up.
2996   APSIntType AdjustmentType(Adjustment);
2997   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
2998     return St;
2999 
3000   llvm::APSInt Point = AdjustmentType.convert(Int) - Adjustment;
3001   RangeSet New = getRange(St, Sym);
3002   New = F.deletePoint(New, Point);
3003 
3004   return setRange(St, Sym, New);
3005 }
3006 
3007 ProgramStateRef
3008 RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
3009                                     const llvm::APSInt &Int,
3010                                     const llvm::APSInt &Adjustment) {
3011   // Before we do any real work, see if the value can even show up.
3012   APSIntType AdjustmentType(Adjustment);
3013   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
3014     return nullptr;
3015 
3016   // [Int-Adjustment, Int-Adjustment]
3017   llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
3018   RangeSet New = getRange(St, Sym);
3019   New = F.intersect(New, AdjInt);
3020 
3021   return setRange(St, Sym, New);
3022 }
3023 
3024 RangeSet RangeConstraintManager::getSymLTRange(ProgramStateRef St,
3025                                                SymbolRef Sym,
3026                                                const llvm::APSInt &Int,
3027                                                const llvm::APSInt &Adjustment) {
3028   // Before we do any real work, see if the value can even show up.
3029   APSIntType AdjustmentType(Adjustment);
3030   switch (AdjustmentType.testInRange(Int, true)) {
3031   case APSIntType::RTR_Below:
3032     return F.getEmptySet();
3033   case APSIntType::RTR_Within:
3034     break;
3035   case APSIntType::RTR_Above:
3036     return getRange(St, Sym);
3037   }
3038 
3039   // Special case for Int == Min. This is always false.
3040   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3041   llvm::APSInt Min = AdjustmentType.getMinValue();
3042   if (ComparisonVal == Min)
3043     return F.getEmptySet();
3044 
3045   llvm::APSInt Lower = Min - Adjustment;
3046   llvm::APSInt Upper = ComparisonVal - Adjustment;
3047   --Upper;
3048 
3049   RangeSet Result = getRange(St, Sym);
3050   return F.intersect(Result, Lower, Upper);
3051 }
3052 
3053 ProgramStateRef
3054 RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
3055                                     const llvm::APSInt &Int,
3056                                     const llvm::APSInt &Adjustment) {
3057   RangeSet New = getSymLTRange(St, Sym, Int, Adjustment);
3058   return setRange(St, Sym, New);
3059 }
3060 
3061 RangeSet RangeConstraintManager::getSymGTRange(ProgramStateRef St,
3062                                                SymbolRef Sym,
3063                                                const llvm::APSInt &Int,
3064                                                const llvm::APSInt &Adjustment) {
3065   // Before we do any real work, see if the value can even show up.
3066   APSIntType AdjustmentType(Adjustment);
3067   switch (AdjustmentType.testInRange(Int, true)) {
3068   case APSIntType::RTR_Below:
3069     return getRange(St, Sym);
3070   case APSIntType::RTR_Within:
3071     break;
3072   case APSIntType::RTR_Above:
3073     return F.getEmptySet();
3074   }
3075 
3076   // Special case for Int == Max. This is always false.
3077   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3078   llvm::APSInt Max = AdjustmentType.getMaxValue();
3079   if (ComparisonVal == Max)
3080     return F.getEmptySet();
3081 
3082   llvm::APSInt Lower = ComparisonVal - Adjustment;
3083   llvm::APSInt Upper = Max - Adjustment;
3084   ++Lower;
3085 
3086   RangeSet SymRange = getRange(St, Sym);
3087   return F.intersect(SymRange, Lower, Upper);
3088 }
3089 
3090 ProgramStateRef
3091 RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
3092                                     const llvm::APSInt &Int,
3093                                     const llvm::APSInt &Adjustment) {
3094   RangeSet New = getSymGTRange(St, Sym, Int, Adjustment);
3095   return setRange(St, Sym, New);
3096 }
3097 
3098 RangeSet RangeConstraintManager::getSymGERange(ProgramStateRef St,
3099                                                SymbolRef Sym,
3100                                                const llvm::APSInt &Int,
3101                                                const llvm::APSInt &Adjustment) {
3102   // Before we do any real work, see if the value can even show up.
3103   APSIntType AdjustmentType(Adjustment);
3104   switch (AdjustmentType.testInRange(Int, true)) {
3105   case APSIntType::RTR_Below:
3106     return getRange(St, Sym);
3107   case APSIntType::RTR_Within:
3108     break;
3109   case APSIntType::RTR_Above:
3110     return F.getEmptySet();
3111   }
3112 
3113   // Special case for Int == Min. This is always feasible.
3114   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3115   llvm::APSInt Min = AdjustmentType.getMinValue();
3116   if (ComparisonVal == Min)
3117     return getRange(St, Sym);
3118 
3119   llvm::APSInt Max = AdjustmentType.getMaxValue();
3120   llvm::APSInt Lower = ComparisonVal - Adjustment;
3121   llvm::APSInt Upper = Max - Adjustment;
3122 
3123   RangeSet SymRange = getRange(St, Sym);
3124   return F.intersect(SymRange, Lower, Upper);
3125 }
3126 
3127 ProgramStateRef
3128 RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
3129                                     const llvm::APSInt &Int,
3130                                     const llvm::APSInt &Adjustment) {
3131   RangeSet New = getSymGERange(St, Sym, Int, Adjustment);
3132   return setRange(St, Sym, New);
3133 }
3134 
3135 RangeSet
3136 RangeConstraintManager::getSymLERange(llvm::function_ref<RangeSet()> RS,
3137                                       const llvm::APSInt &Int,
3138                                       const llvm::APSInt &Adjustment) {
3139   // Before we do any real work, see if the value can even show up.
3140   APSIntType AdjustmentType(Adjustment);
3141   switch (AdjustmentType.testInRange(Int, true)) {
3142   case APSIntType::RTR_Below:
3143     return F.getEmptySet();
3144   case APSIntType::RTR_Within:
3145     break;
3146   case APSIntType::RTR_Above:
3147     return RS();
3148   }
3149 
3150   // Special case for Int == Max. This is always feasible.
3151   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3152   llvm::APSInt Max = AdjustmentType.getMaxValue();
3153   if (ComparisonVal == Max)
3154     return RS();
3155 
3156   llvm::APSInt Min = AdjustmentType.getMinValue();
3157   llvm::APSInt Lower = Min - Adjustment;
3158   llvm::APSInt Upper = ComparisonVal - Adjustment;
3159 
3160   RangeSet Default = RS();
3161   return F.intersect(Default, Lower, Upper);
3162 }
3163 
3164 RangeSet RangeConstraintManager::getSymLERange(ProgramStateRef St,
3165                                                SymbolRef Sym,
3166                                                const llvm::APSInt &Int,
3167                                                const llvm::APSInt &Adjustment) {
3168   return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment);
3169 }
3170 
3171 ProgramStateRef
3172 RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
3173                                     const llvm::APSInt &Int,
3174                                     const llvm::APSInt &Adjustment) {
3175   RangeSet New = getSymLERange(St, Sym, Int, Adjustment);
3176   return setRange(St, Sym, New);
3177 }
3178 
3179 ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange(
3180     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
3181     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
3182   RangeSet New = getSymGERange(State, Sym, From, Adjustment);
3183   if (New.isEmpty())
3184     return nullptr;
3185   RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment);
3186   return setRange(State, Sym, Out);
3187 }
3188 
3189 ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange(
3190     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
3191     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
3192   RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment);
3193   RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment);
3194   RangeSet New(F.add(RangeLT, RangeGT));
3195   return setRange(State, Sym, New);
3196 }
3197 
3198 //===----------------------------------------------------------------------===//
3199 // Pretty-printing.
3200 //===----------------------------------------------------------------------===//
3201 
3202 void RangeConstraintManager::printJson(raw_ostream &Out, ProgramStateRef State,
3203                                        const char *NL, unsigned int Space,
3204                                        bool IsDot) const {
3205   printConstraints(Out, State, NL, Space, IsDot);
3206   printEquivalenceClasses(Out, State, NL, Space, IsDot);
3207   printDisequalities(Out, State, NL, Space, IsDot);
3208 }
3209 
3210 void RangeConstraintManager::printValue(raw_ostream &Out, ProgramStateRef State,
3211                                         SymbolRef Sym) {
3212   const RangeSet RS = getRange(State, Sym);
3213   Out << RS.getBitWidth() << (RS.isUnsigned() ? "u:" : "s:");
3214   RS.dump(Out);
3215 }
3216 
3217 static std::string toString(const SymbolRef &Sym) {
3218   std::string S;
3219   llvm::raw_string_ostream O(S);
3220   Sym->dumpToStream(O);
3221   return O.str();
3222 }
3223 
3224 void RangeConstraintManager::printConstraints(raw_ostream &Out,
3225                                               ProgramStateRef State,
3226                                               const char *NL,
3227                                               unsigned int Space,
3228                                               bool IsDot) const {
3229   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
3230 
3231   Indent(Out, Space, IsDot) << "\"constraints\": ";
3232   if (Constraints.isEmpty()) {
3233     Out << "null," << NL;
3234     return;
3235   }
3236 
3237   std::map<std::string, RangeSet> OrderedConstraints;
3238   for (std::pair<EquivalenceClass, RangeSet> P : Constraints) {
3239     SymbolSet ClassMembers = P.first.getClassMembers(State);
3240     for (const SymbolRef &ClassMember : ClassMembers) {
3241       bool insertion_took_place;
3242       std::tie(std::ignore, insertion_took_place) =
3243           OrderedConstraints.insert({toString(ClassMember), P.second});
3244       assert(insertion_took_place &&
3245              "two symbols should not have the same dump");
3246     }
3247   }
3248 
3249   ++Space;
3250   Out << '[' << NL;
3251   bool First = true;
3252   for (std::pair<std::string, RangeSet> P : OrderedConstraints) {
3253     if (First) {
3254       First = false;
3255     } else {
3256       Out << ',';
3257       Out << NL;
3258     }
3259     Indent(Out, Space, IsDot)
3260         << "{ \"symbol\": \"" << P.first << "\", \"range\": \"";
3261     P.second.dump(Out);
3262     Out << "\" }";
3263   }
3264   Out << NL;
3265 
3266   --Space;
3267   Indent(Out, Space, IsDot) << "]," << NL;
3268 }
3269 
3270 static std::string toString(ProgramStateRef State, EquivalenceClass Class) {
3271   SymbolSet ClassMembers = Class.getClassMembers(State);
3272   llvm::SmallVector<SymbolRef, 8> ClassMembersSorted(ClassMembers.begin(),
3273                                                      ClassMembers.end());
3274   llvm::sort(ClassMembersSorted,
3275              [](const SymbolRef &LHS, const SymbolRef &RHS) {
3276                return toString(LHS) < toString(RHS);
3277              });
3278 
3279   bool FirstMember = true;
3280 
3281   std::string Str;
3282   llvm::raw_string_ostream Out(Str);
3283   Out << "[ ";
3284   for (SymbolRef ClassMember : ClassMembersSorted) {
3285     if (FirstMember)
3286       FirstMember = false;
3287     else
3288       Out << ", ";
3289     Out << "\"" << ClassMember << "\"";
3290   }
3291   Out << " ]";
3292   return Out.str();
3293 }
3294 
3295 void RangeConstraintManager::printEquivalenceClasses(raw_ostream &Out,
3296                                                      ProgramStateRef State,
3297                                                      const char *NL,
3298                                                      unsigned int Space,
3299                                                      bool IsDot) const {
3300   ClassMembersTy Members = State->get<ClassMembers>();
3301 
3302   Indent(Out, Space, IsDot) << "\"equivalence_classes\": ";
3303   if (Members.isEmpty()) {
3304     Out << "null," << NL;
3305     return;
3306   }
3307 
3308   std::set<std::string> MembersStr;
3309   for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members)
3310     MembersStr.insert(toString(State, ClassToSymbolSet.first));
3311 
3312   ++Space;
3313   Out << '[' << NL;
3314   bool FirstClass = true;
3315   for (const std::string &Str : MembersStr) {
3316     if (FirstClass) {
3317       FirstClass = false;
3318     } else {
3319       Out << ',';
3320       Out << NL;
3321     }
3322     Indent(Out, Space, IsDot);
3323     Out << Str;
3324   }
3325   Out << NL;
3326 
3327   --Space;
3328   Indent(Out, Space, IsDot) << "]," << NL;
3329 }
3330 
3331 void RangeConstraintManager::printDisequalities(raw_ostream &Out,
3332                                                 ProgramStateRef State,
3333                                                 const char *NL,
3334                                                 unsigned int Space,
3335                                                 bool IsDot) const {
3336   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
3337 
3338   Indent(Out, Space, IsDot) << "\"disequality_info\": ";
3339   if (Disequalities.isEmpty()) {
3340     Out << "null," << NL;
3341     return;
3342   }
3343 
3344   // Transform the disequality info to an ordered map of
3345   // [string -> (ordered set of strings)]
3346   using EqClassesStrTy = std::set<std::string>;
3347   using DisequalityInfoStrTy = std::map<std::string, EqClassesStrTy>;
3348   DisequalityInfoStrTy DisequalityInfoStr;
3349   for (std::pair<EquivalenceClass, ClassSet> ClassToDisEqSet : Disequalities) {
3350     EquivalenceClass Class = ClassToDisEqSet.first;
3351     ClassSet DisequalClasses = ClassToDisEqSet.second;
3352     EqClassesStrTy MembersStr;
3353     for (EquivalenceClass DisEqClass : DisequalClasses)
3354       MembersStr.insert(toString(State, DisEqClass));
3355     DisequalityInfoStr.insert({toString(State, Class), MembersStr});
3356   }
3357 
3358   ++Space;
3359   Out << '[' << NL;
3360   bool FirstClass = true;
3361   for (std::pair<std::string, EqClassesStrTy> ClassToDisEqSet :
3362        DisequalityInfoStr) {
3363     const std::string &Class = ClassToDisEqSet.first;
3364     if (FirstClass) {
3365       FirstClass = false;
3366     } else {
3367       Out << ',';
3368       Out << NL;
3369     }
3370     Indent(Out, Space, IsDot) << "{" << NL;
3371     unsigned int DisEqSpace = Space + 1;
3372     Indent(Out, DisEqSpace, IsDot) << "\"class\": ";
3373     Out << Class;
3374     const EqClassesStrTy &DisequalClasses = ClassToDisEqSet.second;
3375     if (!DisequalClasses.empty()) {
3376       Out << "," << NL;
3377       Indent(Out, DisEqSpace, IsDot) << "\"disequal_to\": [" << NL;
3378       unsigned int DisEqClassSpace = DisEqSpace + 1;
3379       Indent(Out, DisEqClassSpace, IsDot);
3380       bool FirstDisEqClass = true;
3381       for (const std::string &DisEqClass : DisequalClasses) {
3382         if (FirstDisEqClass) {
3383           FirstDisEqClass = false;
3384         } else {
3385           Out << ',' << NL;
3386           Indent(Out, DisEqClassSpace, IsDot);
3387         }
3388         Out << DisEqClass;
3389       }
3390       Out << "]" << NL;
3391     }
3392     Indent(Out, Space, IsDot) << "}";
3393   }
3394   Out << NL;
3395 
3396   --Space;
3397   Indent(Out, Space, IsDot) << "]," << NL;
3398 }
3399