CoreEngine.cpp 23 KB

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