1 //===- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -------------===//
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/Expr.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/AST/Stmt.h"
20 #include "clang/Analysis/ProgramPoint.h"
21 #include "clang/Analysis/Support/BumpVector.h"
22 #include "clang/Basic/LLVM.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/FoldingSet.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/PointerUnion.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/Casting.h"
35 using namespace clang;
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // An out of line virtual method to provide a home for the class vtable.
43 ExplodedNode::Auditor::~Auditor() = default;
46 static ExplodedNode::Auditor* NodeAuditor = nullptr;
49 void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 ExplodedGraph::ExplodedGraph() = default;
61 ExplodedGraph::~ExplodedGraph() = default;
63 //===----------------------------------------------------------------------===//
65 //===----------------------------------------------------------------------===//
67 bool ExplodedGraph::isInterestingLValueExpr(const Expr *Ex) {
70 return isa<DeclRefExpr>(Ex) ||
71 isa<MemberExpr>(Ex) ||
72 isa<ObjCIvarRefExpr>(Ex);
75 bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
76 // First, we only consider nodes for reclamation of the following
79 // (1) 1 predecessor (that has one successor)
80 // (2) 1 successor (that has one predecessor)
82 // If a node has no successor it is on the "frontier", while a node
83 // with no predecessor is a root.
85 // After these prerequisites, we discard all "filler" nodes that
86 // are used only for intermediate processing, and are not essential
87 // for analyzer history:
89 // (a) PreStmtPurgeDeadSymbols
91 // We then discard all other nodes where *all* of the following conditions
94 // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
95 // (4) There is no 'tag' for the ProgramPoint.
96 // (5) The 'store' is the same as the predecessor.
97 // (6) The 'GDM' is the same as the predecessor.
98 // (7) The LocationContext is the same as the predecessor.
99 // (8) Expressions that are *not* lvalue expressions.
100 // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
101 // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
102 // PreImplicitCall (so that we would be able to find it when retrying a
103 // call with no inlining).
104 // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
106 // Conditions 1 and 2.
107 if (node->pred_size() != 1 || node->succ_size() != 1)
110 const ExplodedNode *pred = *(node->pred_begin());
111 if (pred->succ_size() != 1)
114 const ExplodedNode *succ = *(node->succ_begin());
115 if (succ->pred_size() != 1)
118 // Now reclaim any nodes that are (by definition) not essential to
119 // analysis history and are not consulted by any client code.
120 ProgramPoint progPoint = node->getLocation();
121 if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
122 return !progPoint.getTag();
125 if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
129 if (progPoint.getTag())
132 // Conditions 5, 6, and 7.
133 ProgramStateRef state = node->getState();
134 ProgramStateRef pred_state = pred->getState();
135 if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
136 progPoint.getLocationContext() != pred->getLocationContext())
139 // All further checks require expressions. As per #3, we know that we have
141 const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
146 // Do not collect nodes for "interesting" lvalue expressions since they are
147 // used extensively for generating path diagnostics.
148 if (isInterestingLValueExpr(Ex))
152 // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
153 // diagnostic generation; specifically, so that we could anchor arrows
154 // pointing to the beginning of statements (as written in code).
155 ParentMap &PM = progPoint.getLocationContext()->getParentMap();
156 if (!PM.isConsumedExpr(Ex))
160 const ProgramPoint SuccLoc = succ->getLocation();
161 if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
162 if (CallEvent::isCallStmt(SP->getStmt()))
165 // Condition 10, continuation.
166 if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
172 void ExplodedGraph::collectNode(ExplodedNode *node) {
173 // Removing a node means:
174 // (a) changing the predecessors successor to the successor of this node
175 // (b) changing the successors predecessor to the predecessor of this node
176 // (c) Putting 'node' onto freeNodes.
177 assert(node->pred_size() == 1 || node->succ_size() == 1);
178 ExplodedNode *pred = *(node->pred_begin());
179 ExplodedNode *succ = *(node->succ_begin());
180 pred->replaceSuccessor(succ);
181 succ->replacePredecessor(pred);
182 FreeNodes.push_back(node);
183 Nodes.RemoveNode(node);
185 node->~ExplodedNode();
188 void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
189 if (ChangedNodes.empty())
192 // Only periodically reclaim nodes so that we can build up a set of
193 // nodes that meet the reclamation criteria. Freshly created nodes
194 // by definition have no successor, and thus cannot be reclaimed (see below).
195 assert(ReclaimCounter > 0);
196 if (--ReclaimCounter != 0)
198 ReclaimCounter = ReclaimNodeInterval;
200 for (const auto node : ChangedNodes)
201 if (shouldCollect(node))
203 ChangedNodes.clear();
206 //===----------------------------------------------------------------------===//
208 //===----------------------------------------------------------------------===//
210 // An NodeGroup's storage type is actually very much like a TinyPtrVector:
211 // it can be either a pointer to a single ExplodedNode, or a pointer to a
212 // BumpVector allocated with the ExplodedGraph's allocator. This allows the
213 // common case of single-node NodeGroups to be implemented with no extra memory.
215 // Consequently, each of the NodeGroup methods have up to four cases to handle:
216 // 1. The flag is set and this group does not actually contain any nodes.
217 // 2. The group is empty, in which case the storage value is null.
218 // 3. The group contains a single node.
219 // 4. The group contains more than one node.
220 using ExplodedNodeVector = BumpVector<ExplodedNode *>;
221 using GroupStorage = llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *>;
223 void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
224 assert(!V->isSink());
226 V->Succs.addNode(this, G);
228 if (NodeAuditor) NodeAuditor->AddEdge(V, this);
232 void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
235 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
236 assert(Storage.is<ExplodedNode *>());
238 assert(Storage.is<ExplodedNode *>());
241 void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
244 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
245 if (Storage.isNull()) {
247 assert(Storage.is<ExplodedNode *>());
251 ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
254 // Switch from single-node to multi-node representation.
255 ExplodedNode *Old = Storage.get<ExplodedNode *>();
257 BumpVectorContext &Ctx = G.getNodeAllocator();
258 V = G.getAllocator().Allocate<ExplodedNodeVector>();
259 new (V) ExplodedNodeVector(Ctx, 4);
260 V->push_back(Old, Ctx);
264 assert(Storage.is<ExplodedNodeVector *>());
267 V->push_back(N, G.getNodeAllocator());
270 unsigned ExplodedNode::NodeGroup::size() const {
274 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
275 if (Storage.isNull())
277 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
282 ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
286 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
287 if (Storage.isNull())
289 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
291 return Storage.getAddrOfPtr1();
294 ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
298 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
299 if (Storage.isNull())
301 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
303 return Storage.getAddrOfPtr1() + 1;
306 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
307 ProgramStateRef State,
310 // Profile 'State' to determine if we already have an existing node.
311 llvm::FoldingSetNodeID profile;
312 void *InsertPos = nullptr;
314 NodeTy::Profile(profile, L, State, IsSink);
315 NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
318 if (!FreeNodes.empty()) {
319 V = FreeNodes.back();
320 FreeNodes.pop_back();
323 // Allocate a new node.
324 V = (NodeTy*) getAllocator().Allocate<NodeTy>();
327 new (V) NodeTy(L, State, IsSink);
329 if (ReclaimNodeInterval)
330 ChangedNodes.push_back(V);
332 // Insert the node into the node set and return it.
333 Nodes.InsertNode(V, InsertPos);
336 if (IsNew) *IsNew = true;
339 if (IsNew) *IsNew = false;
344 ExplodedNode *ExplodedGraph::createUncachedNode(const ProgramPoint &L,
345 ProgramStateRef State,
347 NodeTy *V = (NodeTy *) getAllocator().Allocate<NodeTy>();
348 new (V) NodeTy(L, State, IsSink);
352 std::unique_ptr<ExplodedGraph>
353 ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
354 InterExplodedGraphMap *ForwardMap,
355 InterExplodedGraphMap *InverseMap) const {
359 using Pass1Ty = llvm::DenseSet<const ExplodedNode *>;
362 using Pass2Ty = InterExplodedGraphMap;
363 InterExplodedGraphMap Pass2Scratch;
364 Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
366 SmallVector<const ExplodedNode*, 10> WL1, WL2;
368 // ===- Pass 1 (reverse DFS) -===
369 for (const auto Sink : Sinks)
373 // Process the first worklist until it is empty.
374 while (!WL1.empty()) {
375 const ExplodedNode *N = WL1.pop_back_val();
377 // Have we already visited this node? If so, continue to the next one.
378 if (!Pass1.insert(N).second)
381 // If this is a root enqueue it to the second worklist.
382 if (N->Preds.empty()) {
387 // Visit our predecessors and enqueue them.
388 WL1.append(N->Preds.begin(), N->Preds.end());
391 // We didn't hit a root? Return with a null pointer for the new graph.
395 // Create an empty graph.
396 std::unique_ptr<ExplodedGraph> G = MakeEmptyGraph();
398 // ===- Pass 2 (forward DFS to construct the new graph) -===
399 while (!WL2.empty()) {
400 const ExplodedNode *N = WL2.pop_back_val();
402 // Skip this node if we have already processed it.
403 if (Pass2.find(N) != Pass2.end())
406 // Create the corresponding node in the new graph and record the mapping
407 // from the old node to the new node.
408 ExplodedNode *NewN = G->createUncachedNode(N->getLocation(), N->State, N->isSink());
411 // Also record the reverse mapping from the new node to the old node.
412 if (InverseMap) (*InverseMap)[NewN] = N;
414 // If this node is a root, designate it as such in the graph.
415 if (N->Preds.empty())
418 // In the case that some of the intended predecessors of NewN have already
419 // been created, we should hook them up as predecessors.
421 // Walk through the predecessors of 'N' and hook up their corresponding
422 // nodes in the new graph (if any) to the freshly created node.
423 for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
425 Pass2Ty::iterator PI = Pass2.find(*I);
426 if (PI == Pass2.end())
429 NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
432 // In the case that some of the intended successors of NewN have already
433 // been created, we should hook them up as successors. Otherwise, enqueue
434 // the new nodes from the original graph that should have nodes created
436 for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
438 Pass2Ty::iterator PI = Pass2.find(*I);
439 if (PI != Pass2.end()) {
440 const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
444 // Enqueue nodes to the worklist that were marked during pass 1.