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 LLVM_NODISCARD ProgramStateRef setConstraint(ProgramStateRef State,
673                                              EquivalenceClass Class,
674                                              RangeSet Constraint) {
675   return State->set<ConstraintRange>(Class, Constraint);
676 }
677 
678 LLVM_NODISCARD ProgramStateRef setConstraints(ProgramStateRef State,
679                                               ConstraintRangeTy Constraints) {
680   return State->set<ConstraintRange>(Constraints);
681 }
682 
683 //===----------------------------------------------------------------------===//
684 //                       Equality/diseqiality abstraction
685 //===----------------------------------------------------------------------===//
686 
687 /// A small helper function for detecting symbolic (dis)equality.
688 ///
689 /// Equality check can have different forms (like a == b or a - b) and this
690 /// class encapsulates those away if the only thing the user wants to check -
691 /// whether it's equality/diseqiality or not.
692 ///
693 /// \returns true if assuming this Sym to be true means equality of operands
694 ///          false if it means disequality of operands
695 ///          None otherwise
696 Optional<bool> meansEquality(const SymSymExpr *Sym) {
697   switch (Sym->getOpcode()) {
698   case BO_Sub:
699     // This case is: A - B != 0 -> disequality check.
700     return false;
701   case BO_EQ:
702     // This case is: A == B != 0 -> equality check.
703     return true;
704   case BO_NE:
705     // This case is: A != B != 0 -> diseqiality check.
706     return false;
707   default:
708     return llvm::None;
709   }
710 }
711 
712 //===----------------------------------------------------------------------===//
713 //                            Intersection functions
714 //===----------------------------------------------------------------------===//
715 
716 template <class SecondTy, class... RestTy>
717 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
718                                          SecondTy Second, RestTy... Tail);
719 
720 template <class... RangeTy> struct IntersectionTraits;
721 
722 template <class... TailTy> struct IntersectionTraits<RangeSet, TailTy...> {
723   // Found RangeSet, no need to check any further
724   using Type = RangeSet;
725 };
726 
727 template <> struct IntersectionTraits<> {
728   // We ran out of types, and we didn't find any RangeSet, so the result should
729   // be optional.
730   using Type = Optional<RangeSet>;
731 };
732 
733 template <class OptionalOrPointer, class... TailTy>
734 struct IntersectionTraits<OptionalOrPointer, TailTy...> {
735   // If current type is Optional or a raw pointer, we should keep looking.
736   using Type = typename IntersectionTraits<TailTy...>::Type;
737 };
738 
739 template <class EndTy>
740 LLVM_NODISCARD inline EndTy intersect(RangeSet::Factory &F, EndTy End) {
741   // If the list contains only RangeSet or Optional<RangeSet>, simply return
742   // that range set.
743   return End;
744 }
745 
746 LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED inline Optional<RangeSet>
747 intersect(RangeSet::Factory &F, const RangeSet *End) {
748   // This is an extraneous conversion from a raw pointer into Optional<RangeSet>
749   if (End) {
750     return *End;
751   }
752   return llvm::None;
753 }
754 
755 template <class... RestTy>
756 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
757                                          RangeSet Second, RestTy... Tail) {
758   // Here we call either the <RangeSet,RangeSet,...> or <RangeSet,...> version
759   // of the function and can be sure that the result is RangeSet.
760   return intersect(F, F.intersect(Head, Second), Tail...);
761 }
762 
763 template <class SecondTy, class... RestTy>
764 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
765                                          SecondTy Second, RestTy... Tail) {
766   if (Second) {
767     // Here we call the <RangeSet,RangeSet,...> version of the function...
768     return intersect(F, Head, *Second, Tail...);
769   }
770   // ...and here it is either <RangeSet,RangeSet,...> or <RangeSet,...>, which
771   // means that the result is definitely RangeSet.
772   return intersect(F, Head, Tail...);
773 }
774 
775 /// Main generic intersect function.
776 /// It intersects all of the given range sets.  If some of the given arguments
777 /// don't hold a range set (nullptr or llvm::None), the function will skip them.
778 ///
779 /// Available representations for the arguments are:
780 ///   * RangeSet
781 ///   * Optional<RangeSet>
782 ///   * RangeSet *
783 /// Pointer to a RangeSet is automatically assumed to be nullable and will get
784 /// checked as well as the optional version.  If this behaviour is undesired,
785 /// please dereference the pointer in the call.
786 ///
787 /// Return type depends on the arguments' types.  If we can be sure in compile
788 /// time that there will be a range set as a result, the returning type is
789 /// simply RangeSet, in other cases we have to back off to Optional<RangeSet>.
790 ///
791 /// Please, prefer optional range sets to raw pointers.  If the last argument is
792 /// a raw pointer and all previous arguments are None, it will cost one
793 /// additional check to convert RangeSet * into Optional<RangeSet>.
794 template <class HeadTy, class SecondTy, class... RestTy>
795 LLVM_NODISCARD inline
796     typename IntersectionTraits<HeadTy, SecondTy, RestTy...>::Type
797     intersect(RangeSet::Factory &F, HeadTy Head, SecondTy Second,
798               RestTy... Tail) {
799   if (Head) {
800     return intersect(F, *Head, Second, Tail...);
801   }
802   return intersect(F, Second, Tail...);
803 }
804 
805 //===----------------------------------------------------------------------===//
806 //                           Symbolic reasoning logic
807 //===----------------------------------------------------------------------===//
808 
809 /// A little component aggregating all of the reasoning we have about
810 /// the ranges of symbolic expressions.
811 ///
812 /// Even when we don't know the exact values of the operands, we still
813 /// can get a pretty good estimate of the result's range.
814 class SymbolicRangeInferrer
815     : public SymExprVisitor<SymbolicRangeInferrer, RangeSet> {
816 public:
817   template <class SourceType>
818   static RangeSet inferRange(RangeSet::Factory &F, ProgramStateRef State,
819                              SourceType Origin) {
820     SymbolicRangeInferrer Inferrer(F, State);
821     return Inferrer.infer(Origin);
822   }
823 
824   RangeSet VisitSymExpr(SymbolRef Sym) {
825     // If we got to this function, the actual type of the symbolic
826     // expression is not supported for advanced inference.
827     // In this case, we simply backoff to the default "let's simply
828     // infer the range from the expression's type".
829     return infer(Sym->getType());
830   }
831 
832   RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
833     return VisitBinaryOperator(Sym);
834   }
835 
836   RangeSet VisitIntSymExpr(const IntSymExpr *Sym) {
837     return VisitBinaryOperator(Sym);
838   }
839 
840   RangeSet VisitSymSymExpr(const SymSymExpr *Sym) {
841     return intersect(
842         RangeFactory,
843         // If Sym is (dis)equality, we might have some information
844         // on that in our equality classes data structure.
845         getRangeForEqualities(Sym),
846         // And we should always check what we can get from the operands.
847         VisitBinaryOperator(Sym));
848   }
849 
850 private:
851   SymbolicRangeInferrer(RangeSet::Factory &F, ProgramStateRef S)
852       : ValueFactory(F.getValueFactory()), RangeFactory(F), State(S) {}
853 
854   /// Infer range information from the given integer constant.
855   ///
856   /// It's not a real "inference", but is here for operating with
857   /// sub-expressions in a more polymorphic manner.
858   RangeSet inferAs(const llvm::APSInt &Val, QualType) {
859     return {RangeFactory, Val};
860   }
861 
862   /// Infer range information from symbol in the context of the given type.
863   RangeSet inferAs(SymbolRef Sym, QualType DestType) {
864     QualType ActualType = Sym->getType();
865     // Check that we can reason about the symbol at all.
866     if (ActualType->isIntegralOrEnumerationType() ||
867         Loc::isLocType(ActualType)) {
868       return infer(Sym);
869     }
870     // Otherwise, let's simply infer from the destination type.
871     // We couldn't figure out nothing else about that expression.
872     return infer(DestType);
873   }
874 
875   RangeSet infer(SymbolRef Sym) {
876     return intersect(
877         RangeFactory,
878         // Of course, we should take the constraint directly associated with
879         // this symbol into consideration.
880         getConstraint(State, Sym),
881         // If Sym is a difference of symbols A - B, then maybe we have range
882         // set stored for B - A.
883         //
884         // If we have range set stored for both A - B and B - A then
885         // calculate the effective range set by intersecting the range set
886         // for A - B and the negated range set of B - A.
887         getRangeForNegatedSub(Sym),
888         // If Sym is a comparison expression (except <=>),
889         // find any other comparisons with the same operands.
890         // See function description.
891         getRangeForComparisonSymbol(Sym),
892         // Apart from the Sym itself, we can infer quite a lot if we look
893         // into subexpressions of Sym.
894         Visit(Sym));
895   }
896 
897   RangeSet infer(EquivalenceClass Class) {
898     if (const RangeSet *AssociatedConstraint = getConstraint(State, Class))
899       return *AssociatedConstraint;
900 
901     return infer(Class.getType());
902   }
903 
904   /// Infer range information solely from the type.
905   RangeSet infer(QualType T) {
906     // Lazily generate a new RangeSet representing all possible values for the
907     // given symbol type.
908     RangeSet Result(RangeFactory, ValueFactory.getMinValue(T),
909                     ValueFactory.getMaxValue(T));
910 
911     // References are known to be non-zero.
912     if (T->isReferenceType())
913       return assumeNonZero(Result, T);
914 
915     return Result;
916   }
917 
918   template <class BinarySymExprTy>
919   RangeSet VisitBinaryOperator(const BinarySymExprTy *Sym) {
920     // TODO #1: VisitBinaryOperator implementation might not make a good
921     // use of the inferred ranges.  In this case, we might be calculating
922     // everything for nothing.  This being said, we should introduce some
923     // sort of laziness mechanism here.
924     //
925     // TODO #2: We didn't go into the nested expressions before, so it
926     // might cause us spending much more time doing the inference.
927     // This can be a problem for deeply nested expressions that are
928     // involved in conditions and get tested continuously.  We definitely
929     // need to address this issue and introduce some sort of caching
930     // in here.
931     QualType ResultType = Sym->getType();
932     return VisitBinaryOperator(inferAs(Sym->getLHS(), ResultType),
933                                Sym->getOpcode(),
934                                inferAs(Sym->getRHS(), ResultType), ResultType);
935   }
936 
937   RangeSet VisitBinaryOperator(RangeSet LHS, BinaryOperator::Opcode Op,
938                                RangeSet RHS, QualType T) {
939     switch (Op) {
940     case BO_Or:
941       return VisitBinaryOperator<BO_Or>(LHS, RHS, T);
942     case BO_And:
943       return VisitBinaryOperator<BO_And>(LHS, RHS, T);
944     case BO_Rem:
945       return VisitBinaryOperator<BO_Rem>(LHS, RHS, T);
946     default:
947       return infer(T);
948     }
949   }
950 
951   //===----------------------------------------------------------------------===//
952   //                         Ranges and operators
953   //===----------------------------------------------------------------------===//
954 
955   /// Return a rough approximation of the given range set.
956   ///
957   /// For the range set:
958   ///   { [x_0, y_0], [x_1, y_1], ... , [x_N, y_N] }
959   /// it will return the range [x_0, y_N].
960   static Range fillGaps(RangeSet Origin) {
961     assert(!Origin.isEmpty());
962     return {Origin.getMinValue(), Origin.getMaxValue()};
963   }
964 
965   /// Try to convert given range into the given type.
966   ///
967   /// It will return llvm::None only when the trivial conversion is possible.
968   llvm::Optional<Range> convert(const Range &Origin, APSIntType To) {
969     if (To.testInRange(Origin.From(), false) != APSIntType::RTR_Within ||
970         To.testInRange(Origin.To(), false) != APSIntType::RTR_Within) {
971       return llvm::None;
972     }
973     return Range(ValueFactory.Convert(To, Origin.From()),
974                  ValueFactory.Convert(To, Origin.To()));
975   }
976 
977   template <BinaryOperator::Opcode Op>
978   RangeSet VisitBinaryOperator(RangeSet LHS, RangeSet RHS, QualType T) {
979     // We should propagate information about unfeasbility of one of the
980     // operands to the resulting range.
981     if (LHS.isEmpty() || RHS.isEmpty()) {
982       return RangeFactory.getEmptySet();
983     }
984 
985     Range CoarseLHS = fillGaps(LHS);
986     Range CoarseRHS = fillGaps(RHS);
987 
988     APSIntType ResultType = ValueFactory.getAPSIntType(T);
989 
990     // We need to convert ranges to the resulting type, so we can compare values
991     // and combine them in a meaningful (in terms of the given operation) way.
992     auto ConvertedCoarseLHS = convert(CoarseLHS, ResultType);
993     auto ConvertedCoarseRHS = convert(CoarseRHS, ResultType);
994 
995     // It is hard to reason about ranges when conversion changes
996     // borders of the ranges.
997     if (!ConvertedCoarseLHS || !ConvertedCoarseRHS) {
998       return infer(T);
999     }
1000 
1001     return VisitBinaryOperator<Op>(*ConvertedCoarseLHS, *ConvertedCoarseRHS, T);
1002   }
1003 
1004   template <BinaryOperator::Opcode Op>
1005   RangeSet VisitBinaryOperator(Range LHS, Range RHS, QualType T) {
1006     return infer(T);
1007   }
1008 
1009   /// Return a symmetrical range for the given range and type.
1010   ///
1011   /// If T is signed, return the smallest range [-x..x] that covers the original
1012   /// range, or [-min(T), max(T)] if the aforementioned symmetric range doesn't
1013   /// exist due to original range covering min(T)).
1014   ///
1015   /// If T is unsigned, return the smallest range [0..x] that covers the
1016   /// original range.
1017   Range getSymmetricalRange(Range Origin, QualType T) {
1018     APSIntType RangeType = ValueFactory.getAPSIntType(T);
1019 
1020     if (RangeType.isUnsigned()) {
1021       return Range(ValueFactory.getMinValue(RangeType), Origin.To());
1022     }
1023 
1024     if (Origin.From().isMinSignedValue()) {
1025       // If mini is a minimal signed value, absolute value of it is greater
1026       // than the maximal signed value.  In order to avoid these
1027       // complications, we simply return the whole range.
1028       return {ValueFactory.getMinValue(RangeType),
1029               ValueFactory.getMaxValue(RangeType)};
1030     }
1031 
1032     // At this point, we are sure that the type is signed and we can safely
1033     // use unary - operator.
1034     //
1035     // While calculating absolute maximum, we can use the following formula
1036     // because of these reasons:
1037     //   * If From >= 0 then To >= From and To >= -From.
1038     //     AbsMax == To == max(To, -From)
1039     //   * If To <= 0 then -From >= -To and -From >= From.
1040     //     AbsMax == -From == max(-From, To)
1041     //   * Otherwise, From <= 0, To >= 0, and
1042     //     AbsMax == max(abs(From), abs(To))
1043     llvm::APSInt AbsMax = std::max(-Origin.From(), Origin.To());
1044 
1045     // Intersection is guaranteed to be non-empty.
1046     return {ValueFactory.getValue(-AbsMax), ValueFactory.getValue(AbsMax)};
1047   }
1048 
1049   /// Return a range set subtracting zero from \p Domain.
1050   RangeSet assumeNonZero(RangeSet Domain, QualType T) {
1051     APSIntType IntType = ValueFactory.getAPSIntType(T);
1052     return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
1053   }
1054 
1055   // FIXME: Once SValBuilder supports unary minus, we should use SValBuilder to
1056   //        obtain the negated symbolic expression instead of constructing the
1057   //        symbol manually. This will allow us to support finding ranges of not
1058   //        only negated SymSymExpr-type expressions, but also of other, simpler
1059   //        expressions which we currently do not know how to negate.
1060   Optional<RangeSet> getRangeForNegatedSub(SymbolRef Sym) {
1061     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(Sym)) {
1062       if (SSE->getOpcode() == BO_Sub) {
1063         QualType T = Sym->getType();
1064 
1065         // Do not negate unsigned ranges
1066         if (!T->isUnsignedIntegerOrEnumerationType() &&
1067             !T->isSignedIntegerOrEnumerationType())
1068           return llvm::None;
1069 
1070         SymbolManager &SymMgr = State->getSymbolManager();
1071         SymbolRef NegatedSym =
1072             SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), T);
1073 
1074         if (const RangeSet *NegatedRange = getConstraint(State, NegatedSym)) {
1075           return RangeFactory.negate(*NegatedRange);
1076         }
1077       }
1078     }
1079     return llvm::None;
1080   }
1081 
1082   // Returns ranges only for binary comparison operators (except <=>)
1083   // when left and right operands are symbolic values.
1084   // Finds any other comparisons with the same operands.
1085   // Then do logical calculations and refuse impossible branches.
1086   // E.g. (x < y) and (x > y) at the same time are impossible.
1087   // E.g. (x >= y) and (x != y) at the same time makes (x > y) true only.
1088   // E.g. (x == y) and (y == x) are just reversed but the same.
1089   // It covers all possible combinations (see CmpOpTable description).
1090   // Note that `x` and `y` can also stand for subexpressions,
1091   // not only for actual symbols.
1092   Optional<RangeSet> getRangeForComparisonSymbol(SymbolRef Sym) {
1093     const auto *SSE = dyn_cast<SymSymExpr>(Sym);
1094     if (!SSE)
1095       return llvm::None;
1096 
1097     BinaryOperatorKind CurrentOP = SSE->getOpcode();
1098 
1099     // We currently do not support <=> (C++20).
1100     if (!BinaryOperator::isComparisonOp(CurrentOP) || (CurrentOP == BO_Cmp))
1101       return llvm::None;
1102 
1103     static const OperatorRelationsTable CmpOpTable{};
1104 
1105     const SymExpr *LHS = SSE->getLHS();
1106     const SymExpr *RHS = SSE->getRHS();
1107     QualType T = SSE->getType();
1108 
1109     SymbolManager &SymMgr = State->getSymbolManager();
1110 
1111     int UnknownStates = 0;
1112 
1113     // Loop goes through all of the columns exept the last one ('UnknownX2').
1114     // We treat `UnknownX2` column separately at the end of the loop body.
1115     for (size_t i = 0; i < CmpOpTable.getCmpOpCount(); ++i) {
1116 
1117       // Let's find an expression e.g. (x < y).
1118       BinaryOperatorKind QueriedOP = OperatorRelationsTable::getOpFromIndex(i);
1119       const SymSymExpr *SymSym = SymMgr.getSymSymExpr(LHS, QueriedOP, RHS, T);
1120       const RangeSet *QueriedRangeSet = getConstraint(State, SymSym);
1121 
1122       // If ranges were not previously found,
1123       // try to find a reversed expression (y > x).
1124       if (!QueriedRangeSet) {
1125         const BinaryOperatorKind ROP =
1126             BinaryOperator::reverseComparisonOp(QueriedOP);
1127         SymSym = SymMgr.getSymSymExpr(RHS, ROP, LHS, T);
1128         QueriedRangeSet = getConstraint(State, SymSym);
1129       }
1130 
1131       if (!QueriedRangeSet || QueriedRangeSet->isEmpty())
1132         continue;
1133 
1134       const llvm::APSInt *ConcreteValue = QueriedRangeSet->getConcreteValue();
1135       const bool isInFalseBranch =
1136           ConcreteValue ? (*ConcreteValue == 0) : false;
1137 
1138       // If it is a false branch, we shall be guided by opposite operator,
1139       // because the table is made assuming we are in the true branch.
1140       // E.g. when (x <= y) is false, then (x > y) is true.
1141       if (isInFalseBranch)
1142         QueriedOP = BinaryOperator::negateComparisonOp(QueriedOP);
1143 
1144       OperatorRelationsTable::TriStateKind BranchState =
1145           CmpOpTable.getCmpOpState(CurrentOP, QueriedOP);
1146 
1147       if (BranchState == OperatorRelationsTable::Unknown) {
1148         if (++UnknownStates == 2)
1149           // If we met both Unknown states.
1150           // if (x <= y)    // assume true
1151           //   if (x != y)  // assume true
1152           //     if (x < y) // would be also true
1153           // Get a state from `UnknownX2` column.
1154           BranchState = CmpOpTable.getCmpOpStateForUnknownX2(CurrentOP);
1155         else
1156           continue;
1157       }
1158 
1159       return (BranchState == OperatorRelationsTable::True) ? getTrueRange(T)
1160                                                            : getFalseRange(T);
1161     }
1162 
1163     return llvm::None;
1164   }
1165 
1166   Optional<RangeSet> getRangeForEqualities(const SymSymExpr *Sym) {
1167     Optional<bool> Equality = meansEquality(Sym);
1168 
1169     if (!Equality)
1170       return llvm::None;
1171 
1172     if (Optional<bool> AreEqual =
1173             EquivalenceClass::areEqual(State, Sym->getLHS(), Sym->getRHS())) {
1174       // Here we cover two cases at once:
1175       //   * if Sym is equality and its operands are known to be equal -> true
1176       //   * if Sym is disequality and its operands are disequal -> true
1177       if (*AreEqual == *Equality) {
1178         return getTrueRange(Sym->getType());
1179       }
1180       // Opposite combinations result in false.
1181       return getFalseRange(Sym->getType());
1182     }
1183 
1184     return llvm::None;
1185   }
1186 
1187   RangeSet getTrueRange(QualType T) {
1188     RangeSet TypeRange = infer(T);
1189     return assumeNonZero(TypeRange, T);
1190   }
1191 
1192   RangeSet getFalseRange(QualType T) {
1193     const llvm::APSInt &Zero = ValueFactory.getValue(0, T);
1194     return RangeSet(RangeFactory, Zero);
1195   }
1196 
1197   BasicValueFactory &ValueFactory;
1198   RangeSet::Factory &RangeFactory;
1199   ProgramStateRef State;
1200 };
1201 
1202 //===----------------------------------------------------------------------===//
1203 //               Range-based reasoning about symbolic operations
1204 //===----------------------------------------------------------------------===//
1205 
1206 template <>
1207 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Or>(Range LHS, Range RHS,
1208                                                            QualType T) {
1209   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1210   llvm::APSInt Zero = ResultType.getZeroValue();
1211 
1212   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1213   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1214 
1215   bool IsLHSNegative = LHS.To() < Zero;
1216   bool IsRHSNegative = RHS.To() < Zero;
1217 
1218   // Check if both ranges have the same sign.
1219   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1220       (IsLHSNegative && IsRHSNegative)) {
1221     // The result is definitely greater or equal than any of the operands.
1222     const llvm::APSInt &Min = std::max(LHS.From(), RHS.From());
1223 
1224     // We estimate maximal value for positives as the maximal value for the
1225     // given type.  For negatives, we estimate it with -1 (e.g. 0x11111111).
1226     //
1227     // TODO: We basically, limit the resulting range from below, but don't do
1228     //       anything with the upper bound.
1229     //
1230     //       For positive operands, it can be done as follows: for the upper
1231     //       bound of LHS and RHS we calculate the most significant bit set.
1232     //       Let's call it the N-th bit.  Then we can estimate the maximal
1233     //       number to be 2^(N+1)-1, i.e. the number with all the bits up to
1234     //       the N-th bit set.
1235     const llvm::APSInt &Max = IsLHSNegative
1236                                   ? ValueFactory.getValue(--Zero)
1237                                   : ValueFactory.getMaxValue(ResultType);
1238 
1239     return {RangeFactory, ValueFactory.getValue(Min), Max};
1240   }
1241 
1242   // Otherwise, let's check if at least one of the operands is negative.
1243   if (IsLHSNegative || IsRHSNegative) {
1244     // This means that the result is definitely negative as well.
1245     return {RangeFactory, ValueFactory.getMinValue(ResultType),
1246             ValueFactory.getValue(--Zero)};
1247   }
1248 
1249   RangeSet DefaultRange = infer(T);
1250 
1251   // It is pretty hard to reason about operands with different signs
1252   // (and especially with possibly different signs).  We simply check if it
1253   // can be zero.  In order to conclude that the result could not be zero,
1254   // at least one of the operands should be definitely not zero itself.
1255   if (!LHS.Includes(Zero) || !RHS.Includes(Zero)) {
1256     return assumeNonZero(DefaultRange, T);
1257   }
1258 
1259   // Nothing much else to do here.
1260   return DefaultRange;
1261 }
1262 
1263 template <>
1264 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_And>(Range LHS,
1265                                                             Range RHS,
1266                                                             QualType T) {
1267   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1268   llvm::APSInt Zero = ResultType.getZeroValue();
1269 
1270   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1271   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1272 
1273   bool IsLHSNegative = LHS.To() < Zero;
1274   bool IsRHSNegative = RHS.To() < Zero;
1275 
1276   // Check if both ranges have the same sign.
1277   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1278       (IsLHSNegative && IsRHSNegative)) {
1279     // The result is definitely less or equal than any of the operands.
1280     const llvm::APSInt &Max = std::min(LHS.To(), RHS.To());
1281 
1282     // We conservatively estimate lower bound to be the smallest positive
1283     // or negative value corresponding to the sign of the operands.
1284     const llvm::APSInt &Min = IsLHSNegative
1285                                   ? ValueFactory.getMinValue(ResultType)
1286                                   : ValueFactory.getValue(Zero);
1287 
1288     return {RangeFactory, Min, Max};
1289   }
1290 
1291   // Otherwise, let's check if at least one of the operands is positive.
1292   if (IsLHSPositiveOrZero || IsRHSPositiveOrZero) {
1293     // This makes result definitely positive.
1294     //
1295     // We can also reason about a maximal value by finding the maximal
1296     // value of the positive operand.
1297     const llvm::APSInt &Max = IsLHSPositiveOrZero ? LHS.To() : RHS.To();
1298 
1299     // The minimal value on the other hand is much harder to reason about.
1300     // The only thing we know for sure is that the result is positive.
1301     return {RangeFactory, ValueFactory.getValue(Zero),
1302             ValueFactory.getValue(Max)};
1303   }
1304 
1305   // Nothing much else to do here.
1306   return infer(T);
1307 }
1308 
1309 template <>
1310 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Rem>(Range LHS,
1311                                                             Range RHS,
1312                                                             QualType T) {
1313   llvm::APSInt Zero = ValueFactory.getAPSIntType(T).getZeroValue();
1314 
1315   Range ConservativeRange = getSymmetricalRange(RHS, T);
1316 
1317   llvm::APSInt Max = ConservativeRange.To();
1318   llvm::APSInt Min = ConservativeRange.From();
1319 
1320   if (Max == Zero) {
1321     // It's an undefined behaviour to divide by 0 and it seems like we know
1322     // for sure that RHS is 0.  Let's say that the resulting range is
1323     // simply infeasible for that matter.
1324     return RangeFactory.getEmptySet();
1325   }
1326 
1327   // At this point, our conservative range is closed.  The result, however,
1328   // couldn't be greater than the RHS' maximal absolute value.  Because of
1329   // this reason, we turn the range into open (or half-open in case of
1330   // unsigned integers).
1331   //
1332   // While we operate on integer values, an open interval (a, b) can be easily
1333   // represented by the closed interval [a + 1, b - 1].  And this is exactly
1334   // what we do next.
1335   //
1336   // If we are dealing with unsigned case, we shouldn't move the lower bound.
1337   if (Min.isSigned()) {
1338     ++Min;
1339   }
1340   --Max;
1341 
1342   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1343   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1344 
1345   // Remainder operator results with negative operands is implementation
1346   // defined.  Positive cases are much easier to reason about though.
1347   if (IsLHSPositiveOrZero && IsRHSPositiveOrZero) {
1348     // If maximal value of LHS is less than maximal value of RHS,
1349     // the result won't get greater than LHS.To().
1350     Max = std::min(LHS.To(), Max);
1351     // We want to check if it is a situation similar to the following:
1352     //
1353     // <------------|---[  LHS  ]--------[  RHS  ]----->
1354     //  -INF        0                              +INF
1355     //
1356     // In this situation, we can conclude that (LHS / RHS) == 0 and
1357     // (LHS % RHS) == LHS.
1358     Min = LHS.To() < RHS.From() ? LHS.From() : Zero;
1359   }
1360 
1361   // Nevertheless, the symmetrical range for RHS is a conservative estimate
1362   // for any sign of either LHS, or RHS.
1363   return {RangeFactory, ValueFactory.getValue(Min), ValueFactory.getValue(Max)};
1364 }
1365 
1366 //===----------------------------------------------------------------------===//
1367 //                         Constraint assignment logic
1368 //===----------------------------------------------------------------------===//
1369 
1370 /// ConstraintAssignorBase is a small utility class that unifies visitor
1371 /// for ranges with a visitor for constraints (rangeset/range/constant).
1372 ///
1373 /// It is designed to have one derived class, but generally it can have more.
1374 /// Derived class can control which types we handle by defining methods of the
1375 /// following form:
1376 ///
1377 ///   bool handle${SYMBOL}To${CONSTRAINT}(const SYMBOL *Sym,
1378 ///                                       CONSTRAINT Constraint);
1379 ///
1380 /// where SYMBOL is the type of the symbol (e.g. SymSymExpr, SymbolCast, etc.)
1381 ///       CONSTRAINT is the type of constraint (RangeSet/Range/Const)
1382 ///       return value signifies whether we should try other handle methods
1383 ///          (i.e. false would mean to stop right after calling this method)
1384 template <class Derived> class ConstraintAssignorBase {
1385 public:
1386   using Const = const llvm::APSInt &;
1387 
1388 #define DISPATCH(CLASS) return assign##CLASS##Impl(cast<CLASS>(Sym), Constraint)
1389 
1390 #define ASSIGN(CLASS, TO, SYM, CONSTRAINT)                                     \
1391   if (!static_cast<Derived *>(this)->assign##CLASS##To##TO(SYM, CONSTRAINT))   \
1392   return false
1393 
1394   void assign(SymbolRef Sym, RangeSet Constraint) {
1395     assignImpl(Sym, Constraint);
1396   }
1397 
1398   bool assignImpl(SymbolRef Sym, RangeSet Constraint) {
1399     switch (Sym->getKind()) {
1400 #define SYMBOL(Id, Parent)                                                     \
1401   case SymExpr::Id##Kind:                                                      \
1402     DISPATCH(Id);
1403 #include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
1404     }
1405     llvm_unreachable("Unknown SymExpr kind!");
1406   }
1407 
1408 #define DEFAULT_ASSIGN(Id)                                                     \
1409   bool assign##Id##To##RangeSet(const Id *Sym, RangeSet Constraint) {          \
1410     return true;                                                               \
1411   }                                                                            \
1412   bool assign##Id##To##Range(const Id *Sym, Range Constraint) { return true; } \
1413   bool assign##Id##To##Const(const Id *Sym, Const Constraint) { return true; }
1414 
1415   // When we dispatch for constraint types, we first try to check
1416   // if the new constraint is the constant and try the corresponding
1417   // assignor methods.  If it didn't interrupt, we can proceed to the
1418   // range, and finally to the range set.
1419 #define CONSTRAINT_DISPATCH(Id)                                                \
1420   if (const llvm::APSInt *Const = Constraint.getConcreteValue()) {             \
1421     ASSIGN(Id, Const, Sym, *Const);                                            \
1422   }                                                                            \
1423   if (Constraint.size() == 1) {                                                \
1424     ASSIGN(Id, Range, Sym, *Constraint.begin());                               \
1425   }                                                                            \
1426   ASSIGN(Id, RangeSet, Sym, Constraint)
1427 
1428   // Our internal assign method first tries to call assignor methods for all
1429   // constraint types that apply.  And if not interrupted, continues with its
1430   // parent class.
1431 #define SYMBOL(Id, Parent)                                                     \
1432   bool assign##Id##Impl(const Id *Sym, RangeSet Constraint) {                  \
1433     CONSTRAINT_DISPATCH(Id);                                                   \
1434     DISPATCH(Parent);                                                          \
1435   }                                                                            \
1436   DEFAULT_ASSIGN(Id)
1437 #define ABSTRACT_SYMBOL(Id, Parent) SYMBOL(Id, Parent)
1438 #include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
1439 
1440   // Default implementations for the top class that doesn't have parents.
1441   bool assignSymExprImpl(const SymExpr *Sym, RangeSet Constraint) {
1442     CONSTRAINT_DISPATCH(SymExpr);
1443     return true;
1444   }
1445   DEFAULT_ASSIGN(SymExpr);
1446 
1447 #undef DISPATCH
1448 #undef CONSTRAINT_DISPATCH
1449 #undef DEFAULT_ASSIGN
1450 #undef ASSIGN
1451 };
1452 
1453 /// A little component aggregating all of the reasoning we have about
1454 /// assigning new constraints to symbols.
1455 ///
1456 /// The main purpose of this class is to associate constraints to symbols,
1457 /// and impose additional constraints on other symbols, when we can imply
1458 /// them.
1459 ///
1460 /// It has a nice symmetry with SymbolicRangeInferrer.  When the latter
1461 /// can provide more precise ranges by looking into the operands of the
1462 /// expression in question, ConstraintAssignor looks into the operands
1463 /// to see if we can imply more from the new constraint.
1464 class ConstraintAssignor : public ConstraintAssignorBase<ConstraintAssignor> {
1465 public:
1466   template <class ClassOrSymbol>
1467   LLVM_NODISCARD static ProgramStateRef
1468   assign(ProgramStateRef State, SValBuilder &Builder, RangeSet::Factory &F,
1469          ClassOrSymbol CoS, RangeSet NewConstraint) {
1470     if (!State || NewConstraint.isEmpty())
1471       return nullptr;
1472 
1473     ConstraintAssignor Assignor{State, Builder, F};
1474     return Assignor.assign(CoS, NewConstraint);
1475   }
1476 
1477   inline bool assignSymExprToConst(const SymExpr *Sym, Const Constraint);
1478   inline bool assignSymSymExprToRangeSet(const SymSymExpr *Sym,
1479                                          RangeSet Constraint);
1480 
1481 private:
1482   ConstraintAssignor(ProgramStateRef State, SValBuilder &Builder,
1483                      RangeSet::Factory &F)
1484       : State(State), Builder(Builder), RangeFactory(F) {}
1485   using Base = ConstraintAssignorBase<ConstraintAssignor>;
1486 
1487   /// Base method for handling new constraints for symbols.
1488   LLVM_NODISCARD ProgramStateRef assign(SymbolRef Sym, RangeSet NewConstraint) {
1489     // All constraints are actually associated with equivalence classes, and
1490     // that's what we are going to do first.
1491     State = assign(EquivalenceClass::find(State, Sym), NewConstraint);
1492     if (!State)
1493       return nullptr;
1494 
1495     // And after that we can check what other things we can get from this
1496     // constraint.
1497     Base::assign(Sym, NewConstraint);
1498     return State;
1499   }
1500 
1501   /// Base method for handling new constraints for classes.
1502   LLVM_NODISCARD ProgramStateRef assign(EquivalenceClass Class,
1503                                         RangeSet NewConstraint) {
1504     // There is a chance that we might need to update constraints for the
1505     // classes that are known to be disequal to Class.
1506     //
1507     // In order for this to be even possible, the new constraint should
1508     // be simply a constant because we can't reason about range disequalities.
1509     if (const llvm::APSInt *Point = NewConstraint.getConcreteValue()) {
1510 
1511       ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1512       ConstraintRangeTy::Factory &CF = State->get_context<ConstraintRange>();
1513 
1514       // Add new constraint.
1515       Constraints = CF.add(Constraints, Class, NewConstraint);
1516 
1517       for (EquivalenceClass DisequalClass : Class.getDisequalClasses(State)) {
1518         RangeSet UpdatedConstraint = SymbolicRangeInferrer::inferRange(
1519             RangeFactory, State, DisequalClass);
1520 
1521         UpdatedConstraint = RangeFactory.deletePoint(UpdatedConstraint, *Point);
1522 
1523         // If we end up with at least one of the disequal classes to be
1524         // constrained with an empty range-set, the state is infeasible.
1525         if (UpdatedConstraint.isEmpty())
1526           return nullptr;
1527 
1528         Constraints = CF.add(Constraints, DisequalClass, UpdatedConstraint);
1529       }
1530       assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1531                                          "a state with infeasible constraints");
1532 
1533       return setConstraints(State, Constraints);
1534     }
1535 
1536     return setConstraint(State, Class, NewConstraint);
1537   }
1538 
1539   ProgramStateRef trackDisequality(ProgramStateRef State, SymbolRef LHS,
1540                                    SymbolRef RHS) {
1541     return EquivalenceClass::markDisequal(RangeFactory, State, LHS, RHS);
1542   }
1543 
1544   ProgramStateRef trackEquality(ProgramStateRef State, SymbolRef LHS,
1545                                 SymbolRef RHS) {
1546     return EquivalenceClass::merge(RangeFactory, State, LHS, RHS);
1547   }
1548 
1549   LLVM_NODISCARD Optional<bool> interpreteAsBool(RangeSet Constraint) {
1550     assert(!Constraint.isEmpty() && "Empty ranges shouldn't get here");
1551 
1552     if (Constraint.getConcreteValue())
1553       return !Constraint.getConcreteValue()->isNullValue();
1554 
1555     APSIntType T{Constraint.getMinValue()};
1556     Const Zero = T.getZeroValue();
1557     if (!Constraint.contains(Zero))
1558       return true;
1559 
1560     return llvm::None;
1561   }
1562 
1563   ProgramStateRef State;
1564   SValBuilder &Builder;
1565   RangeSet::Factory &RangeFactory;
1566 };
1567 
1568 //===----------------------------------------------------------------------===//
1569 //                  Constraint manager implementation details
1570 //===----------------------------------------------------------------------===//
1571 
1572 class RangeConstraintManager : public RangedConstraintManager {
1573 public:
1574   RangeConstraintManager(ExprEngine *EE, SValBuilder &SVB)
1575       : RangedConstraintManager(EE, SVB), F(getBasicVals()) {}
1576 
1577   //===------------------------------------------------------------------===//
1578   // Implementation for interface from ConstraintManager.
1579   //===------------------------------------------------------------------===//
1580 
1581   bool haveEqualConstraints(ProgramStateRef S1,
1582                             ProgramStateRef S2) const override {
1583     // NOTE: ClassMembers are as simple as back pointers for ClassMap,
1584     //       so comparing constraint ranges and class maps should be
1585     //       sufficient.
1586     return S1->get<ConstraintRange>() == S2->get<ConstraintRange>() &&
1587            S1->get<ClassMap>() == S2->get<ClassMap>();
1588   }
1589 
1590   bool canReasonAbout(SVal X) const override;
1591 
1592   ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override;
1593 
1594   const llvm::APSInt *getSymVal(ProgramStateRef State,
1595                                 SymbolRef Sym) const override;
1596 
1597   ProgramStateRef removeDeadBindings(ProgramStateRef State,
1598                                      SymbolReaper &SymReaper) override;
1599 
1600   void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
1601                  unsigned int Space = 0, bool IsDot = false) const override;
1602 
1603   //===------------------------------------------------------------------===//
1604   // Implementation for interface from RangedConstraintManager.
1605   //===------------------------------------------------------------------===//
1606 
1607   ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym,
1608                               const llvm::APSInt &V,
1609                               const llvm::APSInt &Adjustment) override;
1610 
1611   ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym,
1612                               const llvm::APSInt &V,
1613                               const llvm::APSInt &Adjustment) override;
1614 
1615   ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym,
1616                               const llvm::APSInt &V,
1617                               const llvm::APSInt &Adjustment) override;
1618 
1619   ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym,
1620                               const llvm::APSInt &V,
1621                               const llvm::APSInt &Adjustment) override;
1622 
1623   ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym,
1624                               const llvm::APSInt &V,
1625                               const llvm::APSInt &Adjustment) override;
1626 
1627   ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym,
1628                               const llvm::APSInt &V,
1629                               const llvm::APSInt &Adjustment) override;
1630 
1631   ProgramStateRef assumeSymWithinInclusiveRange(
1632       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1633       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1634 
1635   ProgramStateRef assumeSymOutsideInclusiveRange(
1636       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1637       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1638 
1639 private:
1640   RangeSet::Factory F;
1641 
1642   RangeSet getRange(ProgramStateRef State, SymbolRef Sym);
1643   RangeSet getRange(ProgramStateRef State, EquivalenceClass Class);
1644   ProgramStateRef setRange(ProgramStateRef State, SymbolRef Sym,
1645                            RangeSet Range);
1646   ProgramStateRef setRange(ProgramStateRef State, EquivalenceClass Class,
1647                            RangeSet Range);
1648 
1649   RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym,
1650                          const llvm::APSInt &Int,
1651                          const llvm::APSInt &Adjustment);
1652   RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym,
1653                          const llvm::APSInt &Int,
1654                          const llvm::APSInt &Adjustment);
1655   RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym,
1656                          const llvm::APSInt &Int,
1657                          const llvm::APSInt &Adjustment);
1658   RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS,
1659                          const llvm::APSInt &Int,
1660                          const llvm::APSInt &Adjustment);
1661   RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym,
1662                          const llvm::APSInt &Int,
1663                          const llvm::APSInt &Adjustment);
1664 };
1665 
1666 bool ConstraintAssignor::assignSymExprToConst(const SymExpr *Sym,
1667                                               const llvm::APSInt &Constraint) {
1668   llvm::SmallSet<EquivalenceClass, 4> SimplifiedClasses;
1669   // Iterate over all equivalence classes and try to simplify them.
1670   ClassMembersTy Members = State->get<ClassMembers>();
1671   for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members) {
1672     EquivalenceClass Class = ClassToSymbolSet.first;
1673     State = Class.simplify(Builder, RangeFactory, State);
1674     if (!State)
1675       return false;
1676     SimplifiedClasses.insert(Class);
1677   }
1678 
1679   // Trivial equivalence classes (those that have only one symbol member) are
1680   // not stored in the State. Thus, we must skim through the constraints as
1681   // well. And we try to simplify symbols in the constraints.
1682   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1683   for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
1684     EquivalenceClass Class = ClassConstraint.first;
1685     if (SimplifiedClasses.count(Class)) // Already simplified.
1686       continue;
1687     State = Class.simplify(Builder, RangeFactory, State);
1688     if (!State)
1689       return false;
1690   }
1691 
1692   return true;
1693 }
1694 
1695 bool ConstraintAssignor::assignSymSymExprToRangeSet(const SymSymExpr *Sym,
1696                                                     RangeSet Constraint) {
1697   Optional<bool> ConstraintAsBool = interpreteAsBool(Constraint);
1698 
1699   if (!ConstraintAsBool)
1700     return true;
1701 
1702   if (Optional<bool> Equality = meansEquality(Sym)) {
1703     // Here we cover two cases:
1704     //   * if Sym is equality and the new constraint is true -> Sym's operands
1705     //     should be marked as equal
1706     //   * if Sym is disequality and the new constraint is false -> Sym's
1707     //     operands should be also marked as equal
1708     if (*Equality == *ConstraintAsBool) {
1709       State = trackEquality(State, Sym->getLHS(), Sym->getRHS());
1710     } else {
1711       // Other combinations leave as with disequal operands.
1712       State = trackDisequality(State, Sym->getLHS(), Sym->getRHS());
1713     }
1714 
1715     if (!State)
1716       return false;
1717   }
1718 
1719   return true;
1720 }
1721 
1722 } // end anonymous namespace
1723 
1724 std::unique_ptr<ConstraintManager>
1725 ento::CreateRangeConstraintManager(ProgramStateManager &StMgr,
1726                                    ExprEngine *Eng) {
1727   return std::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder());
1728 }
1729 
1730 ConstraintMap ento::getConstraintMap(ProgramStateRef State) {
1731   ConstraintMap::Factory &F = State->get_context<ConstraintMap>();
1732   ConstraintMap Result = F.getEmptyMap();
1733 
1734   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1735   for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
1736     EquivalenceClass Class = ClassConstraint.first;
1737     SymbolSet ClassMembers = Class.getClassMembers(State);
1738     assert(!ClassMembers.isEmpty() &&
1739            "Class must always have at least one member!");
1740 
1741     SymbolRef Representative = *ClassMembers.begin();
1742     Result = F.add(Result, Representative, ClassConstraint.second);
1743   }
1744 
1745   return Result;
1746 }
1747 
1748 //===----------------------------------------------------------------------===//
1749 //                     EqualityClass implementation details
1750 //===----------------------------------------------------------------------===//
1751 
1752 inline EquivalenceClass EquivalenceClass::find(ProgramStateRef State,
1753                                                SymbolRef Sym) {
1754   assert(State && "State should not be null");
1755   assert(Sym && "Symbol should not be null");
1756   // We store far from all Symbol -> Class mappings
1757   if (const EquivalenceClass *NontrivialClass = State->get<ClassMap>(Sym))
1758     return *NontrivialClass;
1759 
1760   // This is a trivial class of Sym.
1761   return Sym;
1762 }
1763 
1764 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
1765                                                ProgramStateRef State,
1766                                                SymbolRef First,
1767                                                SymbolRef Second) {
1768   EquivalenceClass FirstClass = find(State, First);
1769   EquivalenceClass SecondClass = find(State, Second);
1770 
1771   return FirstClass.merge(F, State, SecondClass);
1772 }
1773 
1774 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
1775                                                ProgramStateRef State,
1776                                                EquivalenceClass Other) {
1777   // It is already the same class.
1778   if (*this == Other)
1779     return State;
1780 
1781   // FIXME: As of now, we support only equivalence classes of the same type.
1782   //        This limitation is connected to the lack of explicit casts in
1783   //        our symbolic expression model.
1784   //
1785   //        That means that for `int x` and `char y` we don't distinguish
1786   //        between these two very different cases:
1787   //          * `x == y`
1788   //          * `(char)x == y`
1789   //
1790   //        The moment we introduce symbolic casts, this restriction can be
1791   //        lifted.
1792   if (getType() != Other.getType())
1793     return State;
1794 
1795   SymbolSet Members = getClassMembers(State);
1796   SymbolSet OtherMembers = Other.getClassMembers(State);
1797 
1798   // We estimate the size of the class by the height of tree containing
1799   // its members.  Merging is not a trivial operation, so it's easier to
1800   // merge the smaller class into the bigger one.
1801   if (Members.getHeight() >= OtherMembers.getHeight()) {
1802     return mergeImpl(F, State, Members, Other, OtherMembers);
1803   } else {
1804     return Other.mergeImpl(F, State, OtherMembers, *this, Members);
1805   }
1806 }
1807 
1808 inline ProgramStateRef
1809 EquivalenceClass::mergeImpl(RangeSet::Factory &RangeFactory,
1810                             ProgramStateRef State, SymbolSet MyMembers,
1811                             EquivalenceClass Other, SymbolSet OtherMembers) {
1812   // Essentially what we try to recreate here is some kind of union-find
1813   // data structure.  It does have certain limitations due to persistence
1814   // and the need to remove elements from classes.
1815   //
1816   // In this setting, EquialityClass object is the representative of the class
1817   // or the parent element.  ClassMap is a mapping of class members to their
1818   // parent. Unlike the union-find structure, they all point directly to the
1819   // class representative because we don't have an opportunity to actually do
1820   // path compression when dealing with immutability.  This means that we
1821   // compress paths every time we do merges.  It also means that we lose
1822   // the main amortized complexity benefit from the original data structure.
1823   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1824   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
1825 
1826   // 1. If the merged classes have any constraints associated with them, we
1827   //    need to transfer them to the class we have left.
1828   //
1829   // Intersection here makes perfect sense because both of these constraints
1830   // must hold for the whole new class.
1831   if (Optional<RangeSet> NewClassConstraint =
1832           intersect(RangeFactory, getConstraint(State, *this),
1833                     getConstraint(State, Other))) {
1834     // NOTE: Essentially, NewClassConstraint should NEVER be infeasible because
1835     //       range inferrer shouldn't generate ranges incompatible with
1836     //       equivalence classes. However, at the moment, due to imperfections
1837     //       in the solver, it is possible and the merge function can also
1838     //       return infeasible states aka null states.
1839     if (NewClassConstraint->isEmpty())
1840       // Infeasible state
1841       return nullptr;
1842 
1843     // No need in tracking constraints of a now-dissolved class.
1844     Constraints = CRF.remove(Constraints, Other);
1845     // Assign new constraints for this class.
1846     Constraints = CRF.add(Constraints, *this, *NewClassConstraint);
1847 
1848     assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1849                                        "a state with infeasible constraints");
1850 
1851     State = State->set<ConstraintRange>(Constraints);
1852   }
1853 
1854   // 2. Get ALL equivalence-related maps
1855   ClassMapTy Classes = State->get<ClassMap>();
1856   ClassMapTy::Factory &CMF = State->get_context<ClassMap>();
1857 
1858   ClassMembersTy Members = State->get<ClassMembers>();
1859   ClassMembersTy::Factory &MF = State->get_context<ClassMembers>();
1860 
1861   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
1862   DisequalityMapTy::Factory &DF = State->get_context<DisequalityMap>();
1863 
1864   ClassSet::Factory &CF = State->get_context<ClassSet>();
1865   SymbolSet::Factory &F = getMembersFactory(State);
1866 
1867   // 2. Merge members of the Other class into the current class.
1868   SymbolSet NewClassMembers = MyMembers;
1869   for (SymbolRef Sym : OtherMembers) {
1870     NewClassMembers = F.add(NewClassMembers, Sym);
1871     // *this is now the class for all these new symbols.
1872     Classes = CMF.add(Classes, Sym, *this);
1873   }
1874 
1875   // 3. Adjust member mapping.
1876   //
1877   // No need in tracking members of a now-dissolved class.
1878   Members = MF.remove(Members, Other);
1879   // Now only the current class is mapped to all the symbols.
1880   Members = MF.add(Members, *this, NewClassMembers);
1881 
1882   // 4. Update disequality relations
1883   ClassSet DisequalToOther = Other.getDisequalClasses(DisequalityInfo, CF);
1884   // We are about to merge two classes but they are already known to be
1885   // non-equal. This is a contradiction.
1886   if (DisequalToOther.contains(*this))
1887     return nullptr;
1888 
1889   if (!DisequalToOther.isEmpty()) {
1890     ClassSet DisequalToThis = getDisequalClasses(DisequalityInfo, CF);
1891     DisequalityInfo = DF.remove(DisequalityInfo, Other);
1892 
1893     for (EquivalenceClass DisequalClass : DisequalToOther) {
1894       DisequalToThis = CF.add(DisequalToThis, DisequalClass);
1895 
1896       // Disequality is a symmetric relation meaning that if
1897       // DisequalToOther not null then the set for DisequalClass is not
1898       // empty and has at least Other.
1899       ClassSet OriginalSetLinkedToOther =
1900           *DisequalityInfo.lookup(DisequalClass);
1901 
1902       // Other will be eliminated and we should replace it with the bigger
1903       // united class.
1904       ClassSet NewSet = CF.remove(OriginalSetLinkedToOther, Other);
1905       NewSet = CF.add(NewSet, *this);
1906 
1907       DisequalityInfo = DF.add(DisequalityInfo, DisequalClass, NewSet);
1908     }
1909 
1910     DisequalityInfo = DF.add(DisequalityInfo, *this, DisequalToThis);
1911     State = State->set<DisequalityMap>(DisequalityInfo);
1912   }
1913 
1914   // 5. Update the state
1915   State = State->set<ClassMap>(Classes);
1916   State = State->set<ClassMembers>(Members);
1917 
1918   return State;
1919 }
1920 
1921 inline SymbolSet::Factory &
1922 EquivalenceClass::getMembersFactory(ProgramStateRef State) {
1923   return State->get_context<SymbolSet>();
1924 }
1925 
1926 SymbolSet EquivalenceClass::getClassMembers(ProgramStateRef State) const {
1927   if (const SymbolSet *Members = State->get<ClassMembers>(*this))
1928     return *Members;
1929 
1930   // This class is trivial, so we need to construct a set
1931   // with just that one symbol from the class.
1932   SymbolSet::Factory &F = getMembersFactory(State);
1933   return F.add(F.getEmptySet(), getRepresentativeSymbol());
1934 }
1935 
1936 bool EquivalenceClass::isTrivial(ProgramStateRef State) const {
1937   return State->get<ClassMembers>(*this) == nullptr;
1938 }
1939 
1940 bool EquivalenceClass::isTriviallyDead(ProgramStateRef State,
1941                                        SymbolReaper &Reaper) const {
1942   return isTrivial(State) && Reaper.isDead(getRepresentativeSymbol());
1943 }
1944 
1945 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
1946                                                       ProgramStateRef State,
1947                                                       SymbolRef First,
1948                                                       SymbolRef Second) {
1949   return markDisequal(RF, State, find(State, First), find(State, Second));
1950 }
1951 
1952 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
1953                                                       ProgramStateRef State,
1954                                                       EquivalenceClass First,
1955                                                       EquivalenceClass Second) {
1956   return First.markDisequal(RF, State, Second);
1957 }
1958 
1959 inline ProgramStateRef
1960 EquivalenceClass::markDisequal(RangeSet::Factory &RF, ProgramStateRef State,
1961                                EquivalenceClass Other) const {
1962   // If we know that two classes are equal, we can only produce an infeasible
1963   // state.
1964   if (*this == Other) {
1965     return nullptr;
1966   }
1967 
1968   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
1969   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1970 
1971   // Disequality is a symmetric relation, so if we mark A as disequal to B,
1972   // we should also mark B as disequalt to A.
1973   if (!addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, *this,
1974                             Other) ||
1975       !addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, Other,
1976                             *this))
1977     return nullptr;
1978 
1979   assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1980                                      "a state with infeasible constraints");
1981 
1982   State = State->set<DisequalityMap>(DisequalityInfo);
1983   State = State->set<ConstraintRange>(Constraints);
1984 
1985   return State;
1986 }
1987 
1988 inline bool EquivalenceClass::addToDisequalityInfo(
1989     DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
1990     RangeSet::Factory &RF, ProgramStateRef State, EquivalenceClass First,
1991     EquivalenceClass Second) {
1992 
1993   // 1. Get all of the required factories.
1994   DisequalityMapTy::Factory &F = State->get_context<DisequalityMap>();
1995   ClassSet::Factory &CF = State->get_context<ClassSet>();
1996   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
1997 
1998   // 2. Add Second to the set of classes disequal to First.
1999   const ClassSet *CurrentSet = Info.lookup(First);
2000   ClassSet NewSet = CurrentSet ? *CurrentSet : CF.getEmptySet();
2001   NewSet = CF.add(NewSet, Second);
2002 
2003   Info = F.add(Info, First, NewSet);
2004 
2005   // 3. If Second is known to be a constant, we can delete this point
2006   //    from the constraint asociated with First.
2007   //
2008   //    So, if Second == 10, it means that First != 10.
2009   //    At the same time, the same logic does not apply to ranges.
2010   if (const RangeSet *SecondConstraint = Constraints.lookup(Second))
2011     if (const llvm::APSInt *Point = SecondConstraint->getConcreteValue()) {
2012 
2013       RangeSet FirstConstraint = SymbolicRangeInferrer::inferRange(
2014           RF, State, First.getRepresentativeSymbol());
2015 
2016       FirstConstraint = RF.deletePoint(FirstConstraint, *Point);
2017 
2018       // If the First class is about to be constrained with an empty
2019       // range-set, the state is infeasible.
2020       if (FirstConstraint.isEmpty())
2021         return false;
2022 
2023       Constraints = CRF.add(Constraints, First, FirstConstraint);
2024     }
2025 
2026   return true;
2027 }
2028 
2029 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2030                                                  SymbolRef FirstSym,
2031                                                  SymbolRef SecondSym) {
2032   return EquivalenceClass::areEqual(State, find(State, FirstSym),
2033                                     find(State, SecondSym));
2034 }
2035 
2036 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2037                                                  EquivalenceClass First,
2038                                                  EquivalenceClass Second) {
2039   // The same equivalence class => symbols are equal.
2040   if (First == Second)
2041     return true;
2042 
2043   // Let's check if we know anything about these two classes being not equal to
2044   // each other.
2045   ClassSet DisequalToFirst = First.getDisequalClasses(State);
2046   if (DisequalToFirst.contains(Second))
2047     return false;
2048 
2049   // It is not clear.
2050   return llvm::None;
2051 }
2052 
2053 // Iterate over all symbols and try to simplify them. Once a symbol is
2054 // simplified then we check if we can merge the simplified symbol's equivalence
2055 // class to this class. This way, we simplify not just the symbols but the
2056 // classes as well: we strive to keep the number of the classes to be the
2057 // absolute minimum.
2058 LLVM_NODISCARD ProgramStateRef EquivalenceClass::simplify(
2059     SValBuilder &SVB, RangeSet::Factory &F, ProgramStateRef State) {
2060   SymbolSet ClassMembers = getClassMembers(State);
2061   for (const SymbolRef &MemberSym : ClassMembers) {
2062     SymbolRef SimplifiedMemberSym = ento::simplify(State, MemberSym);
2063     if (SimplifiedMemberSym && MemberSym != SimplifiedMemberSym) {
2064       EquivalenceClass ClassOfSimplifiedSym =
2065           EquivalenceClass::find(State, SimplifiedMemberSym);
2066       // The simplified symbol should be the member of the original Class,
2067       // however, it might be in another existing class at the moment. We
2068       // have to merge these classes.
2069       State = merge(F, State, ClassOfSimplifiedSym);
2070       if (!State)
2071         return nullptr;
2072     }
2073   }
2074   return State;
2075 }
2076 
2077 inline ClassSet EquivalenceClass::getDisequalClasses(ProgramStateRef State,
2078                                                      SymbolRef Sym) {
2079   return find(State, Sym).getDisequalClasses(State);
2080 }
2081 
2082 inline ClassSet
2083 EquivalenceClass::getDisequalClasses(ProgramStateRef State) const {
2084   return getDisequalClasses(State->get<DisequalityMap>(),
2085                             State->get_context<ClassSet>());
2086 }
2087 
2088 inline ClassSet
2089 EquivalenceClass::getDisequalClasses(DisequalityMapTy Map,
2090                                      ClassSet::Factory &Factory) const {
2091   if (const ClassSet *DisequalClasses = Map.lookup(*this))
2092     return *DisequalClasses;
2093 
2094   return Factory.getEmptySet();
2095 }
2096 
2097 bool EquivalenceClass::isClassDataConsistent(ProgramStateRef State) {
2098   ClassMembersTy Members = State->get<ClassMembers>();
2099 
2100   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair : Members) {
2101     for (SymbolRef Member : ClassMembersPair.second) {
2102       // Every member of the class should have a mapping back to the class.
2103       if (find(State, Member) == ClassMembersPair.first) {
2104         continue;
2105       }
2106 
2107       return false;
2108     }
2109   }
2110 
2111   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2112   for (std::pair<EquivalenceClass, ClassSet> DisequalityInfo : Disequalities) {
2113     EquivalenceClass Class = DisequalityInfo.first;
2114     ClassSet DisequalClasses = DisequalityInfo.second;
2115 
2116     // There is no use in keeping empty sets in the map.
2117     if (DisequalClasses.isEmpty())
2118       return false;
2119 
2120     // Disequality is symmetrical, i.e. for every Class A and B that A != B,
2121     // B != A should also be true.
2122     for (EquivalenceClass DisequalClass : DisequalClasses) {
2123       const ClassSet *DisequalToDisequalClasses =
2124           Disequalities.lookup(DisequalClass);
2125 
2126       // It should be a set of at least one element: Class
2127       if (!DisequalToDisequalClasses ||
2128           !DisequalToDisequalClasses->contains(Class))
2129         return false;
2130     }
2131   }
2132 
2133   return true;
2134 }
2135 
2136 //===----------------------------------------------------------------------===//
2137 //                    RangeConstraintManager implementation
2138 //===----------------------------------------------------------------------===//
2139 
2140 bool RangeConstraintManager::canReasonAbout(SVal X) const {
2141   Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
2142   if (SymVal && SymVal->isExpression()) {
2143     const SymExpr *SE = SymVal->getSymbol();
2144 
2145     if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
2146       switch (SIE->getOpcode()) {
2147       // We don't reason yet about bitwise-constraints on symbolic values.
2148       case BO_And:
2149       case BO_Or:
2150       case BO_Xor:
2151         return false;
2152       // We don't reason yet about these arithmetic constraints on
2153       // symbolic values.
2154       case BO_Mul:
2155       case BO_Div:
2156       case BO_Rem:
2157       case BO_Shl:
2158       case BO_Shr:
2159         return false;
2160       // All other cases.
2161       default:
2162         return true;
2163       }
2164     }
2165 
2166     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
2167       // FIXME: Handle <=> here.
2168       if (BinaryOperator::isEqualityOp(SSE->getOpcode()) ||
2169           BinaryOperator::isRelationalOp(SSE->getOpcode())) {
2170         // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
2171         // We've recently started producing Loc <> NonLoc comparisons (that
2172         // result from casts of one of the operands between eg. intptr_t and
2173         // void *), but we can't reason about them yet.
2174         if (Loc::isLocType(SSE->getLHS()->getType())) {
2175           return Loc::isLocType(SSE->getRHS()->getType());
2176         }
2177       }
2178     }
2179 
2180     return false;
2181   }
2182 
2183   return true;
2184 }
2185 
2186 ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
2187                                                     SymbolRef Sym) {
2188   const RangeSet *Ranges = getConstraint(State, Sym);
2189 
2190   // If we don't have any information about this symbol, it's underconstrained.
2191   if (!Ranges)
2192     return ConditionTruthVal();
2193 
2194   // If we have a concrete value, see if it's zero.
2195   if (const llvm::APSInt *Value = Ranges->getConcreteValue())
2196     return *Value == 0;
2197 
2198   BasicValueFactory &BV = getBasicVals();
2199   APSIntType IntType = BV.getAPSIntType(Sym->getType());
2200   llvm::APSInt Zero = IntType.getZeroValue();
2201 
2202   // Check if zero is in the set of possible values.
2203   if (!Ranges->contains(Zero))
2204     return false;
2205 
2206   // Zero is a possible value, but it is not the /only/ possible value.
2207   return ConditionTruthVal();
2208 }
2209 
2210 const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St,
2211                                                       SymbolRef Sym) const {
2212   const RangeSet *T = getConstraint(St, Sym);
2213   return T ? T->getConcreteValue() : nullptr;
2214 }
2215 
2216 //===----------------------------------------------------------------------===//
2217 //                Remove dead symbols from existing constraints
2218 //===----------------------------------------------------------------------===//
2219 
2220 /// Scan all symbols referenced by the constraints. If the symbol is not alive
2221 /// as marked in LSymbols, mark it as dead in DSymbols.
2222 ProgramStateRef
2223 RangeConstraintManager::removeDeadBindings(ProgramStateRef State,
2224                                            SymbolReaper &SymReaper) {
2225   ClassMembersTy ClassMembersMap = State->get<ClassMembers>();
2226   ClassMembersTy NewClassMembersMap = ClassMembersMap;
2227   ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>();
2228   SymbolSet::Factory &SetFactory = State->get_context<SymbolSet>();
2229 
2230   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2231   ConstraintRangeTy NewConstraints = Constraints;
2232   ConstraintRangeTy::Factory &ConstraintFactory =
2233       State->get_context<ConstraintRange>();
2234 
2235   ClassMapTy Map = State->get<ClassMap>();
2236   ClassMapTy NewMap = Map;
2237   ClassMapTy::Factory &ClassFactory = State->get_context<ClassMap>();
2238 
2239   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2240   DisequalityMapTy::Factory &DisequalityFactory =
2241       State->get_context<DisequalityMap>();
2242   ClassSet::Factory &ClassSetFactory = State->get_context<ClassSet>();
2243 
2244   bool ClassMapChanged = false;
2245   bool MembersMapChanged = false;
2246   bool ConstraintMapChanged = false;
2247   bool DisequalitiesChanged = false;
2248 
2249   auto removeDeadClass = [&](EquivalenceClass Class) {
2250     // Remove associated constraint ranges.
2251     Constraints = ConstraintFactory.remove(Constraints, Class);
2252     ConstraintMapChanged = true;
2253 
2254     // Update disequality information to not hold any information on the
2255     // removed class.
2256     ClassSet DisequalClasses =
2257         Class.getDisequalClasses(Disequalities, ClassSetFactory);
2258     if (!DisequalClasses.isEmpty()) {
2259       for (EquivalenceClass DisequalClass : DisequalClasses) {
2260         ClassSet DisequalToDisequalSet =
2261             DisequalClass.getDisequalClasses(Disequalities, ClassSetFactory);
2262         // DisequalToDisequalSet is guaranteed to be non-empty for consistent
2263         // disequality info.
2264         assert(!DisequalToDisequalSet.isEmpty());
2265         ClassSet NewSet = ClassSetFactory.remove(DisequalToDisequalSet, Class);
2266 
2267         // No need in keeping an empty set.
2268         if (NewSet.isEmpty()) {
2269           Disequalities =
2270               DisequalityFactory.remove(Disequalities, DisequalClass);
2271         } else {
2272           Disequalities =
2273               DisequalityFactory.add(Disequalities, DisequalClass, NewSet);
2274         }
2275       }
2276       // Remove the data for the class
2277       Disequalities = DisequalityFactory.remove(Disequalities, Class);
2278       DisequalitiesChanged = true;
2279     }
2280   };
2281 
2282   // 1. Let's see if dead symbols are trivial and have associated constraints.
2283   for (std::pair<EquivalenceClass, RangeSet> ClassConstraintPair :
2284        Constraints) {
2285     EquivalenceClass Class = ClassConstraintPair.first;
2286     if (Class.isTriviallyDead(State, SymReaper)) {
2287       // If this class is trivial, we can remove its constraints right away.
2288       removeDeadClass(Class);
2289     }
2290   }
2291 
2292   // 2. We don't need to track classes for dead symbols.
2293   for (std::pair<SymbolRef, EquivalenceClass> SymbolClassPair : Map) {
2294     SymbolRef Sym = SymbolClassPair.first;
2295 
2296     if (SymReaper.isDead(Sym)) {
2297       ClassMapChanged = true;
2298       NewMap = ClassFactory.remove(NewMap, Sym);
2299     }
2300   }
2301 
2302   // 3. Remove dead members from classes and remove dead non-trivial classes
2303   //    and their constraints.
2304   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair :
2305        ClassMembersMap) {
2306     EquivalenceClass Class = ClassMembersPair.first;
2307     SymbolSet LiveMembers = ClassMembersPair.second;
2308     bool MembersChanged = false;
2309 
2310     for (SymbolRef Member : ClassMembersPair.second) {
2311       if (SymReaper.isDead(Member)) {
2312         MembersChanged = true;
2313         LiveMembers = SetFactory.remove(LiveMembers, Member);
2314       }
2315     }
2316 
2317     // Check if the class changed.
2318     if (!MembersChanged)
2319       continue;
2320 
2321     MembersMapChanged = true;
2322 
2323     if (LiveMembers.isEmpty()) {
2324       // The class is dead now, we need to wipe it out of the members map...
2325       NewClassMembersMap = EMFactory.remove(NewClassMembersMap, Class);
2326 
2327       // ...and remove all of its constraints.
2328       removeDeadClass(Class);
2329     } else {
2330       // We need to change the members associated with the class.
2331       NewClassMembersMap =
2332           EMFactory.add(NewClassMembersMap, Class, LiveMembers);
2333     }
2334   }
2335 
2336   // 4. Update the state with new maps.
2337   //
2338   // Here we try to be humble and update a map only if it really changed.
2339   if (ClassMapChanged)
2340     State = State->set<ClassMap>(NewMap);
2341 
2342   if (MembersMapChanged)
2343     State = State->set<ClassMembers>(NewClassMembersMap);
2344 
2345   if (ConstraintMapChanged)
2346     State = State->set<ConstraintRange>(Constraints);
2347 
2348   if (DisequalitiesChanged)
2349     State = State->set<DisequalityMap>(Disequalities);
2350 
2351   assert(EquivalenceClass::isClassDataConsistent(State));
2352 
2353   return State;
2354 }
2355 
2356 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
2357                                           SymbolRef Sym) {
2358   return SymbolicRangeInferrer::inferRange(F, State, Sym);
2359 }
2360 
2361 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
2362                                           EquivalenceClass Class) {
2363   return SymbolicRangeInferrer::inferRange(F, State, Class);
2364 }
2365 
2366 ProgramStateRef RangeConstraintManager::setRange(ProgramStateRef State,
2367                                                  SymbolRef Sym,
2368                                                  RangeSet Range) {
2369   return ConstraintAssignor::assign(State, getSValBuilder(), F, Sym, Range);
2370 }
2371 
2372 ProgramStateRef RangeConstraintManager::setRange(ProgramStateRef State,
2373                                                  EquivalenceClass Class,
2374                                                  RangeSet Range) {
2375   return ConstraintAssignor::assign(State, getSValBuilder(), F, Class, Range);
2376 }
2377 
2378 //===------------------------------------------------------------------------===
2379 // assumeSymX methods: protected interface for RangeConstraintManager.
2380 //===------------------------------------------------------------------------===/
2381 
2382 // The syntax for ranges below is mathematical, using [x, y] for closed ranges
2383 // and (x, y) for open ranges. These ranges are modular, corresponding with
2384 // a common treatment of C integer overflow. This means that these methods
2385 // do not have to worry about overflow; RangeSet::Intersect can handle such a
2386 // "wraparound" range.
2387 // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
2388 // UINT_MAX, 0, 1, and 2.
2389 
2390 ProgramStateRef
2391 RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
2392                                     const llvm::APSInt &Int,
2393                                     const llvm::APSInt &Adjustment) {
2394   // Before we do any real work, see if the value can even show up.
2395   APSIntType AdjustmentType(Adjustment);
2396   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
2397     return St;
2398 
2399   llvm::APSInt Point = AdjustmentType.convert(Int) - Adjustment;
2400   RangeSet New = getRange(St, Sym);
2401   New = F.deletePoint(New, Point);
2402 
2403   return setRange(St, Sym, New);
2404 }
2405 
2406 ProgramStateRef
2407 RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
2408                                     const llvm::APSInt &Int,
2409                                     const llvm::APSInt &Adjustment) {
2410   // Before we do any real work, see if the value can even show up.
2411   APSIntType AdjustmentType(Adjustment);
2412   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
2413     return nullptr;
2414 
2415   // [Int-Adjustment, Int-Adjustment]
2416   llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
2417   RangeSet New = getRange(St, Sym);
2418   New = F.intersect(New, AdjInt);
2419 
2420   return setRange(St, Sym, New);
2421 }
2422 
2423 RangeSet RangeConstraintManager::getSymLTRange(ProgramStateRef St,
2424                                                SymbolRef Sym,
2425                                                const llvm::APSInt &Int,
2426                                                const llvm::APSInt &Adjustment) {
2427   // Before we do any real work, see if the value can even show up.
2428   APSIntType AdjustmentType(Adjustment);
2429   switch (AdjustmentType.testInRange(Int, true)) {
2430   case APSIntType::RTR_Below:
2431     return F.getEmptySet();
2432   case APSIntType::RTR_Within:
2433     break;
2434   case APSIntType::RTR_Above:
2435     return getRange(St, Sym);
2436   }
2437 
2438   // Special case for Int == Min. This is always false.
2439   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2440   llvm::APSInt Min = AdjustmentType.getMinValue();
2441   if (ComparisonVal == Min)
2442     return F.getEmptySet();
2443 
2444   llvm::APSInt Lower = Min - Adjustment;
2445   llvm::APSInt Upper = ComparisonVal - Adjustment;
2446   --Upper;
2447 
2448   RangeSet Result = getRange(St, Sym);
2449   return F.intersect(Result, Lower, Upper);
2450 }
2451 
2452 ProgramStateRef
2453 RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
2454                                     const llvm::APSInt &Int,
2455                                     const llvm::APSInt &Adjustment) {
2456   RangeSet New = getSymLTRange(St, Sym, Int, Adjustment);
2457   return setRange(St, Sym, New);
2458 }
2459 
2460 RangeSet RangeConstraintManager::getSymGTRange(ProgramStateRef St,
2461                                                SymbolRef Sym,
2462                                                const llvm::APSInt &Int,
2463                                                const llvm::APSInt &Adjustment) {
2464   // Before we do any real work, see if the value can even show up.
2465   APSIntType AdjustmentType(Adjustment);
2466   switch (AdjustmentType.testInRange(Int, true)) {
2467   case APSIntType::RTR_Below:
2468     return getRange(St, Sym);
2469   case APSIntType::RTR_Within:
2470     break;
2471   case APSIntType::RTR_Above:
2472     return F.getEmptySet();
2473   }
2474 
2475   // Special case for Int == Max. This is always false.
2476   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2477   llvm::APSInt Max = AdjustmentType.getMaxValue();
2478   if (ComparisonVal == Max)
2479     return F.getEmptySet();
2480 
2481   llvm::APSInt Lower = ComparisonVal - Adjustment;
2482   llvm::APSInt Upper = Max - Adjustment;
2483   ++Lower;
2484 
2485   RangeSet SymRange = getRange(St, Sym);
2486   return F.intersect(SymRange, Lower, Upper);
2487 }
2488 
2489 ProgramStateRef
2490 RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
2491                                     const llvm::APSInt &Int,
2492                                     const llvm::APSInt &Adjustment) {
2493   RangeSet New = getSymGTRange(St, Sym, Int, Adjustment);
2494   return setRange(St, Sym, New);
2495 }
2496 
2497 RangeSet RangeConstraintManager::getSymGERange(ProgramStateRef St,
2498                                                SymbolRef Sym,
2499                                                const llvm::APSInt &Int,
2500                                                const llvm::APSInt &Adjustment) {
2501   // Before we do any real work, see if the value can even show up.
2502   APSIntType AdjustmentType(Adjustment);
2503   switch (AdjustmentType.testInRange(Int, true)) {
2504   case APSIntType::RTR_Below:
2505     return getRange(St, Sym);
2506   case APSIntType::RTR_Within:
2507     break;
2508   case APSIntType::RTR_Above:
2509     return F.getEmptySet();
2510   }
2511 
2512   // Special case for Int == Min. This is always feasible.
2513   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2514   llvm::APSInt Min = AdjustmentType.getMinValue();
2515   if (ComparisonVal == Min)
2516     return getRange(St, Sym);
2517 
2518   llvm::APSInt Max = AdjustmentType.getMaxValue();
2519   llvm::APSInt Lower = ComparisonVal - Adjustment;
2520   llvm::APSInt Upper = Max - Adjustment;
2521 
2522   RangeSet SymRange = getRange(St, Sym);
2523   return F.intersect(SymRange, Lower, Upper);
2524 }
2525 
2526 ProgramStateRef
2527 RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
2528                                     const llvm::APSInt &Int,
2529                                     const llvm::APSInt &Adjustment) {
2530   RangeSet New = getSymGERange(St, Sym, Int, Adjustment);
2531   return setRange(St, Sym, New);
2532 }
2533 
2534 RangeSet
2535 RangeConstraintManager::getSymLERange(llvm::function_ref<RangeSet()> RS,
2536                                       const llvm::APSInt &Int,
2537                                       const llvm::APSInt &Adjustment) {
2538   // Before we do any real work, see if the value can even show up.
2539   APSIntType AdjustmentType(Adjustment);
2540   switch (AdjustmentType.testInRange(Int, true)) {
2541   case APSIntType::RTR_Below:
2542     return F.getEmptySet();
2543   case APSIntType::RTR_Within:
2544     break;
2545   case APSIntType::RTR_Above:
2546     return RS();
2547   }
2548 
2549   // Special case for Int == Max. This is always feasible.
2550   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2551   llvm::APSInt Max = AdjustmentType.getMaxValue();
2552   if (ComparisonVal == Max)
2553     return RS();
2554 
2555   llvm::APSInt Min = AdjustmentType.getMinValue();
2556   llvm::APSInt Lower = Min - Adjustment;
2557   llvm::APSInt Upper = ComparisonVal - Adjustment;
2558 
2559   RangeSet Default = RS();
2560   return F.intersect(Default, Lower, Upper);
2561 }
2562 
2563 RangeSet RangeConstraintManager::getSymLERange(ProgramStateRef St,
2564                                                SymbolRef Sym,
2565                                                const llvm::APSInt &Int,
2566                                                const llvm::APSInt &Adjustment) {
2567   return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment);
2568 }
2569 
2570 ProgramStateRef
2571 RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
2572                                     const llvm::APSInt &Int,
2573                                     const llvm::APSInt &Adjustment) {
2574   RangeSet New = getSymLERange(St, Sym, Int, Adjustment);
2575   return setRange(St, Sym, New);
2576 }
2577 
2578 ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange(
2579     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2580     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
2581   RangeSet New = getSymGERange(State, Sym, From, Adjustment);
2582   if (New.isEmpty())
2583     return nullptr;
2584   RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment);
2585   return setRange(State, Sym, Out);
2586 }
2587 
2588 ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange(
2589     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2590     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
2591   RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment);
2592   RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment);
2593   RangeSet New(F.add(RangeLT, RangeGT));
2594   return setRange(State, Sym, New);
2595 }
2596 
2597 //===----------------------------------------------------------------------===//
2598 // Pretty-printing.
2599 //===----------------------------------------------------------------------===//
2600 
2601 void RangeConstraintManager::printJson(raw_ostream &Out, ProgramStateRef State,
2602                                        const char *NL, unsigned int Space,
2603                                        bool IsDot) const {
2604   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2605 
2606   Indent(Out, Space, IsDot) << "\"constraints\": ";
2607   if (Constraints.isEmpty()) {
2608     Out << "null," << NL;
2609     return;
2610   }
2611 
2612   ++Space;
2613   Out << '[' << NL;
2614   bool First = true;
2615   for (std::pair<EquivalenceClass, RangeSet> P : Constraints) {
2616     SymbolSet ClassMembers = P.first.getClassMembers(State);
2617 
2618     // We can print the same constraint for every class member.
2619     for (SymbolRef ClassMember : ClassMembers) {
2620       if (First) {
2621         First = false;
2622       } else {
2623         Out << ',';
2624         Out << NL;
2625       }
2626       Indent(Out, Space, IsDot)
2627           << "{ \"symbol\": \"" << ClassMember << "\", \"range\": \"";
2628       P.second.dump(Out);
2629       Out << "\" }";
2630     }
2631   }
2632   Out << NL;
2633 
2634   --Space;
2635   Indent(Out, Space, IsDot) << "]," << NL;
2636 }
2637