SimpleSValBuilder.cpp 34 KB

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