SimpleConstraintManager.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. //== SimpleConstraintManager.cpp --------------------------------*- 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 SimpleConstraintManager, a class that holds code shared
  11. // between BasicConstraintManager and RangeConstraintManager.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "SimpleConstraintManager.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  18. namespace clang {
  19. namespace ento {
  20. SimpleConstraintManager::~SimpleConstraintManager() {}
  21. bool SimpleConstraintManager::canReasonAbout(SVal X) const {
  22. Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
  23. if (SymVal && SymVal->isExpression()) {
  24. const SymExpr *SE = SymVal->getSymbol();
  25. if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
  26. switch (SIE->getOpcode()) {
  27. // We don't reason yet about bitwise-constraints on symbolic values.
  28. case BO_And:
  29. case BO_Or:
  30. case BO_Xor:
  31. return false;
  32. // We don't reason yet about these arithmetic constraints on
  33. // symbolic values.
  34. case BO_Mul:
  35. case BO_Div:
  36. case BO_Rem:
  37. case BO_Shl:
  38. case BO_Shr:
  39. return false;
  40. // All other cases.
  41. default:
  42. return true;
  43. }
  44. }
  45. if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
  46. if (BinaryOperator::isComparisonOp(SSE->getOpcode())) {
  47. // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
  48. if (Loc::isLocType(SSE->getLHS()->getType())) {
  49. assert(Loc::isLocType(SSE->getRHS()->getType()));
  50. return true;
  51. }
  52. }
  53. }
  54. return false;
  55. }
  56. return true;
  57. }
  58. ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
  59. DefinedSVal Cond,
  60. bool Assumption) {
  61. // If we have a Loc value, cast it to a bool NonLoc first.
  62. if (Optional<Loc> LV = Cond.getAs<Loc>()) {
  63. SValBuilder &SVB = state->getStateManager().getSValBuilder();
  64. QualType T;
  65. const MemRegion *MR = LV->getAsRegion();
  66. if (const TypedRegion *TR = dyn_cast_or_null<TypedRegion>(MR))
  67. T = TR->getLocationType();
  68. else
  69. T = SVB.getContext().VoidPtrTy;
  70. Cond = SVB.evalCast(*LV, SVB.getContext().BoolTy, T).castAs<DefinedSVal>();
  71. }
  72. return assume(state, Cond.castAs<NonLoc>(), Assumption);
  73. }
  74. ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
  75. NonLoc cond,
  76. bool assumption) {
  77. state = assumeAux(state, cond, assumption);
  78. if (NotifyAssumeClients && SU)
  79. return SU->processAssume(state, cond, assumption);
  80. return state;
  81. }
  82. ProgramStateRef
  83. SimpleConstraintManager::assumeAuxForSymbol(ProgramStateRef State,
  84. SymbolRef Sym, bool Assumption) {
  85. BasicValueFactory &BVF = getBasicVals();
  86. QualType T = Sym->getType();
  87. // None of the constraint solvers currently support non-integer types.
  88. if (!T->isIntegralOrEnumerationType())
  89. return State;
  90. const llvm::APSInt &zero = BVF.getValue(0, T);
  91. if (Assumption)
  92. return assumeSymNE(State, Sym, zero, zero);
  93. else
  94. return assumeSymEQ(State, Sym, zero, zero);
  95. }
  96. ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef state,
  97. NonLoc Cond,
  98. bool Assumption) {
  99. // We cannot reason about SymSymExprs, and can only reason about some
  100. // SymIntExprs.
  101. if (!canReasonAbout(Cond)) {
  102. // Just add the constraint to the expression without trying to simplify.
  103. SymbolRef sym = Cond.getAsSymExpr();
  104. return assumeAuxForSymbol(state, sym, Assumption);
  105. }
  106. switch (Cond.getSubKind()) {
  107. default:
  108. llvm_unreachable("'Assume' not implemented for this NonLoc");
  109. case nonloc::SymbolValKind: {
  110. nonloc::SymbolVal SV = Cond.castAs<nonloc::SymbolVal>();
  111. SymbolRef sym = SV.getSymbol();
  112. assert(sym);
  113. // Handle SymbolData.
  114. if (!SV.isExpression()) {
  115. return assumeAuxForSymbol(state, sym, Assumption);
  116. // Handle symbolic expression.
  117. } else if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(sym)) {
  118. // We can only simplify expressions whose RHS is an integer.
  119. BinaryOperator::Opcode op = SE->getOpcode();
  120. if (BinaryOperator::isComparisonOp(op)) {
  121. if (!Assumption)
  122. op = BinaryOperator::negateComparisonOp(op);
  123. return assumeSymRel(state, SE->getLHS(), op, SE->getRHS());
  124. }
  125. } else if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(sym)) {
  126. // Translate "a != b" to "(b - a) != 0".
  127. // We invert the order of the operands as a heuristic for how loop
  128. // conditions are usually written ("begin != end") as compared to length
  129. // calculations ("end - begin"). The more correct thing to do would be to
  130. // canonicalize "a - b" and "b - a", which would allow us to treat
  131. // "a != b" and "b != a" the same.
  132. SymbolManager &SymMgr = getSymbolManager();
  133. BinaryOperator::Opcode Op = SSE->getOpcode();
  134. assert(BinaryOperator::isComparisonOp(Op));
  135. // For now, we only support comparing pointers.
  136. assert(Loc::isLocType(SSE->getLHS()->getType()));
  137. assert(Loc::isLocType(SSE->getRHS()->getType()));
  138. QualType DiffTy = SymMgr.getContext().getPointerDiffType();
  139. SymbolRef Subtraction = SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub,
  140. SSE->getLHS(), DiffTy);
  141. const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
  142. Op = BinaryOperator::reverseComparisonOp(Op);
  143. if (!Assumption)
  144. Op = BinaryOperator::negateComparisonOp(Op);
  145. return assumeSymRel(state, Subtraction, Op, Zero);
  146. }
  147. // If we get here, there's nothing else we can do but treat the symbol as
  148. // opaque.
  149. return assumeAuxForSymbol(state, sym, Assumption);
  150. }
  151. case nonloc::ConcreteIntKind: {
  152. bool b = Cond.castAs<nonloc::ConcreteInt>().getValue() != 0;
  153. bool isFeasible = b ? Assumption : !Assumption;
  154. return isFeasible ? state : nullptr;
  155. }
  156. case nonloc::LocAsIntegerKind:
  157. return assume(state, Cond.castAs<nonloc::LocAsInteger>().getLoc(),
  158. Assumption);
  159. } // end switch
  160. }
  161. static void computeAdjustment(SymbolRef &Sym, llvm::APSInt &Adjustment) {
  162. // Is it a "($sym+constant1)" expression?
  163. if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(Sym)) {
  164. BinaryOperator::Opcode Op = SE->getOpcode();
  165. if (Op == BO_Add || Op == BO_Sub) {
  166. Sym = SE->getLHS();
  167. Adjustment = APSIntType(Adjustment).convert(SE->getRHS());
  168. // Don't forget to negate the adjustment if it's being subtracted.
  169. // This should happen /after/ promotion, in case the value being
  170. // subtracted is, say, CHAR_MIN, and the promoted type is 'int'.
  171. if (Op == BO_Sub)
  172. Adjustment = -Adjustment;
  173. }
  174. }
  175. }
  176. ProgramStateRef SimpleConstraintManager::assumeSymRel(ProgramStateRef state,
  177. const SymExpr *LHS,
  178. BinaryOperator::Opcode op,
  179. const llvm::APSInt& Int) {
  180. assert(BinaryOperator::isComparisonOp(op) &&
  181. "Non-comparison ops should be rewritten as comparisons to zero.");
  182. // Get the type used for calculating wraparound.
  183. BasicValueFactory &BVF = getBasicVals();
  184. APSIntType WraparoundType = BVF.getAPSIntType(LHS->getType());
  185. // We only handle simple comparisons of the form "$sym == constant"
  186. // or "($sym+constant1) == constant2".
  187. // The adjustment is "constant1" in the above expression. It's used to
  188. // "slide" the solution range around for modular arithmetic. For example,
  189. // x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], which
  190. // in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
  191. // the subclasses of SimpleConstraintManager to handle the adjustment.
  192. SymbolRef Sym = LHS;
  193. llvm::APSInt Adjustment = WraparoundType.getZeroValue();
  194. computeAdjustment(Sym, Adjustment);
  195. // Convert the right-hand side integer as necessary.
  196. APSIntType ComparisonType = std::max(WraparoundType, APSIntType(Int));
  197. llvm::APSInt ConvertedInt = ComparisonType.convert(Int);
  198. // Prefer unsigned comparisons.
  199. if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
  200. ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
  201. Adjustment.setIsSigned(false);
  202. switch (op) {
  203. default:
  204. llvm_unreachable("invalid operation not caught by assertion above");
  205. case BO_EQ:
  206. return assumeSymEQ(state, Sym, ConvertedInt, Adjustment);
  207. case BO_NE:
  208. return assumeSymNE(state, Sym, ConvertedInt, Adjustment);
  209. case BO_GT:
  210. return assumeSymGT(state, Sym, ConvertedInt, Adjustment);
  211. case BO_GE:
  212. return assumeSymGE(state, Sym, ConvertedInt, Adjustment);
  213. case BO_LT:
  214. return assumeSymLT(state, Sym, ConvertedInt, Adjustment);
  215. case BO_LE:
  216. return assumeSymLE(state, Sym, ConvertedInt, Adjustment);
  217. } // end switch
  218. }
  219. } // end of namespace ento
  220. } // end of namespace clang