SimpleSValBuilder.cpp 34 KB

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