SimpleSValBuilder.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  13. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
  18. using namespace clang;
  19. using namespace ento;
  20. namespace {
  21. class SimpleSValBuilder : public SValBuilder {
  22. protected:
  23. SVal dispatchCast(SVal val, QualType castTy) override;
  24. SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
  25. SVal evalCastFromLoc(Loc val, QualType castTy) override;
  26. public:
  27. SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
  28. ProgramStateManager &stateMgr)
  29. : SValBuilder(alloc, context, stateMgr) {}
  30. ~SimpleSValBuilder() override {}
  31. SVal evalMinus(NonLoc val) override;
  32. SVal evalComplement(NonLoc val) override;
  33. SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
  34. NonLoc lhs, NonLoc rhs, QualType resultTy) override;
  35. SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
  36. Loc lhs, Loc rhs, QualType resultTy) override;
  37. SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
  38. Loc lhs, NonLoc rhs, QualType resultTy) override;
  39. /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
  40. /// (integer) value, that value is returned. Otherwise, returns NULL.
  41. const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
  42. /// Recursively descends into symbolic expressions and replaces symbols
  43. /// with their known values (in the sense of the getKnownValue() method).
  44. SVal simplifySVal(ProgramStateRef State, SVal V) override;
  45. SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
  46. const llvm::APSInt &RHS, QualType resultTy);
  47. };
  48. } // end anonymous namespace
  49. SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
  50. ASTContext &context,
  51. ProgramStateManager &stateMgr) {
  52. return new SimpleSValBuilder(alloc, context, stateMgr);
  53. }
  54. //===----------------------------------------------------------------------===//
  55. // Transfer function for Casts.
  56. //===----------------------------------------------------------------------===//
  57. SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
  58. assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
  59. return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
  60. : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
  61. }
  62. SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
  63. bool isLocType = Loc::isLocType(castTy);
  64. if (val.getAs<nonloc::PointerToMember>())
  65. return val;
  66. if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
  67. if (isLocType)
  68. return LI->getLoc();
  69. // FIXME: Correctly support promotions/truncations.
  70. unsigned castSize = Context.getIntWidth(castTy);
  71. if (castSize == LI->getNumBits())
  72. return val;
  73. return makeLocAsInteger(LI->getLoc(), castSize);
  74. }
  75. if (const SymExpr *se = val.getAsSymbolicExpression()) {
  76. QualType T = Context.getCanonicalType(se->getType());
  77. // If types are the same or both are integers, ignore the cast.
  78. // FIXME: Remove this hack when we support symbolic truncation/extension.
  79. // HACK: If both castTy and T are integers, ignore the cast. This is
  80. // not a permanent solution. Eventually we want to precisely handle
  81. // extension/truncation of symbolic integers. This prevents us from losing
  82. // precision when we assign 'x = y' and 'y' is symbolic and x and y are
  83. // different integer types.
  84. if (haveSameType(T, castTy))
  85. return val;
  86. if (!isLocType)
  87. return makeNonLoc(se, T, castTy);
  88. return UnknownVal();
  89. }
  90. // If value is a non-integer constant, produce unknown.
  91. if (!val.getAs<nonloc::ConcreteInt>())
  92. return UnknownVal();
  93. // Handle casts to a boolean type.
  94. if (castTy->isBooleanType()) {
  95. bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
  96. return makeTruthVal(b, castTy);
  97. }
  98. // Only handle casts from integers to integers - if val is an integer constant
  99. // being cast to a non-integer type, produce unknown.
  100. if (!isLocType && !castTy->isIntegralOrEnumerationType())
  101. return UnknownVal();
  102. llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
  103. BasicVals.getAPSIntType(castTy).apply(i);
  104. if (isLocType)
  105. return makeIntLocVal(i);
  106. else
  107. return makeIntVal(i);
  108. }
  109. SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
  110. // Casts from pointers -> pointers, just return the lval.
  111. //
  112. // Casts from pointers -> references, just return the lval. These
  113. // can be introduced by the frontend for corner cases, e.g
  114. // casting from va_list* to __builtin_va_list&.
  115. //
  116. if (Loc::isLocType(castTy) || castTy->isReferenceType())
  117. return val;
  118. // FIXME: Handle transparent unions where a value can be "transparently"
  119. // lifted into a union type.
  120. if (castTy->isUnionType())
  121. return UnknownVal();
  122. // Casting a Loc to a bool will almost always be true,
  123. // unless this is a weak function or a symbolic region.
  124. if (castTy->isBooleanType()) {
  125. switch (val.getSubKind()) {
  126. case loc::MemRegionValKind: {
  127. const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
  128. if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
  129. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
  130. if (FD->isWeak())
  131. // FIXME: Currently we are using an extent symbol here,
  132. // because there are no generic region address metadata
  133. // symbols to use, only content metadata.
  134. return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
  135. if (const SymbolicRegion *SymR = R->getSymbolicBase())
  136. return makeNonLoc(SymR->getSymbol(), BO_NE,
  137. BasicVals.getZeroWithPtrWidth(), castTy);
  138. // FALL-THROUGH
  139. LLVM_FALLTHROUGH;
  140. }
  141. case loc::GotoLabelKind:
  142. // Labels and non-symbolic memory regions are always true.
  143. return makeTruthVal(true, castTy);
  144. }
  145. }
  146. if (castTy->isIntegralOrEnumerationType()) {
  147. unsigned BitWidth = Context.getIntWidth(castTy);
  148. if (!val.getAs<loc::ConcreteInt>())
  149. return makeLocAsInteger(val, BitWidth);
  150. llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
  151. BasicVals.getAPSIntType(castTy).apply(i);
  152. return makeIntVal(i);
  153. }
  154. // All other cases: return 'UnknownVal'. This includes casting pointers
  155. // to floats, which is probably badness it itself, but this is a good
  156. // intermediate solution until we do something better.
  157. return UnknownVal();
  158. }
  159. //===----------------------------------------------------------------------===//
  160. // Transfer function for unary operators.
  161. //===----------------------------------------------------------------------===//
  162. SVal SimpleSValBuilder::evalMinus(NonLoc val) {
  163. switch (val.getSubKind()) {
  164. case nonloc::ConcreteIntKind:
  165. return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
  166. default:
  167. return UnknownVal();
  168. }
  169. }
  170. SVal SimpleSValBuilder::evalComplement(NonLoc X) {
  171. switch (X.getSubKind()) {
  172. case nonloc::ConcreteIntKind:
  173. return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
  174. default:
  175. return UnknownVal();
  176. }
  177. }
  178. //===----------------------------------------------------------------------===//
  179. // Transfer function for binary operators.
  180. //===----------------------------------------------------------------------===//
  181. SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
  182. BinaryOperator::Opcode op,
  183. const llvm::APSInt &RHS,
  184. QualType resultTy) {
  185. bool isIdempotent = false;
  186. // Check for a few special cases with known reductions first.
  187. switch (op) {
  188. default:
  189. // We can't reduce this case; just treat it normally.
  190. break;
  191. case BO_Mul:
  192. // a*0 and a*1
  193. if (RHS == 0)
  194. return makeIntVal(0, resultTy);
  195. else if (RHS == 1)
  196. isIdempotent = true;
  197. break;
  198. case BO_Div:
  199. // a/0 and a/1
  200. if (RHS == 0)
  201. // This is also handled elsewhere.
  202. return UndefinedVal();
  203. else if (RHS == 1)
  204. isIdempotent = true;
  205. break;
  206. case BO_Rem:
  207. // a%0 and a%1
  208. if (RHS == 0)
  209. // This is also handled elsewhere.
  210. return UndefinedVal();
  211. else if (RHS == 1)
  212. return makeIntVal(0, resultTy);
  213. break;
  214. case BO_Add:
  215. case BO_Sub:
  216. case BO_Shl:
  217. case BO_Shr:
  218. case BO_Xor:
  219. // a+0, a-0, a<<0, a>>0, a^0
  220. if (RHS == 0)
  221. isIdempotent = true;
  222. break;
  223. case BO_And:
  224. // a&0 and a&(~0)
  225. if (RHS == 0)
  226. return makeIntVal(0, resultTy);
  227. else if (RHS.isAllOnesValue())
  228. isIdempotent = true;
  229. break;
  230. case BO_Or:
  231. // a|0 and a|(~0)
  232. if (RHS == 0)
  233. isIdempotent = true;
  234. else if (RHS.isAllOnesValue()) {
  235. const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
  236. return nonloc::ConcreteInt(Result);
  237. }
  238. break;
  239. }
  240. // Idempotent ops (like a*1) can still change the type of an expression.
  241. // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
  242. // dirty work.
  243. if (isIdempotent)
  244. return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
  245. // If we reach this point, the expression cannot be simplified.
  246. // Make a SymbolVal for the entire expression, after converting the RHS.
  247. const llvm::APSInt *ConvertedRHS = &RHS;
  248. if (BinaryOperator::isComparisonOp(op)) {
  249. // We're looking for a type big enough to compare the symbolic value
  250. // with the given constant.
  251. // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
  252. ASTContext &Ctx = getContext();
  253. QualType SymbolType = LHS->getType();
  254. uint64_t ValWidth = RHS.getBitWidth();
  255. uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
  256. if (ValWidth < TypeWidth) {
  257. // If the value is too small, extend it.
  258. ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
  259. } else if (ValWidth == TypeWidth) {
  260. // If the value is signed but the symbol is unsigned, do the comparison
  261. // in unsigned space. [C99 6.3.1.8]
  262. // (For the opposite case, the value is already unsigned.)
  263. if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
  264. ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
  265. }
  266. } else
  267. ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
  268. return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
  269. }
  270. // See if Sym is known to be a relation Rel with Bound.
  271. static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
  272. llvm::APSInt Bound, ProgramStateRef State) {
  273. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  274. SVal Result =
  275. SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
  276. nonloc::ConcreteInt(Bound), SVB.getConditionType());
  277. if (auto DV = Result.getAs<DefinedSVal>()) {
  278. return !State->assume(*DV, false);
  279. }
  280. return false;
  281. }
  282. // See if Sym is known to be within [min/4, max/4], where min and max
  283. // are the bounds of the symbol's integral type. With such symbols,
  284. // some manipulations can be performed without the risk of overflow.
  285. // assume() doesn't cause infinite recursion because we should be dealing
  286. // with simpler symbols on every recursive call.
  287. static bool isWithinConstantOverflowBounds(SymbolRef Sym,
  288. ProgramStateRef State) {
  289. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  290. BasicValueFactory &BV = SVB.getBasicValueFactory();
  291. QualType T = Sym->getType();
  292. assert(T->isSignedIntegerOrEnumerationType() &&
  293. "This only works with signed integers!");
  294. APSIntType AT = BV.getAPSIntType(T);
  295. llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
  296. return isInRelation(BO_LE, Sym, Max, State) &&
  297. isInRelation(BO_GE, Sym, Min, State);
  298. }
  299. // Same for the concrete integers: see if I is within [min/4, max/4].
  300. static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
  301. APSIntType AT(I);
  302. assert(!AT.isUnsigned() &&
  303. "This only works with signed integers!");
  304. llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
  305. return (I <= Max) && (I >= -Max);
  306. }
  307. static std::pair<SymbolRef, llvm::APSInt>
  308. decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
  309. if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
  310. if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
  311. return std::make_pair(SymInt->getLHS(),
  312. (SymInt->getOpcode() == BO_Add) ?
  313. (SymInt->getRHS()) :
  314. (-SymInt->getRHS()));
  315. // Fail to decompose: "reduce" the problem to the "$x + 0" case.
  316. return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
  317. }
  318. // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
  319. // same signed integral type and no overflows occur (which should be checked
  320. // by the caller).
  321. static NonLoc doRearrangeUnchecked(ProgramStateRef State,
  322. BinaryOperator::Opcode Op,
  323. SymbolRef LSym, llvm::APSInt LInt,
  324. SymbolRef RSym, llvm::APSInt RInt) {
  325. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  326. BasicValueFactory &BV = SVB.getBasicValueFactory();
  327. SymbolManager &SymMgr = SVB.getSymbolManager();
  328. QualType SymTy = LSym->getType();
  329. assert(SymTy == RSym->getType() &&
  330. "Symbols are not of the same type!");
  331. assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
  332. "Integers are not of the same type as symbols!");
  333. assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
  334. "Integers are not of the same type as symbols!");
  335. QualType ResultTy;
  336. if (BinaryOperator::isComparisonOp(Op))
  337. ResultTy = SVB.getConditionType();
  338. else if (BinaryOperator::isAdditiveOp(Op))
  339. ResultTy = SymTy;
  340. else
  341. llvm_unreachable("Operation not suitable for unchecked rearrangement!");
  342. // FIXME: Can we use assume() without getting into an infinite recursion?
  343. if (LSym == RSym)
  344. return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
  345. nonloc::ConcreteInt(RInt), ResultTy)
  346. .castAs<NonLoc>();
  347. SymbolRef ResultSym = nullptr;
  348. BinaryOperator::Opcode ResultOp;
  349. llvm::APSInt ResultInt;
  350. if (BinaryOperator::isComparisonOp(Op)) {
  351. // Prefer comparing to a non-negative number.
  352. // FIXME: Maybe it'd be better to have consistency in
  353. // "$x - $y" vs. "$y - $x" because those are solver's keys.
  354. if (LInt > RInt) {
  355. ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
  356. ResultOp = BinaryOperator::reverseComparisonOp(Op);
  357. ResultInt = LInt - RInt; // Opposite order!
  358. } else {
  359. ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
  360. ResultOp = Op;
  361. ResultInt = RInt - LInt; // Opposite order!
  362. }
  363. } else {
  364. ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
  365. ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
  366. ResultOp = BO_Add;
  367. // Bring back the cosmetic difference.
  368. if (ResultInt < 0) {
  369. ResultInt = -ResultInt;
  370. ResultOp = BO_Sub;
  371. } else if (ResultInt == 0) {
  372. // Shortcut: Simplify "$x + 0" to "$x".
  373. return nonloc::SymbolVal(ResultSym);
  374. }
  375. }
  376. const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
  377. return nonloc::SymbolVal(
  378. SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
  379. }
  380. // Rearrange if symbol type matches the result type and if the operator is a
  381. // comparison operator, both symbol and constant must be within constant
  382. // overflow bounds.
  383. static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
  384. SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
  385. return Sym->getType() == Ty &&
  386. (!BinaryOperator::isComparisonOp(Op) ||
  387. (isWithinConstantOverflowBounds(Sym, State) &&
  388. isWithinConstantOverflowBounds(Int)));
  389. }
  390. static Optional<NonLoc> tryRearrange(ProgramStateRef State,
  391. BinaryOperator::Opcode Op, NonLoc Lhs,
  392. NonLoc Rhs, QualType ResultTy) {
  393. ProgramStateManager &StateMgr = State->getStateManager();
  394. SValBuilder &SVB = StateMgr.getSValBuilder();
  395. // We expect everything to be of the same type - this type.
  396. QualType SingleTy;
  397. auto &Opts =
  398. StateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions();
  399. // FIXME: After putting complexity threshold to the symbols we can always
  400. // rearrange additive operations but rearrange comparisons only if
  401. // option is set.
  402. if(!Opts.ShouldAggressivelySimplifyBinaryOperation)
  403. return None;
  404. SymbolRef LSym = Lhs.getAsSymbol();
  405. if (!LSym)
  406. return None;
  407. if (BinaryOperator::isComparisonOp(Op)) {
  408. SingleTy = LSym->getType();
  409. if (ResultTy != SVB.getConditionType())
  410. return None;
  411. // Initialize SingleTy later with a symbol's type.
  412. } else if (BinaryOperator::isAdditiveOp(Op)) {
  413. SingleTy = ResultTy;
  414. if (LSym->getType() != SingleTy)
  415. return None;
  416. } else {
  417. // Don't rearrange other operations.
  418. return None;
  419. }
  420. assert(!SingleTy.isNull() && "We should have figured out the type by now!");
  421. // Rearrange signed symbolic expressions only
  422. if (!SingleTy->isSignedIntegerOrEnumerationType())
  423. return None;
  424. SymbolRef RSym = Rhs.getAsSymbol();
  425. if (!RSym || RSym->getType() != SingleTy)
  426. return None;
  427. BasicValueFactory &BV = State->getBasicVals();
  428. llvm::APSInt LInt, RInt;
  429. std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
  430. std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
  431. if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
  432. !shouldRearrange(State, Op, RSym, RInt, SingleTy))
  433. return None;
  434. // We know that no overflows can occur anymore.
  435. return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
  436. }
  437. SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
  438. BinaryOperator::Opcode op,
  439. NonLoc lhs, NonLoc rhs,
  440. QualType resultTy) {
  441. NonLoc InputLHS = lhs;
  442. NonLoc InputRHS = rhs;
  443. // Handle trivial case where left-side and right-side are the same.
  444. if (lhs == rhs)
  445. switch (op) {
  446. default:
  447. break;
  448. case BO_EQ:
  449. case BO_LE:
  450. case BO_GE:
  451. return makeTruthVal(true, resultTy);
  452. case BO_LT:
  453. case BO_GT:
  454. case BO_NE:
  455. return makeTruthVal(false, resultTy);
  456. case BO_Xor:
  457. case BO_Sub:
  458. if (resultTy->isIntegralOrEnumerationType())
  459. return makeIntVal(0, resultTy);
  460. return evalCastFromNonLoc(makeIntVal(0, /*isUnsigned=*/false), resultTy);
  461. case BO_Or:
  462. case BO_And:
  463. return evalCastFromNonLoc(lhs, resultTy);
  464. }
  465. while (1) {
  466. switch (lhs.getSubKind()) {
  467. default:
  468. return makeSymExprValNN(op, lhs, rhs, resultTy);
  469. case nonloc::PointerToMemberKind: {
  470. assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
  471. "Both SVals should have pointer-to-member-type");
  472. auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
  473. RPTM = rhs.castAs<nonloc::PointerToMember>();
  474. auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
  475. switch (op) {
  476. case BO_EQ:
  477. return makeTruthVal(LPTMD == RPTMD, resultTy);
  478. case BO_NE:
  479. return makeTruthVal(LPTMD != RPTMD, resultTy);
  480. default:
  481. return UnknownVal();
  482. }
  483. }
  484. case nonloc::LocAsIntegerKind: {
  485. Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
  486. switch (rhs.getSubKind()) {
  487. case nonloc::LocAsIntegerKind:
  488. // FIXME: at the moment the implementation
  489. // of modeling "pointers as integers" is not complete.
  490. if (!BinaryOperator::isComparisonOp(op))
  491. return UnknownVal();
  492. return evalBinOpLL(state, op, lhsL,
  493. rhs.castAs<nonloc::LocAsInteger>().getLoc(),
  494. resultTy);
  495. case nonloc::ConcreteIntKind: {
  496. // FIXME: at the moment the implementation
  497. // of modeling "pointers as integers" is not complete.
  498. if (!BinaryOperator::isComparisonOp(op))
  499. return UnknownVal();
  500. // Transform the integer into a location and compare.
  501. // FIXME: This only makes sense for comparisons. If we want to, say,
  502. // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
  503. // then pack it back into a LocAsInteger.
  504. llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
  505. // If the region has a symbolic base, pay attention to the type; it
  506. // might be coming from a non-default address space. For non-symbolic
  507. // regions it doesn't matter that much because such comparisons would
  508. // most likely evaluate to concrete false anyway. FIXME: We might
  509. // still need to handle the non-comparison case.
  510. if (SymbolRef lSym = lhs.getAsLocSymbol(true))
  511. BasicVals.getAPSIntType(lSym->getType()).apply(i);
  512. else
  513. BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
  514. return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
  515. }
  516. default:
  517. switch (op) {
  518. case BO_EQ:
  519. return makeTruthVal(false, resultTy);
  520. case BO_NE:
  521. return makeTruthVal(true, resultTy);
  522. default:
  523. // This case also handles pointer arithmetic.
  524. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  525. }
  526. }
  527. }
  528. case nonloc::ConcreteIntKind: {
  529. llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
  530. // If we're dealing with two known constants, just perform the operation.
  531. if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
  532. llvm::APSInt RHSValue = *KnownRHSValue;
  533. if (BinaryOperator::isComparisonOp(op)) {
  534. // We're looking for a type big enough to compare the two values.
  535. // FIXME: This is not correct. char + short will result in a promotion
  536. // to int. Unfortunately we have lost types by this point.
  537. APSIntType CompareType = std::max(APSIntType(LHSValue),
  538. APSIntType(RHSValue));
  539. CompareType.apply(LHSValue);
  540. CompareType.apply(RHSValue);
  541. } else if (!BinaryOperator::isShiftOp(op)) {
  542. APSIntType IntType = BasicVals.getAPSIntType(resultTy);
  543. IntType.apply(LHSValue);
  544. IntType.apply(RHSValue);
  545. }
  546. const llvm::APSInt *Result =
  547. BasicVals.evalAPSInt(op, LHSValue, RHSValue);
  548. if (!Result)
  549. return UndefinedVal();
  550. return nonloc::ConcreteInt(*Result);
  551. }
  552. // Swap the left and right sides and flip the operator if doing so
  553. // allows us to better reason about the expression (this is a form
  554. // of expression canonicalization).
  555. // While we're at it, catch some special cases for non-commutative ops.
  556. switch (op) {
  557. case BO_LT:
  558. case BO_GT:
  559. case BO_LE:
  560. case BO_GE:
  561. op = BinaryOperator::reverseComparisonOp(op);
  562. LLVM_FALLTHROUGH;
  563. case BO_EQ:
  564. case BO_NE:
  565. case BO_Add:
  566. case BO_Mul:
  567. case BO_And:
  568. case BO_Xor:
  569. case BO_Or:
  570. std::swap(lhs, rhs);
  571. continue;
  572. case BO_Shr:
  573. // (~0)>>a
  574. if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
  575. return evalCastFromNonLoc(lhs, resultTy);
  576. LLVM_FALLTHROUGH;
  577. case BO_Shl:
  578. // 0<<a and 0>>a
  579. if (LHSValue == 0)
  580. return evalCastFromNonLoc(lhs, resultTy);
  581. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  582. default:
  583. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  584. }
  585. }
  586. case nonloc::SymbolValKind: {
  587. // We only handle LHS as simple symbols or SymIntExprs.
  588. SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
  589. // LHS is a symbolic expression.
  590. if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
  591. // Is this a logical not? (!x is represented as x == 0.)
  592. if (op == BO_EQ && rhs.isZeroConstant()) {
  593. // We know how to negate certain expressions. Simplify them here.
  594. BinaryOperator::Opcode opc = symIntExpr->getOpcode();
  595. switch (opc) {
  596. default:
  597. // We don't know how to negate this operation.
  598. // Just handle it as if it were a normal comparison to 0.
  599. break;
  600. case BO_LAnd:
  601. case BO_LOr:
  602. llvm_unreachable("Logical operators handled by branching logic.");
  603. case BO_Assign:
  604. case BO_MulAssign:
  605. case BO_DivAssign:
  606. case BO_RemAssign:
  607. case BO_AddAssign:
  608. case BO_SubAssign:
  609. case BO_ShlAssign:
  610. case BO_ShrAssign:
  611. case BO_AndAssign:
  612. case BO_XorAssign:
  613. case BO_OrAssign:
  614. case BO_Comma:
  615. llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
  616. case BO_PtrMemD:
  617. case BO_PtrMemI:
  618. llvm_unreachable("Pointer arithmetic not handled here.");
  619. case BO_LT:
  620. case BO_GT:
  621. case BO_LE:
  622. case BO_GE:
  623. case BO_EQ:
  624. case BO_NE:
  625. assert(resultTy->isBooleanType() ||
  626. resultTy == getConditionType());
  627. assert(symIntExpr->getType()->isBooleanType() ||
  628. getContext().hasSameUnqualifiedType(symIntExpr->getType(),
  629. getConditionType()));
  630. // Negate the comparison and make a value.
  631. opc = BinaryOperator::negateComparisonOp(opc);
  632. return makeNonLoc(symIntExpr->getLHS(), opc,
  633. symIntExpr->getRHS(), resultTy);
  634. }
  635. }
  636. // For now, only handle expressions whose RHS is a constant.
  637. if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
  638. // If both the LHS and the current expression are additive,
  639. // fold their constants and try again.
  640. if (BinaryOperator::isAdditiveOp(op)) {
  641. BinaryOperator::Opcode lop = symIntExpr->getOpcode();
  642. if (BinaryOperator::isAdditiveOp(lop)) {
  643. // Convert the two constants to a common type, then combine them.
  644. // resultTy may not be the best type to convert to, but it's
  645. // probably the best choice in expressions with mixed type
  646. // (such as x+1U+2LL). The rules for implicit conversions should
  647. // choose a reasonable type to preserve the expression, and will
  648. // at least match how the value is going to be used.
  649. APSIntType IntType = BasicVals.getAPSIntType(resultTy);
  650. const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
  651. const llvm::APSInt &second = IntType.convert(*RHSValue);
  652. const llvm::APSInt *newRHS;
  653. if (lop == op)
  654. newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
  655. else
  656. newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
  657. assert(newRHS && "Invalid operation despite common type!");
  658. rhs = nonloc::ConcreteInt(*newRHS);
  659. lhs = nonloc::SymbolVal(symIntExpr->getLHS());
  660. op = lop;
  661. continue;
  662. }
  663. }
  664. // Otherwise, make a SymIntExpr out of the expression.
  665. return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
  666. }
  667. }
  668. // Does the symbolic expression simplify to a constant?
  669. // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
  670. // and try again.
  671. SVal simplifiedLhs = simplifySVal(state, lhs);
  672. if (simplifiedLhs != lhs)
  673. if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
  674. lhs = *simplifiedLhsAsNonLoc;
  675. continue;
  676. }
  677. // Is the RHS a constant?
  678. if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
  679. return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
  680. if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
  681. return *V;
  682. // Give up -- this is not a symbolic expression we can handle.
  683. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  684. }
  685. }
  686. }
  687. }
  688. static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
  689. const FieldRegion *RightFR,
  690. BinaryOperator::Opcode op,
  691. QualType resultTy,
  692. SimpleSValBuilder &SVB) {
  693. // Only comparisons are meaningful here!
  694. if (!BinaryOperator::isComparisonOp(op))
  695. return UnknownVal();
  696. // Next, see if the two FRs have the same super-region.
  697. // FIXME: This doesn't handle casts yet, and simply stripping the casts
  698. // doesn't help.
  699. if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
  700. return UnknownVal();
  701. const FieldDecl *LeftFD = LeftFR->getDecl();
  702. const FieldDecl *RightFD = RightFR->getDecl();
  703. const RecordDecl *RD = LeftFD->getParent();
  704. // Make sure the two FRs are from the same kind of record. Just in case!
  705. // FIXME: This is probably where inheritance would be a problem.
  706. if (RD != RightFD->getParent())
  707. return UnknownVal();
  708. // We know for sure that the two fields are not the same, since that
  709. // would have given us the same SVal.
  710. if (op == BO_EQ)
  711. return SVB.makeTruthVal(false, resultTy);
  712. if (op == BO_NE)
  713. return SVB.makeTruthVal(true, resultTy);
  714. // Iterate through the fields and see which one comes first.
  715. // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
  716. // members and the units in which bit-fields reside have addresses that
  717. // increase in the order in which they are declared."
  718. bool leftFirst = (op == BO_LT || op == BO_LE);
  719. for (const auto *I : RD->fields()) {
  720. if (I == LeftFD)
  721. return SVB.makeTruthVal(leftFirst, resultTy);
  722. if (I == RightFD)
  723. return SVB.makeTruthVal(!leftFirst, resultTy);
  724. }
  725. llvm_unreachable("Fields not found in parent record's definition");
  726. }
  727. // FIXME: all this logic will change if/when we have MemRegion::getLocation().
  728. SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
  729. BinaryOperator::Opcode op,
  730. Loc lhs, Loc rhs,
  731. QualType resultTy) {
  732. // Only comparisons and subtractions are valid operations on two pointers.
  733. // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
  734. // However, if a pointer is casted to an integer, evalBinOpNN may end up
  735. // calling this function with another operation (PR7527). We don't attempt to
  736. // model this for now, but it could be useful, particularly when the
  737. // "location" is actually an integer value that's been passed through a void*.
  738. if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
  739. return UnknownVal();
  740. // Special cases for when both sides are identical.
  741. if (lhs == rhs) {
  742. switch (op) {
  743. default:
  744. llvm_unreachable("Unimplemented operation for two identical values");
  745. case BO_Sub:
  746. return makeZeroVal(resultTy);
  747. case BO_EQ:
  748. case BO_LE:
  749. case BO_GE:
  750. return makeTruthVal(true, resultTy);
  751. case BO_NE:
  752. case BO_LT:
  753. case BO_GT:
  754. return makeTruthVal(false, resultTy);
  755. }
  756. }
  757. switch (lhs.getSubKind()) {
  758. default:
  759. llvm_unreachable("Ordering not implemented for this Loc.");
  760. case loc::GotoLabelKind:
  761. // The only thing we know about labels is that they're non-null.
  762. if (rhs.isZeroConstant()) {
  763. switch (op) {
  764. default:
  765. break;
  766. case BO_Sub:
  767. return evalCastFromLoc(lhs, resultTy);
  768. case BO_EQ:
  769. case BO_LE:
  770. case BO_LT:
  771. return makeTruthVal(false, resultTy);
  772. case BO_NE:
  773. case BO_GT:
  774. case BO_GE:
  775. return makeTruthVal(true, resultTy);
  776. }
  777. }
  778. // There may be two labels for the same location, and a function region may
  779. // have the same address as a label at the start of the function (depending
  780. // on the ABI).
  781. // FIXME: we can probably do a comparison against other MemRegions, though.
  782. // FIXME: is there a way to tell if two labels refer to the same location?
  783. return UnknownVal();
  784. case loc::ConcreteIntKind: {
  785. // If one of the operands is a symbol and the other is a constant,
  786. // build an expression for use by the constraint manager.
  787. if (SymbolRef rSym = rhs.getAsLocSymbol()) {
  788. // We can only build expressions with symbols on the left,
  789. // so we need a reversible operator.
  790. if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
  791. return UnknownVal();
  792. const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
  793. op = BinaryOperator::reverseComparisonOp(op);
  794. return makeNonLoc(rSym, op, lVal, resultTy);
  795. }
  796. // If both operands are constants, just perform the operation.
  797. if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
  798. SVal ResultVal =
  799. lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
  800. if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
  801. return evalCastFromNonLoc(*Result, resultTy);
  802. assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
  803. return UnknownVal();
  804. }
  805. // Special case comparisons against NULL.
  806. // This must come after the test if the RHS is a symbol, which is used to
  807. // build constraints. The address of any non-symbolic region is guaranteed
  808. // to be non-NULL, as is any label.
  809. assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
  810. if (lhs.isZeroConstant()) {
  811. switch (op) {
  812. default:
  813. break;
  814. case BO_EQ:
  815. case BO_GT:
  816. case BO_GE:
  817. return makeTruthVal(false, resultTy);
  818. case BO_NE:
  819. case BO_LT:
  820. case BO_LE:
  821. return makeTruthVal(true, resultTy);
  822. }
  823. }
  824. // Comparing an arbitrary integer to a region or label address is
  825. // completely unknowable.
  826. return UnknownVal();
  827. }
  828. case loc::MemRegionValKind: {
  829. if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
  830. // If one of the operands is a symbol and the other is a constant,
  831. // build an expression for use by the constraint manager.
  832. if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
  833. if (BinaryOperator::isComparisonOp(op))
  834. return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
  835. return UnknownVal();
  836. }
  837. // Special case comparisons to NULL.
  838. // This must come after the test if the LHS is a symbol, which is used to
  839. // build constraints. The address of any non-symbolic region is guaranteed
  840. // to be non-NULL.
  841. if (rInt->isZeroConstant()) {
  842. if (op == BO_Sub)
  843. return evalCastFromLoc(lhs, resultTy);
  844. if (BinaryOperator::isComparisonOp(op)) {
  845. QualType boolType = getContext().BoolTy;
  846. NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
  847. NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
  848. return evalBinOpNN(state, op, l, r, resultTy);
  849. }
  850. }
  851. // Comparing a region to an arbitrary integer is completely unknowable.
  852. return UnknownVal();
  853. }
  854. // Get both values as regions, if possible.
  855. const MemRegion *LeftMR = lhs.getAsRegion();
  856. assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
  857. const MemRegion *RightMR = rhs.getAsRegion();
  858. if (!RightMR)
  859. // The RHS is probably a label, which in theory could address a region.
  860. // FIXME: we can probably make a more useful statement about non-code
  861. // regions, though.
  862. return UnknownVal();
  863. const MemRegion *LeftBase = LeftMR->getBaseRegion();
  864. const MemRegion *RightBase = RightMR->getBaseRegion();
  865. const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
  866. const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
  867. const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
  868. // If the two regions are from different known memory spaces they cannot be
  869. // equal. Also, assume that no symbolic region (whose memory space is
  870. // unknown) is on the stack.
  871. if (LeftMS != RightMS &&
  872. ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
  873. (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
  874. switch (op) {
  875. default:
  876. return UnknownVal();
  877. case BO_EQ:
  878. return makeTruthVal(false, resultTy);
  879. case BO_NE:
  880. return makeTruthVal(true, resultTy);
  881. }
  882. }
  883. // If both values wrap regions, see if they're from different base regions.
  884. // Note, heap base symbolic regions are assumed to not alias with
  885. // each other; for example, we assume that malloc returns different address
  886. // on each invocation.
  887. // FIXME: ObjC object pointers always reside on the heap, but currently
  888. // we treat their memory space as unknown, because symbolic pointers
  889. // to ObjC objects may alias. There should be a way to construct
  890. // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
  891. // guesses memory space for ObjC object pointers manually instead of
  892. // relying on us.
  893. if (LeftBase != RightBase &&
  894. ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
  895. (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
  896. switch (op) {
  897. default:
  898. return UnknownVal();
  899. case BO_EQ:
  900. return makeTruthVal(false, resultTy);
  901. case BO_NE:
  902. return makeTruthVal(true, resultTy);
  903. }
  904. }
  905. // Handle special cases for when both regions are element regions.
  906. const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
  907. const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
  908. if (RightER && LeftER) {
  909. // Next, see if the two ERs have the same super-region and matching types.
  910. // FIXME: This should do something useful even if the types don't match,
  911. // though if both indexes are constant the RegionRawOffset path will
  912. // give the correct answer.
  913. if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
  914. LeftER->getElementType() == RightER->getElementType()) {
  915. // Get the left index and cast it to the correct type.
  916. // If the index is unknown or undefined, bail out here.
  917. SVal LeftIndexVal = LeftER->getIndex();
  918. Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
  919. if (!LeftIndex)
  920. return UnknownVal();
  921. LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
  922. LeftIndex = LeftIndexVal.getAs<NonLoc>();
  923. if (!LeftIndex)
  924. return UnknownVal();
  925. // Do the same for the right index.
  926. SVal RightIndexVal = RightER->getIndex();
  927. Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
  928. if (!RightIndex)
  929. return UnknownVal();
  930. RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
  931. RightIndex = RightIndexVal.getAs<NonLoc>();
  932. if (!RightIndex)
  933. return UnknownVal();
  934. // Actually perform the operation.
  935. // evalBinOpNN expects the two indexes to already be the right type.
  936. return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
  937. }
  938. }
  939. // Special handling of the FieldRegions, even with symbolic offsets.
  940. const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
  941. const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
  942. if (RightFR && LeftFR) {
  943. SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
  944. *this);
  945. if (!R.isUnknown())
  946. return R;
  947. }
  948. // Compare the regions using the raw offsets.
  949. RegionOffset LeftOffset = LeftMR->getAsOffset();
  950. RegionOffset RightOffset = RightMR->getAsOffset();
  951. if (LeftOffset.getRegion() != nullptr &&
  952. LeftOffset.getRegion() == RightOffset.getRegion() &&
  953. !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
  954. int64_t left = LeftOffset.getOffset();
  955. int64_t right = RightOffset.getOffset();
  956. switch (op) {
  957. default:
  958. return UnknownVal();
  959. case BO_LT:
  960. return makeTruthVal(left < right, resultTy);
  961. case BO_GT:
  962. return makeTruthVal(left > right, resultTy);
  963. case BO_LE:
  964. return makeTruthVal(left <= right, resultTy);
  965. case BO_GE:
  966. return makeTruthVal(left >= right, resultTy);
  967. case BO_EQ:
  968. return makeTruthVal(left == right, resultTy);
  969. case BO_NE:
  970. return makeTruthVal(left != right, resultTy);
  971. }
  972. }
  973. // At this point we're not going to get a good answer, but we can try
  974. // conjuring an expression instead.
  975. SymbolRef LHSSym = lhs.getAsLocSymbol();
  976. SymbolRef RHSSym = rhs.getAsLocSymbol();
  977. if (LHSSym && RHSSym)
  978. return makeNonLoc(LHSSym, op, RHSSym, resultTy);
  979. // If we get here, we have no way of comparing the regions.
  980. return UnknownVal();
  981. }
  982. }
  983. }
  984. SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
  985. BinaryOperator::Opcode op,
  986. Loc lhs, NonLoc rhs, QualType resultTy) {
  987. if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
  988. if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
  989. if (PTMSV->isNullMemberPointer())
  990. return UndefinedVal();
  991. if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
  992. SVal Result = lhs;
  993. for (const auto &I : *PTMSV)
  994. Result = StateMgr.getStoreManager().evalDerivedToBase(
  995. Result, I->getType(),I->isVirtual());
  996. return state->getLValue(FD, Result);
  997. }
  998. }
  999. return rhs;
  1000. }
  1001. assert(!BinaryOperator::isComparisonOp(op) &&
  1002. "arguments to comparison ops must be of the same type");
  1003. // Special case: rhs is a zero constant.
  1004. if (rhs.isZeroConstant())
  1005. return lhs;
  1006. // Perserve the null pointer so that it can be found by the DerefChecker.
  1007. if (lhs.isZeroConstant())
  1008. return lhs;
  1009. // We are dealing with pointer arithmetic.
  1010. // Handle pointer arithmetic on constant values.
  1011. if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
  1012. if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
  1013. const llvm::APSInt &leftI = lhsInt->getValue();
  1014. assert(leftI.isUnsigned());
  1015. llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
  1016. // Convert the bitwidth of rightI. This should deal with overflow
  1017. // since we are dealing with concrete values.
  1018. rightI = rightI.extOrTrunc(leftI.getBitWidth());
  1019. // Offset the increment by the pointer size.
  1020. llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
  1021. QualType pointeeType = resultTy->getPointeeType();
  1022. Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
  1023. rightI *= Multiplicand;
  1024. // Compute the adjusted pointer.
  1025. switch (op) {
  1026. case BO_Add:
  1027. rightI = leftI + rightI;
  1028. break;
  1029. case BO_Sub:
  1030. rightI = leftI - rightI;
  1031. break;
  1032. default:
  1033. llvm_unreachable("Invalid pointer arithmetic operation");
  1034. }
  1035. return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
  1036. }
  1037. }
  1038. // Handle cases where 'lhs' is a region.
  1039. if (const MemRegion *region = lhs.getAsRegion()) {
  1040. rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
  1041. SVal index = UnknownVal();
  1042. const SubRegion *superR = nullptr;
  1043. // We need to know the type of the pointer in order to add an integer to it.
  1044. // Depending on the type, different amount of bytes is added.
  1045. QualType elementType;
  1046. if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
  1047. assert(op == BO_Add || op == BO_Sub);
  1048. index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
  1049. getArrayIndexType());
  1050. superR = cast<SubRegion>(elemReg->getSuperRegion());
  1051. elementType = elemReg->getElementType();
  1052. }
  1053. else if (isa<SubRegion>(region)) {
  1054. assert(op == BO_Add || op == BO_Sub);
  1055. index = (op == BO_Add) ? rhs : evalMinus(rhs);
  1056. superR = cast<SubRegion>(region);
  1057. // TODO: Is this actually reliable? Maybe improving our MemRegion
  1058. // hierarchy to provide typed regions for all non-void pointers would be
  1059. // better. For instance, we cannot extend this towards LocAsInteger
  1060. // operations, where result type of the expression is integer.
  1061. if (resultTy->isAnyPointerType())
  1062. elementType = resultTy->getPointeeType();
  1063. }
  1064. // Represent arithmetic on void pointers as arithmetic on char pointers.
  1065. // It is fine when a TypedValueRegion of char value type represents
  1066. // a void pointer. Note that arithmetic on void pointers is a GCC extension.
  1067. if (elementType->isVoidType())
  1068. elementType = getContext().CharTy;
  1069. if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
  1070. return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
  1071. superR, getContext()));
  1072. }
  1073. }
  1074. return UnknownVal();
  1075. }
  1076. const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
  1077. SVal V) {
  1078. V = simplifySVal(state, V);
  1079. if (V.isUnknownOrUndef())
  1080. return nullptr;
  1081. if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
  1082. return &X->getValue();
  1083. if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
  1084. return &X->getValue();
  1085. if (SymbolRef Sym = V.getAsSymbol())
  1086. return state->getConstraintManager().getSymVal(state, Sym);
  1087. // FIXME: Add support for SymExprs.
  1088. return nullptr;
  1089. }
  1090. SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
  1091. // For now, this function tries to constant-fold symbols inside a
  1092. // nonloc::SymbolVal, and does nothing else. More simplifications should
  1093. // be possible, such as constant-folding an index in an ElementRegion.
  1094. class Simplifier : public FullSValVisitor<Simplifier, SVal> {
  1095. ProgramStateRef State;
  1096. SValBuilder &SVB;
  1097. // Cache results for the lifetime of the Simplifier. Results change every
  1098. // time new constraints are added to the program state, which is the whole
  1099. // point of simplifying, and for that very reason it's pointless to maintain
  1100. // the same cache for the duration of the whole analysis.
  1101. llvm::DenseMap<SymbolRef, SVal> Cached;
  1102. static bool isUnchanged(SymbolRef Sym, SVal Val) {
  1103. return Sym == Val.getAsSymbol();
  1104. }
  1105. SVal cache(SymbolRef Sym, SVal V) {
  1106. Cached[Sym] = V;
  1107. return V;
  1108. }
  1109. SVal skip(SymbolRef Sym) {
  1110. return cache(Sym, SVB.makeSymbolVal(Sym));
  1111. }
  1112. public:
  1113. Simplifier(ProgramStateRef State)
  1114. : State(State), SVB(State->getStateManager().getSValBuilder()) {}
  1115. SVal VisitSymbolData(const SymbolData *S) {
  1116. // No cache here.
  1117. if (const llvm::APSInt *I =
  1118. SVB.getKnownValue(State, SVB.makeSymbolVal(S)))
  1119. return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
  1120. : (SVal)SVB.makeIntVal(*I);
  1121. return SVB.makeSymbolVal(S);
  1122. }
  1123. // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
  1124. // start producing them.
  1125. SVal VisitSymIntExpr(const SymIntExpr *S) {
  1126. auto I = Cached.find(S);
  1127. if (I != Cached.end())
  1128. return I->second;
  1129. SVal LHS = Visit(S->getLHS());
  1130. if (isUnchanged(S->getLHS(), LHS))
  1131. return skip(S);
  1132. SVal RHS;
  1133. // By looking at the APSInt in the right-hand side of S, we cannot
  1134. // figure out if it should be treated as a Loc or as a NonLoc.
  1135. // So make our guess by recalling that we cannot multiply pointers
  1136. // or compare a pointer to an integer.
  1137. if (Loc::isLocType(S->getLHS()->getType()) &&
  1138. BinaryOperator::isComparisonOp(S->getOpcode())) {
  1139. // The usual conversion of $sym to &SymRegion{$sym}, as they have
  1140. // the same meaning for Loc-type symbols, but the latter form
  1141. // is preferred in SVal computations for being Loc itself.
  1142. if (SymbolRef Sym = LHS.getAsSymbol()) {
  1143. assert(Loc::isLocType(Sym->getType()));
  1144. LHS = SVB.makeLoc(Sym);
  1145. }
  1146. RHS = SVB.makeIntLocVal(S->getRHS());
  1147. } else {
  1148. RHS = SVB.makeIntVal(S->getRHS());
  1149. }
  1150. return cache(
  1151. S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
  1152. }
  1153. SVal VisitSymSymExpr(const SymSymExpr *S) {
  1154. auto I = Cached.find(S);
  1155. if (I != Cached.end())
  1156. return I->second;
  1157. // For now don't try to simplify mixed Loc/NonLoc expressions
  1158. // because they often appear from LocAsInteger operations
  1159. // and we don't know how to combine a LocAsInteger
  1160. // with a concrete value.
  1161. if (Loc::isLocType(S->getLHS()->getType()) !=
  1162. Loc::isLocType(S->getRHS()->getType()))
  1163. return skip(S);
  1164. SVal LHS = Visit(S->getLHS());
  1165. SVal RHS = Visit(S->getRHS());
  1166. if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
  1167. return skip(S);
  1168. return cache(
  1169. S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
  1170. }
  1171. SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
  1172. SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
  1173. SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
  1174. // Simplification is much more costly than computing complexity.
  1175. // For high complexity, it may be not worth it.
  1176. return Visit(V.getSymbol());
  1177. }
  1178. SVal VisitSVal(SVal V) { return V; }
  1179. };
  1180. // A crude way of preventing this function from calling itself from evalBinOp.
  1181. static bool isReentering = false;
  1182. if (isReentering)
  1183. return V;
  1184. isReentering = true;
  1185. SVal SimplifiedV = Simplifier(State).Visit(V);
  1186. isReentering = false;
  1187. return SimplifiedV;
  1188. }