ExprEngineC.cpp 37 KB

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