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