RangeConstraintManager.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. //== RangeConstraintManager.cpp - Manage range constraints.------*- C++ -*--==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines RangeConstraintManager, a class that tracks simple
  11. // equality and inequality constraints on symbolic values of ProgramState.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "RangedConstraintManager.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 "llvm/ADT/FoldingSet.h"
  19. #include "llvm/ADT/ImmutableSet.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace clang;
  22. using namespace ento;
  23. /// A Range represents the closed range [from, to]. The caller must
  24. /// guarantee that from <= to. Note that Range is immutable, so as not
  25. /// to subvert RangeSet's immutability.
  26. namespace {
  27. class Range : public std::pair<const llvm::APSInt *, const llvm::APSInt *> {
  28. public:
  29. Range(const llvm::APSInt &from, const llvm::APSInt &to)
  30. : std::pair<const llvm::APSInt *, const llvm::APSInt *>(&from, &to) {
  31. assert(from <= to);
  32. }
  33. bool Includes(const llvm::APSInt &v) const {
  34. return *first <= v && v <= *second;
  35. }
  36. const llvm::APSInt &From() const { return *first; }
  37. const llvm::APSInt &To() const { return *second; }
  38. const llvm::APSInt *getConcreteValue() const {
  39. return &From() == &To() ? &From() : nullptr;
  40. }
  41. void Profile(llvm::FoldingSetNodeID &ID) const {
  42. ID.AddPointer(&From());
  43. ID.AddPointer(&To());
  44. }
  45. };
  46. class RangeTrait : public llvm::ImutContainerInfo<Range> {
  47. public:
  48. // When comparing if one Range is less than another, we should compare
  49. // the actual APSInt values instead of their pointers. This keeps the order
  50. // consistent (instead of comparing by pointer values) and can potentially
  51. // be used to speed up some of the operations in RangeSet.
  52. static inline bool isLess(key_type_ref lhs, key_type_ref rhs) {
  53. return *lhs.first < *rhs.first ||
  54. (!(*rhs.first < *lhs.first) && *lhs.second < *rhs.second);
  55. }
  56. };
  57. /// RangeSet contains a set of ranges. If the set is empty, then
  58. /// there the value of a symbol is overly constrained and there are no
  59. /// possible values for that symbol.
  60. class RangeSet {
  61. typedef llvm::ImmutableSet<Range, RangeTrait> PrimRangeSet;
  62. PrimRangeSet ranges; // no need to make const, since it is an
  63. // ImmutableSet - this allows default operator=
  64. // to work.
  65. public:
  66. typedef PrimRangeSet::Factory Factory;
  67. typedef PrimRangeSet::iterator iterator;
  68. RangeSet(PrimRangeSet RS) : ranges(RS) {}
  69. /// Create a new set with all ranges of this set and RS.
  70. /// Possible intersections are not checked here.
  71. RangeSet addRange(Factory &F, const RangeSet &RS) {
  72. PrimRangeSet Ranges(RS.ranges);
  73. for (const auto &range : ranges)
  74. Ranges = F.add(Ranges, range);
  75. return RangeSet(Ranges);
  76. }
  77. iterator begin() const { return ranges.begin(); }
  78. iterator end() const { return ranges.end(); }
  79. bool isEmpty() const { return ranges.isEmpty(); }
  80. /// Construct a new RangeSet representing '{ [from, to] }'.
  81. RangeSet(Factory &F, const llvm::APSInt &from, const llvm::APSInt &to)
  82. : ranges(F.add(F.getEmptySet(), Range(from, to))) {}
  83. /// Profile - Generates a hash profile of this RangeSet for use
  84. /// by FoldingSet.
  85. void Profile(llvm::FoldingSetNodeID &ID) const { ranges.Profile(ID); }
  86. /// getConcreteValue - If a symbol is contrained to equal a specific integer
  87. /// constant then this method returns that value. Otherwise, it returns
  88. /// NULL.
  89. const llvm::APSInt *getConcreteValue() const {
  90. return ranges.isSingleton() ? ranges.begin()->getConcreteValue() : nullptr;
  91. }
  92. private:
  93. void IntersectInRange(BasicValueFactory &BV, Factory &F,
  94. const llvm::APSInt &Lower, const llvm::APSInt &Upper,
  95. PrimRangeSet &newRanges, PrimRangeSet::iterator &i,
  96. PrimRangeSet::iterator &e) const {
  97. // There are six cases for each range R in the set:
  98. // 1. R is entirely before the intersection range.
  99. // 2. R is entirely after the intersection range.
  100. // 3. R contains the entire intersection range.
  101. // 4. R starts before the intersection range and ends in the middle.
  102. // 5. R starts in the middle of the intersection range and ends after it.
  103. // 6. R is entirely contained in the intersection range.
  104. // These correspond to each of the conditions below.
  105. for (/* i = begin(), e = end() */; i != e; ++i) {
  106. if (i->To() < Lower) {
  107. continue;
  108. }
  109. if (i->From() > Upper) {
  110. break;
  111. }
  112. if (i->Includes(Lower)) {
  113. if (i->Includes(Upper)) {
  114. newRanges =
  115. F.add(newRanges, Range(BV.getValue(Lower), BV.getValue(Upper)));
  116. break;
  117. } else
  118. newRanges = F.add(newRanges, Range(BV.getValue(Lower), i->To()));
  119. } else {
  120. if (i->Includes(Upper)) {
  121. newRanges = F.add(newRanges, Range(i->From(), BV.getValue(Upper)));
  122. break;
  123. } else
  124. newRanges = F.add(newRanges, *i);
  125. }
  126. }
  127. }
  128. const llvm::APSInt &getMinValue() const {
  129. assert(!isEmpty());
  130. return ranges.begin()->From();
  131. }
  132. bool pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
  133. // This function has nine cases, the cartesian product of range-testing
  134. // both the upper and lower bounds against the symbol's type.
  135. // Each case requires a different pinning operation.
  136. // The function returns false if the described range is entirely outside
  137. // the range of values for the associated symbol.
  138. APSIntType Type(getMinValue());
  139. APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower, true);
  140. APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper, true);
  141. switch (LowerTest) {
  142. case APSIntType::RTR_Below:
  143. switch (UpperTest) {
  144. case APSIntType::RTR_Below:
  145. // The entire range is outside the symbol's set of possible values.
  146. // If this is a conventionally-ordered range, the state is infeasible.
  147. if (Lower <= Upper)
  148. return false;
  149. // However, if the range wraps around, it spans all possible values.
  150. Lower = Type.getMinValue();
  151. Upper = Type.getMaxValue();
  152. break;
  153. case APSIntType::RTR_Within:
  154. // The range starts below what's possible but ends within it. Pin.
  155. Lower = Type.getMinValue();
  156. Type.apply(Upper);
  157. break;
  158. case APSIntType::RTR_Above:
  159. // The range spans all possible values for the symbol. Pin.
  160. Lower = Type.getMinValue();
  161. Upper = Type.getMaxValue();
  162. break;
  163. }
  164. break;
  165. case APSIntType::RTR_Within:
  166. switch (UpperTest) {
  167. case APSIntType::RTR_Below:
  168. // The range wraps around, but all lower values are not possible.
  169. Type.apply(Lower);
  170. Upper = Type.getMaxValue();
  171. break;
  172. case APSIntType::RTR_Within:
  173. // The range may or may not wrap around, but both limits are valid.
  174. Type.apply(Lower);
  175. Type.apply(Upper);
  176. break;
  177. case APSIntType::RTR_Above:
  178. // The range starts within what's possible but ends above it. Pin.
  179. Type.apply(Lower);
  180. Upper = Type.getMaxValue();
  181. break;
  182. }
  183. break;
  184. case APSIntType::RTR_Above:
  185. switch (UpperTest) {
  186. case APSIntType::RTR_Below:
  187. // The range wraps but is outside the symbol's set of possible values.
  188. return false;
  189. case APSIntType::RTR_Within:
  190. // The range starts above what's possible but ends within it (wrap).
  191. Lower = Type.getMinValue();
  192. Type.apply(Upper);
  193. break;
  194. case APSIntType::RTR_Above:
  195. // The entire range is outside the symbol's set of possible values.
  196. // If this is a conventionally-ordered range, the state is infeasible.
  197. if (Lower <= Upper)
  198. return false;
  199. // However, if the range wraps around, it spans all possible values.
  200. Lower = Type.getMinValue();
  201. Upper = Type.getMaxValue();
  202. break;
  203. }
  204. break;
  205. }
  206. return true;
  207. }
  208. public:
  209. // Returns a set containing the values in the receiving set, intersected with
  210. // the closed range [Lower, Upper]. Unlike the Range type, this range uses
  211. // modular arithmetic, corresponding to the common treatment of C integer
  212. // overflow. Thus, if the Lower bound is greater than the Upper bound, the
  213. // range is taken to wrap around. This is equivalent to taking the
  214. // intersection with the two ranges [Min, Upper] and [Lower, Max],
  215. // or, alternatively, /removing/ all integers between Upper and Lower.
  216. RangeSet Intersect(BasicValueFactory &BV, Factory &F, llvm::APSInt Lower,
  217. llvm::APSInt Upper) const {
  218. if (!pin(Lower, Upper))
  219. return F.getEmptySet();
  220. PrimRangeSet newRanges = F.getEmptySet();
  221. PrimRangeSet::iterator i = begin(), e = end();
  222. if (Lower <= Upper)
  223. IntersectInRange(BV, F, Lower, Upper, newRanges, i, e);
  224. else {
  225. // The order of the next two statements is important!
  226. // IntersectInRange() does not reset the iteration state for i and e.
  227. // Therefore, the lower range most be handled first.
  228. IntersectInRange(BV, F, BV.getMinValue(Upper), Upper, newRanges, i, e);
  229. IntersectInRange(BV, F, Lower, BV.getMaxValue(Lower), newRanges, i, e);
  230. }
  231. return newRanges;
  232. }
  233. void print(raw_ostream &os) const {
  234. bool isFirst = true;
  235. os << "{ ";
  236. for (iterator i = begin(), e = end(); i != e; ++i) {
  237. if (isFirst)
  238. isFirst = false;
  239. else
  240. os << ", ";
  241. os << '[' << i->From().toString(10) << ", " << i->To().toString(10)
  242. << ']';
  243. }
  244. os << " }";
  245. }
  246. bool operator==(const RangeSet &other) const {
  247. return ranges == other.ranges;
  248. }
  249. };
  250. } // end anonymous namespace
  251. REGISTER_TRAIT_WITH_PROGRAMSTATE(ConstraintRange,
  252. CLANG_ENTO_PROGRAMSTATE_MAP(SymbolRef,
  253. RangeSet))
  254. namespace {
  255. class RangeConstraintManager : public RangedConstraintManager {
  256. public:
  257. RangeConstraintManager(SubEngine *SE, SValBuilder &SVB)
  258. : RangedConstraintManager(SE, SVB) {}
  259. //===------------------------------------------------------------------===//
  260. // Implementation for interface from ConstraintManager.
  261. //===------------------------------------------------------------------===//
  262. bool canReasonAbout(SVal X) const override;
  263. ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override;
  264. const llvm::APSInt *getSymVal(ProgramStateRef State,
  265. SymbolRef Sym) const override;
  266. ProgramStateRef removeDeadBindings(ProgramStateRef State,
  267. SymbolReaper &SymReaper) override;
  268. void print(ProgramStateRef State, raw_ostream &Out, const char *nl,
  269. const char *sep) override;
  270. //===------------------------------------------------------------------===//
  271. // Implementation for interface from RangedConstraintManager.
  272. //===------------------------------------------------------------------===//
  273. ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym,
  274. const llvm::APSInt &V,
  275. const llvm::APSInt &Adjustment) override;
  276. ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym,
  277. const llvm::APSInt &V,
  278. const llvm::APSInt &Adjustment) override;
  279. ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym,
  280. const llvm::APSInt &V,
  281. const llvm::APSInt &Adjustment) override;
  282. ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym,
  283. const llvm::APSInt &V,
  284. const llvm::APSInt &Adjustment) override;
  285. ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym,
  286. const llvm::APSInt &V,
  287. const llvm::APSInt &Adjustment) override;
  288. ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym,
  289. const llvm::APSInt &V,
  290. const llvm::APSInt &Adjustment) override;
  291. ProgramStateRef assumeSymWithinInclusiveRange(
  292. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  293. const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
  294. ProgramStateRef assumeSymOutsideInclusiveRange(
  295. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  296. const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
  297. private:
  298. RangeSet::Factory F;
  299. RangeSet getRange(ProgramStateRef State, SymbolRef Sym);
  300. RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym,
  301. const llvm::APSInt &Int,
  302. const llvm::APSInt &Adjustment);
  303. RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym,
  304. const llvm::APSInt &Int,
  305. const llvm::APSInt &Adjustment);
  306. RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym,
  307. const llvm::APSInt &Int,
  308. const llvm::APSInt &Adjustment);
  309. RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS,
  310. const llvm::APSInt &Int,
  311. const llvm::APSInt &Adjustment);
  312. RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym,
  313. const llvm::APSInt &Int,
  314. const llvm::APSInt &Adjustment);
  315. };
  316. } // end anonymous namespace
  317. std::unique_ptr<ConstraintManager>
  318. ento::CreateRangeConstraintManager(ProgramStateManager &StMgr, SubEngine *Eng) {
  319. return llvm::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder());
  320. }
  321. bool RangeConstraintManager::canReasonAbout(SVal X) const {
  322. Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
  323. if (SymVal && SymVal->isExpression()) {
  324. const SymExpr *SE = SymVal->getSymbol();
  325. if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
  326. switch (SIE->getOpcode()) {
  327. // We don't reason yet about bitwise-constraints on symbolic values.
  328. case BO_And:
  329. case BO_Or:
  330. case BO_Xor:
  331. return false;
  332. // We don't reason yet about these arithmetic constraints on
  333. // symbolic values.
  334. case BO_Mul:
  335. case BO_Div:
  336. case BO_Rem:
  337. case BO_Shl:
  338. case BO_Shr:
  339. return false;
  340. // All other cases.
  341. default:
  342. return true;
  343. }
  344. }
  345. if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
  346. // FIXME: Handle <=> here.
  347. if (BinaryOperator::isEqualityOp(SSE->getOpcode()) ||
  348. BinaryOperator::isRelationalOp(SSE->getOpcode())) {
  349. // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
  350. if (Loc::isLocType(SSE->getLHS()->getType())) {
  351. assert(Loc::isLocType(SSE->getRHS()->getType()));
  352. return true;
  353. }
  354. }
  355. }
  356. return false;
  357. }
  358. return true;
  359. }
  360. ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
  361. SymbolRef Sym) {
  362. const RangeSet *Ranges = State->get<ConstraintRange>(Sym);
  363. // If we don't have any information about this symbol, it's underconstrained.
  364. if (!Ranges)
  365. return ConditionTruthVal();
  366. // If we have a concrete value, see if it's zero.
  367. if (const llvm::APSInt *Value = Ranges->getConcreteValue())
  368. return *Value == 0;
  369. BasicValueFactory &BV = getBasicVals();
  370. APSIntType IntType = BV.getAPSIntType(Sym->getType());
  371. llvm::APSInt Zero = IntType.getZeroValue();
  372. // Check if zero is in the set of possible values.
  373. if (Ranges->Intersect(BV, F, Zero, Zero).isEmpty())
  374. return false;
  375. // Zero is a possible value, but it is not the /only/ possible value.
  376. return ConditionTruthVal();
  377. }
  378. const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St,
  379. SymbolRef Sym) const {
  380. const ConstraintRangeTy::data_type *T = St->get<ConstraintRange>(Sym);
  381. return T ? T->getConcreteValue() : nullptr;
  382. }
  383. /// Scan all symbols referenced by the constraints. If the symbol is not alive
  384. /// as marked in LSymbols, mark it as dead in DSymbols.
  385. ProgramStateRef
  386. RangeConstraintManager::removeDeadBindings(ProgramStateRef State,
  387. SymbolReaper &SymReaper) {
  388. bool Changed = false;
  389. ConstraintRangeTy CR = State->get<ConstraintRange>();
  390. ConstraintRangeTy::Factory &CRFactory = State->get_context<ConstraintRange>();
  391. for (ConstraintRangeTy::iterator I = CR.begin(), E = CR.end(); I != E; ++I) {
  392. SymbolRef Sym = I.getKey();
  393. if (SymReaper.maybeDead(Sym)) {
  394. Changed = true;
  395. CR = CRFactory.remove(CR, Sym);
  396. }
  397. }
  398. return Changed ? State->set<ConstraintRange>(CR) : State;
  399. }
  400. /// Return a range set subtracting zero from \p Domain.
  401. static RangeSet assumeNonZero(
  402. BasicValueFactory &BV,
  403. RangeSet::Factory &F,
  404. SymbolRef Sym,
  405. RangeSet Domain) {
  406. APSIntType IntType = BV.getAPSIntType(Sym->getType());
  407. return Domain.Intersect(BV, F, ++IntType.getZeroValue(),
  408. --IntType.getZeroValue());
  409. }
  410. /// \brief Apply implicit constraints for bitwise OR- and AND-.
  411. /// For unsigned types, bitwise OR with a constant always returns
  412. /// a value greater-or-equal than the constant, and bitwise AND
  413. /// returns a value less-or-equal then the constant.
  414. ///
  415. /// Pattern matches the expression \p Sym against those rule,
  416. /// and applies the required constraints.
  417. /// \p Input Previously established expression range set
  418. static RangeSet applyBitwiseConstraints(
  419. BasicValueFactory &BV,
  420. RangeSet::Factory &F,
  421. RangeSet Input,
  422. const SymIntExpr* SIE) {
  423. QualType T = SIE->getType();
  424. bool IsUnsigned = T->isUnsignedIntegerType();
  425. const llvm::APSInt &RHS = SIE->getRHS();
  426. const llvm::APSInt &Zero = BV.getAPSIntType(T).getZeroValue();
  427. BinaryOperator::Opcode Operator = SIE->getOpcode();
  428. // For unsigned types, the output of bitwise-or is bigger-or-equal than RHS.
  429. if (Operator == BO_Or && IsUnsigned)
  430. return Input.Intersect(BV, F, RHS, BV.getMaxValue(T));
  431. // Bitwise-or with a non-zero constant is always non-zero.
  432. if (Operator == BO_Or && RHS != Zero)
  433. return assumeNonZero(BV, F, SIE, Input);
  434. // For unsigned types, or positive RHS,
  435. // bitwise-and output is always smaller-or-equal than RHS (assuming two's
  436. // complement representation of signed types).
  437. if (Operator == BO_And && (IsUnsigned || RHS >= Zero))
  438. return Input.Intersect(BV, F, BV.getMinValue(T), RHS);
  439. return Input;
  440. }
  441. RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
  442. SymbolRef Sym) {
  443. if (ConstraintRangeTy::data_type *V = State->get<ConstraintRange>(Sym))
  444. return *V;
  445. // Lazily generate a new RangeSet representing all possible values for the
  446. // given symbol type.
  447. BasicValueFactory &BV = getBasicVals();
  448. QualType T = Sym->getType();
  449. RangeSet Result(F, BV.getMinValue(T), BV.getMaxValue(T));
  450. // References are known to be non-zero.
  451. if (T->isReferenceType())
  452. return assumeNonZero(BV, F, Sym, Result);
  453. // Known constraints on ranges of bitwise expressions.
  454. if (const SymIntExpr* SIE = dyn_cast<SymIntExpr>(Sym))
  455. return applyBitwiseConstraints(BV, F, Result, SIE);
  456. return Result;
  457. }
  458. //===------------------------------------------------------------------------===
  459. // assumeSymX methods: protected interface for RangeConstraintManager.
  460. //===------------------------------------------------------------------------===/
  461. // The syntax for ranges below is mathematical, using [x, y] for closed ranges
  462. // and (x, y) for open ranges. These ranges are modular, corresponding with
  463. // a common treatment of C integer overflow. This means that these methods
  464. // do not have to worry about overflow; RangeSet::Intersect can handle such a
  465. // "wraparound" range.
  466. // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
  467. // UINT_MAX, 0, 1, and 2.
  468. ProgramStateRef
  469. RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
  470. const llvm::APSInt &Int,
  471. const llvm::APSInt &Adjustment) {
  472. // Before we do any real work, see if the value can even show up.
  473. APSIntType AdjustmentType(Adjustment);
  474. if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
  475. return St;
  476. llvm::APSInt Lower = AdjustmentType.convert(Int) - Adjustment;
  477. llvm::APSInt Upper = Lower;
  478. --Lower;
  479. ++Upper;
  480. // [Int-Adjustment+1, Int-Adjustment-1]
  481. // Notice that the lower bound is greater than the upper bound.
  482. RangeSet New = getRange(St, Sym).Intersect(getBasicVals(), F, Upper, Lower);
  483. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  484. }
  485. ProgramStateRef
  486. RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
  487. const llvm::APSInt &Int,
  488. const llvm::APSInt &Adjustment) {
  489. // Before we do any real work, see if the value can even show up.
  490. APSIntType AdjustmentType(Adjustment);
  491. if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
  492. return nullptr;
  493. // [Int-Adjustment, Int-Adjustment]
  494. llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
  495. RangeSet New = getRange(St, Sym).Intersect(getBasicVals(), F, AdjInt, AdjInt);
  496. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  497. }
  498. RangeSet RangeConstraintManager::getSymLTRange(ProgramStateRef St,
  499. SymbolRef Sym,
  500. const llvm::APSInt &Int,
  501. const llvm::APSInt &Adjustment) {
  502. // Before we do any real work, see if the value can even show up.
  503. APSIntType AdjustmentType(Adjustment);
  504. switch (AdjustmentType.testInRange(Int, true)) {
  505. case APSIntType::RTR_Below:
  506. return F.getEmptySet();
  507. case APSIntType::RTR_Within:
  508. break;
  509. case APSIntType::RTR_Above:
  510. return getRange(St, Sym);
  511. }
  512. // Special case for Int == Min. This is always false.
  513. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  514. llvm::APSInt Min = AdjustmentType.getMinValue();
  515. if (ComparisonVal == Min)
  516. return F.getEmptySet();
  517. llvm::APSInt Lower = Min - Adjustment;
  518. llvm::APSInt Upper = ComparisonVal - Adjustment;
  519. --Upper;
  520. return getRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
  521. }
  522. ProgramStateRef
  523. RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
  524. const llvm::APSInt &Int,
  525. const llvm::APSInt &Adjustment) {
  526. RangeSet New = getSymLTRange(St, Sym, Int, Adjustment);
  527. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  528. }
  529. RangeSet RangeConstraintManager::getSymGTRange(ProgramStateRef St,
  530. SymbolRef Sym,
  531. const llvm::APSInt &Int,
  532. const llvm::APSInt &Adjustment) {
  533. // Before we do any real work, see if the value can even show up.
  534. APSIntType AdjustmentType(Adjustment);
  535. switch (AdjustmentType.testInRange(Int, true)) {
  536. case APSIntType::RTR_Below:
  537. return getRange(St, Sym);
  538. case APSIntType::RTR_Within:
  539. break;
  540. case APSIntType::RTR_Above:
  541. return F.getEmptySet();
  542. }
  543. // Special case for Int == Max. This is always false.
  544. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  545. llvm::APSInt Max = AdjustmentType.getMaxValue();
  546. if (ComparisonVal == Max)
  547. return F.getEmptySet();
  548. llvm::APSInt Lower = ComparisonVal - Adjustment;
  549. llvm::APSInt Upper = Max - Adjustment;
  550. ++Lower;
  551. return getRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
  552. }
  553. ProgramStateRef
  554. RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
  555. const llvm::APSInt &Int,
  556. const llvm::APSInt &Adjustment) {
  557. RangeSet New = getSymGTRange(St, Sym, Int, Adjustment);
  558. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  559. }
  560. RangeSet RangeConstraintManager::getSymGERange(ProgramStateRef St,
  561. SymbolRef Sym,
  562. const llvm::APSInt &Int,
  563. const llvm::APSInt &Adjustment) {
  564. // Before we do any real work, see if the value can even show up.
  565. APSIntType AdjustmentType(Adjustment);
  566. switch (AdjustmentType.testInRange(Int, true)) {
  567. case APSIntType::RTR_Below:
  568. return getRange(St, Sym);
  569. case APSIntType::RTR_Within:
  570. break;
  571. case APSIntType::RTR_Above:
  572. return F.getEmptySet();
  573. }
  574. // Special case for Int == Min. This is always feasible.
  575. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  576. llvm::APSInt Min = AdjustmentType.getMinValue();
  577. if (ComparisonVal == Min)
  578. return getRange(St, Sym);
  579. llvm::APSInt Max = AdjustmentType.getMaxValue();
  580. llvm::APSInt Lower = ComparisonVal - Adjustment;
  581. llvm::APSInt Upper = Max - Adjustment;
  582. return getRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
  583. }
  584. ProgramStateRef
  585. RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
  586. const llvm::APSInt &Int,
  587. const llvm::APSInt &Adjustment) {
  588. RangeSet New = getSymGERange(St, Sym, Int, Adjustment);
  589. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  590. }
  591. RangeSet RangeConstraintManager::getSymLERange(
  592. llvm::function_ref<RangeSet()> RS,
  593. const llvm::APSInt &Int,
  594. const llvm::APSInt &Adjustment) {
  595. // Before we do any real work, see if the value can even show up.
  596. APSIntType AdjustmentType(Adjustment);
  597. switch (AdjustmentType.testInRange(Int, true)) {
  598. case APSIntType::RTR_Below:
  599. return F.getEmptySet();
  600. case APSIntType::RTR_Within:
  601. break;
  602. case APSIntType::RTR_Above:
  603. return RS();
  604. }
  605. // Special case for Int == Max. This is always feasible.
  606. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  607. llvm::APSInt Max = AdjustmentType.getMaxValue();
  608. if (ComparisonVal == Max)
  609. return RS();
  610. llvm::APSInt Min = AdjustmentType.getMinValue();
  611. llvm::APSInt Lower = Min - Adjustment;
  612. llvm::APSInt Upper = ComparisonVal - Adjustment;
  613. return RS().Intersect(getBasicVals(), F, Lower, Upper);
  614. }
  615. RangeSet RangeConstraintManager::getSymLERange(ProgramStateRef St,
  616. SymbolRef Sym,
  617. const llvm::APSInt &Int,
  618. const llvm::APSInt &Adjustment) {
  619. return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment);
  620. }
  621. ProgramStateRef
  622. RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
  623. const llvm::APSInt &Int,
  624. const llvm::APSInt &Adjustment) {
  625. RangeSet New = getSymLERange(St, Sym, Int, Adjustment);
  626. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  627. }
  628. ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange(
  629. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  630. const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
  631. RangeSet New = getSymGERange(State, Sym, From, Adjustment);
  632. if (New.isEmpty())
  633. return nullptr;
  634. RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment);
  635. return Out.isEmpty() ? nullptr : State->set<ConstraintRange>(Sym, Out);
  636. }
  637. ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange(
  638. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  639. const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
  640. RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment);
  641. RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment);
  642. RangeSet New(RangeLT.addRange(F, RangeGT));
  643. return New.isEmpty() ? nullptr : State->set<ConstraintRange>(Sym, New);
  644. }
  645. //===------------------------------------------------------------------------===
  646. // Pretty-printing.
  647. //===------------------------------------------------------------------------===/
  648. void RangeConstraintManager::print(ProgramStateRef St, raw_ostream &Out,
  649. const char *nl, const char *sep) {
  650. ConstraintRangeTy Ranges = St->get<ConstraintRange>();
  651. if (Ranges.isEmpty()) {
  652. Out << nl << sep << "Ranges are empty." << nl;
  653. return;
  654. }
  655. Out << nl << sep << "Ranges of symbol values:";
  656. for (ConstraintRangeTy::iterator I = Ranges.begin(), E = Ranges.end(); I != E;
  657. ++I) {
  658. Out << nl << ' ' << I.getKey() << " : ";
  659. I.getData().print(Out);
  660. }
  661. Out << nl;
  662. }