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 Original, Range Element) {
114   ContainerType Result;
115   Result.reserve(Original.size() + 1);
116 
117   const_iterator Lower = llvm::lower_bound(Original, Element);
118   Result.insert(Result.end(), Original.begin(), Lower);
119   Result.push_back(Element);
120   Result.insert(Result.end(), Lower, Original.end());
121 
122   return makePersistent(std::move(Result));
123 }
124 
125 RangeSet RangeSet::Factory::add(RangeSet Original, const llvm::APSInt &Point) {
126   return add(Original, Range(Point));
127 }
128 
129 RangeSet RangeSet::Factory::getRangeSet(Range From) {
130   ContainerType Result;
131   Result.push_back(From);
132   return makePersistent(std::move(Result));
133 }
134 
135 RangeSet RangeSet::Factory::makePersistent(ContainerType &&From) {
136   llvm::FoldingSetNodeID ID;
137   void *InsertPos;
138 
139   From.Profile(ID);
140   ContainerType *Result = Cache.FindNodeOrInsertPos(ID, InsertPos);
141 
142   if (!Result) {
143     // It is cheaper to fully construct the resulting range on stack
144     // and move it to the freshly allocated buffer if we don't have
145     // a set like this already.
146     Result = construct(std::move(From));
147     Cache.InsertNode(Result, InsertPos);
148   }
149 
150   return Result;
151 }
152 
153 RangeSet::ContainerType *RangeSet::Factory::construct(ContainerType &&From) {
154   void *Buffer = Arena.Allocate();
155   return new (Buffer) ContainerType(std::move(From));
156 }
157 
158 RangeSet RangeSet::Factory::add(RangeSet LHS, RangeSet RHS) {
159   ContainerType Result;
160   std::merge(LHS.begin(), LHS.end(), RHS.begin(), RHS.end(),
161              std::back_inserter(Result));
162   return makePersistent(std::move(Result));
163 }
164 
165 const llvm::APSInt &RangeSet::getMinValue() const {
166   assert(!isEmpty());
167   return begin()->From();
168 }
169 
170 const llvm::APSInt &RangeSet::getMaxValue() const {
171   assert(!isEmpty());
172   return std::prev(end())->To();
173 }
174 
175 bool RangeSet::containsImpl(llvm::APSInt &Point) const {
176   if (isEmpty() || !pin(Point))
177     return false;
178 
179   Range Dummy(Point);
180   const_iterator It = llvm::upper_bound(*this, Dummy);
181   if (It == begin())
182     return false;
183 
184   return std::prev(It)->Includes(Point);
185 }
186 
187 bool RangeSet::pin(llvm::APSInt &Point) const {
188   APSIntType Type(getMinValue());
189   if (Type.testInRange(Point, true) != APSIntType::RTR_Within)
190     return false;
191 
192   Type.apply(Point);
193   return true;
194 }
195 
196 bool RangeSet::pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
197   // This function has nine cases, the cartesian product of range-testing
198   // both the upper and lower bounds against the symbol's type.
199   // Each case requires a different pinning operation.
200   // The function returns false if the described range is entirely outside
201   // the range of values for the associated symbol.
202   APSIntType Type(getMinValue());
203   APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower, true);
204   APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper, true);
205 
206   switch (LowerTest) {
207   case APSIntType::RTR_Below:
208     switch (UpperTest) {
209     case APSIntType::RTR_Below:
210       // The entire range is outside the symbol's set of possible values.
211       // If this is a conventionally-ordered range, the state is infeasible.
212       if (Lower <= Upper)
213         return false;
214 
215       // However, if the range wraps around, it spans all possible values.
216       Lower = Type.getMinValue();
217       Upper = Type.getMaxValue();
218       break;
219     case APSIntType::RTR_Within:
220       // The range starts below what's possible but ends within it. Pin.
221       Lower = Type.getMinValue();
222       Type.apply(Upper);
223       break;
224     case APSIntType::RTR_Above:
225       // The range spans all possible values for the symbol. Pin.
226       Lower = Type.getMinValue();
227       Upper = Type.getMaxValue();
228       break;
229     }
230     break;
231   case APSIntType::RTR_Within:
232     switch (UpperTest) {
233     case APSIntType::RTR_Below:
234       // The range wraps around, but all lower values are not possible.
235       Type.apply(Lower);
236       Upper = Type.getMaxValue();
237       break;
238     case APSIntType::RTR_Within:
239       // The range may or may not wrap around, but both limits are valid.
240       Type.apply(Lower);
241       Type.apply(Upper);
242       break;
243     case APSIntType::RTR_Above:
244       // The range starts within what's possible but ends above it. Pin.
245       Type.apply(Lower);
246       Upper = Type.getMaxValue();
247       break;
248     }
249     break;
250   case APSIntType::RTR_Above:
251     switch (UpperTest) {
252     case APSIntType::RTR_Below:
253       // The range wraps but is outside the symbol's set of possible values.
254       return false;
255     case APSIntType::RTR_Within:
256       // The range starts above what's possible but ends within it (wrap).
257       Lower = Type.getMinValue();
258       Type.apply(Upper);
259       break;
260     case APSIntType::RTR_Above:
261       // The entire range is outside the symbol's set of possible values.
262       // If this is a conventionally-ordered range, the state is infeasible.
263       if (Lower <= Upper)
264         return false;
265 
266       // However, if the range wraps around, it spans all possible values.
267       Lower = Type.getMinValue();
268       Upper = Type.getMaxValue();
269       break;
270     }
271     break;
272   }
273 
274   return true;
275 }
276 
277 RangeSet RangeSet::Factory::intersect(RangeSet What, llvm::APSInt Lower,
278                                       llvm::APSInt Upper) {
279   if (What.isEmpty() || !What.pin(Lower, Upper))
280     return getEmptySet();
281 
282   ContainerType DummyContainer;
283 
284   if (Lower <= Upper) {
285     // [Lower, Upper] is a regular range.
286     //
287     // Shortcut: check that there is even a possibility of the intersection
288     //           by checking the two following situations:
289     //
290     //               <---[  What  ]---[------]------>
291     //                              Lower  Upper
292     //                            -or-
293     //               <----[------]----[  What  ]---->
294     //                  Lower  Upper
295     if (What.getMaxValue() < Lower || Upper < What.getMinValue())
296       return getEmptySet();
297 
298     DummyContainer.push_back(
299         Range(ValueFactory.getValue(Lower), ValueFactory.getValue(Upper)));
300   } else {
301     // [Lower, Upper] is an inverted range, i.e. [MIN, Upper] U [Lower, MAX]
302     //
303     // Shortcut: check that there is even a possibility of the intersection
304     //           by checking the following situation:
305     //
306     //               <------]---[  What  ]---[------>
307     //                    Upper             Lower
308     if (What.getMaxValue() < Lower && Upper < What.getMinValue())
309       return getEmptySet();
310 
311     DummyContainer.push_back(
312         Range(ValueFactory.getMinValue(Upper), ValueFactory.getValue(Upper)));
313     DummyContainer.push_back(
314         Range(ValueFactory.getValue(Lower), ValueFactory.getMaxValue(Lower)));
315   }
316 
317   return intersect(*What.Impl, DummyContainer);
318 }
319 
320 RangeSet RangeSet::Factory::intersect(const RangeSet::ContainerType &LHS,
321                                       const RangeSet::ContainerType &RHS) {
322   ContainerType Result;
323   Result.reserve(std::max(LHS.size(), RHS.size()));
324 
325   const_iterator First = LHS.begin(), Second = RHS.begin(),
326                  FirstEnd = LHS.end(), SecondEnd = RHS.end();
327 
328   const auto SwapIterators = [&First, &FirstEnd, &Second, &SecondEnd]() {
329     std::swap(First, Second);
330     std::swap(FirstEnd, SecondEnd);
331   };
332 
333   // If we ran out of ranges in one set, but not in the other,
334   // it means that those elements are definitely not in the
335   // intersection.
336   while (First != FirstEnd && Second != SecondEnd) {
337     // We want to keep the following invariant at all times:
338     //
339     //    ----[ First ---------------------->
340     //    --------[ Second ----------------->
341     if (Second->From() < First->From())
342       SwapIterators();
343 
344     // Loop where the invariant holds:
345     do {
346       // Check for the following situation:
347       //
348       //    ----[ First ]--------------------->
349       //    ---------------[ Second ]--------->
350       //
351       // which means that...
352       if (Second->From() > First->To()) {
353         // ...First is not in the intersection.
354         //
355         // We should move on to the next range after First and break out of the
356         // loop because the invariant might not be true.
357         ++First;
358         break;
359       }
360 
361       // We have a guaranteed intersection at this point!
362       // And this is the current situation:
363       //
364       //    ----[   First   ]----------------->
365       //    -------[ Second ------------------>
366       //
367       // Additionally, it definitely starts with Second->From().
368       const llvm::APSInt &IntersectionStart = Second->From();
369 
370       // It is important to know which of the two ranges' ends
371       // is greater.  That "longer" range might have some other
372       // intersections, while the "shorter" range might not.
373       if (Second->To() > First->To()) {
374         // Here we make a decision to keep First as the "longer"
375         // range.
376         SwapIterators();
377       }
378 
379       // At this point, we have the following situation:
380       //
381       //    ---- First      ]-------------------->
382       //    ---- Second ]--[  Second+1 ---------->
383       //
384       // We don't know the relationship between First->From and
385       // Second->From and we don't know whether Second+1 intersects
386       // with First.
387       //
388       // However, we know that [IntersectionStart, Second->To] is
389       // a part of the intersection...
390       Result.push_back(Range(IntersectionStart, Second->To()));
391       ++Second;
392       // ...and that the invariant will hold for a valid Second+1
393       // because First->From <= Second->To < (Second+1)->From.
394     } while (Second != SecondEnd);
395   }
396 
397   if (Result.empty())
398     return getEmptySet();
399 
400   return makePersistent(std::move(Result));
401 }
402 
403 RangeSet RangeSet::Factory::intersect(RangeSet LHS, RangeSet RHS) {
404   // Shortcut: let's see if the intersection is even possible.
405   if (LHS.isEmpty() || RHS.isEmpty() || LHS.getMaxValue() < RHS.getMinValue() ||
406       RHS.getMaxValue() < LHS.getMinValue())
407     return getEmptySet();
408 
409   return intersect(*LHS.Impl, *RHS.Impl);
410 }
411 
412 RangeSet RangeSet::Factory::intersect(RangeSet LHS, llvm::APSInt Point) {
413   if (LHS.containsImpl(Point))
414     return getRangeSet(ValueFactory.getValue(Point));
415 
416   return getEmptySet();
417 }
418 
419 RangeSet RangeSet::Factory::negate(RangeSet What) {
420   if (What.isEmpty())
421     return getEmptySet();
422 
423   const llvm::APSInt SampleValue = What.getMinValue();
424   const llvm::APSInt &MIN = ValueFactory.getMinValue(SampleValue);
425   const llvm::APSInt &MAX = ValueFactory.getMaxValue(SampleValue);
426 
427   ContainerType Result;
428   Result.reserve(What.size() + (SampleValue == MIN));
429 
430   // Handle a special case for MIN value.
431   const_iterator It = What.begin();
432   const_iterator End = What.end();
433 
434   const llvm::APSInt &From = It->From();
435   const llvm::APSInt &To = It->To();
436 
437   if (From == MIN) {
438     // If the range [From, To] is [MIN, MAX], then result is also [MIN, MAX].
439     if (To == MAX) {
440       return What;
441     }
442 
443     const_iterator Last = std::prev(End);
444 
445     // Try to find and unite the following ranges:
446     // [MIN, MIN] & [MIN + 1, N] => [MIN, N].
447     if (Last->To() == MAX) {
448       // It means that in the original range we have ranges
449       //   [MIN, A], ... , [B, MAX]
450       // And the result should be [MIN, -B], ..., [-A, MAX]
451       Result.emplace_back(MIN, ValueFactory.getValue(-Last->From()));
452       // We already negated Last, so we can skip it.
453       End = Last;
454     } else {
455       // Add a separate range for the lowest value.
456       Result.emplace_back(MIN, MIN);
457     }
458 
459     // Skip adding the second range in case when [From, To] are [MIN, MIN].
460     if (To != MIN) {
461       Result.emplace_back(ValueFactory.getValue(-To), MAX);
462     }
463 
464     // Skip the first range in the loop.
465     ++It;
466   }
467 
468   // Negate all other ranges.
469   for (; It != End; ++It) {
470     // Negate int values.
471     const llvm::APSInt &NewFrom = ValueFactory.getValue(-It->To());
472     const llvm::APSInt &NewTo = ValueFactory.getValue(-It->From());
473 
474     // Add a negated range.
475     Result.emplace_back(NewFrom, NewTo);
476   }
477 
478   llvm::sort(Result);
479   return makePersistent(std::move(Result));
480 }
481 
482 RangeSet RangeSet::Factory::deletePoint(RangeSet From,
483                                         const llvm::APSInt &Point) {
484   if (!From.contains(Point))
485     return From;
486 
487   llvm::APSInt Upper = Point;
488   llvm::APSInt Lower = Point;
489 
490   ++Upper;
491   --Lower;
492 
493   // Notice that the lower bound is greater than the upper bound.
494   return intersect(From, Upper, Lower);
495 }
496 
497 void Range::dump(raw_ostream &OS) const {
498   OS << '[' << toString(From(), 10) << ", " << toString(To(), 10) << ']';
499 }
500 
501 void RangeSet::dump(raw_ostream &OS) const {
502   OS << "{ ";
503   llvm::interleaveComma(*this, OS, [&OS](const Range &R) { R.dump(OS); });
504   OS << " }";
505 }
506 
507 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet, SymbolRef)
508 
509 namespace {
510 class EquivalenceClass;
511 } // end anonymous namespace
512 
513 REGISTER_MAP_WITH_PROGRAMSTATE(ClassMap, SymbolRef, EquivalenceClass)
514 REGISTER_MAP_WITH_PROGRAMSTATE(ClassMembers, EquivalenceClass, SymbolSet)
515 REGISTER_MAP_WITH_PROGRAMSTATE(ConstraintRange, EquivalenceClass, RangeSet)
516 
517 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ClassSet, EquivalenceClass)
518 REGISTER_MAP_WITH_PROGRAMSTATE(DisequalityMap, EquivalenceClass, ClassSet)
519 
520 namespace {
521 /// This class encapsulates a set of symbols equal to each other.
522 ///
523 /// The main idea of the approach requiring such classes is in narrowing
524 /// and sharing constraints between symbols within the class.  Also we can
525 /// conclude that there is no practical need in storing constraints for
526 /// every member of the class separately.
527 ///
528 /// Main terminology:
529 ///
530 ///   * "Equivalence class" is an object of this class, which can be efficiently
531 ///     compared to other classes.  It represents the whole class without
532 ///     storing the actual in it.  The members of the class however can be
533 ///     retrieved from the state.
534 ///
535 ///   * "Class members" are the symbols corresponding to the class.  This means
536 ///     that A == B for every member symbols A and B from the class.  Members of
537 ///     each class are stored in the state.
538 ///
539 ///   * "Trivial class" is a class that has and ever had only one same symbol.
540 ///
541 ///   * "Merge operation" merges two classes into one.  It is the main operation
542 ///     to produce non-trivial classes.
543 ///     If, at some point, we can assume that two symbols from two distinct
544 ///     classes are equal, we can merge these classes.
545 class EquivalenceClass : public llvm::FoldingSetNode {
546 public:
547   /// Find equivalence class for the given symbol in the given state.
548   LLVM_NODISCARD static inline EquivalenceClass find(ProgramStateRef State,
549                                                      SymbolRef Sym);
550 
551   /// Merge classes for the given symbols and return a new state.
552   LLVM_NODISCARD static inline ProgramStateRef merge(RangeSet::Factory &F,
553                                                      ProgramStateRef State,
554                                                      SymbolRef First,
555                                                      SymbolRef Second);
556   // Merge this class with the given class and return a new state.
557   LLVM_NODISCARD inline ProgramStateRef
558   merge(RangeSet::Factory &F, ProgramStateRef State, EquivalenceClass Other);
559 
560   /// Return a set of class members for the given state.
561   LLVM_NODISCARD inline SymbolSet getClassMembers(ProgramStateRef State) const;
562   /// Return true if the current class is trivial in the given state.
563   LLVM_NODISCARD inline bool isTrivial(ProgramStateRef State) const;
564   /// Return true if the current class is trivial and its only member is dead.
565   LLVM_NODISCARD inline bool isTriviallyDead(ProgramStateRef State,
566                                              SymbolReaper &Reaper) const;
567 
568   LLVM_NODISCARD static inline ProgramStateRef
569   markDisequal(RangeSet::Factory &F, ProgramStateRef State, SymbolRef First,
570                SymbolRef Second);
571   LLVM_NODISCARD static inline ProgramStateRef
572   markDisequal(RangeSet::Factory &F, ProgramStateRef State,
573                EquivalenceClass First, EquivalenceClass Second);
574   LLVM_NODISCARD inline ProgramStateRef
575   markDisequal(RangeSet::Factory &F, ProgramStateRef State,
576                EquivalenceClass Other) const;
577   LLVM_NODISCARD static inline ClassSet
578   getDisequalClasses(ProgramStateRef State, SymbolRef Sym);
579   LLVM_NODISCARD inline ClassSet
580   getDisequalClasses(ProgramStateRef State) const;
581   LLVM_NODISCARD inline ClassSet
582   getDisequalClasses(DisequalityMapTy Map, ClassSet::Factory &Factory) const;
583 
584   LLVM_NODISCARD static inline Optional<bool> areEqual(ProgramStateRef State,
585                                                        EquivalenceClass First,
586                                                        EquivalenceClass Second);
587   LLVM_NODISCARD static inline Optional<bool>
588   areEqual(ProgramStateRef State, SymbolRef First, SymbolRef Second);
589 
590   /// Iterate over all symbols and try to simplify them.
591   LLVM_NODISCARD ProgramStateRef simplify(SValBuilder &SVB,
592                                           RangeSet::Factory &F,
593                                           ProgramStateRef State);
594 
595   /// Check equivalence data for consistency.
596   LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED static bool
597   isClassDataConsistent(ProgramStateRef State);
598 
599   LLVM_NODISCARD QualType getType() const {
600     return getRepresentativeSymbol()->getType();
601   }
602 
603   EquivalenceClass() = delete;
604   EquivalenceClass(const EquivalenceClass &) = default;
605   EquivalenceClass &operator=(const EquivalenceClass &) = delete;
606   EquivalenceClass(EquivalenceClass &&) = default;
607   EquivalenceClass &operator=(EquivalenceClass &&) = delete;
608 
609   bool operator==(const EquivalenceClass &Other) const {
610     return ID == Other.ID;
611   }
612   bool operator<(const EquivalenceClass &Other) const { return ID < Other.ID; }
613   bool operator!=(const EquivalenceClass &Other) const {
614     return !operator==(Other);
615   }
616 
617   static void Profile(llvm::FoldingSetNodeID &ID, uintptr_t CID) {
618     ID.AddInteger(CID);
619   }
620 
621   void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, this->ID); }
622 
623 private:
624   /* implicit */ EquivalenceClass(SymbolRef Sym)
625       : ID(reinterpret_cast<uintptr_t>(Sym)) {}
626 
627   /// This function is intended to be used ONLY within the class.
628   /// The fact that ID is a pointer to a symbol is an implementation detail
629   /// and should stay that way.
630   /// In the current implementation, we use it to retrieve the only member
631   /// of the trivial class.
632   SymbolRef getRepresentativeSymbol() const {
633     return reinterpret_cast<SymbolRef>(ID);
634   }
635   static inline SymbolSet::Factory &getMembersFactory(ProgramStateRef State);
636 
637   inline ProgramStateRef mergeImpl(RangeSet::Factory &F, ProgramStateRef State,
638                                    SymbolSet Members, EquivalenceClass Other,
639                                    SymbolSet OtherMembers);
640   static inline bool
641   addToDisequalityInfo(DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
642                        RangeSet::Factory &F, ProgramStateRef State,
643                        EquivalenceClass First, EquivalenceClass Second);
644 
645   /// This is a unique identifier of the class.
646   uintptr_t ID;
647 };
648 
649 //===----------------------------------------------------------------------===//
650 //                             Constraint functions
651 //===----------------------------------------------------------------------===//
652 
653 LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED bool
654 areFeasible(ConstraintRangeTy Constraints) {
655   return llvm::none_of(
656       Constraints,
657       [](const std::pair<EquivalenceClass, RangeSet> &ClassConstraint) {
658         return ClassConstraint.second.isEmpty();
659       });
660 }
661 
662 LLVM_NODISCARD inline const RangeSet *getConstraint(ProgramStateRef State,
663                                                     EquivalenceClass Class) {
664   return State->get<ConstraintRange>(Class);
665 }
666 
667 LLVM_NODISCARD inline const RangeSet *getConstraint(ProgramStateRef State,
668                                                     SymbolRef Sym) {
669   return getConstraint(State, EquivalenceClass::find(State, Sym));
670 }
671 
672 //===----------------------------------------------------------------------===//
673 //                       Equality/diseqiality abstraction
674 //===----------------------------------------------------------------------===//
675 
676 /// A small helper structure representing symbolic equality.
677 ///
678 /// Equality check can have different forms (like a == b or a - b) and this
679 /// class encapsulates those away if the only thing the user wants to check -
680 /// whether it's equality/diseqiality or not and have an easy access to the
681 /// compared symbols.
682 struct EqualityInfo {
683 public:
684   SymbolRef Left, Right;
685   // true for equality and false for disequality.
686   bool IsEquality = true;
687 
688   void invert() { IsEquality = !IsEquality; }
689   /// Extract equality information from the given symbol and the constants.
690   ///
691   /// This function assumes the following expression Sym + Adjustment != Int.
692   /// It is a default because the most widespread case of the equality check
693   /// is (A == B) + 0 != 0.
694   static Optional<EqualityInfo> extract(SymbolRef Sym, const llvm::APSInt &Int,
695                                         const llvm::APSInt &Adjustment) {
696     // As of now, the only equality form supported is Sym + 0 != 0.
697     if (!Int.isNullValue() || !Adjustment.isNullValue())
698       return llvm::None;
699 
700     return extract(Sym);
701   }
702   /// Extract equality information from the given symbol.
703   static Optional<EqualityInfo> extract(SymbolRef Sym) {
704     return EqualityExtractor().Visit(Sym);
705   }
706 
707 private:
708   class EqualityExtractor
709       : public SymExprVisitor<EqualityExtractor, Optional<EqualityInfo>> {
710   public:
711     Optional<EqualityInfo> VisitSymSymExpr(const SymSymExpr *Sym) const {
712       switch (Sym->getOpcode()) {
713       case BO_Sub:
714         // This case is: A - B != 0 -> disequality check.
715         return EqualityInfo{Sym->getLHS(), Sym->getRHS(), false};
716       case BO_EQ:
717         // This case is: A == B != 0 -> equality check.
718         return EqualityInfo{Sym->getLHS(), Sym->getRHS(), true};
719       case BO_NE:
720         // This case is: A != B != 0 -> diseqiality check.
721         return EqualityInfo{Sym->getLHS(), Sym->getRHS(), false};
722       default:
723         return llvm::None;
724       }
725     }
726   };
727 };
728 
729 //===----------------------------------------------------------------------===//
730 //                            Intersection functions
731 //===----------------------------------------------------------------------===//
732 
733 template <class SecondTy, class... RestTy>
734 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
735                                          SecondTy Second, RestTy... Tail);
736 
737 template <class... RangeTy> struct IntersectionTraits;
738 
739 template <class... TailTy> struct IntersectionTraits<RangeSet, TailTy...> {
740   // Found RangeSet, no need to check any further
741   using Type = RangeSet;
742 };
743 
744 template <> struct IntersectionTraits<> {
745   // We ran out of types, and we didn't find any RangeSet, so the result should
746   // be optional.
747   using Type = Optional<RangeSet>;
748 };
749 
750 template <class OptionalOrPointer, class... TailTy>
751 struct IntersectionTraits<OptionalOrPointer, TailTy...> {
752   // If current type is Optional or a raw pointer, we should keep looking.
753   using Type = typename IntersectionTraits<TailTy...>::Type;
754 };
755 
756 template <class EndTy>
757 LLVM_NODISCARD inline EndTy intersect(RangeSet::Factory &F, EndTy End) {
758   // If the list contains only RangeSet or Optional<RangeSet>, simply return
759   // that range set.
760   return End;
761 }
762 
763 LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED inline Optional<RangeSet>
764 intersect(RangeSet::Factory &F, const RangeSet *End) {
765   // This is an extraneous conversion from a raw pointer into Optional<RangeSet>
766   if (End) {
767     return *End;
768   }
769   return llvm::None;
770 }
771 
772 template <class... RestTy>
773 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
774                                          RangeSet Second, RestTy... Tail) {
775   // Here we call either the <RangeSet,RangeSet,...> or <RangeSet,...> version
776   // of the function and can be sure that the result is RangeSet.
777   return intersect(F, F.intersect(Head, Second), Tail...);
778 }
779 
780 template <class SecondTy, class... RestTy>
781 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
782                                          SecondTy Second, RestTy... Tail) {
783   if (Second) {
784     // Here we call the <RangeSet,RangeSet,...> version of the function...
785     return intersect(F, Head, *Second, Tail...);
786   }
787   // ...and here it is either <RangeSet,RangeSet,...> or <RangeSet,...>, which
788   // means that the result is definitely RangeSet.
789   return intersect(F, Head, Tail...);
790 }
791 
792 /// Main generic intersect function.
793 /// It intersects all of the given range sets.  If some of the given arguments
794 /// don't hold a range set (nullptr or llvm::None), the function will skip them.
795 ///
796 /// Available representations for the arguments are:
797 ///   * RangeSet
798 ///   * Optional<RangeSet>
799 ///   * RangeSet *
800 /// Pointer to a RangeSet is automatically assumed to be nullable and will get
801 /// checked as well as the optional version.  If this behaviour is undesired,
802 /// please dereference the pointer in the call.
803 ///
804 /// Return type depends on the arguments' types.  If we can be sure in compile
805 /// time that there will be a range set as a result, the returning type is
806 /// simply RangeSet, in other cases we have to back off to Optional<RangeSet>.
807 ///
808 /// Please, prefer optional range sets to raw pointers.  If the last argument is
809 /// a raw pointer and all previous arguments are None, it will cost one
810 /// additional check to convert RangeSet * into Optional<RangeSet>.
811 template <class HeadTy, class SecondTy, class... RestTy>
812 LLVM_NODISCARD inline
813     typename IntersectionTraits<HeadTy, SecondTy, RestTy...>::Type
814     intersect(RangeSet::Factory &F, HeadTy Head, SecondTy Second,
815               RestTy... Tail) {
816   if (Head) {
817     return intersect(F, *Head, Second, Tail...);
818   }
819   return intersect(F, Second, Tail...);
820 }
821 
822 //===----------------------------------------------------------------------===//
823 //                           Symbolic reasoning logic
824 //===----------------------------------------------------------------------===//
825 
826 /// A little component aggregating all of the reasoning we have about
827 /// the ranges of symbolic expressions.
828 ///
829 /// Even when we don't know the exact values of the operands, we still
830 /// can get a pretty good estimate of the result's range.
831 class SymbolicRangeInferrer
832     : public SymExprVisitor<SymbolicRangeInferrer, RangeSet> {
833 public:
834   template <class SourceType>
835   static RangeSet inferRange(RangeSet::Factory &F, ProgramStateRef State,
836                              SourceType Origin) {
837     SymbolicRangeInferrer Inferrer(F, State);
838     return Inferrer.infer(Origin);
839   }
840 
841   RangeSet VisitSymExpr(SymbolRef Sym) {
842     // If we got to this function, the actual type of the symbolic
843     // expression is not supported for advanced inference.
844     // In this case, we simply backoff to the default "let's simply
845     // infer the range from the expression's type".
846     return infer(Sym->getType());
847   }
848 
849   RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
850     return VisitBinaryOperator(Sym);
851   }
852 
853   RangeSet VisitIntSymExpr(const IntSymExpr *Sym) {
854     return VisitBinaryOperator(Sym);
855   }
856 
857   RangeSet VisitSymSymExpr(const SymSymExpr *Sym) {
858     return VisitBinaryOperator(Sym);
859   }
860 
861 private:
862   SymbolicRangeInferrer(RangeSet::Factory &F, ProgramStateRef S)
863       : ValueFactory(F.getValueFactory()), RangeFactory(F), State(S) {}
864 
865   /// Infer range information from the given integer constant.
866   ///
867   /// It's not a real "inference", but is here for operating with
868   /// sub-expressions in a more polymorphic manner.
869   RangeSet inferAs(const llvm::APSInt &Val, QualType) {
870     return {RangeFactory, Val};
871   }
872 
873   /// Infer range information from symbol in the context of the given type.
874   RangeSet inferAs(SymbolRef Sym, QualType DestType) {
875     QualType ActualType = Sym->getType();
876     // Check that we can reason about the symbol at all.
877     if (ActualType->isIntegralOrEnumerationType() ||
878         Loc::isLocType(ActualType)) {
879       return infer(Sym);
880     }
881     // Otherwise, let's simply infer from the destination type.
882     // We couldn't figure out nothing else about that expression.
883     return infer(DestType);
884   }
885 
886   RangeSet infer(SymbolRef Sym) {
887     if (Optional<RangeSet> ConstraintBasedRange = intersect(
888             RangeFactory, getConstraint(State, Sym),
889             // If Sym is a difference of symbols A - B, then maybe we have range
890             // set stored for B - A.
891             //
892             // If we have range set stored for both A - B and B - A then
893             // calculate the effective range set by intersecting the range set
894             // for A - B and the negated range set of B - A.
895             getRangeForNegatedSub(Sym), getRangeForEqualities(Sym))) {
896       return *ConstraintBasedRange;
897     }
898 
899     // If Sym is a comparison expression (except <=>),
900     // find any other comparisons with the same operands.
901     // See function description.
902     if (Optional<RangeSet> CmpRangeSet = getRangeForComparisonSymbol(Sym)) {
903       return *CmpRangeSet;
904     }
905 
906     return Visit(Sym);
907   }
908 
909   RangeSet infer(EquivalenceClass Class) {
910     if (const RangeSet *AssociatedConstraint = getConstraint(State, Class))
911       return *AssociatedConstraint;
912 
913     return infer(Class.getType());
914   }
915 
916   /// Infer range information solely from the type.
917   RangeSet infer(QualType T) {
918     // Lazily generate a new RangeSet representing all possible values for the
919     // given symbol type.
920     RangeSet Result(RangeFactory, ValueFactory.getMinValue(T),
921                     ValueFactory.getMaxValue(T));
922 
923     // References are known to be non-zero.
924     if (T->isReferenceType())
925       return assumeNonZero(Result, T);
926 
927     return Result;
928   }
929 
930   template <class BinarySymExprTy>
931   RangeSet VisitBinaryOperator(const BinarySymExprTy *Sym) {
932     // TODO #1: VisitBinaryOperator implementation might not make a good
933     // use of the inferred ranges.  In this case, we might be calculating
934     // everything for nothing.  This being said, we should introduce some
935     // sort of laziness mechanism here.
936     //
937     // TODO #2: We didn't go into the nested expressions before, so it
938     // might cause us spending much more time doing the inference.
939     // This can be a problem for deeply nested expressions that are
940     // involved in conditions and get tested continuously.  We definitely
941     // need to address this issue and introduce some sort of caching
942     // in here.
943     QualType ResultType = Sym->getType();
944     return VisitBinaryOperator(inferAs(Sym->getLHS(), ResultType),
945                                Sym->getOpcode(),
946                                inferAs(Sym->getRHS(), ResultType), ResultType);
947   }
948 
949   RangeSet VisitBinaryOperator(RangeSet LHS, BinaryOperator::Opcode Op,
950                                RangeSet RHS, QualType T) {
951     switch (Op) {
952     case BO_Or:
953       return VisitBinaryOperator<BO_Or>(LHS, RHS, T);
954     case BO_And:
955       return VisitBinaryOperator<BO_And>(LHS, RHS, T);
956     case BO_Rem:
957       return VisitBinaryOperator<BO_Rem>(LHS, RHS, T);
958     default:
959       return infer(T);
960     }
961   }
962 
963   //===----------------------------------------------------------------------===//
964   //                         Ranges and operators
965   //===----------------------------------------------------------------------===//
966 
967   /// Return a rough approximation of the given range set.
968   ///
969   /// For the range set:
970   ///   { [x_0, y_0], [x_1, y_1], ... , [x_N, y_N] }
971   /// it will return the range [x_0, y_N].
972   static Range fillGaps(RangeSet Origin) {
973     assert(!Origin.isEmpty());
974     return {Origin.getMinValue(), Origin.getMaxValue()};
975   }
976 
977   /// Try to convert given range into the given type.
978   ///
979   /// It will return llvm::None only when the trivial conversion is possible.
980   llvm::Optional<Range> convert(const Range &Origin, APSIntType To) {
981     if (To.testInRange(Origin.From(), false) != APSIntType::RTR_Within ||
982         To.testInRange(Origin.To(), false) != APSIntType::RTR_Within) {
983       return llvm::None;
984     }
985     return Range(ValueFactory.Convert(To, Origin.From()),
986                  ValueFactory.Convert(To, Origin.To()));
987   }
988 
989   template <BinaryOperator::Opcode Op>
990   RangeSet VisitBinaryOperator(RangeSet LHS, RangeSet RHS, QualType T) {
991     // We should propagate information about unfeasbility of one of the
992     // operands to the resulting range.
993     if (LHS.isEmpty() || RHS.isEmpty()) {
994       return RangeFactory.getEmptySet();
995     }
996 
997     Range CoarseLHS = fillGaps(LHS);
998     Range CoarseRHS = fillGaps(RHS);
999 
1000     APSIntType ResultType = ValueFactory.getAPSIntType(T);
1001 
1002     // We need to convert ranges to the resulting type, so we can compare values
1003     // and combine them in a meaningful (in terms of the given operation) way.
1004     auto ConvertedCoarseLHS = convert(CoarseLHS, ResultType);
1005     auto ConvertedCoarseRHS = convert(CoarseRHS, ResultType);
1006 
1007     // It is hard to reason about ranges when conversion changes
1008     // borders of the ranges.
1009     if (!ConvertedCoarseLHS || !ConvertedCoarseRHS) {
1010       return infer(T);
1011     }
1012 
1013     return VisitBinaryOperator<Op>(*ConvertedCoarseLHS, *ConvertedCoarseRHS, T);
1014   }
1015 
1016   template <BinaryOperator::Opcode Op>
1017   RangeSet VisitBinaryOperator(Range LHS, Range RHS, QualType T) {
1018     return infer(T);
1019   }
1020 
1021   /// Return a symmetrical range for the given range and type.
1022   ///
1023   /// If T is signed, return the smallest range [-x..x] that covers the original
1024   /// range, or [-min(T), max(T)] if the aforementioned symmetric range doesn't
1025   /// exist due to original range covering min(T)).
1026   ///
1027   /// If T is unsigned, return the smallest range [0..x] that covers the
1028   /// original range.
1029   Range getSymmetricalRange(Range Origin, QualType T) {
1030     APSIntType RangeType = ValueFactory.getAPSIntType(T);
1031 
1032     if (RangeType.isUnsigned()) {
1033       return Range(ValueFactory.getMinValue(RangeType), Origin.To());
1034     }
1035 
1036     if (Origin.From().isMinSignedValue()) {
1037       // If mini is a minimal signed value, absolute value of it is greater
1038       // than the maximal signed value.  In order to avoid these
1039       // complications, we simply return the whole range.
1040       return {ValueFactory.getMinValue(RangeType),
1041               ValueFactory.getMaxValue(RangeType)};
1042     }
1043 
1044     // At this point, we are sure that the type is signed and we can safely
1045     // use unary - operator.
1046     //
1047     // While calculating absolute maximum, we can use the following formula
1048     // because of these reasons:
1049     //   * If From >= 0 then To >= From and To >= -From.
1050     //     AbsMax == To == max(To, -From)
1051     //   * If To <= 0 then -From >= -To and -From >= From.
1052     //     AbsMax == -From == max(-From, To)
1053     //   * Otherwise, From <= 0, To >= 0, and
1054     //     AbsMax == max(abs(From), abs(To))
1055     llvm::APSInt AbsMax = std::max(-Origin.From(), Origin.To());
1056 
1057     // Intersection is guaranteed to be non-empty.
1058     return {ValueFactory.getValue(-AbsMax), ValueFactory.getValue(AbsMax)};
1059   }
1060 
1061   /// Return a range set subtracting zero from \p Domain.
1062   RangeSet assumeNonZero(RangeSet Domain, QualType T) {
1063     APSIntType IntType = ValueFactory.getAPSIntType(T);
1064     return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
1065   }
1066 
1067   // FIXME: Once SValBuilder supports unary minus, we should use SValBuilder to
1068   //        obtain the negated symbolic expression instead of constructing the
1069   //        symbol manually. This will allow us to support finding ranges of not
1070   //        only negated SymSymExpr-type expressions, but also of other, simpler
1071   //        expressions which we currently do not know how to negate.
1072   Optional<RangeSet> getRangeForNegatedSub(SymbolRef Sym) {
1073     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(Sym)) {
1074       if (SSE->getOpcode() == BO_Sub) {
1075         QualType T = Sym->getType();
1076 
1077         // Do not negate unsigned ranges
1078         if (!T->isUnsignedIntegerOrEnumerationType() &&
1079             !T->isSignedIntegerOrEnumerationType())
1080           return llvm::None;
1081 
1082         SymbolManager &SymMgr = State->getSymbolManager();
1083         SymbolRef NegatedSym =
1084             SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), T);
1085 
1086         if (const RangeSet *NegatedRange = getConstraint(State, NegatedSym)) {
1087           return RangeFactory.negate(*NegatedRange);
1088         }
1089       }
1090     }
1091     return llvm::None;
1092   }
1093 
1094   // Returns ranges only for binary comparison operators (except <=>)
1095   // when left and right operands are symbolic values.
1096   // Finds any other comparisons with the same operands.
1097   // Then do logical calculations and refuse impossible branches.
1098   // E.g. (x < y) and (x > y) at the same time are impossible.
1099   // E.g. (x >= y) and (x != y) at the same time makes (x > y) true only.
1100   // E.g. (x == y) and (y == x) are just reversed but the same.
1101   // It covers all possible combinations (see CmpOpTable description).
1102   // Note that `x` and `y` can also stand for subexpressions,
1103   // not only for actual symbols.
1104   Optional<RangeSet> getRangeForComparisonSymbol(SymbolRef Sym) {
1105     const auto *SSE = dyn_cast<SymSymExpr>(Sym);
1106     if (!SSE)
1107       return llvm::None;
1108 
1109     BinaryOperatorKind CurrentOP = SSE->getOpcode();
1110 
1111     // We currently do not support <=> (C++20).
1112     if (!BinaryOperator::isComparisonOp(CurrentOP) || (CurrentOP == BO_Cmp))
1113       return llvm::None;
1114 
1115     static const OperatorRelationsTable CmpOpTable{};
1116 
1117     const SymExpr *LHS = SSE->getLHS();
1118     const SymExpr *RHS = SSE->getRHS();
1119     QualType T = SSE->getType();
1120 
1121     SymbolManager &SymMgr = State->getSymbolManager();
1122 
1123     int UnknownStates = 0;
1124 
1125     // Loop goes through all of the columns exept the last one ('UnknownX2').
1126     // We treat `UnknownX2` column separately at the end of the loop body.
1127     for (size_t i = 0; i < CmpOpTable.getCmpOpCount(); ++i) {
1128 
1129       // Let's find an expression e.g. (x < y).
1130       BinaryOperatorKind QueriedOP = OperatorRelationsTable::getOpFromIndex(i);
1131       const SymSymExpr *SymSym = SymMgr.getSymSymExpr(LHS, QueriedOP, RHS, T);
1132       const RangeSet *QueriedRangeSet = getConstraint(State, SymSym);
1133 
1134       // If ranges were not previously found,
1135       // try to find a reversed expression (y > x).
1136       if (!QueriedRangeSet) {
1137         const BinaryOperatorKind ROP =
1138             BinaryOperator::reverseComparisonOp(QueriedOP);
1139         SymSym = SymMgr.getSymSymExpr(RHS, ROP, LHS, T);
1140         QueriedRangeSet = getConstraint(State, SymSym);
1141       }
1142 
1143       if (!QueriedRangeSet || QueriedRangeSet->isEmpty())
1144         continue;
1145 
1146       const llvm::APSInt *ConcreteValue = QueriedRangeSet->getConcreteValue();
1147       const bool isInFalseBranch =
1148           ConcreteValue ? (*ConcreteValue == 0) : false;
1149 
1150       // If it is a false branch, we shall be guided by opposite operator,
1151       // because the table is made assuming we are in the true branch.
1152       // E.g. when (x <= y) is false, then (x > y) is true.
1153       if (isInFalseBranch)
1154         QueriedOP = BinaryOperator::negateComparisonOp(QueriedOP);
1155 
1156       OperatorRelationsTable::TriStateKind BranchState =
1157           CmpOpTable.getCmpOpState(CurrentOP, QueriedOP);
1158 
1159       if (BranchState == OperatorRelationsTable::Unknown) {
1160         if (++UnknownStates == 2)
1161           // If we met both Unknown states.
1162           // if (x <= y)    // assume true
1163           //   if (x != y)  // assume true
1164           //     if (x < y) // would be also true
1165           // Get a state from `UnknownX2` column.
1166           BranchState = CmpOpTable.getCmpOpStateForUnknownX2(CurrentOP);
1167         else
1168           continue;
1169       }
1170 
1171       return (BranchState == OperatorRelationsTable::True) ? getTrueRange(T)
1172                                                            : getFalseRange(T);
1173     }
1174 
1175     return llvm::None;
1176   }
1177 
1178   Optional<RangeSet> getRangeForEqualities(SymbolRef Sym) {
1179     Optional<EqualityInfo> Equality = EqualityInfo::extract(Sym);
1180 
1181     if (!Equality)
1182       return llvm::None;
1183 
1184     if (Optional<bool> AreEqual = EquivalenceClass::areEqual(
1185             State, Equality->Left, Equality->Right)) {
1186       if (*AreEqual == Equality->IsEquality) {
1187         return getTrueRange(Sym->getType());
1188       }
1189       return getFalseRange(Sym->getType());
1190     }
1191 
1192     return llvm::None;
1193   }
1194 
1195   RangeSet getTrueRange(QualType T) {
1196     RangeSet TypeRange = infer(T);
1197     return assumeNonZero(TypeRange, T);
1198   }
1199 
1200   RangeSet getFalseRange(QualType T) {
1201     const llvm::APSInt &Zero = ValueFactory.getValue(0, T);
1202     return RangeSet(RangeFactory, Zero);
1203   }
1204 
1205   BasicValueFactory &ValueFactory;
1206   RangeSet::Factory &RangeFactory;
1207   ProgramStateRef State;
1208 };
1209 
1210 //===----------------------------------------------------------------------===//
1211 //               Range-based reasoning about symbolic operations
1212 //===----------------------------------------------------------------------===//
1213 
1214 template <>
1215 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Or>(Range LHS, Range RHS,
1216                                                            QualType T) {
1217   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1218   llvm::APSInt Zero = ResultType.getZeroValue();
1219 
1220   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1221   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1222 
1223   bool IsLHSNegative = LHS.To() < Zero;
1224   bool IsRHSNegative = RHS.To() < Zero;
1225 
1226   // Check if both ranges have the same sign.
1227   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1228       (IsLHSNegative && IsRHSNegative)) {
1229     // The result is definitely greater or equal than any of the operands.
1230     const llvm::APSInt &Min = std::max(LHS.From(), RHS.From());
1231 
1232     // We estimate maximal value for positives as the maximal value for the
1233     // given type.  For negatives, we estimate it with -1 (e.g. 0x11111111).
1234     //
1235     // TODO: We basically, limit the resulting range from below, but don't do
1236     //       anything with the upper bound.
1237     //
1238     //       For positive operands, it can be done as follows: for the upper
1239     //       bound of LHS and RHS we calculate the most significant bit set.
1240     //       Let's call it the N-th bit.  Then we can estimate the maximal
1241     //       number to be 2^(N+1)-1, i.e. the number with all the bits up to
1242     //       the N-th bit set.
1243     const llvm::APSInt &Max = IsLHSNegative
1244                                   ? ValueFactory.getValue(--Zero)
1245                                   : ValueFactory.getMaxValue(ResultType);
1246 
1247     return {RangeFactory, ValueFactory.getValue(Min), Max};
1248   }
1249 
1250   // Otherwise, let's check if at least one of the operands is negative.
1251   if (IsLHSNegative || IsRHSNegative) {
1252     // This means that the result is definitely negative as well.
1253     return {RangeFactory, ValueFactory.getMinValue(ResultType),
1254             ValueFactory.getValue(--Zero)};
1255   }
1256 
1257   RangeSet DefaultRange = infer(T);
1258 
1259   // It is pretty hard to reason about operands with different signs
1260   // (and especially with possibly different signs).  We simply check if it
1261   // can be zero.  In order to conclude that the result could not be zero,
1262   // at least one of the operands should be definitely not zero itself.
1263   if (!LHS.Includes(Zero) || !RHS.Includes(Zero)) {
1264     return assumeNonZero(DefaultRange, T);
1265   }
1266 
1267   // Nothing much else to do here.
1268   return DefaultRange;
1269 }
1270 
1271 template <>
1272 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_And>(Range LHS,
1273                                                             Range RHS,
1274                                                             QualType T) {
1275   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1276   llvm::APSInt Zero = ResultType.getZeroValue();
1277 
1278   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1279   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1280 
1281   bool IsLHSNegative = LHS.To() < Zero;
1282   bool IsRHSNegative = RHS.To() < Zero;
1283 
1284   // Check if both ranges have the same sign.
1285   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1286       (IsLHSNegative && IsRHSNegative)) {
1287     // The result is definitely less or equal than any of the operands.
1288     const llvm::APSInt &Max = std::min(LHS.To(), RHS.To());
1289 
1290     // We conservatively estimate lower bound to be the smallest positive
1291     // or negative value corresponding to the sign of the operands.
1292     const llvm::APSInt &Min = IsLHSNegative
1293                                   ? ValueFactory.getMinValue(ResultType)
1294                                   : ValueFactory.getValue(Zero);
1295 
1296     return {RangeFactory, Min, Max};
1297   }
1298 
1299   // Otherwise, let's check if at least one of the operands is positive.
1300   if (IsLHSPositiveOrZero || IsRHSPositiveOrZero) {
1301     // This makes result definitely positive.
1302     //
1303     // We can also reason about a maximal value by finding the maximal
1304     // value of the positive operand.
1305     const llvm::APSInt &Max = IsLHSPositiveOrZero ? LHS.To() : RHS.To();
1306 
1307     // The minimal value on the other hand is much harder to reason about.
1308     // The only thing we know for sure is that the result is positive.
1309     return {RangeFactory, ValueFactory.getValue(Zero),
1310             ValueFactory.getValue(Max)};
1311   }
1312 
1313   // Nothing much else to do here.
1314   return infer(T);
1315 }
1316 
1317 template <>
1318 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Rem>(Range LHS,
1319                                                             Range RHS,
1320                                                             QualType T) {
1321   llvm::APSInt Zero = ValueFactory.getAPSIntType(T).getZeroValue();
1322 
1323   Range ConservativeRange = getSymmetricalRange(RHS, T);
1324 
1325   llvm::APSInt Max = ConservativeRange.To();
1326   llvm::APSInt Min = ConservativeRange.From();
1327 
1328   if (Max == Zero) {
1329     // It's an undefined behaviour to divide by 0 and it seems like we know
1330     // for sure that RHS is 0.  Let's say that the resulting range is
1331     // simply infeasible for that matter.
1332     return RangeFactory.getEmptySet();
1333   }
1334 
1335   // At this point, our conservative range is closed.  The result, however,
1336   // couldn't be greater than the RHS' maximal absolute value.  Because of
1337   // this reason, we turn the range into open (or half-open in case of
1338   // unsigned integers).
1339   //
1340   // While we operate on integer values, an open interval (a, b) can be easily
1341   // represented by the closed interval [a + 1, b - 1].  And this is exactly
1342   // what we do next.
1343   //
1344   // If we are dealing with unsigned case, we shouldn't move the lower bound.
1345   if (Min.isSigned()) {
1346     ++Min;
1347   }
1348   --Max;
1349 
1350   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1351   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1352 
1353   // Remainder operator results with negative operands is implementation
1354   // defined.  Positive cases are much easier to reason about though.
1355   if (IsLHSPositiveOrZero && IsRHSPositiveOrZero) {
1356     // If maximal value of LHS is less than maximal value of RHS,
1357     // the result won't get greater than LHS.To().
1358     Max = std::min(LHS.To(), Max);
1359     // We want to check if it is a situation similar to the following:
1360     //
1361     // <------------|---[  LHS  ]--------[  RHS  ]----->
1362     //  -INF        0                              +INF
1363     //
1364     // In this situation, we can conclude that (LHS / RHS) == 0 and
1365     // (LHS % RHS) == LHS.
1366     Min = LHS.To() < RHS.From() ? LHS.From() : Zero;
1367   }
1368 
1369   // Nevertheless, the symmetrical range for RHS is a conservative estimate
1370   // for any sign of either LHS, or RHS.
1371   return {RangeFactory, ValueFactory.getValue(Min), ValueFactory.getValue(Max)};
1372 }
1373 
1374 //===----------------------------------------------------------------------===//
1375 //                  Constraint manager implementation details
1376 //===----------------------------------------------------------------------===//
1377 
1378 class RangeConstraintManager : public RangedConstraintManager {
1379 public:
1380   RangeConstraintManager(ExprEngine *EE, SValBuilder &SVB)
1381       : RangedConstraintManager(EE, SVB), F(getBasicVals()) {}
1382 
1383   //===------------------------------------------------------------------===//
1384   // Implementation for interface from ConstraintManager.
1385   //===------------------------------------------------------------------===//
1386 
1387   bool haveEqualConstraints(ProgramStateRef S1,
1388                             ProgramStateRef S2) const override {
1389     // NOTE: ClassMembers are as simple as back pointers for ClassMap,
1390     //       so comparing constraint ranges and class maps should be
1391     //       sufficient.
1392     return S1->get<ConstraintRange>() == S2->get<ConstraintRange>() &&
1393            S1->get<ClassMap>() == S2->get<ClassMap>();
1394   }
1395 
1396   bool canReasonAbout(SVal X) const override;
1397 
1398   ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override;
1399 
1400   const llvm::APSInt *getSymVal(ProgramStateRef State,
1401                                 SymbolRef Sym) const override;
1402 
1403   ProgramStateRef removeDeadBindings(ProgramStateRef State,
1404                                      SymbolReaper &SymReaper) override;
1405 
1406   void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
1407                  unsigned int Space = 0, bool IsDot = false) const override;
1408 
1409   //===------------------------------------------------------------------===//
1410   // Implementation for interface from RangedConstraintManager.
1411   //===------------------------------------------------------------------===//
1412 
1413   ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym,
1414                               const llvm::APSInt &V,
1415                               const llvm::APSInt &Adjustment) override;
1416 
1417   ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym,
1418                               const llvm::APSInt &V,
1419                               const llvm::APSInt &Adjustment) override;
1420 
1421   ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym,
1422                               const llvm::APSInt &V,
1423                               const llvm::APSInt &Adjustment) override;
1424 
1425   ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym,
1426                               const llvm::APSInt &V,
1427                               const llvm::APSInt &Adjustment) override;
1428 
1429   ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym,
1430                               const llvm::APSInt &V,
1431                               const llvm::APSInt &Adjustment) override;
1432 
1433   ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym,
1434                               const llvm::APSInt &V,
1435                               const llvm::APSInt &Adjustment) override;
1436 
1437   ProgramStateRef assumeSymWithinInclusiveRange(
1438       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1439       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1440 
1441   ProgramStateRef assumeSymOutsideInclusiveRange(
1442       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1443       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1444 
1445 private:
1446   RangeSet::Factory F;
1447 
1448   RangeSet getRange(ProgramStateRef State, SymbolRef Sym);
1449   RangeSet getRange(ProgramStateRef State, EquivalenceClass Class);
1450 
1451   RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym,
1452                          const llvm::APSInt &Int,
1453                          const llvm::APSInt &Adjustment);
1454   RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym,
1455                          const llvm::APSInt &Int,
1456                          const llvm::APSInt &Adjustment);
1457   RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym,
1458                          const llvm::APSInt &Int,
1459                          const llvm::APSInt &Adjustment);
1460   RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS,
1461                          const llvm::APSInt &Int,
1462                          const llvm::APSInt &Adjustment);
1463   RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym,
1464                          const llvm::APSInt &Int,
1465                          const llvm::APSInt &Adjustment);
1466 
1467   //===------------------------------------------------------------------===//
1468   // Equality tracking implementation
1469   //===------------------------------------------------------------------===//
1470 
1471   ProgramStateRef trackEQ(RangeSet NewConstraint, ProgramStateRef State,
1472                           SymbolRef Sym, const llvm::APSInt &Int,
1473                           const llvm::APSInt &Adjustment) {
1474     return track<true>(NewConstraint, State, Sym, Int, Adjustment);
1475   }
1476 
1477   ProgramStateRef trackNE(RangeSet NewConstraint, ProgramStateRef State,
1478                           SymbolRef Sym, const llvm::APSInt &Int,
1479                           const llvm::APSInt &Adjustment) {
1480     return track<false>(NewConstraint, State, Sym, Int, Adjustment);
1481   }
1482 
1483   template <bool EQ>
1484   ProgramStateRef track(RangeSet NewConstraint, ProgramStateRef State,
1485                         SymbolRef Sym, const llvm::APSInt &Int,
1486                         const llvm::APSInt &Adjustment) {
1487     if (NewConstraint.isEmpty())
1488       // This is an infeasible assumption.
1489       return nullptr;
1490 
1491     if (ProgramStateRef NewState = setConstraint(State, Sym, NewConstraint)) {
1492       if (auto Equality = EqualityInfo::extract(Sym, Int, Adjustment)) {
1493         // If the original assumption is not Sym + Adjustment !=/</> Int,
1494         // we should invert IsEquality flag.
1495         Equality->IsEquality = Equality->IsEquality != EQ;
1496         return track(NewState, *Equality);
1497       }
1498 
1499       return NewState;
1500     }
1501 
1502     return nullptr;
1503   }
1504 
1505   ProgramStateRef track(ProgramStateRef State, EqualityInfo ToTrack) {
1506     if (ToTrack.IsEquality) {
1507       return trackEquality(State, ToTrack.Left, ToTrack.Right);
1508     }
1509     return trackDisequality(State, ToTrack.Left, ToTrack.Right);
1510   }
1511 
1512   ProgramStateRef trackDisequality(ProgramStateRef State, SymbolRef LHS,
1513                                    SymbolRef RHS) {
1514     return EquivalenceClass::markDisequal(F, State, LHS, RHS);
1515   }
1516 
1517   ProgramStateRef trackEquality(ProgramStateRef State, SymbolRef LHS,
1518                                 SymbolRef RHS) {
1519     return EquivalenceClass::merge(F, State, LHS, RHS);
1520   }
1521 
1522   LLVM_NODISCARD ProgramStateRef setConstraint(ProgramStateRef State,
1523                                                EquivalenceClass Class,
1524                                                RangeSet Constraint) {
1525     ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1526     ConstraintRangeTy::Factory &CF = State->get_context<ConstraintRange>();
1527 
1528     assert(!Constraint.isEmpty() && "New constraint should not be empty");
1529 
1530     // Add new constraint.
1531     Constraints = CF.add(Constraints, Class, Constraint);
1532 
1533     // There is a chance that we might need to update constraints for the
1534     // classes that are known to be disequal to Class.
1535     //
1536     // In order for this to be even possible, the new constraint should
1537     // be simply a constant because we can't reason about range disequalities.
1538     if (const llvm::APSInt *Point = Constraint.getConcreteValue())
1539       for (EquivalenceClass DisequalClass : Class.getDisequalClasses(State)) {
1540         RangeSet UpdatedConstraint = getRange(State, DisequalClass);
1541         UpdatedConstraint = F.deletePoint(UpdatedConstraint, *Point);
1542 
1543         // If we end up with at least one of the disequal classes to be
1544         // constrained with an empty range-set, the state is infeasible.
1545         if (UpdatedConstraint.isEmpty())
1546           return nullptr;
1547 
1548         Constraints = CF.add(Constraints, DisequalClass, UpdatedConstraint);
1549       }
1550 
1551     assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1552                                        "a state with infeasible constraints");
1553 
1554     return State->set<ConstraintRange>(Constraints);
1555   }
1556 
1557   // Associate a constraint to a symbolic expression. First, we set the
1558   // constraint in the State, then we try to simplify existing symbolic
1559   // expressions based on the newly set constraint.
1560   LLVM_NODISCARD inline ProgramStateRef
1561   setConstraint(ProgramStateRef State, SymbolRef Sym, RangeSet Constraint) {
1562     assert(State);
1563 
1564     State = setConstraint(State, EquivalenceClass::find(State, Sym), Constraint);
1565     if (!State)
1566       return nullptr;
1567 
1568     // We have a chance to simplify existing symbolic values if the new
1569     // constraint is a constant.
1570     if (!Constraint.getConcreteValue())
1571       return State;
1572 
1573     llvm::SmallSet<EquivalenceClass, 4> SimplifiedClasses;
1574     // Iterate over all equivalence classes and try to simplify them.
1575     ClassMembersTy Members = State->get<ClassMembers>();
1576     for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members) {
1577       EquivalenceClass Class = ClassToSymbolSet.first;
1578       State = Class.simplify(getSValBuilder(), F, State);
1579       if (!State)
1580         return nullptr;
1581       SimplifiedClasses.insert(Class);
1582     }
1583 
1584     // Trivial equivalence classes (those that have only one symbol member) are
1585     // not stored in the State. Thus, we must skim through the constraints as
1586     // well. And we try to simplify symbols in the constraints.
1587     ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1588     for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
1589       EquivalenceClass Class = ClassConstraint.first;
1590       if (SimplifiedClasses.count(Class)) // Already simplified.
1591         continue;
1592       State = Class.simplify(getSValBuilder(), F, State);
1593       if (!State)
1594         return nullptr;
1595     }
1596 
1597     return State;
1598   }
1599 };
1600 
1601 } // end anonymous namespace
1602 
1603 std::unique_ptr<ConstraintManager>
1604 ento::CreateRangeConstraintManager(ProgramStateManager &StMgr,
1605                                    ExprEngine *Eng) {
1606   return std::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder());
1607 }
1608 
1609 ConstraintMap ento::getConstraintMap(ProgramStateRef State) {
1610   ConstraintMap::Factory &F = State->get_context<ConstraintMap>();
1611   ConstraintMap Result = F.getEmptyMap();
1612 
1613   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1614   for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
1615     EquivalenceClass Class = ClassConstraint.first;
1616     SymbolSet ClassMembers = Class.getClassMembers(State);
1617     assert(!ClassMembers.isEmpty() &&
1618            "Class must always have at least one member!");
1619 
1620     SymbolRef Representative = *ClassMembers.begin();
1621     Result = F.add(Result, Representative, ClassConstraint.second);
1622   }
1623 
1624   return Result;
1625 }
1626 
1627 //===----------------------------------------------------------------------===//
1628 //                     EqualityClass implementation details
1629 //===----------------------------------------------------------------------===//
1630 
1631 inline EquivalenceClass EquivalenceClass::find(ProgramStateRef State,
1632                                                SymbolRef Sym) {
1633   assert(State && "State should not be null");
1634   assert(Sym && "Symbol should not be null");
1635   // We store far from all Symbol -> Class mappings
1636   if (const EquivalenceClass *NontrivialClass = State->get<ClassMap>(Sym))
1637     return *NontrivialClass;
1638 
1639   // This is a trivial class of Sym.
1640   return Sym;
1641 }
1642 
1643 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
1644                                                ProgramStateRef State,
1645                                                SymbolRef First,
1646                                                SymbolRef Second) {
1647   EquivalenceClass FirstClass = find(State, First);
1648   EquivalenceClass SecondClass = find(State, Second);
1649 
1650   return FirstClass.merge(F, State, SecondClass);
1651 }
1652 
1653 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
1654                                                ProgramStateRef State,
1655                                                EquivalenceClass Other) {
1656   // It is already the same class.
1657   if (*this == Other)
1658     return State;
1659 
1660   // FIXME: As of now, we support only equivalence classes of the same type.
1661   //        This limitation is connected to the lack of explicit casts in
1662   //        our symbolic expression model.
1663   //
1664   //        That means that for `int x` and `char y` we don't distinguish
1665   //        between these two very different cases:
1666   //          * `x == y`
1667   //          * `(char)x == y`
1668   //
1669   //        The moment we introduce symbolic casts, this restriction can be
1670   //        lifted.
1671   if (getType() != Other.getType())
1672     return State;
1673 
1674   SymbolSet Members = getClassMembers(State);
1675   SymbolSet OtherMembers = Other.getClassMembers(State);
1676 
1677   // We estimate the size of the class by the height of tree containing
1678   // its members.  Merging is not a trivial operation, so it's easier to
1679   // merge the smaller class into the bigger one.
1680   if (Members.getHeight() >= OtherMembers.getHeight()) {
1681     return mergeImpl(F, State, Members, Other, OtherMembers);
1682   } else {
1683     return Other.mergeImpl(F, State, OtherMembers, *this, Members);
1684   }
1685 }
1686 
1687 inline ProgramStateRef
1688 EquivalenceClass::mergeImpl(RangeSet::Factory &RangeFactory,
1689                             ProgramStateRef State, SymbolSet MyMembers,
1690                             EquivalenceClass Other, SymbolSet OtherMembers) {
1691   // Essentially what we try to recreate here is some kind of union-find
1692   // data structure.  It does have certain limitations due to persistence
1693   // and the need to remove elements from classes.
1694   //
1695   // In this setting, EquialityClass object is the representative of the class
1696   // or the parent element.  ClassMap is a mapping of class members to their
1697   // parent. Unlike the union-find structure, they all point directly to the
1698   // class representative because we don't have an opportunity to actually do
1699   // path compression when dealing with immutability.  This means that we
1700   // compress paths every time we do merges.  It also means that we lose
1701   // the main amortized complexity benefit from the original data structure.
1702   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1703   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
1704 
1705   // 1. If the merged classes have any constraints associated with them, we
1706   //    need to transfer them to the class we have left.
1707   //
1708   // Intersection here makes perfect sense because both of these constraints
1709   // must hold for the whole new class.
1710   if (Optional<RangeSet> NewClassConstraint =
1711           intersect(RangeFactory, getConstraint(State, *this),
1712                     getConstraint(State, Other))) {
1713     // NOTE: Essentially, NewClassConstraint should NEVER be infeasible because
1714     //       range inferrer shouldn't generate ranges incompatible with
1715     //       equivalence classes. However, at the moment, due to imperfections
1716     //       in the solver, it is possible and the merge function can also
1717     //       return infeasible states aka null states.
1718     if (NewClassConstraint->isEmpty())
1719       // Infeasible state
1720       return nullptr;
1721 
1722     // No need in tracking constraints of a now-dissolved class.
1723     Constraints = CRF.remove(Constraints, Other);
1724     // Assign new constraints for this class.
1725     Constraints = CRF.add(Constraints, *this, *NewClassConstraint);
1726 
1727     assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1728                                        "a state with infeasible constraints");
1729 
1730     State = State->set<ConstraintRange>(Constraints);
1731   }
1732 
1733   // 2. Get ALL equivalence-related maps
1734   ClassMapTy Classes = State->get<ClassMap>();
1735   ClassMapTy::Factory &CMF = State->get_context<ClassMap>();
1736 
1737   ClassMembersTy Members = State->get<ClassMembers>();
1738   ClassMembersTy::Factory &MF = State->get_context<ClassMembers>();
1739 
1740   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
1741   DisequalityMapTy::Factory &DF = State->get_context<DisequalityMap>();
1742 
1743   ClassSet::Factory &CF = State->get_context<ClassSet>();
1744   SymbolSet::Factory &F = getMembersFactory(State);
1745 
1746   // 2. Merge members of the Other class into the current class.
1747   SymbolSet NewClassMembers = MyMembers;
1748   for (SymbolRef Sym : OtherMembers) {
1749     NewClassMembers = F.add(NewClassMembers, Sym);
1750     // *this is now the class for all these new symbols.
1751     Classes = CMF.add(Classes, Sym, *this);
1752   }
1753 
1754   // 3. Adjust member mapping.
1755   //
1756   // No need in tracking members of a now-dissolved class.
1757   Members = MF.remove(Members, Other);
1758   // Now only the current class is mapped to all the symbols.
1759   Members = MF.add(Members, *this, NewClassMembers);
1760 
1761   // 4. Update disequality relations
1762   ClassSet DisequalToOther = Other.getDisequalClasses(DisequalityInfo, CF);
1763   // We are about to merge two classes but they are already known to be
1764   // non-equal. This is a contradiction.
1765   if (DisequalToOther.contains(*this))
1766     return nullptr;
1767 
1768   if (!DisequalToOther.isEmpty()) {
1769     ClassSet DisequalToThis = getDisequalClasses(DisequalityInfo, CF);
1770     DisequalityInfo = DF.remove(DisequalityInfo, Other);
1771 
1772     for (EquivalenceClass DisequalClass : DisequalToOther) {
1773       DisequalToThis = CF.add(DisequalToThis, DisequalClass);
1774 
1775       // Disequality is a symmetric relation meaning that if
1776       // DisequalToOther not null then the set for DisequalClass is not
1777       // empty and has at least Other.
1778       ClassSet OriginalSetLinkedToOther =
1779           *DisequalityInfo.lookup(DisequalClass);
1780 
1781       // Other will be eliminated and we should replace it with the bigger
1782       // united class.
1783       ClassSet NewSet = CF.remove(OriginalSetLinkedToOther, Other);
1784       NewSet = CF.add(NewSet, *this);
1785 
1786       DisequalityInfo = DF.add(DisequalityInfo, DisequalClass, NewSet);
1787     }
1788 
1789     DisequalityInfo = DF.add(DisequalityInfo, *this, DisequalToThis);
1790     State = State->set<DisequalityMap>(DisequalityInfo);
1791   }
1792 
1793   // 5. Update the state
1794   State = State->set<ClassMap>(Classes);
1795   State = State->set<ClassMembers>(Members);
1796 
1797   return State;
1798 }
1799 
1800 inline SymbolSet::Factory &
1801 EquivalenceClass::getMembersFactory(ProgramStateRef State) {
1802   return State->get_context<SymbolSet>();
1803 }
1804 
1805 SymbolSet EquivalenceClass::getClassMembers(ProgramStateRef State) const {
1806   if (const SymbolSet *Members = State->get<ClassMembers>(*this))
1807     return *Members;
1808 
1809   // This class is trivial, so we need to construct a set
1810   // with just that one symbol from the class.
1811   SymbolSet::Factory &F = getMembersFactory(State);
1812   return F.add(F.getEmptySet(), getRepresentativeSymbol());
1813 }
1814 
1815 bool EquivalenceClass::isTrivial(ProgramStateRef State) const {
1816   return State->get<ClassMembers>(*this) == nullptr;
1817 }
1818 
1819 bool EquivalenceClass::isTriviallyDead(ProgramStateRef State,
1820                                        SymbolReaper &Reaper) const {
1821   return isTrivial(State) && Reaper.isDead(getRepresentativeSymbol());
1822 }
1823 
1824 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
1825                                                       ProgramStateRef State,
1826                                                       SymbolRef First,
1827                                                       SymbolRef Second) {
1828   return markDisequal(RF, State, find(State, First), find(State, Second));
1829 }
1830 
1831 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
1832                                                       ProgramStateRef State,
1833                                                       EquivalenceClass First,
1834                                                       EquivalenceClass Second) {
1835   return First.markDisequal(RF, State, Second);
1836 }
1837 
1838 inline ProgramStateRef
1839 EquivalenceClass::markDisequal(RangeSet::Factory &RF, ProgramStateRef State,
1840                                EquivalenceClass Other) const {
1841   // If we know that two classes are equal, we can only produce an infeasible
1842   // state.
1843   if (*this == Other) {
1844     return nullptr;
1845   }
1846 
1847   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
1848   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1849 
1850   // Disequality is a symmetric relation, so if we mark A as disequal to B,
1851   // we should also mark B as disequalt to A.
1852   if (!addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, *this,
1853                             Other) ||
1854       !addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, Other,
1855                             *this))
1856     return nullptr;
1857 
1858   assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1859                                      "a state with infeasible constraints");
1860 
1861   State = State->set<DisequalityMap>(DisequalityInfo);
1862   State = State->set<ConstraintRange>(Constraints);
1863 
1864   return State;
1865 }
1866 
1867 inline bool EquivalenceClass::addToDisequalityInfo(
1868     DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
1869     RangeSet::Factory &RF, ProgramStateRef State, EquivalenceClass First,
1870     EquivalenceClass Second) {
1871 
1872   // 1. Get all of the required factories.
1873   DisequalityMapTy::Factory &F = State->get_context<DisequalityMap>();
1874   ClassSet::Factory &CF = State->get_context<ClassSet>();
1875   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
1876 
1877   // 2. Add Second to the set of classes disequal to First.
1878   const ClassSet *CurrentSet = Info.lookup(First);
1879   ClassSet NewSet = CurrentSet ? *CurrentSet : CF.getEmptySet();
1880   NewSet = CF.add(NewSet, Second);
1881 
1882   Info = F.add(Info, First, NewSet);
1883 
1884   // 3. If Second is known to be a constant, we can delete this point
1885   //    from the constraint asociated with First.
1886   //
1887   //    So, if Second == 10, it means that First != 10.
1888   //    At the same time, the same logic does not apply to ranges.
1889   if (const RangeSet *SecondConstraint = Constraints.lookup(Second))
1890     if (const llvm::APSInt *Point = SecondConstraint->getConcreteValue()) {
1891 
1892       RangeSet FirstConstraint = SymbolicRangeInferrer::inferRange(
1893           RF, State, First.getRepresentativeSymbol());
1894 
1895       FirstConstraint = RF.deletePoint(FirstConstraint, *Point);
1896 
1897       // If the First class is about to be constrained with an empty
1898       // range-set, the state is infeasible.
1899       if (FirstConstraint.isEmpty())
1900         return false;
1901 
1902       Constraints = CRF.add(Constraints, First, FirstConstraint);
1903     }
1904 
1905   return true;
1906 }
1907 
1908 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
1909                                                  SymbolRef FirstSym,
1910                                                  SymbolRef SecondSym) {
1911   return EquivalenceClass::areEqual(State, find(State, FirstSym),
1912                                     find(State, SecondSym));
1913 }
1914 
1915 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
1916                                                  EquivalenceClass First,
1917                                                  EquivalenceClass Second) {
1918   // The same equivalence class => symbols are equal.
1919   if (First == Second)
1920     return true;
1921 
1922   // Let's check if we know anything about these two classes being not equal to
1923   // each other.
1924   ClassSet DisequalToFirst = First.getDisequalClasses(State);
1925   if (DisequalToFirst.contains(Second))
1926     return false;
1927 
1928   // It is not clear.
1929   return llvm::None;
1930 }
1931 
1932 // Iterate over all symbols and try to simplify them. Once a symbol is
1933 // simplified then we check if we can merge the simplified symbol's equivalence
1934 // class to this class. This way, we simplify not just the symbols but the
1935 // classes as well: we strive to keep the number of the classes to be the
1936 // absolute minimum.
1937 LLVM_NODISCARD ProgramStateRef EquivalenceClass::simplify(
1938     SValBuilder &SVB, RangeSet::Factory &F, ProgramStateRef State) {
1939   SymbolSet ClassMembers = getClassMembers(State);
1940   for (const SymbolRef &MemberSym : ClassMembers) {
1941     SymbolRef SimplifiedMemberSym = ento::simplify(State, MemberSym);
1942     if (SimplifiedMemberSym && MemberSym != SimplifiedMemberSym) {
1943       EquivalenceClass ClassOfSimplifiedSym =
1944           EquivalenceClass::find(State, SimplifiedMemberSym);
1945       // The simplified symbol should be the member of the original Class,
1946       // however, it might be in another existing class at the moment. We
1947       // have to merge these classes.
1948       State = merge(F, State, ClassOfSimplifiedSym);
1949       if (!State)
1950         return nullptr;
1951     }
1952   }
1953   return State;
1954 }
1955 
1956 inline ClassSet EquivalenceClass::getDisequalClasses(ProgramStateRef State,
1957                                                      SymbolRef Sym) {
1958   return find(State, Sym).getDisequalClasses(State);
1959 }
1960 
1961 inline ClassSet
1962 EquivalenceClass::getDisequalClasses(ProgramStateRef State) const {
1963   return getDisequalClasses(State->get<DisequalityMap>(),
1964                             State->get_context<ClassSet>());
1965 }
1966 
1967 inline ClassSet
1968 EquivalenceClass::getDisequalClasses(DisequalityMapTy Map,
1969                                      ClassSet::Factory &Factory) const {
1970   if (const ClassSet *DisequalClasses = Map.lookup(*this))
1971     return *DisequalClasses;
1972 
1973   return Factory.getEmptySet();
1974 }
1975 
1976 bool EquivalenceClass::isClassDataConsistent(ProgramStateRef State) {
1977   ClassMembersTy Members = State->get<ClassMembers>();
1978 
1979   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair : Members) {
1980     for (SymbolRef Member : ClassMembersPair.second) {
1981       // Every member of the class should have a mapping back to the class.
1982       if (find(State, Member) == ClassMembersPair.first) {
1983         continue;
1984       }
1985 
1986       return false;
1987     }
1988   }
1989 
1990   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
1991   for (std::pair<EquivalenceClass, ClassSet> DisequalityInfo : Disequalities) {
1992     EquivalenceClass Class = DisequalityInfo.first;
1993     ClassSet DisequalClasses = DisequalityInfo.second;
1994 
1995     // There is no use in keeping empty sets in the map.
1996     if (DisequalClasses.isEmpty())
1997       return false;
1998 
1999     // Disequality is symmetrical, i.e. for every Class A and B that A != B,
2000     // B != A should also be true.
2001     for (EquivalenceClass DisequalClass : DisequalClasses) {
2002       const ClassSet *DisequalToDisequalClasses =
2003           Disequalities.lookup(DisequalClass);
2004 
2005       // It should be a set of at least one element: Class
2006       if (!DisequalToDisequalClasses ||
2007           !DisequalToDisequalClasses->contains(Class))
2008         return false;
2009     }
2010   }
2011 
2012   return true;
2013 }
2014 
2015 //===----------------------------------------------------------------------===//
2016 //                    RangeConstraintManager implementation
2017 //===----------------------------------------------------------------------===//
2018 
2019 bool RangeConstraintManager::canReasonAbout(SVal X) const {
2020   Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
2021   if (SymVal && SymVal->isExpression()) {
2022     const SymExpr *SE = SymVal->getSymbol();
2023 
2024     if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
2025       switch (SIE->getOpcode()) {
2026       // We don't reason yet about bitwise-constraints on symbolic values.
2027       case BO_And:
2028       case BO_Or:
2029       case BO_Xor:
2030         return false;
2031       // We don't reason yet about these arithmetic constraints on
2032       // symbolic values.
2033       case BO_Mul:
2034       case BO_Div:
2035       case BO_Rem:
2036       case BO_Shl:
2037       case BO_Shr:
2038         return false;
2039       // All other cases.
2040       default:
2041         return true;
2042       }
2043     }
2044 
2045     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
2046       // FIXME: Handle <=> here.
2047       if (BinaryOperator::isEqualityOp(SSE->getOpcode()) ||
2048           BinaryOperator::isRelationalOp(SSE->getOpcode())) {
2049         // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
2050         // We've recently started producing Loc <> NonLoc comparisons (that
2051         // result from casts of one of the operands between eg. intptr_t and
2052         // void *), but we can't reason about them yet.
2053         if (Loc::isLocType(SSE->getLHS()->getType())) {
2054           return Loc::isLocType(SSE->getRHS()->getType());
2055         }
2056       }
2057     }
2058 
2059     return false;
2060   }
2061 
2062   return true;
2063 }
2064 
2065 ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
2066                                                     SymbolRef Sym) {
2067   const RangeSet *Ranges = getConstraint(State, Sym);
2068 
2069   // If we don't have any information about this symbol, it's underconstrained.
2070   if (!Ranges)
2071     return ConditionTruthVal();
2072 
2073   // If we have a concrete value, see if it's zero.
2074   if (const llvm::APSInt *Value = Ranges->getConcreteValue())
2075     return *Value == 0;
2076 
2077   BasicValueFactory &BV = getBasicVals();
2078   APSIntType IntType = BV.getAPSIntType(Sym->getType());
2079   llvm::APSInt Zero = IntType.getZeroValue();
2080 
2081   // Check if zero is in the set of possible values.
2082   if (!Ranges->contains(Zero))
2083     return false;
2084 
2085   // Zero is a possible value, but it is not the /only/ possible value.
2086   return ConditionTruthVal();
2087 }
2088 
2089 const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St,
2090                                                       SymbolRef Sym) const {
2091   const RangeSet *T = getConstraint(St, Sym);
2092   return T ? T->getConcreteValue() : nullptr;
2093 }
2094 
2095 //===----------------------------------------------------------------------===//
2096 //                Remove dead symbols from existing constraints
2097 //===----------------------------------------------------------------------===//
2098 
2099 /// Scan all symbols referenced by the constraints. If the symbol is not alive
2100 /// as marked in LSymbols, mark it as dead in DSymbols.
2101 ProgramStateRef
2102 RangeConstraintManager::removeDeadBindings(ProgramStateRef State,
2103                                            SymbolReaper &SymReaper) {
2104   ClassMembersTy ClassMembersMap = State->get<ClassMembers>();
2105   ClassMembersTy NewClassMembersMap = ClassMembersMap;
2106   ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>();
2107   SymbolSet::Factory &SetFactory = State->get_context<SymbolSet>();
2108 
2109   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2110   ConstraintRangeTy NewConstraints = Constraints;
2111   ConstraintRangeTy::Factory &ConstraintFactory =
2112       State->get_context<ConstraintRange>();
2113 
2114   ClassMapTy Map = State->get<ClassMap>();
2115   ClassMapTy NewMap = Map;
2116   ClassMapTy::Factory &ClassFactory = State->get_context<ClassMap>();
2117 
2118   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2119   DisequalityMapTy::Factory &DisequalityFactory =
2120       State->get_context<DisequalityMap>();
2121   ClassSet::Factory &ClassSetFactory = State->get_context<ClassSet>();
2122 
2123   bool ClassMapChanged = false;
2124   bool MembersMapChanged = false;
2125   bool ConstraintMapChanged = false;
2126   bool DisequalitiesChanged = false;
2127 
2128   auto removeDeadClass = [&](EquivalenceClass Class) {
2129     // Remove associated constraint ranges.
2130     Constraints = ConstraintFactory.remove(Constraints, Class);
2131     ConstraintMapChanged = true;
2132 
2133     // Update disequality information to not hold any information on the
2134     // removed class.
2135     ClassSet DisequalClasses =
2136         Class.getDisequalClasses(Disequalities, ClassSetFactory);
2137     if (!DisequalClasses.isEmpty()) {
2138       for (EquivalenceClass DisequalClass : DisequalClasses) {
2139         ClassSet DisequalToDisequalSet =
2140             DisequalClass.getDisequalClasses(Disequalities, ClassSetFactory);
2141         // DisequalToDisequalSet is guaranteed to be non-empty for consistent
2142         // disequality info.
2143         assert(!DisequalToDisequalSet.isEmpty());
2144         ClassSet NewSet = ClassSetFactory.remove(DisequalToDisequalSet, Class);
2145 
2146         // No need in keeping an empty set.
2147         if (NewSet.isEmpty()) {
2148           Disequalities =
2149               DisequalityFactory.remove(Disequalities, DisequalClass);
2150         } else {
2151           Disequalities =
2152               DisequalityFactory.add(Disequalities, DisequalClass, NewSet);
2153         }
2154       }
2155       // Remove the data for the class
2156       Disequalities = DisequalityFactory.remove(Disequalities, Class);
2157       DisequalitiesChanged = true;
2158     }
2159   };
2160 
2161   // 1. Let's see if dead symbols are trivial and have associated constraints.
2162   for (std::pair<EquivalenceClass, RangeSet> ClassConstraintPair :
2163        Constraints) {
2164     EquivalenceClass Class = ClassConstraintPair.first;
2165     if (Class.isTriviallyDead(State, SymReaper)) {
2166       // If this class is trivial, we can remove its constraints right away.
2167       removeDeadClass(Class);
2168     }
2169   }
2170 
2171   // 2. We don't need to track classes for dead symbols.
2172   for (std::pair<SymbolRef, EquivalenceClass> SymbolClassPair : Map) {
2173     SymbolRef Sym = SymbolClassPair.first;
2174 
2175     if (SymReaper.isDead(Sym)) {
2176       ClassMapChanged = true;
2177       NewMap = ClassFactory.remove(NewMap, Sym);
2178     }
2179   }
2180 
2181   // 3. Remove dead members from classes and remove dead non-trivial classes
2182   //    and their constraints.
2183   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair :
2184        ClassMembersMap) {
2185     EquivalenceClass Class = ClassMembersPair.first;
2186     SymbolSet LiveMembers = ClassMembersPair.second;
2187     bool MembersChanged = false;
2188 
2189     for (SymbolRef Member : ClassMembersPair.second) {
2190       if (SymReaper.isDead(Member)) {
2191         MembersChanged = true;
2192         LiveMembers = SetFactory.remove(LiveMembers, Member);
2193       }
2194     }
2195 
2196     // Check if the class changed.
2197     if (!MembersChanged)
2198       continue;
2199 
2200     MembersMapChanged = true;
2201 
2202     if (LiveMembers.isEmpty()) {
2203       // The class is dead now, we need to wipe it out of the members map...
2204       NewClassMembersMap = EMFactory.remove(NewClassMembersMap, Class);
2205 
2206       // ...and remove all of its constraints.
2207       removeDeadClass(Class);
2208     } else {
2209       // We need to change the members associated with the class.
2210       NewClassMembersMap =
2211           EMFactory.add(NewClassMembersMap, Class, LiveMembers);
2212     }
2213   }
2214 
2215   // 4. Update the state with new maps.
2216   //
2217   // Here we try to be humble and update a map only if it really changed.
2218   if (ClassMapChanged)
2219     State = State->set<ClassMap>(NewMap);
2220 
2221   if (MembersMapChanged)
2222     State = State->set<ClassMembers>(NewClassMembersMap);
2223 
2224   if (ConstraintMapChanged)
2225     State = State->set<ConstraintRange>(Constraints);
2226 
2227   if (DisequalitiesChanged)
2228     State = State->set<DisequalityMap>(Disequalities);
2229 
2230   assert(EquivalenceClass::isClassDataConsistent(State));
2231 
2232   return State;
2233 }
2234 
2235 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
2236                                           SymbolRef Sym) {
2237   return SymbolicRangeInferrer::inferRange(F, State, Sym);
2238 }
2239 
2240 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
2241                                           EquivalenceClass Class) {
2242   return SymbolicRangeInferrer::inferRange(F, State, Class);
2243 }
2244 
2245 //===------------------------------------------------------------------------===
2246 // assumeSymX methods: protected interface for RangeConstraintManager.
2247 //===------------------------------------------------------------------------===/
2248 
2249 // The syntax for ranges below is mathematical, using [x, y] for closed ranges
2250 // and (x, y) for open ranges. These ranges are modular, corresponding with
2251 // a common treatment of C integer overflow. This means that these methods
2252 // do not have to worry about overflow; RangeSet::Intersect can handle such a
2253 // "wraparound" range.
2254 // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
2255 // UINT_MAX, 0, 1, and 2.
2256 
2257 ProgramStateRef
2258 RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
2259                                     const llvm::APSInt &Int,
2260                                     const llvm::APSInt &Adjustment) {
2261   // Before we do any real work, see if the value can even show up.
2262   APSIntType AdjustmentType(Adjustment);
2263   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
2264     return St;
2265 
2266   llvm::APSInt Point = AdjustmentType.convert(Int) - Adjustment;
2267   RangeSet New = getRange(St, Sym);
2268   New = F.deletePoint(New, Point);
2269 
2270   return trackNE(New, St, Sym, Int, Adjustment);
2271 }
2272 
2273 ProgramStateRef
2274 RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
2275                                     const llvm::APSInt &Int,
2276                                     const llvm::APSInt &Adjustment) {
2277   // Before we do any real work, see if the value can even show up.
2278   APSIntType AdjustmentType(Adjustment);
2279   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
2280     return nullptr;
2281 
2282   // [Int-Adjustment, Int-Adjustment]
2283   llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
2284   RangeSet New = getRange(St, Sym);
2285   New = F.intersect(New, AdjInt);
2286 
2287   return trackEQ(New, St, Sym, Int, Adjustment);
2288 }
2289 
2290 RangeSet RangeConstraintManager::getSymLTRange(ProgramStateRef St,
2291                                                SymbolRef Sym,
2292                                                const llvm::APSInt &Int,
2293                                                const llvm::APSInt &Adjustment) {
2294   // Before we do any real work, see if the value can even show up.
2295   APSIntType AdjustmentType(Adjustment);
2296   switch (AdjustmentType.testInRange(Int, true)) {
2297   case APSIntType::RTR_Below:
2298     return F.getEmptySet();
2299   case APSIntType::RTR_Within:
2300     break;
2301   case APSIntType::RTR_Above:
2302     return getRange(St, Sym);
2303   }
2304 
2305   // Special case for Int == Min. This is always false.
2306   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2307   llvm::APSInt Min = AdjustmentType.getMinValue();
2308   if (ComparisonVal == Min)
2309     return F.getEmptySet();
2310 
2311   llvm::APSInt Lower = Min - Adjustment;
2312   llvm::APSInt Upper = ComparisonVal - Adjustment;
2313   --Upper;
2314 
2315   RangeSet Result = getRange(St, Sym);
2316   return F.intersect(Result, Lower, Upper);
2317 }
2318 
2319 ProgramStateRef
2320 RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
2321                                     const llvm::APSInt &Int,
2322                                     const llvm::APSInt &Adjustment) {
2323   RangeSet New = getSymLTRange(St, Sym, Int, Adjustment);
2324   return trackNE(New, St, Sym, Int, Adjustment);
2325 }
2326 
2327 RangeSet RangeConstraintManager::getSymGTRange(ProgramStateRef St,
2328                                                SymbolRef Sym,
2329                                                const llvm::APSInt &Int,
2330                                                const llvm::APSInt &Adjustment) {
2331   // Before we do any real work, see if the value can even show up.
2332   APSIntType AdjustmentType(Adjustment);
2333   switch (AdjustmentType.testInRange(Int, true)) {
2334   case APSIntType::RTR_Below:
2335     return getRange(St, Sym);
2336   case APSIntType::RTR_Within:
2337     break;
2338   case APSIntType::RTR_Above:
2339     return F.getEmptySet();
2340   }
2341 
2342   // Special case for Int == Max. This is always false.
2343   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2344   llvm::APSInt Max = AdjustmentType.getMaxValue();
2345   if (ComparisonVal == Max)
2346     return F.getEmptySet();
2347 
2348   llvm::APSInt Lower = ComparisonVal - Adjustment;
2349   llvm::APSInt Upper = Max - Adjustment;
2350   ++Lower;
2351 
2352   RangeSet SymRange = getRange(St, Sym);
2353   return F.intersect(SymRange, Lower, Upper);
2354 }
2355 
2356 ProgramStateRef
2357 RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
2358                                     const llvm::APSInt &Int,
2359                                     const llvm::APSInt &Adjustment) {
2360   RangeSet New = getSymGTRange(St, Sym, Int, Adjustment);
2361   return trackNE(New, St, Sym, Int, Adjustment);
2362 }
2363 
2364 RangeSet RangeConstraintManager::getSymGERange(ProgramStateRef St,
2365                                                SymbolRef Sym,
2366                                                const llvm::APSInt &Int,
2367                                                const llvm::APSInt &Adjustment) {
2368   // Before we do any real work, see if the value can even show up.
2369   APSIntType AdjustmentType(Adjustment);
2370   switch (AdjustmentType.testInRange(Int, true)) {
2371   case APSIntType::RTR_Below:
2372     return getRange(St, Sym);
2373   case APSIntType::RTR_Within:
2374     break;
2375   case APSIntType::RTR_Above:
2376     return F.getEmptySet();
2377   }
2378 
2379   // Special case for Int == Min. This is always feasible.
2380   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2381   llvm::APSInt Min = AdjustmentType.getMinValue();
2382   if (ComparisonVal == Min)
2383     return getRange(St, Sym);
2384 
2385   llvm::APSInt Max = AdjustmentType.getMaxValue();
2386   llvm::APSInt Lower = ComparisonVal - Adjustment;
2387   llvm::APSInt Upper = Max - Adjustment;
2388 
2389   RangeSet SymRange = getRange(St, Sym);
2390   return F.intersect(SymRange, Lower, Upper);
2391 }
2392 
2393 ProgramStateRef
2394 RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
2395                                     const llvm::APSInt &Int,
2396                                     const llvm::APSInt &Adjustment) {
2397   RangeSet New = getSymGERange(St, Sym, Int, Adjustment);
2398   return New.isEmpty() ? nullptr : setConstraint(St, Sym, New);
2399 }
2400 
2401 RangeSet
2402 RangeConstraintManager::getSymLERange(llvm::function_ref<RangeSet()> RS,
2403                                       const llvm::APSInt &Int,
2404                                       const llvm::APSInt &Adjustment) {
2405   // Before we do any real work, see if the value can even show up.
2406   APSIntType AdjustmentType(Adjustment);
2407   switch (AdjustmentType.testInRange(Int, true)) {
2408   case APSIntType::RTR_Below:
2409     return F.getEmptySet();
2410   case APSIntType::RTR_Within:
2411     break;
2412   case APSIntType::RTR_Above:
2413     return RS();
2414   }
2415 
2416   // Special case for Int == Max. This is always feasible.
2417   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2418   llvm::APSInt Max = AdjustmentType.getMaxValue();
2419   if (ComparisonVal == Max)
2420     return RS();
2421 
2422   llvm::APSInt Min = AdjustmentType.getMinValue();
2423   llvm::APSInt Lower = Min - Adjustment;
2424   llvm::APSInt Upper = ComparisonVal - Adjustment;
2425 
2426   RangeSet Default = RS();
2427   return F.intersect(Default, Lower, Upper);
2428 }
2429 
2430 RangeSet RangeConstraintManager::getSymLERange(ProgramStateRef St,
2431                                                SymbolRef Sym,
2432                                                const llvm::APSInt &Int,
2433                                                const llvm::APSInt &Adjustment) {
2434   return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment);
2435 }
2436 
2437 ProgramStateRef
2438 RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
2439                                     const llvm::APSInt &Int,
2440                                     const llvm::APSInt &Adjustment) {
2441   RangeSet New = getSymLERange(St, Sym, Int, Adjustment);
2442   return New.isEmpty() ? nullptr : setConstraint(St, Sym, New);
2443 }
2444 
2445 ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange(
2446     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2447     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
2448   RangeSet New = getSymGERange(State, Sym, From, Adjustment);
2449   if (New.isEmpty())
2450     return nullptr;
2451   RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment);
2452   return Out.isEmpty() ? nullptr : setConstraint(State, Sym, Out);
2453 }
2454 
2455 ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange(
2456     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2457     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
2458   RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment);
2459   RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment);
2460   RangeSet New(F.add(RangeLT, RangeGT));
2461   return New.isEmpty() ? nullptr : setConstraint(State, Sym, New);
2462 }
2463 
2464 //===----------------------------------------------------------------------===//
2465 // Pretty-printing.
2466 //===----------------------------------------------------------------------===//
2467 
2468 void RangeConstraintManager::printJson(raw_ostream &Out, ProgramStateRef State,
2469                                        const char *NL, unsigned int Space,
2470                                        bool IsDot) const {
2471   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2472 
2473   Indent(Out, Space, IsDot) << "\"constraints\": ";
2474   if (Constraints.isEmpty()) {
2475     Out << "null," << NL;
2476     return;
2477   }
2478 
2479   ++Space;
2480   Out << '[' << NL;
2481   bool First = true;
2482   for (std::pair<EquivalenceClass, RangeSet> P : Constraints) {
2483     SymbolSet ClassMembers = P.first.getClassMembers(State);
2484 
2485     // We can print the same constraint for every class member.
2486     for (SymbolRef ClassMember : ClassMembers) {
2487       if (First) {
2488         First = false;
2489       } else {
2490         Out << ',';
2491         Out << NL;
2492       }
2493       Indent(Out, Space, IsDot)
2494           << "{ \"symbol\": \"" << ClassMember << "\", \"range\": \"";
2495       P.second.dump(Out);
2496       Out << "\" }";
2497     }
2498   }
2499   Out << NL;
2500 
2501   --Space;
2502   Indent(Out, Space, IsDot) << "]," << NL;
2503 }
2504