ExprEngineC.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- 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 ExprEngine's support for C expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ExprCXX.h"
  13. #include "clang/AST/DeclCXX.h"
  14. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  16. using namespace clang;
  17. using namespace ento;
  18. using llvm::APSInt;
  19. /// Optionally conjure and return a symbol for offset when processing
  20. /// an expression \p Expression.
  21. /// If \p Other is a location, conjure a symbol for \p Symbol
  22. /// (offset) if it is unknown so that memory arithmetic always
  23. /// results in an ElementRegion.
  24. /// \p Count The number of times the current basic block was visited.
  25. static SVal conjureOffsetSymbolOnLocation(
  26. SVal Symbol, SVal Other, Expr* Expression, SValBuilder &svalBuilder,
  27. unsigned Count, const LocationContext *LCtx) {
  28. QualType Ty = Expression->getType();
  29. if (Other.getAs<Loc>() &&
  30. Ty->isIntegralOrEnumerationType() &&
  31. Symbol.isUnknown()) {
  32. return svalBuilder.conjureSymbolVal(Expression, LCtx, Ty, Count);
  33. }
  34. return Symbol;
  35. }
  36. void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
  37. ExplodedNode *Pred,
  38. ExplodedNodeSet &Dst) {
  39. Expr *LHS = B->getLHS()->IgnoreParens();
  40. Expr *RHS = B->getRHS()->IgnoreParens();
  41. // FIXME: Prechecks eventually go in ::Visit().
  42. ExplodedNodeSet CheckedSet;
  43. ExplodedNodeSet Tmp2;
  44. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
  45. // With both the LHS and RHS evaluated, process the operation itself.
  46. for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
  47. it != ei; ++it) {
  48. ProgramStateRef state = (*it)->getState();
  49. const LocationContext *LCtx = (*it)->getLocationContext();
  50. SVal LeftV = state->getSVal(LHS, LCtx);
  51. SVal RightV = state->getSVal(RHS, LCtx);
  52. BinaryOperator::Opcode Op = B->getOpcode();
  53. if (Op == BO_Assign) {
  54. // EXPERIMENTAL: "Conjured" symbols.
  55. // FIXME: Handle structs.
  56. if (RightV.isUnknown()) {
  57. unsigned Count = currBldrCtx->blockCount();
  58. RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
  59. Count);
  60. }
  61. // Simulate the effects of a "store": bind the value of the RHS
  62. // to the L-Value represented by the LHS.
  63. SVal ExprVal = B->isGLValue() ? LeftV : RightV;
  64. evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
  65. LeftV, RightV);
  66. continue;
  67. }
  68. if (!B->isAssignmentOp()) {
  69. StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
  70. if (B->isAdditiveOp()) {
  71. // TODO: This can be removed after we enable history tracking with
  72. // SymSymExpr.
  73. unsigned Count = currBldrCtx->blockCount();
  74. RightV = conjureOffsetSymbolOnLocation(
  75. RightV, LeftV, RHS, svalBuilder, Count, LCtx);
  76. LeftV = conjureOffsetSymbolOnLocation(
  77. LeftV, RightV, LHS, svalBuilder, Count, LCtx);
  78. }
  79. // Although we don't yet model pointers-to-members, we do need to make
  80. // sure that the members of temporaries have a valid 'this' pointer for
  81. // other checks.
  82. if (B->getOpcode() == BO_PtrMemD)
  83. state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
  84. // Process non-assignments except commas or short-circuited
  85. // logical expressions (LAnd and LOr).
  86. SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
  87. if (!Result.isUnknown()) {
  88. state = state->BindExpr(B, LCtx, Result);
  89. } else {
  90. // If we cannot evaluate the operation escape the operands.
  91. state = escapeValue(state, LeftV, PSK_EscapeOther);
  92. state = escapeValue(state, RightV, PSK_EscapeOther);
  93. }
  94. Bldr.generateNode(B, *it, state);
  95. continue;
  96. }
  97. assert (B->isCompoundAssignmentOp());
  98. switch (Op) {
  99. default:
  100. llvm_unreachable("Invalid opcode for compound assignment.");
  101. case BO_MulAssign: Op = BO_Mul; break;
  102. case BO_DivAssign: Op = BO_Div; break;
  103. case BO_RemAssign: Op = BO_Rem; break;
  104. case BO_AddAssign: Op = BO_Add; break;
  105. case BO_SubAssign: Op = BO_Sub; break;
  106. case BO_ShlAssign: Op = BO_Shl; break;
  107. case BO_ShrAssign: Op = BO_Shr; break;
  108. case BO_AndAssign: Op = BO_And; break;
  109. case BO_XorAssign: Op = BO_Xor; break;
  110. case BO_OrAssign: Op = BO_Or; break;
  111. }
  112. // Perform a load (the LHS). This performs the checks for
  113. // null dereferences, and so on.
  114. ExplodedNodeSet Tmp;
  115. SVal location = LeftV;
  116. evalLoad(Tmp, B, LHS, *it, state, location);
  117. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
  118. ++I) {
  119. state = (*I)->getState();
  120. const LocationContext *LCtx = (*I)->getLocationContext();
  121. SVal V = state->getSVal(LHS, LCtx);
  122. // Get the computation type.
  123. QualType CTy =
  124. cast<CompoundAssignOperator>(B)->getComputationResultType();
  125. CTy = getContext().getCanonicalType(CTy);
  126. QualType CLHSTy =
  127. cast<CompoundAssignOperator>(B)->getComputationLHSType();
  128. CLHSTy = getContext().getCanonicalType(CLHSTy);
  129. QualType LTy = getContext().getCanonicalType(LHS->getType());
  130. // Promote LHS.
  131. V = svalBuilder.evalCast(V, CLHSTy, LTy);
  132. // Compute the result of the operation.
  133. SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
  134. B->getType(), CTy);
  135. // EXPERIMENTAL: "Conjured" symbols.
  136. // FIXME: Handle structs.
  137. SVal LHSVal;
  138. if (Result.isUnknown()) {
  139. // The symbolic value is actually for the type of the left-hand side
  140. // expression, not the computation type, as this is the value the
  141. // LValue on the LHS will bind to.
  142. LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
  143. currBldrCtx->blockCount());
  144. // However, we need to convert the symbol to the computation type.
  145. Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
  146. }
  147. else {
  148. // The left-hand side may bind to a different value then the
  149. // computation type.
  150. LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
  151. }
  152. // In C++, assignment and compound assignment operators return an
  153. // lvalue.
  154. if (B->isGLValue())
  155. state = state->BindExpr(B, LCtx, location);
  156. else
  157. state = state->BindExpr(B, LCtx, Result);
  158. evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
  159. }
  160. }
  161. // FIXME: postvisits eventually go in ::Visit()
  162. getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
  163. }
  164. void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
  165. ExplodedNodeSet &Dst) {
  166. CanQualType T = getContext().getCanonicalType(BE->getType());
  167. const BlockDecl *BD = BE->getBlockDecl();
  168. // Get the value of the block itself.
  169. SVal V = svalBuilder.getBlockPointer(BD, T,
  170. Pred->getLocationContext(),
  171. currBldrCtx->blockCount());
  172. ProgramStateRef State = Pred->getState();
  173. // If we created a new MemRegion for the block, we should explicitly bind
  174. // the captured variables.
  175. if (const BlockDataRegion *BDR =
  176. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  177. BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
  178. E = BDR->referenced_vars_end();
  179. auto CI = BD->capture_begin();
  180. auto CE = BD->capture_end();
  181. for (; I != E; ++I) {
  182. const VarRegion *capturedR = I.getCapturedRegion();
  183. const VarRegion *originalR = I.getOriginalRegion();
  184. // If the capture had a copy expression, use the result of evaluating
  185. // that expression, otherwise use the original value.
  186. // We rely on the invariant that the block declaration's capture variables
  187. // are a prefix of the BlockDataRegion's referenced vars (which may include
  188. // referenced globals, etc.) to enable fast lookup of the capture for a
  189. // given referenced var.
  190. const Expr *copyExpr = nullptr;
  191. if (CI != CE) {
  192. assert(CI->getVariable() == capturedR->getDecl());
  193. copyExpr = CI->getCopyExpr();
  194. CI++;
  195. }
  196. if (capturedR != originalR) {
  197. SVal originalV;
  198. const LocationContext *LCtx = Pred->getLocationContext();
  199. if (copyExpr) {
  200. originalV = State->getSVal(copyExpr, LCtx);
  201. } else {
  202. originalV = State->getSVal(loc::MemRegionVal(originalR));
  203. }
  204. State = State->bindLoc(loc::MemRegionVal(capturedR), originalV, LCtx);
  205. }
  206. }
  207. }
  208. ExplodedNodeSet Tmp;
  209. StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
  210. Bldr.generateNode(BE, Pred,
  211. State->BindExpr(BE, Pred->getLocationContext(), V),
  212. nullptr, ProgramPoint::PostLValueKind);
  213. // FIXME: Move all post/pre visits to ::Visit().
  214. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
  215. }
  216. ProgramStateRef ExprEngine::handleLValueBitCast(
  217. ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
  218. QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
  219. ExplodedNode* Pred) {
  220. if (T->isLValueReferenceType()) {
  221. assert(!CastE->getType()->isLValueReferenceType());
  222. ExTy = getContext().getLValueReferenceType(ExTy);
  223. } else if (T->isRValueReferenceType()) {
  224. assert(!CastE->getType()->isRValueReferenceType());
  225. ExTy = getContext().getRValueReferenceType(ExTy);
  226. }
  227. // Delegate to SValBuilder to process.
  228. SVal OrigV = state->getSVal(Ex, LCtx);
  229. SVal V = svalBuilder.evalCast(OrigV, T, ExTy);
  230. // Negate the result if we're treating the boolean as a signed i1
  231. if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
  232. V = evalMinus(V);
  233. state = state->BindExpr(CastE, LCtx, V);
  234. if (V.isUnknown() && !OrigV.isUnknown()) {
  235. state = escapeValue(state, OrigV, PSK_EscapeOther);
  236. }
  237. Bldr.generateNode(CastE, Pred, state);
  238. return state;
  239. }
  240. ProgramStateRef ExprEngine::handleLVectorSplat(
  241. ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE,
  242. StmtNodeBuilder &Bldr, ExplodedNode* Pred) {
  243. // Recover some path sensitivity by conjuring a new value.
  244. QualType resultType = CastE->getType();
  245. if (CastE->isGLValue())
  246. resultType = getContext().getPointerType(resultType);
  247. SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
  248. resultType,
  249. currBldrCtx->blockCount());
  250. state = state->BindExpr(CastE, LCtx, result);
  251. Bldr.generateNode(CastE, Pred, state);
  252. return state;
  253. }
  254. void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
  255. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  256. ExplodedNodeSet dstPreStmt;
  257. getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
  258. if (CastE->getCastKind() == CK_LValueToRValue) {
  259. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  260. I!=E; ++I) {
  261. ExplodedNode *subExprNode = *I;
  262. ProgramStateRef state = subExprNode->getState();
  263. const LocationContext *LCtx = subExprNode->getLocationContext();
  264. evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
  265. }
  266. return;
  267. }
  268. // All other casts.
  269. QualType T = CastE->getType();
  270. QualType ExTy = Ex->getType();
  271. if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
  272. T = ExCast->getTypeAsWritten();
  273. StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
  274. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  275. I != E; ++I) {
  276. Pred = *I;
  277. ProgramStateRef state = Pred->getState();
  278. const LocationContext *LCtx = Pred->getLocationContext();
  279. switch (CastE->getCastKind()) {
  280. case CK_LValueToRValue:
  281. llvm_unreachable("LValueToRValue casts handled earlier.");
  282. case CK_ToVoid:
  283. continue;
  284. // The analyzer doesn't do anything special with these casts,
  285. // since it understands retain/release semantics already.
  286. case CK_ARCProduceObject:
  287. case CK_ARCConsumeObject:
  288. case CK_ARCReclaimReturnedObject:
  289. case CK_ARCExtendBlockObject: // Fall-through.
  290. case CK_CopyAndAutoreleaseBlockObject:
  291. // The analyser can ignore atomic casts for now, although some future
  292. // checkers may want to make certain that you're not modifying the same
  293. // value through atomic and nonatomic pointers.
  294. case CK_AtomicToNonAtomic:
  295. case CK_NonAtomicToAtomic:
  296. // True no-ops.
  297. case CK_NoOp:
  298. case CK_ConstructorConversion:
  299. case CK_UserDefinedConversion:
  300. case CK_FunctionToPointerDecay:
  301. case CK_BuiltinFnToFnPtr: {
  302. // Copy the SVal of Ex to CastE.
  303. ProgramStateRef state = Pred->getState();
  304. const LocationContext *LCtx = Pred->getLocationContext();
  305. SVal V = state->getSVal(Ex, LCtx);
  306. state = state->BindExpr(CastE, LCtx, V);
  307. Bldr.generateNode(CastE, Pred, state);
  308. continue;
  309. }
  310. case CK_MemberPointerToBoolean:
  311. case CK_PointerToBoolean: {
  312. SVal V = state->getSVal(Ex, LCtx);
  313. auto PTMSV = V.getAs<nonloc::PointerToMember>();
  314. if (PTMSV)
  315. V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
  316. if (V.isUndef() || PTMSV) {
  317. state = state->BindExpr(CastE, LCtx, V);
  318. Bldr.generateNode(CastE, Pred, state);
  319. continue;
  320. }
  321. // Explicitly proceed with default handler for this case cascade.
  322. state =
  323. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  324. continue;
  325. }
  326. case CK_Dependent:
  327. case CK_ArrayToPointerDecay:
  328. case CK_BitCast:
  329. case CK_LValueToRValueBitCast:
  330. case CK_AddressSpaceConversion:
  331. case CK_BooleanToSignedIntegral:
  332. case CK_IntegralToPointer:
  333. case CK_PointerToIntegral: {
  334. SVal V = state->getSVal(Ex, LCtx);
  335. if (V.getAs<nonloc::PointerToMember>()) {
  336. state = state->BindExpr(CastE, LCtx, UnknownVal());
  337. Bldr.generateNode(CastE, Pred, state);
  338. continue;
  339. }
  340. // Explicitly proceed with default handler for this case cascade.
  341. state =
  342. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  343. continue;
  344. }
  345. case CK_IntegralToBoolean:
  346. case CK_IntegralToFloating:
  347. case CK_FloatingToIntegral:
  348. case CK_FloatingToBoolean:
  349. case CK_FloatingCast:
  350. case CK_FloatingRealToComplex:
  351. case CK_FloatingComplexToReal:
  352. case CK_FloatingComplexToBoolean:
  353. case CK_FloatingComplexCast:
  354. case CK_FloatingComplexToIntegralComplex:
  355. case CK_IntegralRealToComplex:
  356. case CK_IntegralComplexToReal:
  357. case CK_IntegralComplexToBoolean:
  358. case CK_IntegralComplexCast:
  359. case CK_IntegralComplexToFloatingComplex:
  360. case CK_CPointerToObjCPointerCast:
  361. case CK_BlockPointerToObjCPointerCast:
  362. case CK_AnyPointerToBlockPointerCast:
  363. case CK_ObjCObjectLValueCast:
  364. case CK_ZeroToOCLOpaqueType:
  365. case CK_IntToOCLSampler:
  366. case CK_LValueBitCast:
  367. case CK_FixedPointCast:
  368. case CK_FixedPointToBoolean:
  369. case CK_FixedPointToIntegral:
  370. case CK_IntegralToFixedPoint: {
  371. state =
  372. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  373. continue;
  374. }
  375. case CK_IntegralCast: {
  376. // Delegate to SValBuilder to process.
  377. SVal V = state->getSVal(Ex, LCtx);
  378. V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
  379. state = state->BindExpr(CastE, LCtx, V);
  380. Bldr.generateNode(CastE, Pred, state);
  381. continue;
  382. }
  383. case CK_DerivedToBase:
  384. case CK_UncheckedDerivedToBase: {
  385. // For DerivedToBase cast, delegate to the store manager.
  386. SVal val = state->getSVal(Ex, LCtx);
  387. val = getStoreManager().evalDerivedToBase(val, CastE);
  388. state = state->BindExpr(CastE, LCtx, val);
  389. Bldr.generateNode(CastE, Pred, state);
  390. continue;
  391. }
  392. // Handle C++ dyn_cast.
  393. case CK_Dynamic: {
  394. SVal val = state->getSVal(Ex, LCtx);
  395. // Compute the type of the result.
  396. QualType resultType = CastE->getType();
  397. if (CastE->isGLValue())
  398. resultType = getContext().getPointerType(resultType);
  399. bool Failed = false;
  400. // Check if the value being cast evaluates to 0.
  401. if (val.isZeroConstant())
  402. Failed = true;
  403. // Else, evaluate the cast.
  404. else
  405. val = getStoreManager().attemptDownCast(val, T, Failed);
  406. if (Failed) {
  407. if (T->isReferenceType()) {
  408. // A bad_cast exception is thrown if input value is a reference.
  409. // Currently, we model this, by generating a sink.
  410. Bldr.generateSink(CastE, Pred, state);
  411. continue;
  412. } else {
  413. // If the cast fails on a pointer, bind to 0.
  414. state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
  415. }
  416. } else {
  417. // If we don't know if the cast succeeded, conjure a new symbol.
  418. if (val.isUnknown()) {
  419. DefinedOrUnknownSVal NewSym =
  420. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  421. currBldrCtx->blockCount());
  422. state = state->BindExpr(CastE, LCtx, NewSym);
  423. } else
  424. // Else, bind to the derived region value.
  425. state = state->BindExpr(CastE, LCtx, val);
  426. }
  427. Bldr.generateNode(CastE, Pred, state);
  428. continue;
  429. }
  430. case CK_BaseToDerived: {
  431. SVal val = state->getSVal(Ex, LCtx);
  432. QualType resultType = CastE->getType();
  433. if (CastE->isGLValue())
  434. resultType = getContext().getPointerType(resultType);
  435. bool Failed = false;
  436. if (!val.isConstant()) {
  437. val = getStoreManager().attemptDownCast(val, T, Failed);
  438. }
  439. // Failed to cast or the result is unknown, fall back to conservative.
  440. if (Failed || val.isUnknown()) {
  441. val =
  442. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  443. currBldrCtx->blockCount());
  444. }
  445. state = state->BindExpr(CastE, LCtx, val);
  446. Bldr.generateNode(CastE, Pred, state);
  447. continue;
  448. }
  449. case CK_NullToPointer: {
  450. SVal V = svalBuilder.makeNull();
  451. state = state->BindExpr(CastE, LCtx, V);
  452. Bldr.generateNode(CastE, Pred, state);
  453. continue;
  454. }
  455. case CK_NullToMemberPointer: {
  456. SVal V = svalBuilder.getMemberPointer(nullptr);
  457. state = state->BindExpr(CastE, LCtx, V);
  458. Bldr.generateNode(CastE, Pred, state);
  459. continue;
  460. }
  461. case CK_DerivedToBaseMemberPointer:
  462. case CK_BaseToDerivedMemberPointer:
  463. case CK_ReinterpretMemberPointer: {
  464. SVal V = state->getSVal(Ex, LCtx);
  465. if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
  466. SVal CastedPTMSV = svalBuilder.makePointerToMember(
  467. getBasicVals().accumCXXBase(
  468. llvm::make_range<CastExpr::path_const_iterator>(
  469. CastE->path_begin(), CastE->path_end()), *PTMSV));
  470. state = state->BindExpr(CastE, LCtx, CastedPTMSV);
  471. Bldr.generateNode(CastE, Pred, state);
  472. continue;
  473. }
  474. // Explicitly proceed with default handler for this case cascade.
  475. state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
  476. continue;
  477. }
  478. // Various C++ casts that are not handled yet.
  479. case CK_ToUnion:
  480. case CK_VectorSplat: {
  481. state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
  482. continue;
  483. }
  484. }
  485. }
  486. }
  487. void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
  488. ExplodedNode *Pred,
  489. ExplodedNodeSet &Dst) {
  490. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  491. ProgramStateRef State = Pred->getState();
  492. const LocationContext *LCtx = Pred->getLocationContext();
  493. const Expr *Init = CL->getInitializer();
  494. SVal V = State->getSVal(CL->getInitializer(), LCtx);
  495. if (isa<CXXConstructExpr>(Init) || isa<CXXStdInitializerListExpr>(Init)) {
  496. // No work needed. Just pass the value up to this expression.
  497. } else {
  498. assert(isa<InitListExpr>(Init));
  499. Loc CLLoc = State->getLValue(CL, LCtx);
  500. State = State->bindLoc(CLLoc, V, LCtx);
  501. if (CL->isGLValue())
  502. V = CLLoc;
  503. }
  504. B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
  505. }
  506. void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
  507. ExplodedNodeSet &Dst) {
  508. // Assumption: The CFG has one DeclStmt per Decl.
  509. const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
  510. if (!VD) {
  511. //TODO:AZ: remove explicit insertion after refactoring is done.
  512. Dst.insert(Pred);
  513. return;
  514. }
  515. // FIXME: all pre/post visits should eventually be handled by ::Visit().
  516. ExplodedNodeSet dstPreVisit;
  517. getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
  518. ExplodedNodeSet dstEvaluated;
  519. StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
  520. for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
  521. I!=E; ++I) {
  522. ExplodedNode *N = *I;
  523. ProgramStateRef state = N->getState();
  524. const LocationContext *LC = N->getLocationContext();
  525. // Decls without InitExpr are not initialized explicitly.
  526. if (const Expr *InitEx = VD->getInit()) {
  527. // Note in the state that the initialization has occurred.
  528. ExplodedNode *UpdatedN = N;
  529. SVal InitVal = state->getSVal(InitEx, LC);
  530. assert(DS->isSingleDecl());
  531. if (getObjectUnderConstruction(state, DS, LC)) {
  532. state = finishObjectConstruction(state, DS, LC);
  533. // We constructed the object directly in the variable.
  534. // No need to bind anything.
  535. B.generateNode(DS, UpdatedN, state);
  536. } else {
  537. // Recover some path-sensitivity if a scalar value evaluated to
  538. // UnknownVal.
  539. if (InitVal.isUnknown()) {
  540. QualType Ty = InitEx->getType();
  541. if (InitEx->isGLValue()) {
  542. Ty = getContext().getPointerType(Ty);
  543. }
  544. InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
  545. currBldrCtx->blockCount());
  546. }
  547. B.takeNodes(UpdatedN);
  548. ExplodedNodeSet Dst2;
  549. evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
  550. B.addNodes(Dst2);
  551. }
  552. }
  553. else {
  554. B.generateNode(DS, N, state);
  555. }
  556. }
  557. getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
  558. }
  559. void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
  560. ExplodedNodeSet &Dst) {
  561. // This method acts upon CFG elements for logical operators && and ||
  562. // and attaches the value (true or false) to them as expressions.
  563. // It doesn't produce any state splits.
  564. // If we made it that far, we're past the point when we modeled the short
  565. // circuit. It means that we should have precise knowledge about whether
  566. // we've short-circuited. If we did, we already know the value we need to
  567. // bind. If we didn't, the value of the RHS (casted to the boolean type)
  568. // is the answer.
  569. // Currently this method tries to figure out whether we've short-circuited
  570. // by looking at the ExplodedGraph. This method is imperfect because there
  571. // could inevitably have been merges that would have resulted in multiple
  572. // potential path traversal histories. We bail out when we fail.
  573. // Due to this ambiguity, a more reliable solution would have been to
  574. // track the short circuit operation history path-sensitively until
  575. // we evaluate the respective logical operator.
  576. assert(B->getOpcode() == BO_LAnd ||
  577. B->getOpcode() == BO_LOr);
  578. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  579. ProgramStateRef state = Pred->getState();
  580. if (B->getType()->isVectorType()) {
  581. // FIXME: We do not model vector arithmetic yet. When adding support for
  582. // that, note that the CFG-based reasoning below does not apply, because
  583. // logical operators on vectors are not short-circuit. Currently they are
  584. // modeled as short-circuit in Clang CFG but this is incorrect.
  585. // Do not set the value for the expression. It'd be UnknownVal by default.
  586. Bldr.generateNode(B, Pred, state);
  587. return;
  588. }
  589. ExplodedNode *N = Pred;
  590. while (!N->getLocation().getAs<BlockEntrance>()) {
  591. ProgramPoint P = N->getLocation();
  592. assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
  593. (void) P;
  594. if (N->pred_size() != 1) {
  595. // We failed to track back where we came from.
  596. Bldr.generateNode(B, Pred, state);
  597. return;
  598. }
  599. N = *N->pred_begin();
  600. }
  601. if (N->pred_size() != 1) {
  602. // We failed to track back where we came from.
  603. Bldr.generateNode(B, Pred, state);
  604. return;
  605. }
  606. N = *N->pred_begin();
  607. BlockEdge BE = N->getLocation().castAs<BlockEdge>();
  608. SVal X;
  609. // Determine the value of the expression by introspecting how we
  610. // got this location in the CFG. This requires looking at the previous
  611. // block we were in and what kind of control-flow transfer was involved.
  612. const CFGBlock *SrcBlock = BE.getSrc();
  613. // The only terminator (if there is one) that makes sense is a logical op.
  614. CFGTerminator T = SrcBlock->getTerminator();
  615. if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
  616. (void) Term;
  617. assert(Term->isLogicalOp());
  618. assert(SrcBlock->succ_size() == 2);
  619. // Did we take the true or false branch?
  620. unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
  621. X = svalBuilder.makeIntVal(constant, B->getType());
  622. }
  623. else {
  624. // If there is no terminator, by construction the last statement
  625. // in SrcBlock is the value of the enclosing expression.
  626. // However, we still need to constrain that value to be 0 or 1.
  627. assert(!SrcBlock->empty());
  628. CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
  629. const Expr *RHS = cast<Expr>(Elem.getStmt());
  630. SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
  631. if (RHSVal.isUndef()) {
  632. X = RHSVal;
  633. } else {
  634. // We evaluate "RHSVal != 0" expression which result in 0 if the value is
  635. // known to be false, 1 if the value is known to be true and a new symbol
  636. // when the assumption is unknown.
  637. nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
  638. X = evalBinOp(N->getState(), BO_NE,
  639. svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
  640. Zero, B->getType());
  641. }
  642. }
  643. Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
  644. }
  645. void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
  646. ExplodedNode *Pred,
  647. ExplodedNodeSet &Dst) {
  648. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  649. ProgramStateRef state = Pred->getState();
  650. const LocationContext *LCtx = Pred->getLocationContext();
  651. QualType T = getContext().getCanonicalType(IE->getType());
  652. unsigned NumInitElements = IE->getNumInits();
  653. if (!IE->isGLValue() && !IE->isTransparent() &&
  654. (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
  655. T->isAnyComplexType())) {
  656. llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
  657. // Handle base case where the initializer has no elements.
  658. // e.g: static int* myArray[] = {};
  659. if (NumInitElements == 0) {
  660. SVal V = svalBuilder.makeCompoundVal(T, vals);
  661. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  662. return;
  663. }
  664. for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
  665. ei = IE->rend(); it != ei; ++it) {
  666. SVal V = state->getSVal(cast<Expr>(*it), LCtx);
  667. vals = getBasicVals().prependSVal(V, vals);
  668. }
  669. B.generateNode(IE, Pred,
  670. state->BindExpr(IE, LCtx,
  671. svalBuilder.makeCompoundVal(T, vals)));
  672. return;
  673. }
  674. // Handle scalars: int{5} and int{} and GLvalues.
  675. // Note, if the InitListExpr is a GLvalue, it means that there is an address
  676. // representing it, so it must have a single init element.
  677. assert(NumInitElements <= 1);
  678. SVal V;
  679. if (NumInitElements == 0)
  680. V = getSValBuilder().makeZeroVal(T);
  681. else
  682. V = state->getSVal(IE->getInit(0), LCtx);
  683. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  684. }
  685. void ExprEngine::VisitGuardedExpr(const Expr *Ex,
  686. const Expr *L,
  687. const Expr *R,
  688. ExplodedNode *Pred,
  689. ExplodedNodeSet &Dst) {
  690. assert(L && R);
  691. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  692. ProgramStateRef state = Pred->getState();
  693. const LocationContext *LCtx = Pred->getLocationContext();
  694. const CFGBlock *SrcBlock = nullptr;
  695. // Find the predecessor block.
  696. ProgramStateRef SrcState = state;
  697. for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
  698. ProgramPoint PP = N->getLocation();
  699. if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
  700. // If the state N has multiple predecessors P, it means that successors
  701. // of P are all equivalent.
  702. // In turn, that means that all nodes at P are equivalent in terms
  703. // of observable behavior at N, and we can follow any of them.
  704. // FIXME: a more robust solution which does not walk up the tree.
  705. continue;
  706. }
  707. SrcBlock = PP.castAs<BlockEdge>().getSrc();
  708. SrcState = N->getState();
  709. break;
  710. }
  711. assert(SrcBlock && "missing function entry");
  712. // Find the last expression in the predecessor block. That is the
  713. // expression that is used for the value of the ternary expression.
  714. bool hasValue = false;
  715. SVal V;
  716. for (CFGElement CE : llvm::reverse(*SrcBlock)) {
  717. if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
  718. const Expr *ValEx = cast<Expr>(CS->getStmt());
  719. ValEx = ValEx->IgnoreParens();
  720. // For GNU extension '?:' operator, the left hand side will be an
  721. // OpaqueValueExpr, so get the underlying expression.
  722. if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
  723. L = OpaqueEx->getSourceExpr();
  724. // If the last expression in the predecessor block matches true or false
  725. // subexpression, get its the value.
  726. if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
  727. hasValue = true;
  728. V = SrcState->getSVal(ValEx, LCtx);
  729. }
  730. break;
  731. }
  732. }
  733. if (!hasValue)
  734. V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  735. currBldrCtx->blockCount());
  736. // Generate a new node with the binding from the appropriate path.
  737. B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
  738. }
  739. void ExprEngine::
  740. VisitOffsetOfExpr(const OffsetOfExpr *OOE,
  741. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  742. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  743. Expr::EvalResult Result;
  744. if (OOE->EvaluateAsInt(Result, getContext())) {
  745. APSInt IV = Result.Val.getInt();
  746. assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
  747. assert(OOE->getType()->castAs<BuiltinType>()->isInteger());
  748. assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
  749. SVal X = svalBuilder.makeIntVal(IV);
  750. B.generateNode(OOE, Pred,
  751. Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
  752. X));
  753. }
  754. // FIXME: Handle the case where __builtin_offsetof is not a constant.
  755. }
  756. void ExprEngine::
  757. VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
  758. ExplodedNode *Pred,
  759. ExplodedNodeSet &Dst) {
  760. // FIXME: Prechecks eventually go in ::Visit().
  761. ExplodedNodeSet CheckedSet;
  762. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
  763. ExplodedNodeSet EvalSet;
  764. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  765. QualType T = Ex->getTypeOfArgument();
  766. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  767. I != E; ++I) {
  768. if (Ex->getKind() == UETT_SizeOf) {
  769. if (!T->isIncompleteType() && !T->isConstantSizeType()) {
  770. assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
  771. // FIXME: Add support for VLA type arguments and VLA expressions.
  772. // When that happens, we should probably refactor VLASizeChecker's code.
  773. continue;
  774. } else if (T->getAs<ObjCObjectType>()) {
  775. // Some code tries to take the sizeof an ObjCObjectType, relying that
  776. // the compiler has laid out its representation. Just report Unknown
  777. // for these.
  778. continue;
  779. }
  780. }
  781. APSInt Value = Ex->EvaluateKnownConstInt(getContext());
  782. CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
  783. ProgramStateRef state = (*I)->getState();
  784. state = state->BindExpr(Ex, (*I)->getLocationContext(),
  785. svalBuilder.makeIntVal(amt.getQuantity(),
  786. Ex->getType()));
  787. Bldr.generateNode(Ex, *I, state);
  788. }
  789. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
  790. }
  791. void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
  792. const UnaryOperator *U,
  793. StmtNodeBuilder &Bldr) {
  794. // FIXME: We can probably just have some magic in Environment::getSVal()
  795. // that propagates values, instead of creating a new node here.
  796. //
  797. // Unary "+" is a no-op, similar to a parentheses. We still have places
  798. // where it may be a block-level expression, so we need to
  799. // generate an extra node that just propagates the value of the
  800. // subexpression.
  801. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  802. ProgramStateRef state = (*I)->getState();
  803. const LocationContext *LCtx = (*I)->getLocationContext();
  804. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  805. state->getSVal(Ex, LCtx)));
  806. }
  807. void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
  808. ExplodedNodeSet &Dst) {
  809. // FIXME: Prechecks eventually go in ::Visit().
  810. ExplodedNodeSet CheckedSet;
  811. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
  812. ExplodedNodeSet EvalSet;
  813. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  814. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  815. I != E; ++I) {
  816. switch (U->getOpcode()) {
  817. default: {
  818. Bldr.takeNodes(*I);
  819. ExplodedNodeSet Tmp;
  820. VisitIncrementDecrementOperator(U, *I, Tmp);
  821. Bldr.addNodes(Tmp);
  822. break;
  823. }
  824. case UO_Real: {
  825. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  826. // FIXME: We don't have complex SValues yet.
  827. if (Ex->getType()->isAnyComplexType()) {
  828. // Just report "Unknown."
  829. break;
  830. }
  831. // For all other types, UO_Real is an identity operation.
  832. assert (U->getType() == Ex->getType());
  833. ProgramStateRef state = (*I)->getState();
  834. const LocationContext *LCtx = (*I)->getLocationContext();
  835. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  836. state->getSVal(Ex, LCtx)));
  837. break;
  838. }
  839. case UO_Imag: {
  840. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  841. // FIXME: We don't have complex SValues yet.
  842. if (Ex->getType()->isAnyComplexType()) {
  843. // Just report "Unknown."
  844. break;
  845. }
  846. // For all other types, UO_Imag returns 0.
  847. ProgramStateRef state = (*I)->getState();
  848. const LocationContext *LCtx = (*I)->getLocationContext();
  849. SVal X = svalBuilder.makeZeroVal(Ex->getType());
  850. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
  851. break;
  852. }
  853. case UO_AddrOf: {
  854. // Process pointer-to-member address operation.
  855. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  856. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
  857. const ValueDecl *VD = DRE->getDecl();
  858. if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) {
  859. ProgramStateRef State = (*I)->getState();
  860. const LocationContext *LCtx = (*I)->getLocationContext();
  861. SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD));
  862. Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
  863. break;
  864. }
  865. }
  866. // Explicitly proceed with default handler for this case cascade.
  867. handleUOExtension(I, U, Bldr);
  868. break;
  869. }
  870. case UO_Plus:
  871. assert(!U->isGLValue());
  872. LLVM_FALLTHROUGH;
  873. case UO_Deref:
  874. case UO_Extension: {
  875. handleUOExtension(I, U, Bldr);
  876. break;
  877. }
  878. case UO_LNot:
  879. case UO_Minus:
  880. case UO_Not: {
  881. assert (!U->isGLValue());
  882. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  883. ProgramStateRef state = (*I)->getState();
  884. const LocationContext *LCtx = (*I)->getLocationContext();
  885. // Get the value of the subexpression.
  886. SVal V = state->getSVal(Ex, LCtx);
  887. if (V.isUnknownOrUndef()) {
  888. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
  889. break;
  890. }
  891. switch (U->getOpcode()) {
  892. default:
  893. llvm_unreachable("Invalid Opcode.");
  894. case UO_Not:
  895. // FIXME: Do we need to handle promotions?
  896. state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
  897. break;
  898. case UO_Minus:
  899. // FIXME: Do we need to handle promotions?
  900. state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
  901. break;
  902. case UO_LNot:
  903. // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
  904. //
  905. // Note: technically we do "E == 0", but this is the same in the
  906. // transfer functions as "0 == E".
  907. SVal Result;
  908. if (Optional<Loc> LV = V.getAs<Loc>()) {
  909. Loc X = svalBuilder.makeNullWithType(Ex->getType());
  910. Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
  911. } else if (Ex->getType()->isFloatingType()) {
  912. // FIXME: handle floating point types.
  913. Result = UnknownVal();
  914. } else {
  915. nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
  916. Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
  917. U->getType());
  918. }
  919. state = state->BindExpr(U, LCtx, Result);
  920. break;
  921. }
  922. Bldr.generateNode(U, *I, state);
  923. break;
  924. }
  925. }
  926. }
  927. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
  928. }
  929. void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
  930. ExplodedNode *Pred,
  931. ExplodedNodeSet &Dst) {
  932. // Handle ++ and -- (both pre- and post-increment).
  933. assert (U->isIncrementDecrementOp());
  934. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  935. const LocationContext *LCtx = Pred->getLocationContext();
  936. ProgramStateRef state = Pred->getState();
  937. SVal loc = state->getSVal(Ex, LCtx);
  938. // Perform a load.
  939. ExplodedNodeSet Tmp;
  940. evalLoad(Tmp, U, Ex, Pred, state, loc);
  941. ExplodedNodeSet Dst2;
  942. StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
  943. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
  944. state = (*I)->getState();
  945. assert(LCtx == (*I)->getLocationContext());
  946. SVal V2_untested = state->getSVal(Ex, LCtx);
  947. // Propagate unknown and undefined values.
  948. if (V2_untested.isUnknownOrUndef()) {
  949. state = state->BindExpr(U, LCtx, V2_untested);
  950. // Perform the store, so that the uninitialized value detection happens.
  951. Bldr.takeNodes(*I);
  952. ExplodedNodeSet Dst3;
  953. evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
  954. Bldr.addNodes(Dst3);
  955. continue;
  956. }
  957. DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
  958. // Handle all other values.
  959. BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
  960. // If the UnaryOperator has non-location type, use its type to create the
  961. // constant value. If the UnaryOperator has location type, create the
  962. // constant with int type and pointer width.
  963. SVal RHS;
  964. SVal Result;
  965. if (U->getType()->isAnyPointerType())
  966. RHS = svalBuilder.makeArrayIndex(1);
  967. else if (U->getType()->isIntegralOrEnumerationType())
  968. RHS = svalBuilder.makeIntVal(1, U->getType());
  969. else
  970. RHS = UnknownVal();
  971. // The use of an operand of type bool with the ++ operators is deprecated
  972. // but valid until C++17. And if the operand of the ++ operator is of type
  973. // bool, it is set to true until C++17. Note that for '_Bool', it is also
  974. // set to true when it encounters ++ operator.
  975. if (U->getType()->isBooleanType() && U->isIncrementOp())
  976. Result = svalBuilder.makeTruthVal(true, U->getType());
  977. else
  978. Result = evalBinOp(state, Op, V2, RHS, U->getType());
  979. // Conjure a new symbol if necessary to recover precision.
  980. if (Result.isUnknown()){
  981. DefinedOrUnknownSVal SymVal =
  982. svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
  983. currBldrCtx->blockCount());
  984. Result = SymVal;
  985. // If the value is a location, ++/-- should always preserve
  986. // non-nullness. Check if the original value was non-null, and if so
  987. // propagate that constraint.
  988. if (Loc::isLocType(U->getType())) {
  989. DefinedOrUnknownSVal Constraint =
  990. svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
  991. if (!state->assume(Constraint, true)) {
  992. // It isn't feasible for the original value to be null.
  993. // Propagate this constraint.
  994. Constraint = svalBuilder.evalEQ(state, SymVal,
  995. svalBuilder.makeZeroVal(U->getType()));
  996. state = state->assume(Constraint, false);
  997. assert(state);
  998. }
  999. }
  1000. }
  1001. // Since the lvalue-to-rvalue conversion is explicit in the AST,
  1002. // we bind an l-value if the operator is prefix and an lvalue (in C++).
  1003. if (U->isGLValue())
  1004. state = state->BindExpr(U, LCtx, loc);
  1005. else
  1006. state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
  1007. // Perform the store.
  1008. Bldr.takeNodes(*I);
  1009. ExplodedNodeSet Dst3;
  1010. evalStore(Dst3, U, Ex, *I, state, loc, Result);
  1011. Bldr.addNodes(Dst3);
  1012. }
  1013. Dst.insert(Dst2);
  1014. }