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