CoreEngine.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. //==- CoreEngine.cpp - Path-Sensitive Dataflow Engine ------------*- 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 a generic engine for intraprocedural, path-sensitive,
  11. // dataflow analysis via graph reachability engine.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/StmtCXX.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Support/Casting.h"
  23. using namespace clang;
  24. using namespace ento;
  25. #define DEBUG_TYPE "CoreEngine"
  26. STATISTIC(NumSteps,
  27. "The # of steps executed.");
  28. STATISTIC(NumReachedMaxSteps,
  29. "The # of times we reached the max number of steps.");
  30. STATISTIC(NumPathsExplored,
  31. "The # of paths explored by the analyzer.");
  32. //===----------------------------------------------------------------------===//
  33. // Worklist classes for exploration of reachable states.
  34. //===----------------------------------------------------------------------===//
  35. WorkList::Visitor::~Visitor() {}
  36. namespace {
  37. class DFS : public WorkList {
  38. SmallVector<WorkListUnit,20> Stack;
  39. public:
  40. bool hasWork() const override {
  41. return !Stack.empty();
  42. }
  43. void enqueue(const WorkListUnit& U) override {
  44. Stack.push_back(U);
  45. }
  46. WorkListUnit dequeue() override {
  47. assert (!Stack.empty());
  48. const WorkListUnit& U = Stack.back();
  49. Stack.pop_back(); // This technically "invalidates" U, but we are fine.
  50. return U;
  51. }
  52. bool visitItemsInWorkList(Visitor &V) override {
  53. for (SmallVectorImpl<WorkListUnit>::iterator
  54. I = Stack.begin(), E = Stack.end(); I != E; ++I) {
  55. if (V.visit(*I))
  56. return true;
  57. }
  58. return false;
  59. }
  60. };
  61. class BFS : public WorkList {
  62. std::deque<WorkListUnit> Queue;
  63. public:
  64. bool hasWork() const override {
  65. return !Queue.empty();
  66. }
  67. void enqueue(const WorkListUnit& U) override {
  68. Queue.push_back(U);
  69. }
  70. WorkListUnit dequeue() override {
  71. WorkListUnit U = Queue.front();
  72. Queue.pop_front();
  73. return U;
  74. }
  75. bool visitItemsInWorkList(Visitor &V) override {
  76. for (std::deque<WorkListUnit>::iterator
  77. I = Queue.begin(), E = Queue.end(); I != E; ++I) {
  78. if (V.visit(*I))
  79. return true;
  80. }
  81. return false;
  82. }
  83. };
  84. } // end anonymous namespace
  85. // Place the dstor for WorkList here because it contains virtual member
  86. // functions, and we the code for the dstor generated in one compilation unit.
  87. WorkList::~WorkList() {}
  88. WorkList *WorkList::makeDFS() { return new DFS(); }
  89. WorkList *WorkList::makeBFS() { return new BFS(); }
  90. namespace {
  91. class BFSBlockDFSContents : public WorkList {
  92. std::deque<WorkListUnit> Queue;
  93. SmallVector<WorkListUnit,20> Stack;
  94. public:
  95. bool hasWork() const override {
  96. return !Queue.empty() || !Stack.empty();
  97. }
  98. void enqueue(const WorkListUnit& U) override {
  99. if (U.getNode()->getLocation().getAs<BlockEntrance>())
  100. Queue.push_front(U);
  101. else
  102. Stack.push_back(U);
  103. }
  104. WorkListUnit dequeue() override {
  105. // Process all basic blocks to completion.
  106. if (!Stack.empty()) {
  107. const WorkListUnit& U = Stack.back();
  108. Stack.pop_back(); // This technically "invalidates" U, but we are fine.
  109. return U;
  110. }
  111. assert(!Queue.empty());
  112. // Don't use const reference. The subsequent pop_back() might make it
  113. // unsafe.
  114. WorkListUnit U = Queue.front();
  115. Queue.pop_front();
  116. return U;
  117. }
  118. bool visitItemsInWorkList(Visitor &V) override {
  119. for (SmallVectorImpl<WorkListUnit>::iterator
  120. I = Stack.begin(), E = Stack.end(); I != E; ++I) {
  121. if (V.visit(*I))
  122. return true;
  123. }
  124. for (std::deque<WorkListUnit>::iterator
  125. I = Queue.begin(), E = Queue.end(); I != E; ++I) {
  126. if (V.visit(*I))
  127. return true;
  128. }
  129. return false;
  130. }
  131. };
  132. } // end anonymous namespace
  133. WorkList* WorkList::makeBFSBlockDFSContents() {
  134. return new BFSBlockDFSContents();
  135. }
  136. //===----------------------------------------------------------------------===//
  137. // Core analysis engine.
  138. //===----------------------------------------------------------------------===//
  139. /// ExecuteWorkList - Run the worklist algorithm for a maximum number of steps.
  140. bool CoreEngine::ExecuteWorkList(const LocationContext *L, unsigned Steps,
  141. ProgramStateRef InitState) {
  142. if (G.num_roots() == 0) { // Initialize the analysis by constructing
  143. // the root if none exists.
  144. const CFGBlock *Entry = &(L->getCFG()->getEntry());
  145. assert (Entry->empty() &&
  146. "Entry block must be empty.");
  147. assert (Entry->succ_size() == 1 &&
  148. "Entry block must have 1 successor.");
  149. // Mark the entry block as visited.
  150. FunctionSummaries->markVisitedBasicBlock(Entry->getBlockID(),
  151. L->getDecl(),
  152. L->getCFG()->getNumBlockIDs());
  153. // Get the solitary successor.
  154. const CFGBlock *Succ = *(Entry->succ_begin());
  155. // Construct an edge representing the
  156. // starting location in the function.
  157. BlockEdge StartLoc(Entry, Succ, L);
  158. // Set the current block counter to being empty.
  159. WList->setBlockCounter(BCounterFactory.GetEmptyCounter());
  160. if (!InitState)
  161. // Generate the root.
  162. generateNode(StartLoc, SubEng.getInitialState(L), nullptr);
  163. else
  164. generateNode(StartLoc, InitState, nullptr);
  165. }
  166. // Check if we have a steps limit
  167. bool UnlimitedSteps = Steps == 0;
  168. while (WList->hasWork()) {
  169. if (!UnlimitedSteps) {
  170. if (Steps == 0) {
  171. NumReachedMaxSteps++;
  172. break;
  173. }
  174. --Steps;
  175. }
  176. NumSteps++;
  177. const WorkListUnit& WU = WList->dequeue();
  178. // Set the current block counter.
  179. WList->setBlockCounter(WU.getBlockCounter());
  180. // Retrieve the node.
  181. ExplodedNode *Node = WU.getNode();
  182. dispatchWorkItem(Node, Node->getLocation(), WU);
  183. }
  184. SubEng.processEndWorklist(hasWorkRemaining());
  185. return WList->hasWork();
  186. }
  187. void CoreEngine::dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
  188. const WorkListUnit& WU) {
  189. // Dispatch on the location type.
  190. switch (Loc.getKind()) {
  191. case ProgramPoint::BlockEdgeKind:
  192. HandleBlockEdge(Loc.castAs<BlockEdge>(), Pred);
  193. break;
  194. case ProgramPoint::BlockEntranceKind:
  195. HandleBlockEntrance(Loc.castAs<BlockEntrance>(), Pred);
  196. break;
  197. case ProgramPoint::BlockExitKind:
  198. assert (false && "BlockExit location never occur in forward analysis.");
  199. break;
  200. case ProgramPoint::CallEnterKind: {
  201. CallEnter CEnter = Loc.castAs<CallEnter>();
  202. SubEng.processCallEnter(CEnter, Pred);
  203. break;
  204. }
  205. case ProgramPoint::CallExitBeginKind:
  206. SubEng.processCallExit(Pred);
  207. break;
  208. case ProgramPoint::EpsilonKind: {
  209. assert(Pred->hasSinglePred() &&
  210. "Assume epsilon has exactly one predecessor by construction");
  211. ExplodedNode *PNode = Pred->getFirstPred();
  212. dispatchWorkItem(Pred, PNode->getLocation(), WU);
  213. break;
  214. }
  215. default:
  216. assert(Loc.getAs<PostStmt>() ||
  217. Loc.getAs<PostInitializer>() ||
  218. Loc.getAs<PostImplicitCall>() ||
  219. Loc.getAs<CallExitEnd>());
  220. HandlePostStmt(WU.getBlock(), WU.getIndex(), Pred);
  221. break;
  222. }
  223. }
  224. bool CoreEngine::ExecuteWorkListWithInitialState(const LocationContext *L,
  225. unsigned Steps,
  226. ProgramStateRef InitState,
  227. ExplodedNodeSet &Dst) {
  228. bool DidNotFinish = ExecuteWorkList(L, Steps, InitState);
  229. for (ExplodedGraph::eop_iterator I = G.eop_begin(), E = G.eop_end(); I != E;
  230. ++I) {
  231. Dst.Add(*I);
  232. }
  233. return DidNotFinish;
  234. }
  235. void CoreEngine::HandleBlockEdge(const BlockEdge &L, ExplodedNode *Pred) {
  236. const CFGBlock *Blk = L.getDst();
  237. NodeBuilderContext BuilderCtx(*this, Blk, Pred);
  238. // Mark this block as visited.
  239. const LocationContext *LC = Pred->getLocationContext();
  240. FunctionSummaries->markVisitedBasicBlock(Blk->getBlockID(),
  241. LC->getDecl(),
  242. LC->getCFG()->getNumBlockIDs());
  243. // Check if we are entering the EXIT block.
  244. if (Blk == &(L.getLocationContext()->getCFG()->getExit())) {
  245. assert (L.getLocationContext()->getCFG()->getExit().size() == 0
  246. && "EXIT block cannot contain Stmts.");
  247. // Process the final state transition.
  248. SubEng.processEndOfFunction(BuilderCtx, Pred);
  249. // This path is done. Don't enqueue any more nodes.
  250. return;
  251. }
  252. // Call into the SubEngine to process entering the CFGBlock.
  253. ExplodedNodeSet dstNodes;
  254. BlockEntrance BE(Blk, Pred->getLocationContext());
  255. NodeBuilderWithSinks nodeBuilder(Pred, dstNodes, BuilderCtx, BE);
  256. SubEng.processCFGBlockEntrance(L, nodeBuilder, Pred);
  257. // Auto-generate a node.
  258. if (!nodeBuilder.hasGeneratedNodes()) {
  259. nodeBuilder.generateNode(Pred->State, Pred);
  260. }
  261. // Enqueue nodes onto the worklist.
  262. enqueue(dstNodes);
  263. }
  264. void CoreEngine::HandleBlockEntrance(const BlockEntrance &L,
  265. ExplodedNode *Pred) {
  266. // Increment the block counter.
  267. const LocationContext *LC = Pred->getLocationContext();
  268. unsigned BlockId = L.getBlock()->getBlockID();
  269. BlockCounter Counter = WList->getBlockCounter();
  270. Counter = BCounterFactory.IncrementCount(Counter, LC->getCurrentStackFrame(),
  271. BlockId);
  272. WList->setBlockCounter(Counter);
  273. // Process the entrance of the block.
  274. if (Optional<CFGElement> E = L.getFirstElement()) {
  275. NodeBuilderContext Ctx(*this, L.getBlock(), Pred);
  276. SubEng.processCFGElement(*E, Pred, 0, &Ctx);
  277. }
  278. else
  279. HandleBlockExit(L.getBlock(), Pred);
  280. }
  281. void CoreEngine::HandleBlockExit(const CFGBlock * B, ExplodedNode *Pred) {
  282. if (const Stmt *Term = B->getTerminator()) {
  283. switch (Term->getStmtClass()) {
  284. default:
  285. llvm_unreachable("Analysis for this terminator not implemented.");
  286. case Stmt::CXXBindTemporaryExprClass:
  287. HandleCleanupTemporaryBranch(
  288. cast<CXXBindTemporaryExpr>(B->getTerminator().getStmt()), B, Pred);
  289. return;
  290. // Model static initializers.
  291. case Stmt::DeclStmtClass:
  292. HandleStaticInit(cast<DeclStmt>(Term), B, Pred);
  293. return;
  294. case Stmt::BinaryOperatorClass: // '&&' and '||'
  295. HandleBranch(cast<BinaryOperator>(Term)->getLHS(), Term, B, Pred);
  296. return;
  297. case Stmt::BinaryConditionalOperatorClass:
  298. case Stmt::ConditionalOperatorClass:
  299. HandleBranch(cast<AbstractConditionalOperator>(Term)->getCond(),
  300. Term, B, Pred);
  301. return;
  302. // FIXME: Use constant-folding in CFG construction to simplify this
  303. // case.
  304. case Stmt::ChooseExprClass:
  305. HandleBranch(cast<ChooseExpr>(Term)->getCond(), Term, B, Pred);
  306. return;
  307. case Stmt::CXXTryStmtClass: {
  308. // Generate a node for each of the successors.
  309. // Our logic for EH analysis can certainly be improved.
  310. for (CFGBlock::const_succ_iterator it = B->succ_begin(),
  311. et = B->succ_end(); it != et; ++it) {
  312. if (const CFGBlock *succ = *it) {
  313. generateNode(BlockEdge(B, succ, Pred->getLocationContext()),
  314. Pred->State, Pred);
  315. }
  316. }
  317. return;
  318. }
  319. case Stmt::DoStmtClass:
  320. HandleBranch(cast<DoStmt>(Term)->getCond(), Term, B, Pred);
  321. return;
  322. case Stmt::CXXForRangeStmtClass:
  323. HandleBranch(cast<CXXForRangeStmt>(Term)->getCond(), Term, B, Pred);
  324. return;
  325. case Stmt::ForStmtClass:
  326. HandleBranch(cast<ForStmt>(Term)->getCond(), Term, B, Pred);
  327. return;
  328. case Stmt::ContinueStmtClass:
  329. case Stmt::BreakStmtClass:
  330. case Stmt::GotoStmtClass:
  331. break;
  332. case Stmt::IfStmtClass:
  333. HandleBranch(cast<IfStmt>(Term)->getCond(), Term, B, Pred);
  334. return;
  335. case Stmt::IndirectGotoStmtClass: {
  336. // Only 1 successor: the indirect goto dispatch block.
  337. assert (B->succ_size() == 1);
  338. IndirectGotoNodeBuilder
  339. builder(Pred, B, cast<IndirectGotoStmt>(Term)->getTarget(),
  340. *(B->succ_begin()), this);
  341. SubEng.processIndirectGoto(builder);
  342. return;
  343. }
  344. case Stmt::ObjCForCollectionStmtClass: {
  345. // In the case of ObjCForCollectionStmt, it appears twice in a CFG:
  346. //
  347. // (1) inside a basic block, which represents the binding of the
  348. // 'element' variable to a value.
  349. // (2) in a terminator, which represents the branch.
  350. //
  351. // For (1), subengines will bind a value (i.e., 0 or 1) indicating
  352. // whether or not collection contains any more elements. We cannot
  353. // just test to see if the element is nil because a container can
  354. // contain nil elements.
  355. HandleBranch(Term, Term, B, Pred);
  356. return;
  357. }
  358. case Stmt::SwitchStmtClass: {
  359. SwitchNodeBuilder builder(Pred, B, cast<SwitchStmt>(Term)->getCond(),
  360. this);
  361. SubEng.processSwitch(builder);
  362. return;
  363. }
  364. case Stmt::WhileStmtClass:
  365. HandleBranch(cast<WhileStmt>(Term)->getCond(), Term, B, Pred);
  366. return;
  367. }
  368. }
  369. assert (B->succ_size() == 1 &&
  370. "Blocks with no terminator should have at most 1 successor.");
  371. generateNode(BlockEdge(B, *(B->succ_begin()), Pred->getLocationContext()),
  372. Pred->State, Pred);
  373. }
  374. void CoreEngine::HandleBranch(const Stmt *Cond, const Stmt *Term,
  375. const CFGBlock * B, ExplodedNode *Pred) {
  376. assert(B->succ_size() == 2);
  377. NodeBuilderContext Ctx(*this, B, Pred);
  378. ExplodedNodeSet Dst;
  379. SubEng.processBranch(Cond, Term, Ctx, Pred, Dst,
  380. *(B->succ_begin()), *(B->succ_begin()+1));
  381. // Enqueue the new frontier onto the worklist.
  382. enqueue(Dst);
  383. }
  384. void CoreEngine::HandleCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
  385. const CFGBlock *B,
  386. ExplodedNode *Pred) {
  387. assert(B->succ_size() == 2);
  388. NodeBuilderContext Ctx(*this, B, Pred);
  389. ExplodedNodeSet Dst;
  390. SubEng.processCleanupTemporaryBranch(BTE, Ctx, Pred, Dst, *(B->succ_begin()),
  391. *(B->succ_begin() + 1));
  392. // Enqueue the new frontier onto the worklist.
  393. enqueue(Dst);
  394. }
  395. void CoreEngine::HandleStaticInit(const DeclStmt *DS, const CFGBlock *B,
  396. ExplodedNode *Pred) {
  397. assert(B->succ_size() == 2);
  398. NodeBuilderContext Ctx(*this, B, Pred);
  399. ExplodedNodeSet Dst;
  400. SubEng.processStaticInitializer(DS, Ctx, Pred, Dst,
  401. *(B->succ_begin()), *(B->succ_begin()+1));
  402. // Enqueue the new frontier onto the worklist.
  403. enqueue(Dst);
  404. }
  405. void CoreEngine::HandlePostStmt(const CFGBlock *B, unsigned StmtIdx,
  406. ExplodedNode *Pred) {
  407. assert(B);
  408. assert(!B->empty());
  409. if (StmtIdx == B->size())
  410. HandleBlockExit(B, Pred);
  411. else {
  412. NodeBuilderContext Ctx(*this, B, Pred);
  413. SubEng.processCFGElement((*B)[StmtIdx], Pred, StmtIdx, &Ctx);
  414. }
  415. }
  416. /// generateNode - Utility method to generate nodes, hook up successors,
  417. /// and add nodes to the worklist.
  418. void CoreEngine::generateNode(const ProgramPoint &Loc,
  419. ProgramStateRef State,
  420. ExplodedNode *Pred) {
  421. bool IsNew;
  422. ExplodedNode *Node = G.getNode(Loc, State, false, &IsNew);
  423. if (Pred)
  424. Node->addPredecessor(Pred, G); // Link 'Node' with its predecessor.
  425. else {
  426. assert (IsNew);
  427. G.addRoot(Node); // 'Node' has no predecessor. Make it a root.
  428. }
  429. // Only add 'Node' to the worklist if it was freshly generated.
  430. if (IsNew) WList->enqueue(Node);
  431. }
  432. void CoreEngine::enqueueStmtNode(ExplodedNode *N,
  433. const CFGBlock *Block, unsigned Idx) {
  434. assert(Block);
  435. assert (!N->isSink());
  436. // Check if this node entered a callee.
  437. if (N->getLocation().getAs<CallEnter>()) {
  438. // Still use the index of the CallExpr. It's needed to create the callee
  439. // StackFrameContext.
  440. WList->enqueue(N, Block, Idx);
  441. return;
  442. }
  443. // Do not create extra nodes. Move to the next CFG element.
  444. if (N->getLocation().getAs<PostInitializer>() ||
  445. N->getLocation().getAs<PostImplicitCall>()) {
  446. WList->enqueue(N, Block, Idx+1);
  447. return;
  448. }
  449. if (N->getLocation().getAs<EpsilonPoint>()) {
  450. WList->enqueue(N, Block, Idx);
  451. return;
  452. }
  453. if ((*Block)[Idx].getKind() == CFGElement::NewAllocator) {
  454. WList->enqueue(N, Block, Idx+1);
  455. return;
  456. }
  457. // At this point, we know we're processing a normal statement.
  458. CFGStmt CS = (*Block)[Idx].castAs<CFGStmt>();
  459. PostStmt Loc(CS.getStmt(), N->getLocationContext());
  460. if (Loc == N->getLocation().withTag(nullptr)) {
  461. // Note: 'N' should be a fresh node because otherwise it shouldn't be
  462. // a member of Deferred.
  463. WList->enqueue(N, Block, Idx+1);
  464. return;
  465. }
  466. bool IsNew;
  467. ExplodedNode *Succ = G.getNode(Loc, N->getState(), false, &IsNew);
  468. Succ->addPredecessor(N, G);
  469. if (IsNew)
  470. WList->enqueue(Succ, Block, Idx+1);
  471. }
  472. ExplodedNode *CoreEngine::generateCallExitBeginNode(ExplodedNode *N) {
  473. // Create a CallExitBegin node and enqueue it.
  474. const StackFrameContext *LocCtx
  475. = cast<StackFrameContext>(N->getLocationContext());
  476. // Use the callee location context.
  477. CallExitBegin Loc(LocCtx);
  478. bool isNew;
  479. ExplodedNode *Node = G.getNode(Loc, N->getState(), false, &isNew);
  480. Node->addPredecessor(N, G);
  481. return isNew ? Node : nullptr;
  482. }
  483. void CoreEngine::enqueue(ExplodedNodeSet &Set) {
  484. for (ExplodedNodeSet::iterator I = Set.begin(),
  485. E = Set.end(); I != E; ++I) {
  486. WList->enqueue(*I);
  487. }
  488. }
  489. void CoreEngine::enqueue(ExplodedNodeSet &Set,
  490. const CFGBlock *Block, unsigned Idx) {
  491. for (ExplodedNodeSet::iterator I = Set.begin(),
  492. E = Set.end(); I != E; ++I) {
  493. enqueueStmtNode(*I, Block, Idx);
  494. }
  495. }
  496. void CoreEngine::enqueueEndOfFunction(ExplodedNodeSet &Set) {
  497. for (ExplodedNodeSet::iterator I = Set.begin(), E = Set.end(); I != E; ++I) {
  498. ExplodedNode *N = *I;
  499. // If we are in an inlined call, generate CallExitBegin node.
  500. if (N->getLocationContext()->getParent()) {
  501. N = generateCallExitBeginNode(N);
  502. if (N)
  503. WList->enqueue(N);
  504. } else {
  505. // TODO: We should run remove dead bindings here.
  506. G.addEndOfPath(N);
  507. NumPathsExplored++;
  508. }
  509. }
  510. }
  511. void NodeBuilder::anchor() { }
  512. ExplodedNode* NodeBuilder::generateNodeImpl(const ProgramPoint &Loc,
  513. ProgramStateRef State,
  514. ExplodedNode *FromN,
  515. bool MarkAsSink) {
  516. HasGeneratedNodes = true;
  517. bool IsNew;
  518. ExplodedNode *N = C.Eng.G.getNode(Loc, State, MarkAsSink, &IsNew);
  519. N->addPredecessor(FromN, C.Eng.G);
  520. Frontier.erase(FromN);
  521. if (!IsNew)
  522. return nullptr;
  523. if (!MarkAsSink)
  524. Frontier.Add(N);
  525. return N;
  526. }
  527. void NodeBuilderWithSinks::anchor() { }
  528. StmtNodeBuilder::~StmtNodeBuilder() {
  529. if (EnclosingBldr)
  530. for (ExplodedNodeSet::iterator I = Frontier.begin(),
  531. E = Frontier.end(); I != E; ++I )
  532. EnclosingBldr->addNodes(*I);
  533. }
  534. void BranchNodeBuilder::anchor() { }
  535. ExplodedNode *BranchNodeBuilder::generateNode(ProgramStateRef State,
  536. bool branch,
  537. ExplodedNode *NodePred) {
  538. // If the branch has been marked infeasible we should not generate a node.
  539. if (!isFeasible(branch))
  540. return nullptr;
  541. ProgramPoint Loc = BlockEdge(C.Block, branch ? DstT:DstF,
  542. NodePred->getLocationContext());
  543. ExplodedNode *Succ = generateNodeImpl(Loc, State, NodePred);
  544. return Succ;
  545. }
  546. ExplodedNode*
  547. IndirectGotoNodeBuilder::generateNode(const iterator &I,
  548. ProgramStateRef St,
  549. bool IsSink) {
  550. bool IsNew;
  551. ExplodedNode *Succ =
  552. Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
  553. St, IsSink, &IsNew);
  554. Succ->addPredecessor(Pred, Eng.G);
  555. if (!IsNew)
  556. return nullptr;
  557. if (!IsSink)
  558. Eng.WList->enqueue(Succ);
  559. return Succ;
  560. }
  561. ExplodedNode*
  562. SwitchNodeBuilder::generateCaseStmtNode(const iterator &I,
  563. ProgramStateRef St) {
  564. bool IsNew;
  565. ExplodedNode *Succ =
  566. Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
  567. St, false, &IsNew);
  568. Succ->addPredecessor(Pred, Eng.G);
  569. if (!IsNew)
  570. return nullptr;
  571. Eng.WList->enqueue(Succ);
  572. return Succ;
  573. }
  574. ExplodedNode*
  575. SwitchNodeBuilder::generateDefaultCaseNode(ProgramStateRef St,
  576. bool IsSink) {
  577. // Get the block for the default case.
  578. assert(Src->succ_rbegin() != Src->succ_rend());
  579. CFGBlock *DefaultBlock = *Src->succ_rbegin();
  580. // Sanity check for default blocks that are unreachable and not caught
  581. // by earlier stages.
  582. if (!DefaultBlock)
  583. return nullptr;
  584. bool IsNew;
  585. ExplodedNode *Succ =
  586. Eng.G.getNode(BlockEdge(Src, DefaultBlock, Pred->getLocationContext()),
  587. St, IsSink, &IsNew);
  588. Succ->addPredecessor(Pred, Eng.G);
  589. if (!IsNew)
  590. return nullptr;
  591. if (!IsSink)
  592. Eng.WList->enqueue(Succ);
  593. return Succ;
  594. }