ExprEngineC.cpp 36 KB

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