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/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
18 #include "clang/AST/Stmt.h"
19 #include "clang/AST/ParentMap.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/DenseMap.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 = 0;
40 void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 static const unsigned CounterTop = 1000;
52 ExplodedGraph::ExplodedGraph()
53 : NumNodes(0), reclaimNodes(false), reclaimCounter(CounterTop) {}
55 ExplodedGraph::~ExplodedGraph() {}
57 //===----------------------------------------------------------------------===//
59 //===----------------------------------------------------------------------===//
61 bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
62 // Reclaim all nodes that match *all* the following criteria:
64 // (1) 1 predecessor (that has one successor)
65 // (2) 1 successor (that has one predecessor)
66 // (3) The ProgramPoint is for a PostStmt.
67 // (4) There is no 'tag' for the ProgramPoint.
68 // (5) The 'store' is the same as the predecessor.
69 // (6) The 'GDM' is the same as the predecessor.
70 // (7) The LocationContext is the same as the predecessor.
71 // (8) The PostStmt is for a non-consumed Stmt or Expr.
72 // (9) The successor is not a CallExpr StmtPoint (so that we would be able to
73 // find it when retrying a call with no inlining).
74 // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
76 // Conditions 1 and 2.
77 if (node->pred_size() != 1 || node->succ_size() != 1)
80 const ExplodedNode *pred = *(node->pred_begin());
81 if (pred->succ_size() != 1)
84 const ExplodedNode *succ = *(node->succ_begin());
85 if (succ->pred_size() != 1)
89 ProgramPoint progPoint = node->getLocation();
90 if (!isa<PostStmt>(progPoint))
94 PostStmt ps = cast<PostStmt>(progPoint);
98 if (isa<BinaryOperator>(ps.getStmt()))
101 // Conditions 5, 6, and 7.
102 ProgramStateRef state = node->getState();
103 ProgramStateRef pred_state = pred->getState();
104 if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
105 progPoint.getLocationContext() != pred->getLocationContext())
109 if (const Expr *Ex = dyn_cast<Expr>(ps.getStmt())) {
110 ParentMap &PM = progPoint.getLocationContext()->getParentMap();
111 if (!PM.isConsumedExpr(Ex))
116 const ProgramPoint SuccLoc = succ->getLocation();
117 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&SuccLoc))
118 if (CallEvent::mayBeInlined(SP->getStmt()))
124 void ExplodedGraph::collectNode(ExplodedNode *node) {
125 // Removing a node means:
126 // (a) changing the predecessors successor to the successor of this node
127 // (b) changing the successors predecessor to the predecessor of this node
128 // (c) Putting 'node' onto freeNodes.
129 assert(node->pred_size() == 1 || node->succ_size() == 1);
130 ExplodedNode *pred = *(node->pred_begin());
131 ExplodedNode *succ = *(node->succ_begin());
132 pred->replaceSuccessor(succ);
133 succ->replacePredecessor(pred);
134 FreeNodes.push_back(node);
135 Nodes.RemoveNode(node);
137 node->~ExplodedNode();
140 void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
141 if (ChangedNodes.empty())
144 // Only periodically relcaim nodes so that we can build up a set of
145 // nodes that meet the reclamation criteria. Freshly created nodes
146 // by definition have no successor, and thus cannot be reclaimed (see below).
147 assert(reclaimCounter > 0);
148 if (--reclaimCounter != 0)
150 reclaimCounter = CounterTop;
152 for (NodeVector::iterator it = ChangedNodes.begin(), et = ChangedNodes.end();
154 ExplodedNode *node = *it;
155 if (shouldCollect(node))
158 ChangedNodes.clear();
161 //===----------------------------------------------------------------------===//
163 //===----------------------------------------------------------------------===//
165 static inline BumpVector<ExplodedNode*>& getVector(void *P) {
166 return *reinterpret_cast<BumpVector<ExplodedNode*>*>(P);
169 void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
170 assert (!V->isSink());
172 V->Succs.addNode(this, G);
174 if (NodeAuditor) NodeAuditor->AddEdge(V, this);
178 void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
179 assert(getKind() == Size1);
180 P = reinterpret_cast<uintptr_t>(node);
181 assert(getKind() == Size1);
184 void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
185 assert((reinterpret_cast<uintptr_t>(N) & Mask) == 0x0);
188 if (getKind() == Size1) {
189 if (ExplodedNode *NOld = getNode()) {
190 BumpVectorContext &Ctx = G.getNodeAllocator();
191 BumpVector<ExplodedNode*> *V =
192 G.getAllocator().Allocate<BumpVector<ExplodedNode*> >();
193 new (V) BumpVector<ExplodedNode*>(Ctx, 4);
195 assert((reinterpret_cast<uintptr_t>(V) & Mask) == 0x0);
196 V->push_back(NOld, Ctx);
197 V->push_back(N, Ctx);
198 P = reinterpret_cast<uintptr_t>(V) | SizeOther;
199 assert(getPtr() == (void*) V);
200 assert(getKind() == SizeOther);
203 P = reinterpret_cast<uintptr_t>(N);
204 assert(getKind() == Size1);
208 assert(getKind() == SizeOther);
209 getVector(getPtr()).push_back(N, G.getNodeAllocator());
213 unsigned ExplodedNode::NodeGroup::size() const {
217 if (getKind() == Size1)
218 return getNode() ? 1 : 0;
220 return getVector(getPtr()).size();
223 ExplodedNode **ExplodedNode::NodeGroup::begin() const {
227 if (getKind() == Size1)
228 return (ExplodedNode**) (getPtr() ? &P : NULL);
230 return const_cast<ExplodedNode**>(&*(getVector(getPtr()).begin()));
233 ExplodedNode** ExplodedNode::NodeGroup::end() const {
237 if (getKind() == Size1)
238 return (ExplodedNode**) (getPtr() ? &P+1 : NULL);
240 // Dereferencing end() is undefined behaviour. The vector is not empty, so
241 // we can dereference the last elem and then add 1 to the result.
242 return const_cast<ExplodedNode**>(getVector(getPtr()).end());
246 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
247 ProgramStateRef State,
250 // Profile 'State' to determine if we already have an existing node.
251 llvm::FoldingSetNodeID profile;
254 NodeTy::Profile(profile, L, State, IsSink);
255 NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
258 if (!FreeNodes.empty()) {
259 V = FreeNodes.back();
260 FreeNodes.pop_back();
263 // Allocate a new node.
264 V = (NodeTy*) getAllocator().Allocate<NodeTy>();
267 new (V) NodeTy(L, State, IsSink);
270 ChangedNodes.push_back(V);
272 // Insert the node into the node set and return it.
273 Nodes.InsertNode(V, InsertPos);
276 if (IsNew) *IsNew = true;
279 if (IsNew) *IsNew = false;
284 std::pair<ExplodedGraph*, InterExplodedGraphMap*>
285 ExplodedGraph::Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd,
286 llvm::DenseMap<const void*, const void*> *InverseMap) const {
289 return std::make_pair((ExplodedGraph*) 0,
290 (InterExplodedGraphMap*) 0);
292 assert (NBeg < NEnd);
294 OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap());
296 ExplodedGraph* G = TrimInternal(NBeg, NEnd, M.get(), InverseMap);
298 return std::make_pair(static_cast<ExplodedGraph*>(G), M.take());
302 ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources,
303 const ExplodedNode* const* EndSources,
304 InterExplodedGraphMap* M,
305 llvm::DenseMap<const void*, const void*> *InverseMap) const {
307 typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty;
310 typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> Pass2Ty;
311 Pass2Ty& Pass2 = M->M;
313 SmallVector<const ExplodedNode*, 10> WL1, WL2;
315 // ===- Pass 1 (reverse DFS) -===
316 for (const ExplodedNode* const* I = BeginSources; I != EndSources; ++I) {
321 // Process the first worklist until it is empty. Because it is a std::list
322 // it acts like a FIFO queue.
323 while (!WL1.empty()) {
324 const ExplodedNode *N = WL1.back();
327 // Have we already visited this node? If so, continue to the next one.
331 // Otherwise, mark this node as visited.
334 // If this is a root enqueue it to the second worklist.
335 if (N->Preds.empty()) {
340 // Visit our predecessors and enqueue them.
341 for (ExplodedNode** I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I)
345 // We didn't hit a root? Return with a null pointer for the new graph.
349 // Create an empty graph.
350 ExplodedGraph* G = MakeEmptyGraph();
352 // ===- Pass 2 (forward DFS to construct the new graph) -===
353 while (!WL2.empty()) {
354 const ExplodedNode *N = WL2.back();
357 // Skip this node if we have already processed it.
358 if (Pass2.find(N) != Pass2.end())
361 // Create the corresponding node in the new graph and record the mapping
362 // from the old node to the new node.
363 ExplodedNode *NewN = G->getNode(N->getLocation(), N->State, N->isSink(), 0);
366 // Also record the reverse mapping from the new node to the old node.
367 if (InverseMap) (*InverseMap)[NewN] = N;
369 // If this node is a root, designate it as such in the graph.
370 if (N->Preds.empty())
373 // In the case that some of the intended predecessors of NewN have already
374 // been created, we should hook them up as predecessors.
376 // Walk through the predecessors of 'N' and hook up their corresponding
377 // nodes in the new graph (if any) to the freshly created node.
378 for (ExplodedNode **I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) {
379 Pass2Ty::iterator PI = Pass2.find(*I);
380 if (PI == Pass2.end())
383 NewN->addPredecessor(PI->second, *G);
386 // In the case that some of the intended successors of NewN have already
387 // been created, we should hook them up as successors. Otherwise, enqueue
388 // the new nodes from the original graph that should have nodes created
390 for (ExplodedNode **I=N->Succs.begin(), **E=N->Succs.end(); I!=E; ++I) {
391 Pass2Ty::iterator PI = Pass2.find(*I);
392 if (PI != Pass2.end()) {
393 PI->second->addPredecessor(NewN, *G);
397 // Enqueue nodes to the worklist that were marked during pass 1.
406 void InterExplodedGraphMap::anchor() { }
409 InterExplodedGraphMap::getMappedNode(const ExplodedNode *N) const {
410 llvm::DenseMap<const ExplodedNode*, ExplodedNode*>::const_iterator I =
413 return I == M.end() ? 0 : I->second;