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