SimpleSValBuilder.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- 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 SimpleSValBuilder, a basic implementation of SValBuilder.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  16. using namespace clang;
  17. using namespace ento;
  18. namespace {
  19. class SimpleSValBuilder : public SValBuilder {
  20. protected:
  21. virtual SVal dispatchCast(SVal val, QualType castTy);
  22. virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy);
  23. virtual SVal evalCastFromLoc(Loc val, QualType castTy);
  24. public:
  25. SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
  26. ProgramStateManager &stateMgr)
  27. : SValBuilder(alloc, context, stateMgr) {}
  28. virtual ~SimpleSValBuilder() {}
  29. virtual SVal evalMinus(NonLoc val);
  30. virtual SVal evalComplement(NonLoc val);
  31. virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
  32. NonLoc lhs, NonLoc rhs, QualType resultTy);
  33. virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
  34. Loc lhs, Loc rhs, QualType resultTy);
  35. virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
  36. Loc lhs, NonLoc rhs, QualType resultTy);
  37. /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
  38. /// (integer) value, that value is returned. Otherwise, returns NULL.
  39. virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V);
  40. SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
  41. const llvm::APSInt &RHS, QualType resultTy);
  42. };
  43. } // end anonymous namespace
  44. SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
  45. ASTContext &context,
  46. ProgramStateManager &stateMgr) {
  47. return new SimpleSValBuilder(alloc, context, stateMgr);
  48. }
  49. //===----------------------------------------------------------------------===//
  50. // Transfer function for Casts.
  51. //===----------------------------------------------------------------------===//
  52. SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
  53. assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
  54. return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
  55. : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
  56. }
  57. SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
  58. bool isLocType = Loc::isLocType(castTy);
  59. if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
  60. if (isLocType)
  61. return LI->getLoc();
  62. // FIXME: Correctly support promotions/truncations.
  63. unsigned castSize = Context.getTypeSize(castTy);
  64. if (castSize == LI->getNumBits())
  65. return val;
  66. return makeLocAsInteger(LI->getLoc(), castSize);
  67. }
  68. if (const SymExpr *se = val.getAsSymbolicExpression()) {
  69. QualType T = Context.getCanonicalType(se->getType());
  70. // If types are the same or both are integers, ignore the cast.
  71. // FIXME: Remove this hack when we support symbolic truncation/extension.
  72. // HACK: If both castTy and T are integers, ignore the cast. This is
  73. // not a permanent solution. Eventually we want to precisely handle
  74. // extension/truncation of symbolic integers. This prevents us from losing
  75. // precision when we assign 'x = y' and 'y' is symbolic and x and y are
  76. // different integer types.
  77. if (haveSameType(T, castTy))
  78. return val;
  79. if (!isLocType)
  80. return makeNonLoc(se, T, castTy);
  81. return UnknownVal();
  82. }
  83. // If value is a non integer constant, produce unknown.
  84. if (!val.getAs<nonloc::ConcreteInt>())
  85. return UnknownVal();
  86. // Handle casts to a boolean type.
  87. if (castTy->isBooleanType()) {
  88. bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
  89. return makeTruthVal(b, castTy);
  90. }
  91. // Only handle casts from integers to integers - if val is an integer constant
  92. // being cast to a non integer type, produce unknown.
  93. if (!isLocType && !castTy->isIntegerType())
  94. return UnknownVal();
  95. llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
  96. BasicVals.getAPSIntType(castTy).apply(i);
  97. if (isLocType)
  98. return makeIntLocVal(i);
  99. else
  100. return makeIntVal(i);
  101. }
  102. SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
  103. // Casts from pointers -> pointers, just return the lval.
  104. //
  105. // Casts from pointers -> references, just return the lval. These
  106. // can be introduced by the frontend for corner cases, e.g
  107. // casting from va_list* to __builtin_va_list&.
  108. //
  109. if (Loc::isLocType(castTy) || castTy->isReferenceType())
  110. return val;
  111. // FIXME: Handle transparent unions where a value can be "transparently"
  112. // lifted into a union type.
  113. if (castTy->isUnionType())
  114. return UnknownVal();
  115. if (castTy->isIntegerType()) {
  116. unsigned BitWidth = Context.getTypeSize(castTy);
  117. if (!val.getAs<loc::ConcreteInt>())
  118. return makeLocAsInteger(val, BitWidth);
  119. llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
  120. BasicVals.getAPSIntType(castTy).apply(i);
  121. return makeIntVal(i);
  122. }
  123. // All other cases: return 'UnknownVal'. This includes casting pointers
  124. // to floats, which is probably badness it itself, but this is a good
  125. // intermediate solution until we do something better.
  126. return UnknownVal();
  127. }
  128. //===----------------------------------------------------------------------===//
  129. // Transfer function for unary operators.
  130. //===----------------------------------------------------------------------===//
  131. SVal SimpleSValBuilder::evalMinus(NonLoc val) {
  132. switch (val.getSubKind()) {
  133. case nonloc::ConcreteIntKind:
  134. return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
  135. default:
  136. return UnknownVal();
  137. }
  138. }
  139. SVal SimpleSValBuilder::evalComplement(NonLoc X) {
  140. switch (X.getSubKind()) {
  141. case nonloc::ConcreteIntKind:
  142. return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
  143. default:
  144. return UnknownVal();
  145. }
  146. }
  147. //===----------------------------------------------------------------------===//
  148. // Transfer function for binary operators.
  149. //===----------------------------------------------------------------------===//
  150. static BinaryOperator::Opcode NegateComparison(BinaryOperator::Opcode op) {
  151. switch (op) {
  152. default:
  153. llvm_unreachable("Invalid opcode.");
  154. case BO_LT: return BO_GE;
  155. case BO_GT: return BO_LE;
  156. case BO_LE: return BO_GT;
  157. case BO_GE: return BO_LT;
  158. case BO_EQ: return BO_NE;
  159. case BO_NE: return BO_EQ;
  160. }
  161. }
  162. static BinaryOperator::Opcode ReverseComparison(BinaryOperator::Opcode op) {
  163. switch (op) {
  164. default:
  165. llvm_unreachable("Invalid opcode.");
  166. case BO_LT: return BO_GT;
  167. case BO_GT: return BO_LT;
  168. case BO_LE: return BO_GE;
  169. case BO_GE: return BO_LE;
  170. case BO_EQ:
  171. case BO_NE:
  172. return op;
  173. }
  174. }
  175. SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
  176. BinaryOperator::Opcode op,
  177. const llvm::APSInt &RHS,
  178. QualType resultTy) {
  179. bool isIdempotent = false;
  180. // Check for a few special cases with known reductions first.
  181. switch (op) {
  182. default:
  183. // We can't reduce this case; just treat it normally.
  184. break;
  185. case BO_Mul:
  186. // a*0 and a*1
  187. if (RHS == 0)
  188. return makeIntVal(0, resultTy);
  189. else if (RHS == 1)
  190. isIdempotent = true;
  191. break;
  192. case BO_Div:
  193. // a/0 and a/1
  194. if (RHS == 0)
  195. // This is also handled elsewhere.
  196. return UndefinedVal();
  197. else if (RHS == 1)
  198. isIdempotent = true;
  199. break;
  200. case BO_Rem:
  201. // a%0 and a%1
  202. if (RHS == 0)
  203. // This is also handled elsewhere.
  204. return UndefinedVal();
  205. else if (RHS == 1)
  206. return makeIntVal(0, resultTy);
  207. break;
  208. case BO_Add:
  209. case BO_Sub:
  210. case BO_Shl:
  211. case BO_Shr:
  212. case BO_Xor:
  213. // a+0, a-0, a<<0, a>>0, a^0
  214. if (RHS == 0)
  215. isIdempotent = true;
  216. break;
  217. case BO_And:
  218. // a&0 and a&(~0)
  219. if (RHS == 0)
  220. return makeIntVal(0, resultTy);
  221. else if (RHS.isAllOnesValue())
  222. isIdempotent = true;
  223. break;
  224. case BO_Or:
  225. // a|0 and a|(~0)
  226. if (RHS == 0)
  227. isIdempotent = true;
  228. else if (RHS.isAllOnesValue()) {
  229. const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
  230. return nonloc::ConcreteInt(Result);
  231. }
  232. break;
  233. }
  234. // Idempotent ops (like a*1) can still change the type of an expression.
  235. // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
  236. // dirty work.
  237. if (isIdempotent)
  238. return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
  239. // If we reach this point, the expression cannot be simplified.
  240. // Make a SymbolVal for the entire expression, after converting the RHS.
  241. const llvm::APSInt *ConvertedRHS = &RHS;
  242. if (BinaryOperator::isComparisonOp(op)) {
  243. // We're looking for a type big enough to compare the symbolic value
  244. // with the given constant.
  245. // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
  246. ASTContext &Ctx = getContext();
  247. QualType SymbolType = LHS->getType();
  248. uint64_t ValWidth = RHS.getBitWidth();
  249. uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
  250. if (ValWidth < TypeWidth) {
  251. // If the value is too small, extend it.
  252. ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
  253. } else if (ValWidth == TypeWidth) {
  254. // If the value is signed but the symbol is unsigned, do the comparison
  255. // in unsigned space. [C99 6.3.1.8]
  256. // (For the opposite case, the value is already unsigned.)
  257. if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
  258. ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
  259. }
  260. } else
  261. ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
  262. return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
  263. }
  264. SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
  265. BinaryOperator::Opcode op,
  266. NonLoc lhs, NonLoc rhs,
  267. QualType resultTy) {
  268. NonLoc InputLHS = lhs;
  269. NonLoc InputRHS = rhs;
  270. // Handle trivial case where left-side and right-side are the same.
  271. if (lhs == rhs)
  272. switch (op) {
  273. default:
  274. break;
  275. case BO_EQ:
  276. case BO_LE:
  277. case BO_GE:
  278. return makeTruthVal(true, resultTy);
  279. case BO_LT:
  280. case BO_GT:
  281. case BO_NE:
  282. return makeTruthVal(false, resultTy);
  283. case BO_Xor:
  284. case BO_Sub:
  285. if (resultTy->isIntegralOrEnumerationType())
  286. return makeIntVal(0, resultTy);
  287. return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
  288. case BO_Or:
  289. case BO_And:
  290. return evalCastFromNonLoc(lhs, resultTy);
  291. }
  292. while (1) {
  293. switch (lhs.getSubKind()) {
  294. default:
  295. return makeSymExprValNN(state, op, lhs, rhs, resultTy);
  296. case nonloc::LocAsIntegerKind: {
  297. Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
  298. switch (rhs.getSubKind()) {
  299. case nonloc::LocAsIntegerKind:
  300. return evalBinOpLL(state, op, lhsL,
  301. rhs.castAs<nonloc::LocAsInteger>().getLoc(),
  302. resultTy);
  303. case nonloc::ConcreteIntKind: {
  304. // Transform the integer into a location and compare.
  305. llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
  306. BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
  307. return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
  308. }
  309. default:
  310. switch (op) {
  311. case BO_EQ:
  312. return makeTruthVal(false, resultTy);
  313. case BO_NE:
  314. return makeTruthVal(true, resultTy);
  315. default:
  316. // This case also handles pointer arithmetic.
  317. return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
  318. }
  319. }
  320. }
  321. case nonloc::ConcreteIntKind: {
  322. llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
  323. // If we're dealing with two known constants, just perform the operation.
  324. if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
  325. llvm::APSInt RHSValue = *KnownRHSValue;
  326. if (BinaryOperator::isComparisonOp(op)) {
  327. // We're looking for a type big enough to compare the two values.
  328. // FIXME: This is not correct. char + short will result in a promotion
  329. // to int. Unfortunately we have lost types by this point.
  330. APSIntType CompareType = std::max(APSIntType(LHSValue),
  331. APSIntType(RHSValue));
  332. CompareType.apply(LHSValue);
  333. CompareType.apply(RHSValue);
  334. } else if (!BinaryOperator::isShiftOp(op)) {
  335. APSIntType IntType = BasicVals.getAPSIntType(resultTy);
  336. IntType.apply(LHSValue);
  337. IntType.apply(RHSValue);
  338. }
  339. const llvm::APSInt *Result =
  340. BasicVals.evalAPSInt(op, LHSValue, RHSValue);
  341. if (!Result)
  342. return UndefinedVal();
  343. return nonloc::ConcreteInt(*Result);
  344. }
  345. // Swap the left and right sides and flip the operator if doing so
  346. // allows us to better reason about the expression (this is a form
  347. // of expression canonicalization).
  348. // While we're at it, catch some special cases for non-commutative ops.
  349. switch (op) {
  350. case BO_LT:
  351. case BO_GT:
  352. case BO_LE:
  353. case BO_GE:
  354. op = ReverseComparison(op);
  355. // FALL-THROUGH
  356. case BO_EQ:
  357. case BO_NE:
  358. case BO_Add:
  359. case BO_Mul:
  360. case BO_And:
  361. case BO_Xor:
  362. case BO_Or:
  363. std::swap(lhs, rhs);
  364. continue;
  365. case BO_Shr:
  366. // (~0)>>a
  367. if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
  368. return evalCastFromNonLoc(lhs, resultTy);
  369. // FALL-THROUGH
  370. case BO_Shl:
  371. // 0<<a and 0>>a
  372. if (LHSValue == 0)
  373. return evalCastFromNonLoc(lhs, resultTy);
  374. return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
  375. default:
  376. return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
  377. }
  378. }
  379. case nonloc::SymbolValKind: {
  380. // We only handle LHS as simple symbols or SymIntExprs.
  381. SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
  382. // LHS is a symbolic expression.
  383. if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
  384. // Is this a logical not? (!x is represented as x == 0.)
  385. if (op == BO_EQ && rhs.isZeroConstant()) {
  386. // We know how to negate certain expressions. Simplify them here.
  387. BinaryOperator::Opcode opc = symIntExpr->getOpcode();
  388. switch (opc) {
  389. default:
  390. // We don't know how to negate this operation.
  391. // Just handle it as if it were a normal comparison to 0.
  392. break;
  393. case BO_LAnd:
  394. case BO_LOr:
  395. llvm_unreachable("Logical operators handled by branching logic.");
  396. case BO_Assign:
  397. case BO_MulAssign:
  398. case BO_DivAssign:
  399. case BO_RemAssign:
  400. case BO_AddAssign:
  401. case BO_SubAssign:
  402. case BO_ShlAssign:
  403. case BO_ShrAssign:
  404. case BO_AndAssign:
  405. case BO_XorAssign:
  406. case BO_OrAssign:
  407. case BO_Comma:
  408. llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
  409. case BO_PtrMemD:
  410. case BO_PtrMemI:
  411. llvm_unreachable("Pointer arithmetic not handled here.");
  412. case BO_LT:
  413. case BO_GT:
  414. case BO_LE:
  415. case BO_GE:
  416. case BO_EQ:
  417. case BO_NE:
  418. // Negate the comparison and make a value.
  419. opc = NegateComparison(opc);
  420. assert(symIntExpr->getType() == resultTy);
  421. return makeNonLoc(symIntExpr->getLHS(), opc,
  422. symIntExpr->getRHS(), resultTy);
  423. }
  424. }
  425. // For now, only handle expressions whose RHS is a constant.
  426. if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
  427. // If both the LHS and the current expression are additive,
  428. // fold their constants and try again.
  429. if (BinaryOperator::isAdditiveOp(op)) {
  430. BinaryOperator::Opcode lop = symIntExpr->getOpcode();
  431. if (BinaryOperator::isAdditiveOp(lop)) {
  432. // Convert the two constants to a common type, then combine them.
  433. // resultTy may not be the best type to convert to, but it's
  434. // probably the best choice in expressions with mixed type
  435. // (such as x+1U+2LL). The rules for implicit conversions should
  436. // choose a reasonable type to preserve the expression, and will
  437. // at least match how the value is going to be used.
  438. APSIntType IntType = BasicVals.getAPSIntType(resultTy);
  439. const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
  440. const llvm::APSInt &second = IntType.convert(*RHSValue);
  441. const llvm::APSInt *newRHS;
  442. if (lop == op)
  443. newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
  444. else
  445. newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
  446. assert(newRHS && "Invalid operation despite common type!");
  447. rhs = nonloc::ConcreteInt(*newRHS);
  448. lhs = nonloc::SymbolVal(symIntExpr->getLHS());
  449. op = lop;
  450. continue;
  451. }
  452. }
  453. // Otherwise, make a SymIntExpr out of the expression.
  454. return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
  455. }
  456. } else if (isa<SymbolData>(Sym)) {
  457. // Does the symbol simplify to a constant? If so, "fold" the constant
  458. // by setting 'lhs' to a ConcreteInt and try again.
  459. if (const llvm::APSInt *Constant = state->getConstraintManager()
  460. .getSymVal(state, Sym)) {
  461. lhs = nonloc::ConcreteInt(*Constant);
  462. continue;
  463. }
  464. // Is the RHS a constant?
  465. if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
  466. return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
  467. }
  468. // Give up -- this is not a symbolic expression we can handle.
  469. return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
  470. }
  471. }
  472. }
  473. }
  474. // FIXME: all this logic will change if/when we have MemRegion::getLocation().
  475. SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
  476. BinaryOperator::Opcode op,
  477. Loc lhs, Loc rhs,
  478. QualType resultTy) {
  479. // Only comparisons and subtractions are valid operations on two pointers.
  480. // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
  481. // However, if a pointer is casted to an integer, evalBinOpNN may end up
  482. // calling this function with another operation (PR7527). We don't attempt to
  483. // model this for now, but it could be useful, particularly when the
  484. // "location" is actually an integer value that's been passed through a void*.
  485. if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
  486. return UnknownVal();
  487. // Special cases for when both sides are identical.
  488. if (lhs == rhs) {
  489. switch (op) {
  490. default:
  491. llvm_unreachable("Unimplemented operation for two identical values");
  492. case BO_Sub:
  493. return makeZeroVal(resultTy);
  494. case BO_EQ:
  495. case BO_LE:
  496. case BO_GE:
  497. return makeTruthVal(true, resultTy);
  498. case BO_NE:
  499. case BO_LT:
  500. case BO_GT:
  501. return makeTruthVal(false, resultTy);
  502. }
  503. }
  504. switch (lhs.getSubKind()) {
  505. default:
  506. llvm_unreachable("Ordering not implemented for this Loc.");
  507. case loc::GotoLabelKind:
  508. // The only thing we know about labels is that they're non-null.
  509. if (rhs.isZeroConstant()) {
  510. switch (op) {
  511. default:
  512. break;
  513. case BO_Sub:
  514. return evalCastFromLoc(lhs, resultTy);
  515. case BO_EQ:
  516. case BO_LE:
  517. case BO_LT:
  518. return makeTruthVal(false, resultTy);
  519. case BO_NE:
  520. case BO_GT:
  521. case BO_GE:
  522. return makeTruthVal(true, resultTy);
  523. }
  524. }
  525. // There may be two labels for the same location, and a function region may
  526. // have the same address as a label at the start of the function (depending
  527. // on the ABI).
  528. // FIXME: we can probably do a comparison against other MemRegions, though.
  529. // FIXME: is there a way to tell if two labels refer to the same location?
  530. return UnknownVal();
  531. case loc::ConcreteIntKind: {
  532. // If one of the operands is a symbol and the other is a constant,
  533. // build an expression for use by the constraint manager.
  534. if (SymbolRef rSym = rhs.getAsLocSymbol()) {
  535. // We can only build expressions with symbols on the left,
  536. // so we need a reversible operator.
  537. if (!BinaryOperator::isComparisonOp(op))
  538. return UnknownVal();
  539. const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
  540. return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy);
  541. }
  542. // If both operands are constants, just perform the operation.
  543. if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
  544. SVal ResultVal =
  545. lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
  546. if (Optional<Loc> Result = ResultVal.getAs<Loc>())
  547. return evalCastFromLoc(*Result, resultTy);
  548. else
  549. return UnknownVal();
  550. }
  551. // Special case comparisons against NULL.
  552. // This must come after the test if the RHS is a symbol, which is used to
  553. // build constraints. The address of any non-symbolic region is guaranteed
  554. // to be non-NULL, as is any label.
  555. assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
  556. if (lhs.isZeroConstant()) {
  557. switch (op) {
  558. default:
  559. break;
  560. case BO_EQ:
  561. case BO_GT:
  562. case BO_GE:
  563. return makeTruthVal(false, resultTy);
  564. case BO_NE:
  565. case BO_LT:
  566. case BO_LE:
  567. return makeTruthVal(true, resultTy);
  568. }
  569. }
  570. // Comparing an arbitrary integer to a region or label address is
  571. // completely unknowable.
  572. return UnknownVal();
  573. }
  574. case loc::MemRegionKind: {
  575. if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
  576. // If one of the operands is a symbol and the other is a constant,
  577. // build an expression for use by the constraint manager.
  578. if (SymbolRef lSym = lhs.getAsLocSymbol())
  579. return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
  580. // Special case comparisons to NULL.
  581. // This must come after the test if the LHS is a symbol, which is used to
  582. // build constraints. The address of any non-symbolic region is guaranteed
  583. // to be non-NULL.
  584. if (rInt->isZeroConstant()) {
  585. switch (op) {
  586. default:
  587. break;
  588. case BO_Sub:
  589. return evalCastFromLoc(lhs, resultTy);
  590. case BO_EQ:
  591. case BO_LT:
  592. case BO_LE:
  593. return makeTruthVal(false, resultTy);
  594. case BO_NE:
  595. case BO_GT:
  596. case BO_GE:
  597. return makeTruthVal(true, resultTy);
  598. }
  599. }
  600. // Comparing a region to an arbitrary integer is completely unknowable.
  601. return UnknownVal();
  602. }
  603. // Get both values as regions, if possible.
  604. const MemRegion *LeftMR = lhs.getAsRegion();
  605. assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
  606. const MemRegion *RightMR = rhs.getAsRegion();
  607. if (!RightMR)
  608. // The RHS is probably a label, which in theory could address a region.
  609. // FIXME: we can probably make a more useful statement about non-code
  610. // regions, though.
  611. return UnknownVal();
  612. const MemSpaceRegion *LeftMS = LeftMR->getMemorySpace();
  613. const MemSpaceRegion *RightMS = RightMR->getMemorySpace();
  614. const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
  615. const MemRegion *LeftBase = LeftMR->getBaseRegion();
  616. const MemRegion *RightBase = RightMR->getBaseRegion();
  617. // If the two regions are from different known memory spaces they cannot be
  618. // equal. Also, assume that no symbolic region (whose memory space is
  619. // unknown) is on the stack.
  620. if (LeftMS != RightMS &&
  621. ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
  622. (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
  623. switch (op) {
  624. default:
  625. return UnknownVal();
  626. case BO_EQ:
  627. return makeTruthVal(false, resultTy);
  628. case BO_NE:
  629. return makeTruthVal(true, resultTy);
  630. }
  631. }
  632. // If both values wrap regions, see if they're from different base regions.
  633. // Note, heap base symbolic regions are assumed to not alias with
  634. // each other; for example, we assume that malloc returns different address
  635. // on each invocation.
  636. if (LeftBase != RightBase &&
  637. ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
  638. (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
  639. switch (op) {
  640. default:
  641. return UnknownVal();
  642. case BO_EQ:
  643. return makeTruthVal(false, resultTy);
  644. case BO_NE:
  645. return makeTruthVal(true, resultTy);
  646. }
  647. }
  648. // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
  649. // ElementRegion path and the FieldRegion path below should be unified.
  650. if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
  651. // First see if the right region is also an ElementRegion.
  652. const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
  653. if (!RightER)
  654. return UnknownVal();
  655. // Next, see if the two ERs have the same super-region and matching types.
  656. // FIXME: This should do something useful even if the types don't match,
  657. // though if both indexes are constant the RegionRawOffset path will
  658. // give the correct answer.
  659. if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
  660. LeftER->getElementType() == RightER->getElementType()) {
  661. // Get the left index and cast it to the correct type.
  662. // If the index is unknown or undefined, bail out here.
  663. SVal LeftIndexVal = LeftER->getIndex();
  664. Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
  665. if (!LeftIndex)
  666. return UnknownVal();
  667. LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
  668. LeftIndex = LeftIndexVal.getAs<NonLoc>();
  669. if (!LeftIndex)
  670. return UnknownVal();
  671. // Do the same for the right index.
  672. SVal RightIndexVal = RightER->getIndex();
  673. Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
  674. if (!RightIndex)
  675. return UnknownVal();
  676. RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
  677. RightIndex = RightIndexVal.getAs<NonLoc>();
  678. if (!RightIndex)
  679. return UnknownVal();
  680. // Actually perform the operation.
  681. // evalBinOpNN expects the two indexes to already be the right type.
  682. return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
  683. }
  684. // If the element indexes aren't comparable, see if the raw offsets are.
  685. RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
  686. RegionRawOffset RightOffset = RightER->getAsArrayOffset();
  687. if (LeftOffset.getRegion() != NULL &&
  688. LeftOffset.getRegion() == RightOffset.getRegion()) {
  689. CharUnits left = LeftOffset.getOffset();
  690. CharUnits right = RightOffset.getOffset();
  691. switch (op) {
  692. default:
  693. return UnknownVal();
  694. case BO_LT:
  695. return makeTruthVal(left < right, resultTy);
  696. case BO_GT:
  697. return makeTruthVal(left > right, resultTy);
  698. case BO_LE:
  699. return makeTruthVal(left <= right, resultTy);
  700. case BO_GE:
  701. return makeTruthVal(left >= right, resultTy);
  702. case BO_EQ:
  703. return makeTruthVal(left == right, resultTy);
  704. case BO_NE:
  705. return makeTruthVal(left != right, resultTy);
  706. }
  707. }
  708. // If we get here, we have no way of comparing the ElementRegions.
  709. return UnknownVal();
  710. }
  711. // See if both regions are fields of the same structure.
  712. // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
  713. if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
  714. // Only comparisons are meaningful here!
  715. if (!BinaryOperator::isComparisonOp(op))
  716. return UnknownVal();
  717. // First see if the right region is also a FieldRegion.
  718. const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
  719. if (!RightFR)
  720. return UnknownVal();
  721. // Next, see if the two FRs have the same super-region.
  722. // FIXME: This doesn't handle casts yet, and simply stripping the casts
  723. // doesn't help.
  724. if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
  725. return UnknownVal();
  726. const FieldDecl *LeftFD = LeftFR->getDecl();
  727. const FieldDecl *RightFD = RightFR->getDecl();
  728. const RecordDecl *RD = LeftFD->getParent();
  729. // Make sure the two FRs are from the same kind of record. Just in case!
  730. // FIXME: This is probably where inheritance would be a problem.
  731. if (RD != RightFD->getParent())
  732. return UnknownVal();
  733. // We know for sure that the two fields are not the same, since that
  734. // would have given us the same SVal.
  735. if (op == BO_EQ)
  736. return makeTruthVal(false, resultTy);
  737. if (op == BO_NE)
  738. return makeTruthVal(true, resultTy);
  739. // Iterate through the fields and see which one comes first.
  740. // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
  741. // members and the units in which bit-fields reside have addresses that
  742. // increase in the order in which they are declared."
  743. bool leftFirst = (op == BO_LT || op == BO_LE);
  744. for (RecordDecl::field_iterator I = RD->field_begin(),
  745. E = RD->field_end(); I!=E; ++I) {
  746. if (*I == LeftFD)
  747. return makeTruthVal(leftFirst, resultTy);
  748. if (*I == RightFD)
  749. return makeTruthVal(!leftFirst, resultTy);
  750. }
  751. llvm_unreachable("Fields not found in parent record's definition");
  752. }
  753. // If we get here, we have no way of comparing the regions.
  754. return UnknownVal();
  755. }
  756. }
  757. }
  758. SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
  759. BinaryOperator::Opcode op,
  760. Loc lhs, NonLoc rhs, QualType resultTy) {
  761. // Special case: rhs is a zero constant.
  762. if (rhs.isZeroConstant())
  763. return lhs;
  764. // Special case: 'rhs' is an integer that has the same width as a pointer and
  765. // we are using the integer location in a comparison. Normally this cannot be
  766. // triggered, but transfer functions like those for OSCompareAndSwapBarrier32
  767. // can generate comparisons that trigger this code.
  768. // FIXME: Are all locations guaranteed to have pointer width?
  769. if (BinaryOperator::isComparisonOp(op)) {
  770. if (Optional<nonloc::ConcreteInt> rhsInt =
  771. rhs.getAs<nonloc::ConcreteInt>()) {
  772. const llvm::APSInt *x = &rhsInt->getValue();
  773. ASTContext &ctx = Context;
  774. if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
  775. // Convert the signedness of the integer (if necessary).
  776. if (x->isSigned())
  777. x = &getBasicValueFactory().getValue(*x, true);
  778. return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
  779. }
  780. }
  781. return UnknownVal();
  782. }
  783. // We are dealing with pointer arithmetic.
  784. // Handle pointer arithmetic on constant values.
  785. if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
  786. if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
  787. const llvm::APSInt &leftI = lhsInt->getValue();
  788. assert(leftI.isUnsigned());
  789. llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
  790. // Convert the bitwidth of rightI. This should deal with overflow
  791. // since we are dealing with concrete values.
  792. rightI = rightI.extOrTrunc(leftI.getBitWidth());
  793. // Offset the increment by the pointer size.
  794. llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
  795. rightI *= Multiplicand;
  796. // Compute the adjusted pointer.
  797. switch (op) {
  798. case BO_Add:
  799. rightI = leftI + rightI;
  800. break;
  801. case BO_Sub:
  802. rightI = leftI - rightI;
  803. break;
  804. default:
  805. llvm_unreachable("Invalid pointer arithmetic operation");
  806. }
  807. return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
  808. }
  809. }
  810. // Handle cases where 'lhs' is a region.
  811. if (const MemRegion *region = lhs.getAsRegion()) {
  812. rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
  813. SVal index = UnknownVal();
  814. const MemRegion *superR = 0;
  815. QualType elementType;
  816. if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
  817. assert(op == BO_Add || op == BO_Sub);
  818. index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
  819. getArrayIndexType());
  820. superR = elemReg->getSuperRegion();
  821. elementType = elemReg->getElementType();
  822. }
  823. else if (isa<SubRegion>(region)) {
  824. superR = region;
  825. index = rhs;
  826. if (resultTy->isAnyPointerType())
  827. elementType = resultTy->getPointeeType();
  828. }
  829. if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
  830. return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
  831. superR, getContext()));
  832. }
  833. }
  834. return UnknownVal();
  835. }
  836. const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
  837. SVal V) {
  838. if (V.isUnknownOrUndef())
  839. return NULL;
  840. if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
  841. return &X->getValue();
  842. if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
  843. return &X->getValue();
  844. if (SymbolRef Sym = V.getAsSymbol())
  845. return state->getConstraintManager().getSymVal(state, Sym);
  846. // FIXME: Add support for SymExprs.
  847. return NULL;
  848. }