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