1 //=-- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -*- C++ -*------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the template classes ExplodedNode and ExplodedGraph,
11 // which represent a path-sensitive, intra-procedural "exploded graph."
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
16 #include "clang/AST/ParentMap.h"
17 #include "clang/AST/Stmt.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
26 using namespace clang;
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 // An out of line virtual method to provide a home for the class vtable.
34 ExplodedNode::Auditor::~Auditor() {}
37 static ExplodedNode::Auditor* NodeAuditor = nullptr;
40 void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 ExplodedGraph::ExplodedGraph()
51 : NumNodes(0), ReclaimNodeInterval(0) {}
53 ExplodedGraph::~ExplodedGraph() {}
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 bool ExplodedGraph::isInterestingLValueExpr(const Expr *Ex) {
62 return isa<DeclRefExpr>(Ex) ||
63 isa<MemberExpr>(Ex) ||
64 isa<ObjCIvarRefExpr>(Ex);
67 bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
68 // First, we only consider nodes for reclamation of the following
71 // (1) 1 predecessor (that has one successor)
72 // (2) 1 successor (that has one predecessor)
74 // If a node has no successor it is on the "frontier", while a node
75 // with no predecessor is a root.
77 // After these prerequisites, we discard all "filler" nodes that
78 // are used only for intermediate processing, and are not essential
79 // for analyzer history:
81 // (a) PreStmtPurgeDeadSymbols
83 // We then discard all other nodes where *all* of the following conditions
86 // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
87 // (4) There is no 'tag' for the ProgramPoint.
88 // (5) The 'store' is the same as the predecessor.
89 // (6) The 'GDM' is the same as the predecessor.
90 // (7) The LocationContext is the same as the predecessor.
91 // (8) Expressions that are *not* lvalue expressions.
92 // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
93 // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
94 // PreImplicitCall (so that we would be able to find it when retrying a
95 // call with no inlining).
96 // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
98 // Conditions 1 and 2.
99 if (node->pred_size() != 1 || node->succ_size() != 1)
102 const ExplodedNode *pred = *(node->pred_begin());
103 if (pred->succ_size() != 1)
106 const ExplodedNode *succ = *(node->succ_begin());
107 if (succ->pred_size() != 1)
110 // Now reclaim any nodes that are (by definition) not essential to
111 // analysis history and are not consulted by any client code.
112 ProgramPoint progPoint = node->getLocation();
113 if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
114 return !progPoint.getTag();
117 if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
121 if (progPoint.getTag())
124 // Conditions 5, 6, and 7.
125 ProgramStateRef state = node->getState();
126 ProgramStateRef pred_state = pred->getState();
127 if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
128 progPoint.getLocationContext() != pred->getLocationContext())
131 // All further checks require expressions. As per #3, we know that we have
133 const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
138 // Do not collect nodes for "interesting" lvalue expressions since they are
139 // used extensively for generating path diagnostics.
140 if (isInterestingLValueExpr(Ex))
144 // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
145 // diagnostic generation; specifically, so that we could anchor arrows
146 // pointing to the beginning of statements (as written in code).
147 ParentMap &PM = progPoint.getLocationContext()->getParentMap();
148 if (!PM.isConsumedExpr(Ex))
152 const ProgramPoint SuccLoc = succ->getLocation();
153 if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
154 if (CallEvent::isCallStmt(SP->getStmt()))
157 // Condition 10, continuation.
158 if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
164 void ExplodedGraph::collectNode(ExplodedNode *node) {
165 // Removing a node means:
166 // (a) changing the predecessors successor to the successor of this node
167 // (b) changing the successors predecessor to the predecessor of this node
168 // (c) Putting 'node' onto freeNodes.
169 assert(node->pred_size() == 1 || node->succ_size() == 1);
170 ExplodedNode *pred = *(node->pred_begin());
171 ExplodedNode *succ = *(node->succ_begin());
172 pred->replaceSuccessor(succ);
173 succ->replacePredecessor(pred);
174 FreeNodes.push_back(node);
175 Nodes.RemoveNode(node);
177 node->~ExplodedNode();
180 void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
181 if (ChangedNodes.empty())
184 // Only periodically reclaim nodes so that we can build up a set of
185 // nodes that meet the reclamation criteria. Freshly created nodes
186 // by definition have no successor, and thus cannot be reclaimed (see below).
187 assert(ReclaimCounter > 0);
188 if (--ReclaimCounter != 0)
190 ReclaimCounter = ReclaimNodeInterval;
192 for (NodeVector::iterator it = ChangedNodes.begin(), et = ChangedNodes.end();
194 ExplodedNode *node = *it;
195 if (shouldCollect(node))
198 ChangedNodes.clear();
201 //===----------------------------------------------------------------------===//
203 //===----------------------------------------------------------------------===//
205 // An NodeGroup's storage type is actually very much like a TinyPtrVector:
206 // it can be either a pointer to a single ExplodedNode, or a pointer to a
207 // BumpVector allocated with the ExplodedGraph's allocator. This allows the
208 // common case of single-node NodeGroups to be implemented with no extra memory.
210 // Consequently, each of the NodeGroup methods have up to four cases to handle:
211 // 1. The flag is set and this group does not actually contain any nodes.
212 // 2. The group is empty, in which case the storage value is null.
213 // 3. The group contains a single node.
214 // 4. The group contains more than one node.
215 typedef BumpVector<ExplodedNode *> ExplodedNodeVector;
216 typedef llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *> GroupStorage;
218 void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
219 assert (!V->isSink());
221 V->Succs.addNode(this, G);
223 if (NodeAuditor) NodeAuditor->AddEdge(V, this);
227 void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
230 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
231 assert(Storage.is<ExplodedNode *>());
233 assert(Storage.is<ExplodedNode *>());
236 void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
239 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
240 if (Storage.isNull()) {
242 assert(Storage.is<ExplodedNode *>());
246 ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
249 // Switch from single-node to multi-node representation.
250 ExplodedNode *Old = Storage.get<ExplodedNode *>();
252 BumpVectorContext &Ctx = G.getNodeAllocator();
253 V = G.getAllocator().Allocate<ExplodedNodeVector>();
254 new (V) ExplodedNodeVector(Ctx, 4);
255 V->push_back(Old, Ctx);
259 assert(Storage.is<ExplodedNodeVector *>());
262 V->push_back(N, G.getNodeAllocator());
265 unsigned ExplodedNode::NodeGroup::size() const {
269 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
270 if (Storage.isNull())
272 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
277 ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
281 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
282 if (Storage.isNull())
284 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
286 return Storage.getAddrOfPtr1();
289 ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
293 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
294 if (Storage.isNull())
296 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
298 return Storage.getAddrOfPtr1() + 1;
301 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
302 ProgramStateRef State,
305 // Profile 'State' to determine if we already have an existing node.
306 llvm::FoldingSetNodeID profile;
307 void *InsertPos = nullptr;
309 NodeTy::Profile(profile, L, State, IsSink);
310 NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
313 if (!FreeNodes.empty()) {
314 V = FreeNodes.back();
315 FreeNodes.pop_back();
318 // Allocate a new node.
319 V = (NodeTy*) getAllocator().Allocate<NodeTy>();
322 new (V) NodeTy(L, State, IsSink);
324 if (ReclaimNodeInterval)
325 ChangedNodes.push_back(V);
327 // Insert the node into the node set and return it.
328 Nodes.InsertNode(V, InsertPos);
331 if (IsNew) *IsNew = true;
334 if (IsNew) *IsNew = false;
339 std::unique_ptr<ExplodedGraph>
340 ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
341 InterExplodedGraphMap *ForwardMap,
342 InterExplodedGraphMap *InverseMap) const {
347 typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty;
350 typedef InterExplodedGraphMap Pass2Ty;
351 InterExplodedGraphMap Pass2Scratch;
352 Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
354 SmallVector<const ExplodedNode*, 10> WL1, WL2;
356 // ===- Pass 1 (reverse DFS) -===
357 for (ArrayRef<const NodeTy *>::iterator I = Sinks.begin(), E = Sinks.end();
363 // Process the first worklist until it is empty.
364 while (!WL1.empty()) {
365 const ExplodedNode *N = WL1.pop_back_val();
367 // Have we already visited this node? If so, continue to the next one.
368 if (!Pass1.insert(N).second)
371 // If this is a root enqueue it to the second worklist.
372 if (N->Preds.empty()) {
377 // Visit our predecessors and enqueue them.
378 WL1.append(N->Preds.begin(), N->Preds.end());
381 // We didn't hit a root? Return with a null pointer for the new graph.
385 // Create an empty graph.
386 std::unique_ptr<ExplodedGraph> G = MakeEmptyGraph();
388 // ===- Pass 2 (forward DFS to construct the new graph) -===
389 while (!WL2.empty()) {
390 const ExplodedNode *N = WL2.pop_back_val();
392 // Skip this node if we have already processed it.
393 if (Pass2.find(N) != Pass2.end())
396 // Create the corresponding node in the new graph and record the mapping
397 // from the old node to the new node.
398 ExplodedNode *NewN = G->getNode(N->getLocation(), N->State, N->isSink(),
402 // Also record the reverse mapping from the new node to the old node.
403 if (InverseMap) (*InverseMap)[NewN] = N;
405 // If this node is a root, designate it as such in the graph.
406 if (N->Preds.empty())
409 // In the case that some of the intended predecessors of NewN have already
410 // been created, we should hook them up as predecessors.
412 // Walk through the predecessors of 'N' and hook up their corresponding
413 // nodes in the new graph (if any) to the freshly created node.
414 for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
416 Pass2Ty::iterator PI = Pass2.find(*I);
417 if (PI == Pass2.end())
420 NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
423 // In the case that some of the intended successors of NewN have already
424 // been created, we should hook them up as successors. Otherwise, enqueue
425 // the new nodes from the original graph that should have nodes created
427 for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
429 Pass2Ty::iterator PI = Pass2.find(*I);
430 if (PI != Pass2.end()) {
431 const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
435 // Enqueue nodes to the worklist that were marked during pass 1.