1e580d831SEugene Zelenko //===- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -------------===//
2fa0734ecSArgyrios Kyrtzidis //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fa0734ecSArgyrios Kyrtzidis //
7fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
8fa0734ecSArgyrios Kyrtzidis //
9fa0734ecSArgyrios Kyrtzidis //  This file defines the template classes ExplodedNode and ExplodedGraph,
10fa0734ecSArgyrios Kyrtzidis //  which represent a path-sensitive, intra-procedural "exploded graph."
11fa0734ecSArgyrios Kyrtzidis //
12fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
13fa0734ecSArgyrios Kyrtzidis 
14f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
15e580d831SEugene Zelenko #include "clang/AST/Expr.h"
16e580d831SEugene Zelenko #include "clang/AST/ExprObjC.h"
173a02247dSChandler Carruth #include "clang/AST/ParentMap.h"
183a02247dSChandler Carruth #include "clang/AST/Stmt.h"
19e580d831SEugene Zelenko #include "clang/Analysis/ProgramPoint.h"
20e580d831SEugene Zelenko #include "clang/Analysis/Support/BumpVector.h"
21e580d831SEugene Zelenko #include "clang/Basic/LLVM.h"
224f7df9beSJordan Rose #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24e580d831SEugene Zelenko #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
253a02247dSChandler Carruth #include "llvm/ADT/DenseSet.h"
26e580d831SEugene Zelenko #include "llvm/ADT/FoldingSet.h"
27e580d831SEugene Zelenko #include "llvm/ADT/Optional.h"
28e580d831SEugene Zelenko #include "llvm/ADT/PointerUnion.h"
29fa0734ecSArgyrios Kyrtzidis #include "llvm/ADT/SmallVector.h"
30e580d831SEugene Zelenko #include "llvm/Support/Casting.h"
31e580d831SEugene Zelenko #include <cassert>
32e580d831SEugene Zelenko #include <memory>
33fa0734ecSArgyrios Kyrtzidis 
34fa0734ecSArgyrios Kyrtzidis using namespace clang;
35fa0734ecSArgyrios Kyrtzidis using namespace ento;
36fa0734ecSArgyrios Kyrtzidis 
37fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
38a40f8ebcSTed Kremenek // Cleanup.
39a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
40a40f8ebcSTed Kremenek 
41e580d831SEugene Zelenko ExplodedGraph::ExplodedGraph() = default;
4244d2973bSTed Kremenek 
43e580d831SEugene Zelenko ExplodedGraph::~ExplodedGraph() = default;
44a40f8ebcSTed Kremenek 
45a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
46a40f8ebcSTed Kremenek // Node reclamation.
47a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
48a40f8ebcSTed Kremenek 
4904fa9e3dSTed Kremenek bool ExplodedGraph::isInterestingLValueExpr(const Expr *Ex) {
5004fa9e3dSTed Kremenek   if (!Ex->isLValue())
5104fa9e3dSTed Kremenek     return false;
5204fa9e3dSTed Kremenek   return isa<DeclRefExpr>(Ex) ||
5304fa9e3dSTed Kremenek          isa<MemberExpr>(Ex) ||
5404fa9e3dSTed Kremenek          isa<ObjCIvarRefExpr>(Ex);
5504fa9e3dSTed Kremenek }
5604fa9e3dSTed Kremenek 
571dd7fd71STed Kremenek bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
588f564058STed Kremenek   // First, we only consider nodes for reclamation of the following
598f564058STed Kremenek   // conditions apply:
601dd7fd71STed Kremenek   //
611dd7fd71STed Kremenek   // (1) 1 predecessor (that has one successor)
621dd7fd71STed Kremenek   // (2) 1 successor (that has one predecessor)
638f564058STed Kremenek   //
648f564058STed Kremenek   // If a node has no successor it is on the "frontier", while a node
658f564058STed Kremenek   // with no predecessor is a root.
668f564058STed Kremenek   //
678f564058STed Kremenek   // After these prerequisites, we discard all "filler" nodes that
688f564058STed Kremenek   // are used only for intermediate processing, and are not essential
698f564058STed Kremenek   // for analyzer history:
708f564058STed Kremenek   //
718f564058STed Kremenek   // (a) PreStmtPurgeDeadSymbols
728f564058STed Kremenek   //
738f564058STed Kremenek   // We then discard all other nodes where *all* of the following conditions
748f564058STed Kremenek   // apply:
758f564058STed Kremenek   //
76199fdd82SJordan Rose   // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
771dd7fd71STed Kremenek   // (4) There is no 'tag' for the ProgramPoint.
781dd7fd71STed Kremenek   // (5) The 'store' is the same as the predecessor.
791dd7fd71STed Kremenek   // (6) The 'GDM' is the same as the predecessor.
801dd7fd71STed Kremenek   // (7) The LocationContext is the same as the predecessor.
8196250482STed Kremenek   // (8) Expressions that are *not* lvalue expressions.
8296250482STed Kremenek   // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
8368a172caSAnton Yartsev   // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
8468a172caSAnton Yartsev   //      PreImplicitCall (so that we would be able to find it when retrying a
8568a172caSAnton Yartsev   //      call with no inlining).
86681cce99SJordan Rose   // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
871dd7fd71STed Kremenek 
881dd7fd71STed Kremenek   // Conditions 1 and 2.
891dd7fd71STed Kremenek   if (node->pred_size() != 1 || node->succ_size() != 1)
901dd7fd71STed Kremenek     return false;
911dd7fd71STed Kremenek 
921dd7fd71STed Kremenek   const ExplodedNode *pred = *(node->pred_begin());
931dd7fd71STed Kremenek   if (pred->succ_size() != 1)
941dd7fd71STed Kremenek     return false;
951dd7fd71STed Kremenek 
961dd7fd71STed Kremenek   const ExplodedNode *succ = *(node->succ_begin());
971dd7fd71STed Kremenek   if (succ->pred_size() != 1)
981dd7fd71STed Kremenek     return false;
991dd7fd71STed Kremenek 
1008f564058STed Kremenek   // Now reclaim any nodes that are (by definition) not essential to
1018f564058STed Kremenek   // analysis history and are not consulted by any client code.
1021dd7fd71STed Kremenek   ProgramPoint progPoint = node->getLocation();
1038f564058STed Kremenek   if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
104f352d8c7STed Kremenek     return !progPoint.getTag();
1058f564058STed Kremenek 
1068f564058STed Kremenek   // Condition 3.
10787396b9bSDavid Blaikie   if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
1081dd7fd71STed Kremenek     return false;
1091dd7fd71STed Kremenek 
1101dd7fd71STed Kremenek   // Condition 4.
11154417f6dSAnna Zaks   if (progPoint.getTag())
1121dd7fd71STed Kremenek     return false;
1131dd7fd71STed Kremenek 
1141dd7fd71STed Kremenek   // Conditions 5, 6, and 7.
1151dd7fd71STed Kremenek   ProgramStateRef state = node->getState();
1161dd7fd71STed Kremenek   ProgramStateRef pred_state = pred->getState();
1171dd7fd71STed Kremenek   if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
1181dd7fd71STed Kremenek       progPoint.getLocationContext() != pred->getLocationContext())
1191dd7fd71STed Kremenek     return false;
1201dd7fd71STed Kremenek 
12154417f6dSAnna Zaks   // All further checks require expressions. As per #3, we know that we have
12254417f6dSAnna Zaks   // a PostStmt.
12354417f6dSAnna Zaks   const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
12404fa9e3dSTed Kremenek   if (!Ex)
12504fa9e3dSTed Kremenek     return false;
12604fa9e3dSTed Kremenek 
12704fa9e3dSTed Kremenek   // Condition 8.
12804fa9e3dSTed Kremenek   // Do not collect nodes for "interesting" lvalue expressions since they are
12904fa9e3dSTed Kremenek   // used extensively for generating path diagnostics.
13004fa9e3dSTed Kremenek   if (isInterestingLValueExpr(Ex))
13196250482STed Kremenek     return false;
13296250482STed Kremenek 
13396250482STed Kremenek   // Condition 9.
13467e0062bSAnna Zaks   // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
13567e0062bSAnna Zaks   // diagnostic generation; specifically, so that we could anchor arrows
13667e0062bSAnna Zaks   // pointing to the beginning of statements (as written in code).
137*fc76d855SKristof Umann   const ParentMap &PM = progPoint.getLocationContext()->getParentMap();
1381dd7fd71STed Kremenek   if (!PM.isConsumedExpr(Ex))
1391dd7fd71STed Kremenek     return false;
1401dd7fd71STed Kremenek 
14196250482STed Kremenek   // Condition 10.
142bec49efdSAnna Zaks   const ProgramPoint SuccLoc = succ->getLocation();
14387396b9bSDavid Blaikie   if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
144e537cc05SJordan Rose     if (CallEvent::isCallStmt(SP->getStmt()))
145bec49efdSAnna Zaks       return false;
146bec49efdSAnna Zaks 
14768a172caSAnton Yartsev   // Condition 10, continuation.
14868a172caSAnton Yartsev   if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
14968a172caSAnton Yartsev     return false;
15068a172caSAnton Yartsev 
1511dd7fd71STed Kremenek   return true;
1521dd7fd71STed Kremenek }
1531dd7fd71STed Kremenek 
1541dd7fd71STed Kremenek void ExplodedGraph::collectNode(ExplodedNode *node) {
1551dd7fd71STed Kremenek   // Removing a node means:
1561dd7fd71STed Kremenek   // (a) changing the predecessors successor to the successor of this node
1571dd7fd71STed Kremenek   // (b) changing the successors predecessor to the predecessor of this node
1581dd7fd71STed Kremenek   // (c) Putting 'node' onto freeNodes.
1591dd7fd71STed Kremenek   assert(node->pred_size() == 1 || node->succ_size() == 1);
1601dd7fd71STed Kremenek   ExplodedNode *pred = *(node->pred_begin());
1611dd7fd71STed Kremenek   ExplodedNode *succ = *(node->succ_begin());
1621dd7fd71STed Kremenek   pred->replaceSuccessor(succ);
1631dd7fd71STed Kremenek   succ->replacePredecessor(pred);
164a2aa929eSTed Kremenek   FreeNodes.push_back(node);
1651dd7fd71STed Kremenek   Nodes.RemoveNode(node);
1661dd7fd71STed Kremenek   --NumNodes;
1671dd7fd71STed Kremenek   node->~ExplodedNode();
1681dd7fd71STed Kremenek }
1691dd7fd71STed Kremenek 
17035e55fe4STed Kremenek void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
171a2aa929eSTed Kremenek   if (ChangedNodes.empty())
172a40f8ebcSTed Kremenek     return;
17344d2973bSTed Kremenek 
174746c06d0SJordan Rose   // Only periodically reclaim nodes so that we can build up a set of
17535e55fe4STed Kremenek   // nodes that meet the reclamation criteria.  Freshly created nodes
17635e55fe4STed Kremenek   // by definition have no successor, and thus cannot be reclaimed (see below).
177746c06d0SJordan Rose   assert(ReclaimCounter > 0);
178746c06d0SJordan Rose   if (--ReclaimCounter != 0)
17935e55fe4STed Kremenek     return;
180746c06d0SJordan Rose   ReclaimCounter = ReclaimNodeInterval;
18135e55fe4STed Kremenek 
182e580d831SEugene Zelenko   for (const auto node : ChangedNodes)
1831dd7fd71STed Kremenek     if (shouldCollect(node))
1841dd7fd71STed Kremenek       collectNode(node);
185a2aa929eSTed Kremenek   ChangedNodes.clear();
186a40f8ebcSTed Kremenek }
187a40f8ebcSTed Kremenek 
188a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
189fa0734ecSArgyrios Kyrtzidis // ExplodedNode.
190fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
191fa0734ecSArgyrios Kyrtzidis 
1922b10f3f8SJordan Rose // An NodeGroup's storage type is actually very much like a TinyPtrVector:
1932b10f3f8SJordan Rose // it can be either a pointer to a single ExplodedNode, or a pointer to a
1942b10f3f8SJordan Rose // BumpVector allocated with the ExplodedGraph's allocator. This allows the
1952b10f3f8SJordan Rose // common case of single-node NodeGroups to be implemented with no extra memory.
1962b10f3f8SJordan Rose //
1972b10f3f8SJordan Rose // Consequently, each of the NodeGroup methods have up to four cases to handle:
1982b10f3f8SJordan Rose // 1. The flag is set and this group does not actually contain any nodes.
1992b10f3f8SJordan Rose // 2. The group is empty, in which case the storage value is null.
2002b10f3f8SJordan Rose // 3. The group contains a single node.
2012b10f3f8SJordan Rose // 4. The group contains more than one node.
202e580d831SEugene Zelenko using ExplodedNodeVector = BumpVector<ExplodedNode *>;
203e580d831SEugene Zelenko using GroupStorage = llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *>;
204fa0734ecSArgyrios Kyrtzidis 
205fa0734ecSArgyrios Kyrtzidis void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
206fa0734ecSArgyrios Kyrtzidis   assert(!V->isSink());
207fa0734ecSArgyrios Kyrtzidis   Preds.addNode(V, G);
208fa0734ecSArgyrios Kyrtzidis   V->Succs.addNode(this, G);
209fa0734ecSArgyrios Kyrtzidis }
210fa0734ecSArgyrios Kyrtzidis 
211a40f8ebcSTed Kremenek void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
2122b10f3f8SJordan Rose   assert(!getFlag());
2132b10f3f8SJordan Rose 
21480547386SJordan Rose   GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
21580547386SJordan Rose   assert(Storage.is<ExplodedNode *>());
21680547386SJordan Rose   Storage = node;
21780547386SJordan Rose   assert(Storage.is<ExplodedNode *>());
218a40f8ebcSTed Kremenek }
219a40f8ebcSTed Kremenek 
220fa0734ecSArgyrios Kyrtzidis void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
221fa0734ecSArgyrios Kyrtzidis   assert(!getFlag());
222fa0734ecSArgyrios Kyrtzidis 
22380547386SJordan Rose   GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
22480547386SJordan Rose   if (Storage.isNull()) {
22580547386SJordan Rose     Storage = N;
22680547386SJordan Rose     assert(Storage.is<ExplodedNode *>());
22780547386SJordan Rose     return;
22880547386SJordan Rose   }
229fa0734ecSArgyrios Kyrtzidis 
23080547386SJordan Rose   ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
23180547386SJordan Rose 
23280547386SJordan Rose   if (!V) {
23380547386SJordan Rose     // Switch from single-node to multi-node representation.
23480547386SJordan Rose     ExplodedNode *Old = Storage.get<ExplodedNode *>();
23580547386SJordan Rose 
23680547386SJordan Rose     BumpVectorContext &Ctx = G.getNodeAllocator();
23780547386SJordan Rose     V = G.getAllocator().Allocate<ExplodedNodeVector>();
23880547386SJordan Rose     new (V) ExplodedNodeVector(Ctx, 4);
23980547386SJordan Rose     V->push_back(Old, Ctx);
24080547386SJordan Rose 
24180547386SJordan Rose     Storage = V;
24280547386SJordan Rose     assert(!getFlag());
24380547386SJordan Rose     assert(Storage.is<ExplodedNodeVector *>());
244fa0734ecSArgyrios Kyrtzidis   }
24580547386SJordan Rose 
24680547386SJordan Rose   V->push_back(N, G.getNodeAllocator());
247fa0734ecSArgyrios Kyrtzidis }
248fa0734ecSArgyrios Kyrtzidis 
249fa0734ecSArgyrios Kyrtzidis unsigned ExplodedNode::NodeGroup::size() const {
250fa0734ecSArgyrios Kyrtzidis   if (getFlag())
251fa0734ecSArgyrios Kyrtzidis     return 0;
252fa0734ecSArgyrios Kyrtzidis 
25380547386SJordan Rose   const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
25480547386SJordan Rose   if (Storage.isNull())
25580547386SJordan Rose     return 0;
25680547386SJordan Rose   if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
25780547386SJordan Rose     return V->size();
25880547386SJordan Rose   return 1;
259fa0734ecSArgyrios Kyrtzidis }
260fa0734ecSArgyrios Kyrtzidis 
26180547386SJordan Rose ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
262fa0734ecSArgyrios Kyrtzidis   if (getFlag())
2630dbb783cSCraig Topper     return nullptr;
264fa0734ecSArgyrios Kyrtzidis 
26580547386SJordan Rose   const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
26680547386SJordan Rose   if (Storage.isNull())
2670dbb783cSCraig Topper     return nullptr;
26880547386SJordan Rose   if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
26980547386SJordan Rose     return V->begin();
27080547386SJordan Rose   return Storage.getAddrOfPtr1();
271fa0734ecSArgyrios Kyrtzidis }
272fa0734ecSArgyrios Kyrtzidis 
27380547386SJordan Rose ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
274fa0734ecSArgyrios Kyrtzidis   if (getFlag())
2750dbb783cSCraig Topper     return nullptr;
276fa0734ecSArgyrios Kyrtzidis 
27780547386SJordan Rose   const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
27880547386SJordan Rose   if (Storage.isNull())
2790dbb783cSCraig Topper     return nullptr;
28080547386SJordan Rose   if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
28180547386SJordan Rose     return V->end();
28280547386SJordan Rose   return Storage.getAddrOfPtr1() + 1;
283fa0734ecSArgyrios Kyrtzidis }
284fa0734ecSArgyrios Kyrtzidis 
28584a2b30bSGeorge Karpenkov int64_t ExplodedNode::getID(ExplodedGraph *G) const {
286057647d8SArtem Dergachev   return G->getAllocator().identifyKnownAlignedObject<ExplodedNode>(this);
28784a2b30bSGeorge Karpenkov }
28884a2b30bSGeorge Karpenkov 
28998bee022SGeorge Karpenkov bool ExplodedNode::isTrivial() const {
29098bee022SGeorge Karpenkov   return pred_size() == 1 && succ_size() == 1 &&
291ff6df778SGeorge Karpenkov          getFirstPred()->getState()->getID() == getState()->getID() &&
292ff6df778SGeorge Karpenkov          getFirstPred()->succ_size() == 1;
29398bee022SGeorge Karpenkov }
29498bee022SGeorge Karpenkov 
295fa0734ecSArgyrios Kyrtzidis ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
29649b1e38eSTed Kremenek                                      ProgramStateRef State,
29749ea5bf5SAnna Zaks                                      bool IsSink,
29849ea5bf5SAnna Zaks                                      bool* IsNew) {
299fa0734ecSArgyrios Kyrtzidis   // Profile 'State' to determine if we already have an existing node.
300fa0734ecSArgyrios Kyrtzidis   llvm::FoldingSetNodeID profile;
3010dbb783cSCraig Topper   void *InsertPos = nullptr;
302fa0734ecSArgyrios Kyrtzidis 
30349ea5bf5SAnna Zaks   NodeTy::Profile(profile, L, State, IsSink);
304fa0734ecSArgyrios Kyrtzidis   NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
305fa0734ecSArgyrios Kyrtzidis 
306fa0734ecSArgyrios Kyrtzidis   if (!V) {
307a2aa929eSTed Kremenek     if (!FreeNodes.empty()) {
308a2aa929eSTed Kremenek       V = FreeNodes.back();
309a2aa929eSTed Kremenek       FreeNodes.pop_back();
310a40f8ebcSTed Kremenek     }
311a40f8ebcSTed Kremenek     else {
312fa0734ecSArgyrios Kyrtzidis       // Allocate a new node.
313fa0734ecSArgyrios Kyrtzidis       V = (NodeTy*) getAllocator().Allocate<NodeTy>();
314a40f8ebcSTed Kremenek     }
315a40f8ebcSTed Kremenek 
31649ea5bf5SAnna Zaks     new (V) NodeTy(L, State, IsSink);
317fa0734ecSArgyrios Kyrtzidis 
318746c06d0SJordan Rose     if (ReclaimNodeInterval)
31935e55fe4STed Kremenek       ChangedNodes.push_back(V);
32035e55fe4STed Kremenek 
321fa0734ecSArgyrios Kyrtzidis     // Insert the node into the node set and return it.
322fa0734ecSArgyrios Kyrtzidis     Nodes.InsertNode(V, InsertPos);
323fa0734ecSArgyrios Kyrtzidis     ++NumNodes;
324fa0734ecSArgyrios Kyrtzidis 
325fa0734ecSArgyrios Kyrtzidis     if (IsNew) *IsNew = true;
326fa0734ecSArgyrios Kyrtzidis   }
327fa0734ecSArgyrios Kyrtzidis   else
328fa0734ecSArgyrios Kyrtzidis     if (IsNew) *IsNew = false;
329fa0734ecSArgyrios Kyrtzidis 
330fa0734ecSArgyrios Kyrtzidis   return V;
331fa0734ecSArgyrios Kyrtzidis }
332fa0734ecSArgyrios Kyrtzidis 
3334067e35fSBen Craig ExplodedNode *ExplodedGraph::createUncachedNode(const ProgramPoint &L,
3344067e35fSBen Craig                                                 ProgramStateRef State,
3354067e35fSBen Craig                                                 bool IsSink) {
3364067e35fSBen Craig   NodeTy *V = (NodeTy *) getAllocator().Allocate<NodeTy>();
3374067e35fSBen Craig   new (V) NodeTy(L, State, IsSink);
3384067e35fSBen Craig   return V;
3394067e35fSBen Craig }
3404067e35fSBen Craig 
341b564d1fbSDavid Blaikie std::unique_ptr<ExplodedGraph>
34225fac2f6SJordan Rose ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
3430833c84aSJordan Rose                     InterExplodedGraphMap *ForwardMap,
3440833c84aSJordan Rose                     InterExplodedGraphMap *InverseMap) const {
3450833c84aSJordan Rose   if (Nodes.empty())
3460dbb783cSCraig Topper     return nullptr;
347fa0734ecSArgyrios Kyrtzidis 
348e580d831SEugene Zelenko   using Pass1Ty = llvm::DenseSet<const ExplodedNode *>;
349fa0734ecSArgyrios Kyrtzidis   Pass1Ty Pass1;
350fa0734ecSArgyrios Kyrtzidis 
351e580d831SEugene Zelenko   using Pass2Ty = InterExplodedGraphMap;
3520833c84aSJordan Rose   InterExplodedGraphMap Pass2Scratch;
3530833c84aSJordan Rose   Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
354fa0734ecSArgyrios Kyrtzidis 
3550e62c1ccSChris Lattner   SmallVector<const ExplodedNode*, 10> WL1, WL2;
356fa0734ecSArgyrios Kyrtzidis 
357fa0734ecSArgyrios Kyrtzidis   // ===- Pass 1 (reverse DFS) -===
358e580d831SEugene Zelenko   for (const auto Sink : Sinks)
359e580d831SEugene Zelenko     if (Sink)
360e580d831SEugene Zelenko       WL1.push_back(Sink);
361fa0734ecSArgyrios Kyrtzidis 
3620833c84aSJordan Rose   // Process the first worklist until it is empty.
363fa0734ecSArgyrios Kyrtzidis   while (!WL1.empty()) {
36425284cc9SRobert Wilhelm     const ExplodedNode *N = WL1.pop_back_val();
365fa0734ecSArgyrios Kyrtzidis 
366fa0734ecSArgyrios Kyrtzidis     // Have we already visited this node?  If so, continue to the next one.
367ad8e079cSBenjamin Kramer     if (!Pass1.insert(N).second)
368fa0734ecSArgyrios Kyrtzidis       continue;
369fa0734ecSArgyrios Kyrtzidis 
370fa0734ecSArgyrios Kyrtzidis     // If this is a root enqueue it to the second worklist.
371fa0734ecSArgyrios Kyrtzidis     if (N->Preds.empty()) {
372fa0734ecSArgyrios Kyrtzidis       WL2.push_back(N);
373fa0734ecSArgyrios Kyrtzidis       continue;
374fa0734ecSArgyrios Kyrtzidis     }
375fa0734ecSArgyrios Kyrtzidis 
376fa0734ecSArgyrios Kyrtzidis     // Visit our predecessors and enqueue them.
377ad8e079cSBenjamin Kramer     WL1.append(N->Preds.begin(), N->Preds.end());
378fa0734ecSArgyrios Kyrtzidis   }
379fa0734ecSArgyrios Kyrtzidis 
380fa0734ecSArgyrios Kyrtzidis   // We didn't hit a root? Return with a null pointer for the new graph.
381fa0734ecSArgyrios Kyrtzidis   if (WL2.empty())
3820dbb783cSCraig Topper     return nullptr;
383fa0734ecSArgyrios Kyrtzidis 
384fa0734ecSArgyrios Kyrtzidis   // Create an empty graph.
385b564d1fbSDavid Blaikie   std::unique_ptr<ExplodedGraph> G = MakeEmptyGraph();
386fa0734ecSArgyrios Kyrtzidis 
387fa0734ecSArgyrios Kyrtzidis   // ===- Pass 2 (forward DFS to construct the new graph) -===
388fa0734ecSArgyrios Kyrtzidis   while (!WL2.empty()) {
38925284cc9SRobert Wilhelm     const ExplodedNode *N = WL2.pop_back_val();
390fa0734ecSArgyrios Kyrtzidis 
391fa0734ecSArgyrios Kyrtzidis     // Skip this node if we have already processed it.
392fa0734ecSArgyrios Kyrtzidis     if (Pass2.find(N) != Pass2.end())
393fa0734ecSArgyrios Kyrtzidis       continue;
394fa0734ecSArgyrios Kyrtzidis 
395fa0734ecSArgyrios Kyrtzidis     // Create the corresponding node in the new graph and record the mapping
396fa0734ecSArgyrios Kyrtzidis     // from the old node to the new node.
3974067e35fSBen Craig     ExplodedNode *NewN = G->createUncachedNode(N->getLocation(), N->State, N->isSink());
398fa0734ecSArgyrios Kyrtzidis     Pass2[N] = NewN;
399fa0734ecSArgyrios Kyrtzidis 
400fa0734ecSArgyrios Kyrtzidis     // Also record the reverse mapping from the new node to the old node.
401fa0734ecSArgyrios Kyrtzidis     if (InverseMap) (*InverseMap)[NewN] = N;
402fa0734ecSArgyrios Kyrtzidis 
403fa0734ecSArgyrios Kyrtzidis     // If this node is a root, designate it as such in the graph.
404fa0734ecSArgyrios Kyrtzidis     if (N->Preds.empty())
405fa0734ecSArgyrios Kyrtzidis       G->addRoot(NewN);
406fa0734ecSArgyrios Kyrtzidis 
407fa0734ecSArgyrios Kyrtzidis     // In the case that some of the intended predecessors of NewN have already
408fa0734ecSArgyrios Kyrtzidis     // been created, we should hook them up as predecessors.
409fa0734ecSArgyrios Kyrtzidis 
410fa0734ecSArgyrios Kyrtzidis     // Walk through the predecessors of 'N' and hook up their corresponding
411fa0734ecSArgyrios Kyrtzidis     // nodes in the new graph (if any) to the freshly created node.
41280547386SJordan Rose     for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
41380547386SJordan Rose          I != E; ++I) {
414fa0734ecSArgyrios Kyrtzidis       Pass2Ty::iterator PI = Pass2.find(*I);
415fa0734ecSArgyrios Kyrtzidis       if (PI == Pass2.end())
416fa0734ecSArgyrios Kyrtzidis         continue;
417fa0734ecSArgyrios Kyrtzidis 
4180833c84aSJordan Rose       NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
419fa0734ecSArgyrios Kyrtzidis     }
420fa0734ecSArgyrios Kyrtzidis 
421fa0734ecSArgyrios Kyrtzidis     // In the case that some of the intended successors of NewN have already
422fa0734ecSArgyrios Kyrtzidis     // been created, we should hook them up as successors.  Otherwise, enqueue
423fa0734ecSArgyrios Kyrtzidis     // the new nodes from the original graph that should have nodes created
424fa0734ecSArgyrios Kyrtzidis     // in the new graph.
42580547386SJordan Rose     for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
42680547386SJordan Rose          I != E; ++I) {
427fa0734ecSArgyrios Kyrtzidis       Pass2Ty::iterator PI = Pass2.find(*I);
428fa0734ecSArgyrios Kyrtzidis       if (PI != Pass2.end()) {
4290833c84aSJordan Rose         const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
430fa0734ecSArgyrios Kyrtzidis         continue;
431fa0734ecSArgyrios Kyrtzidis       }
432fa0734ecSArgyrios Kyrtzidis 
433fa0734ecSArgyrios Kyrtzidis       // Enqueue nodes to the worklist that were marked during pass 1.
434fa0734ecSArgyrios Kyrtzidis       if (Pass1.count(*I))
435fa0734ecSArgyrios Kyrtzidis         WL2.push_back(*I);
436fa0734ecSArgyrios Kyrtzidis     }
437fa0734ecSArgyrios Kyrtzidis   }
438fa0734ecSArgyrios Kyrtzidis 
439fa0734ecSArgyrios Kyrtzidis   return G;
440fa0734ecSArgyrios Kyrtzidis }
441