ExprEngineC.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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()->isBuiltinType());
  748. assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
  749. assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
  750. SVal X = svalBuilder.makeIntVal(IV);
  751. B.generateNode(OOE, Pred,
  752. Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
  753. X));
  754. }
  755. // FIXME: Handle the case where __builtin_offsetof is not a constant.
  756. }
  757. void ExprEngine::
  758. VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
  759. ExplodedNode *Pred,
  760. ExplodedNodeSet &Dst) {
  761. // FIXME: Prechecks eventually go in ::Visit().
  762. ExplodedNodeSet CheckedSet;
  763. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
  764. ExplodedNodeSet EvalSet;
  765. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  766. QualType T = Ex->getTypeOfArgument();
  767. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  768. I != E; ++I) {
  769. if (Ex->getKind() == UETT_SizeOf) {
  770. if (!T->isIncompleteType() && !T->isConstantSizeType()) {
  771. assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
  772. // FIXME: Add support for VLA type arguments and VLA expressions.
  773. // When that happens, we should probably refactor VLASizeChecker's code.
  774. continue;
  775. } else if (T->getAs<ObjCObjectType>()) {
  776. // Some code tries to take the sizeof an ObjCObjectType, relying that
  777. // the compiler has laid out its representation. Just report Unknown
  778. // for these.
  779. continue;
  780. }
  781. }
  782. APSInt Value = Ex->EvaluateKnownConstInt(getContext());
  783. CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
  784. ProgramStateRef state = (*I)->getState();
  785. state = state->BindExpr(Ex, (*I)->getLocationContext(),
  786. svalBuilder.makeIntVal(amt.getQuantity(),
  787. Ex->getType()));
  788. Bldr.generateNode(Ex, *I, state);
  789. }
  790. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
  791. }
  792. void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
  793. const UnaryOperator *U,
  794. StmtNodeBuilder &Bldr) {
  795. // FIXME: We can probably just have some magic in Environment::getSVal()
  796. // that propagates values, instead of creating a new node here.
  797. //
  798. // Unary "+" is a no-op, similar to a parentheses. We still have places
  799. // where it may be a block-level expression, so we need to
  800. // generate an extra node that just propagates the value of the
  801. // subexpression.
  802. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  803. ProgramStateRef state = (*I)->getState();
  804. const LocationContext *LCtx = (*I)->getLocationContext();
  805. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  806. state->getSVal(Ex, LCtx)));
  807. }
  808. void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
  809. ExplodedNodeSet &Dst) {
  810. // FIXME: Prechecks eventually go in ::Visit().
  811. ExplodedNodeSet CheckedSet;
  812. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
  813. ExplodedNodeSet EvalSet;
  814. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  815. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  816. I != E; ++I) {
  817. switch (U->getOpcode()) {
  818. default: {
  819. Bldr.takeNodes(*I);
  820. ExplodedNodeSet Tmp;
  821. VisitIncrementDecrementOperator(U, *I, Tmp);
  822. Bldr.addNodes(Tmp);
  823. break;
  824. }
  825. case UO_Real: {
  826. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  827. // FIXME: We don't have complex SValues yet.
  828. if (Ex->getType()->isAnyComplexType()) {
  829. // Just report "Unknown."
  830. break;
  831. }
  832. // For all other types, UO_Real is an identity operation.
  833. assert (U->getType() == Ex->getType());
  834. ProgramStateRef state = (*I)->getState();
  835. const LocationContext *LCtx = (*I)->getLocationContext();
  836. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  837. state->getSVal(Ex, LCtx)));
  838. break;
  839. }
  840. case UO_Imag: {
  841. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  842. // FIXME: We don't have complex SValues yet.
  843. if (Ex->getType()->isAnyComplexType()) {
  844. // Just report "Unknown."
  845. break;
  846. }
  847. // For all other types, UO_Imag returns 0.
  848. ProgramStateRef state = (*I)->getState();
  849. const LocationContext *LCtx = (*I)->getLocationContext();
  850. SVal X = svalBuilder.makeZeroVal(Ex->getType());
  851. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
  852. break;
  853. }
  854. case UO_AddrOf: {
  855. // Process pointer-to-member address operation.
  856. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  857. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
  858. const ValueDecl *VD = DRE->getDecl();
  859. if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) {
  860. ProgramStateRef State = (*I)->getState();
  861. const LocationContext *LCtx = (*I)->getLocationContext();
  862. SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD));
  863. Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
  864. break;
  865. }
  866. }
  867. // Explicitly proceed with default handler for this case cascade.
  868. handleUOExtension(I, U, Bldr);
  869. break;
  870. }
  871. case UO_Plus:
  872. assert(!U->isGLValue());
  873. LLVM_FALLTHROUGH;
  874. case UO_Deref:
  875. case UO_Extension: {
  876. handleUOExtension(I, U, Bldr);
  877. break;
  878. }
  879. case UO_LNot:
  880. case UO_Minus:
  881. case UO_Not: {
  882. assert (!U->isGLValue());
  883. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  884. ProgramStateRef state = (*I)->getState();
  885. const LocationContext *LCtx = (*I)->getLocationContext();
  886. // Get the value of the subexpression.
  887. SVal V = state->getSVal(Ex, LCtx);
  888. if (V.isUnknownOrUndef()) {
  889. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
  890. break;
  891. }
  892. switch (U->getOpcode()) {
  893. default:
  894. llvm_unreachable("Invalid Opcode.");
  895. case UO_Not:
  896. // FIXME: Do we need to handle promotions?
  897. state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
  898. break;
  899. case UO_Minus:
  900. // FIXME: Do we need to handle promotions?
  901. state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
  902. break;
  903. case UO_LNot:
  904. // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
  905. //
  906. // Note: technically we do "E == 0", but this is the same in the
  907. // transfer functions as "0 == E".
  908. SVal Result;
  909. if (Optional<Loc> LV = V.getAs<Loc>()) {
  910. Loc X = svalBuilder.makeNullWithType(Ex->getType());
  911. Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
  912. } else if (Ex->getType()->isFloatingType()) {
  913. // FIXME: handle floating point types.
  914. Result = UnknownVal();
  915. } else {
  916. nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
  917. Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
  918. U->getType());
  919. }
  920. state = state->BindExpr(U, LCtx, Result);
  921. break;
  922. }
  923. Bldr.generateNode(U, *I, state);
  924. break;
  925. }
  926. }
  927. }
  928. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
  929. }
  930. void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
  931. ExplodedNode *Pred,
  932. ExplodedNodeSet &Dst) {
  933. // Handle ++ and -- (both pre- and post-increment).
  934. assert (U->isIncrementDecrementOp());
  935. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  936. const LocationContext *LCtx = Pred->getLocationContext();
  937. ProgramStateRef state = Pred->getState();
  938. SVal loc = state->getSVal(Ex, LCtx);
  939. // Perform a load.
  940. ExplodedNodeSet Tmp;
  941. evalLoad(Tmp, U, Ex, Pred, state, loc);
  942. ExplodedNodeSet Dst2;
  943. StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
  944. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
  945. state = (*I)->getState();
  946. assert(LCtx == (*I)->getLocationContext());
  947. SVal V2_untested = state->getSVal(Ex, LCtx);
  948. // Propagate unknown and undefined values.
  949. if (V2_untested.isUnknownOrUndef()) {
  950. state = state->BindExpr(U, LCtx, V2_untested);
  951. // Perform the store, so that the uninitialized value detection happens.
  952. Bldr.takeNodes(*I);
  953. ExplodedNodeSet Dst3;
  954. evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
  955. Bldr.addNodes(Dst3);
  956. continue;
  957. }
  958. DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
  959. // Handle all other values.
  960. BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
  961. // If the UnaryOperator has non-location type, use its type to create the
  962. // constant value. If the UnaryOperator has location type, create the
  963. // constant with int type and pointer width.
  964. SVal RHS;
  965. SVal Result;
  966. if (U->getType()->isAnyPointerType())
  967. RHS = svalBuilder.makeArrayIndex(1);
  968. else if (U->getType()->isIntegralOrEnumerationType())
  969. RHS = svalBuilder.makeIntVal(1, U->getType());
  970. else
  971. RHS = UnknownVal();
  972. // The use of an operand of type bool with the ++ operators is deprecated
  973. // but valid until C++17. And if the operand of the ++ operator is of type
  974. // bool, it is set to true until C++17. Note that for '_Bool', it is also
  975. // set to true when it encounters ++ operator.
  976. if (U->getType()->isBooleanType() && U->isIncrementOp())
  977. Result = svalBuilder.makeTruthVal(true, U->getType());
  978. else
  979. Result = evalBinOp(state, Op, V2, RHS, U->getType());
  980. // Conjure a new symbol if necessary to recover precision.
  981. if (Result.isUnknown()){
  982. DefinedOrUnknownSVal SymVal =
  983. svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
  984. currBldrCtx->blockCount());
  985. Result = SymVal;
  986. // If the value is a location, ++/-- should always preserve
  987. // non-nullness. Check if the original value was non-null, and if so
  988. // propagate that constraint.
  989. if (Loc::isLocType(U->getType())) {
  990. DefinedOrUnknownSVal Constraint =
  991. svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
  992. if (!state->assume(Constraint, true)) {
  993. // It isn't feasible for the original value to be null.
  994. // Propagate this constraint.
  995. Constraint = svalBuilder.evalEQ(state, SymVal,
  996. svalBuilder.makeZeroVal(U->getType()));
  997. state = state->assume(Constraint, false);
  998. assert(state);
  999. }
  1000. }
  1001. }
  1002. // Since the lvalue-to-rvalue conversion is explicit in the AST,
  1003. // we bind an l-value if the operator is prefix and an lvalue (in C++).
  1004. if (U->isGLValue())
  1005. state = state->BindExpr(U, LCtx, loc);
  1006. else
  1007. state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
  1008. // Perform the store.
  1009. Bldr.takeNodes(*I);
  1010. ExplodedNodeSet Dst3;
  1011. evalStore(Dst3, U, Ex, *I, state, loc, Result);
  1012. Bldr.addNodes(Dst3);
  1013. }
  1014. Dst.insert(Dst2);
  1015. }