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