1 //===- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the template classes ExplodedNode and ExplodedGraph,
10 // which represent a path-sensitive, intra-procedural "exploded graph."
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/ParentMap.h"
18 #include "clang/AST/Stmt.h"
19 #include "clang/Analysis/CFGStmtMap.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 ExplodedGraph::ExplodedGraph() = default;
44 ExplodedGraph::~ExplodedGraph() = default;
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 bool ExplodedGraph::isInterestingLValueExpr(const Expr *Ex) {
53 return isa<DeclRefExpr>(Ex) ||
54 isa<MemberExpr>(Ex) ||
55 isa<ObjCIvarRefExpr>(Ex);
58 bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
59 // First, we only consider nodes for reclamation of the following
62 // (1) 1 predecessor (that has one successor)
63 // (2) 1 successor (that has one predecessor)
65 // If a node has no successor it is on the "frontier", while a node
66 // with no predecessor is a root.
68 // After these prerequisites, we discard all "filler" nodes that
69 // are used only for intermediate processing, and are not essential
70 // for analyzer history:
72 // (a) PreStmtPurgeDeadSymbols
74 // We then discard all other nodes where *all* of the following conditions
77 // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
78 // (4) There is no 'tag' for the ProgramPoint.
79 // (5) The 'store' is the same as the predecessor.
80 // (6) The 'GDM' is the same as the predecessor.
81 // (7) The LocationContext is the same as the predecessor.
82 // (8) Expressions that are *not* lvalue expressions.
83 // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
84 // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
85 // PreImplicitCall (so that we would be able to find it when retrying a
86 // call with no inlining).
87 // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
89 // Conditions 1 and 2.
90 if (node->pred_size() != 1 || node->succ_size() != 1)
93 const ExplodedNode *pred = *(node->pred_begin());
94 if (pred->succ_size() != 1)
97 const ExplodedNode *succ = *(node->succ_begin());
98 if (succ->pred_size() != 1)
101 // Now reclaim any nodes that are (by definition) not essential to
102 // analysis history and are not consulted by any client code.
103 ProgramPoint progPoint = node->getLocation();
104 if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
105 return !progPoint.getTag();
108 if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
112 if (progPoint.getTag())
115 // Conditions 5, 6, and 7.
116 ProgramStateRef state = node->getState();
117 ProgramStateRef pred_state = pred->getState();
118 if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
119 progPoint.getLocationContext() != pred->getLocationContext())
122 // All further checks require expressions. As per #3, we know that we have
124 const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
129 // Do not collect nodes for "interesting" lvalue expressions since they are
130 // used extensively for generating path diagnostics.
131 if (isInterestingLValueExpr(Ex))
135 // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
136 // diagnostic generation; specifically, so that we could anchor arrows
137 // pointing to the beginning of statements (as written in code).
138 const ParentMap &PM = progPoint.getLocationContext()->getParentMap();
139 if (!PM.isConsumedExpr(Ex))
143 const ProgramPoint SuccLoc = succ->getLocation();
144 if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
145 if (CallEvent::isCallStmt(SP->getStmt()))
148 // Condition 10, continuation.
149 if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
155 void ExplodedGraph::collectNode(ExplodedNode *node) {
156 // Removing a node means:
157 // (a) changing the predecessors successor to the successor of this node
158 // (b) changing the successors predecessor to the predecessor of this node
159 // (c) Putting 'node' onto freeNodes.
160 assert(node->pred_size() == 1 || node->succ_size() == 1);
161 ExplodedNode *pred = *(node->pred_begin());
162 ExplodedNode *succ = *(node->succ_begin());
163 pred->replaceSuccessor(succ);
164 succ->replacePredecessor(pred);
165 FreeNodes.push_back(node);
166 Nodes.RemoveNode(node);
168 node->~ExplodedNode();
171 void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
172 if (ChangedNodes.empty())
175 // Only periodically reclaim nodes so that we can build up a set of
176 // nodes that meet the reclamation criteria. Freshly created nodes
177 // by definition have no successor, and thus cannot be reclaimed (see below).
178 assert(ReclaimCounter > 0);
179 if (--ReclaimCounter != 0)
181 ReclaimCounter = ReclaimNodeInterval;
183 for (const auto node : ChangedNodes)
184 if (shouldCollect(node))
186 ChangedNodes.clear();
189 //===----------------------------------------------------------------------===//
191 //===----------------------------------------------------------------------===//
193 // An NodeGroup's storage type is actually very much like a TinyPtrVector:
194 // it can be either a pointer to a single ExplodedNode, or a pointer to a
195 // BumpVector allocated with the ExplodedGraph's allocator. This allows the
196 // common case of single-node NodeGroups to be implemented with no extra memory.
198 // Consequently, each of the NodeGroup methods have up to four cases to handle:
199 // 1. The flag is set and this group does not actually contain any nodes.
200 // 2. The group is empty, in which case the storage value is null.
201 // 3. The group contains a single node.
202 // 4. The group contains more than one node.
203 using ExplodedNodeVector = BumpVector<ExplodedNode *>;
204 using GroupStorage = llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *>;
206 void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
207 assert(!V->isSink());
209 V->Succs.addNode(this, G);
212 void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
215 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
216 assert(Storage.is<ExplodedNode *>());
218 assert(Storage.is<ExplodedNode *>());
221 void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
224 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
225 if (Storage.isNull()) {
227 assert(Storage.is<ExplodedNode *>());
231 ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
234 // Switch from single-node to multi-node representation.
235 ExplodedNode *Old = Storage.get<ExplodedNode *>();
237 BumpVectorContext &Ctx = G.getNodeAllocator();
238 V = G.getAllocator().Allocate<ExplodedNodeVector>();
239 new (V) ExplodedNodeVector(Ctx, 4);
240 V->push_back(Old, Ctx);
244 assert(Storage.is<ExplodedNodeVector *>());
247 V->push_back(N, G.getNodeAllocator());
250 unsigned ExplodedNode::NodeGroup::size() const {
254 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
255 if (Storage.isNull())
257 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
262 ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
266 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
267 if (Storage.isNull())
269 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
271 return Storage.getAddrOfPtr1();
274 ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
278 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
279 if (Storage.isNull())
281 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
283 return Storage.getAddrOfPtr1() + 1;
286 bool ExplodedNode::isTrivial() const {
287 return pred_size() == 1 && succ_size() == 1 &&
288 getFirstPred()->getState()->getID() == getState()->getID() &&
289 getFirstPred()->succ_size() == 1;
292 const CFGBlock *ExplodedNode::getCFGBlock() const {
293 ProgramPoint P = getLocation();
294 if (auto BEP = P.getAs<BlockEntrance>())
295 return BEP->getBlock();
297 // Find the node's current statement in the CFG.
298 // FIXME: getStmtForDiagnostics() does nasty things in order to provide
299 // a valid statement for body farms, do we need this behavior here?
300 if (const Stmt *S = getStmtForDiagnostics())
301 return getLocationContext()
302 ->getAnalysisDeclContext()
309 static const LocationContext *
310 findTopAutosynthesizedParentContext(const LocationContext *LC) {
311 assert(LC->getAnalysisDeclContext()->isBodyAutosynthesized());
312 const LocationContext *ParentLC = LC->getParent();
313 assert(ParentLC && "We don't start analysis from autosynthesized code");
314 while (ParentLC->getAnalysisDeclContext()->isBodyAutosynthesized()) {
316 ParentLC = LC->getParent();
317 assert(ParentLC && "We don't start analysis from autosynthesized code");
322 const Stmt *ExplodedNode::getStmtForDiagnostics() const {
323 // We cannot place diagnostics on autosynthesized code.
324 // Put them onto the call site through which we jumped into autosynthesized
325 // code for the first time.
326 const LocationContext *LC = getLocationContext();
327 if (LC->getAnalysisDeclContext()->isBodyAutosynthesized()) {
328 // It must be a stack frame because we only autosynthesize functions.
329 return cast<StackFrameContext>(findTopAutosynthesizedParentContext(LC))
332 // Otherwise, see if the node's program point directly points to a statement.
333 // FIXME: Refactor into a ProgramPoint method?
334 ProgramPoint P = getLocation();
335 if (auto SP = P.getAs<StmtPoint>())
336 return SP->getStmt();
337 if (auto BE = P.getAs<BlockEdge>())
338 return BE->getSrc()->getTerminatorStmt();
339 if (auto CE = P.getAs<CallEnter>())
340 return CE->getCallExpr();
341 if (auto CEE = P.getAs<CallExitEnd>())
342 return CEE->getCalleeContext()->getCallSite();
343 if (auto PIPP = P.getAs<PostInitializer>())
344 return PIPP->getInitializer()->getInit();
345 if (auto CEB = P.getAs<CallExitBegin>())
346 return CEB->getReturnStmt();
347 if (auto FEP = P.getAs<FunctionExitPoint>())
348 return FEP->getStmt();
353 const Stmt *ExplodedNode::getNextStmtForDiagnostics() const {
354 for (const ExplodedNode *N = getFirstSucc(); N; N = N->getFirstSucc()) {
355 if (const Stmt *S = N->getStmtForDiagnostics()) {
356 // Check if the statement is '?' or '&&'/'||'. These are "merges",
357 // not actual statement points.
358 switch (S->getStmtClass()) {
359 case Stmt::ChooseExprClass:
360 case Stmt::BinaryConditionalOperatorClass:
361 case Stmt::ConditionalOperatorClass:
363 case Stmt::BinaryOperatorClass: {
364 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
365 if (Op == BO_LAnd || Op == BO_LOr)
372 // We found the statement, so return it.
380 const Stmt *ExplodedNode::getPreviousStmtForDiagnostics() const {
381 for (const ExplodedNode *N = getFirstPred(); N; N = N->getFirstPred())
382 if (const Stmt *S = N->getStmtForDiagnostics())
388 const Stmt *ExplodedNode::getCurrentOrPreviousStmtForDiagnostics() const {
389 if (const Stmt *S = getStmtForDiagnostics())
392 return getPreviousStmtForDiagnostics();
395 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
396 ProgramStateRef State,
399 // Profile 'State' to determine if we already have an existing node.
400 llvm::FoldingSetNodeID profile;
401 void *InsertPos = nullptr;
403 NodeTy::Profile(profile, L, State, IsSink);
404 NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
407 if (!FreeNodes.empty()) {
408 V = FreeNodes.back();
409 FreeNodes.pop_back();
412 // Allocate a new node.
413 V = (NodeTy*) getAllocator().Allocate<NodeTy>();
417 new (V) NodeTy(L, State, NumNodes, IsSink);
419 if (ReclaimNodeInterval)
420 ChangedNodes.push_back(V);
422 // Insert the node into the node set and return it.
423 Nodes.InsertNode(V, InsertPos);
425 if (IsNew) *IsNew = true;
428 if (IsNew) *IsNew = false;
433 ExplodedNode *ExplodedGraph::createUncachedNode(const ProgramPoint &L,
434 ProgramStateRef State,
437 NodeTy *V = (NodeTy *) getAllocator().Allocate<NodeTy>();
438 new (V) NodeTy(L, State, Id, IsSink);
442 std::unique_ptr<ExplodedGraph>
443 ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
444 InterExplodedGraphMap *ForwardMap,
445 InterExplodedGraphMap *InverseMap) const {
449 using Pass1Ty = llvm::DenseSet<const ExplodedNode *>;
452 using Pass2Ty = InterExplodedGraphMap;
453 InterExplodedGraphMap Pass2Scratch;
454 Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
456 SmallVector<const ExplodedNode*, 10> WL1, WL2;
458 // ===- Pass 1 (reverse DFS) -===
459 for (const auto Sink : Sinks)
463 // Process the first worklist until it is empty.
464 while (!WL1.empty()) {
465 const ExplodedNode *N = WL1.pop_back_val();
467 // Have we already visited this node? If so, continue to the next one.
468 if (!Pass1.insert(N).second)
471 // If this is a root enqueue it to the second worklist.
472 if (N->Preds.empty()) {
477 // Visit our predecessors and enqueue them.
478 WL1.append(N->Preds.begin(), N->Preds.end());
481 // We didn't hit a root? Return with a null pointer for the new graph.
485 // Create an empty graph.
486 std::unique_ptr<ExplodedGraph> G = MakeEmptyGraph();
488 // ===- Pass 2 (forward DFS to construct the new graph) -===
489 while (!WL2.empty()) {
490 const ExplodedNode *N = WL2.pop_back_val();
492 // Skip this node if we have already processed it.
493 if (Pass2.find(N) != Pass2.end())
496 // Create the corresponding node in the new graph and record the mapping
497 // from the old node to the new node.
498 ExplodedNode *NewN = G->createUncachedNode(N->getLocation(), N->State,
499 N->getID(), N->isSink());
502 // Also record the reverse mapping from the new node to the old node.
503 if (InverseMap) (*InverseMap)[NewN] = N;
505 // If this node is a root, designate it as such in the graph.
506 if (N->Preds.empty())
509 // In the case that some of the intended predecessors of NewN have already
510 // been created, we should hook them up as predecessors.
512 // Walk through the predecessors of 'N' and hook up their corresponding
513 // nodes in the new graph (if any) to the freshly created node.
514 for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
516 Pass2Ty::iterator PI = Pass2.find(*I);
517 if (PI == Pass2.end())
520 NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
523 // In the case that some of the intended successors of NewN have already
524 // been created, we should hook them up as successors. Otherwise, enqueue
525 // the new nodes from the original graph that should have nodes created
527 for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
529 Pass2Ty::iterator PI = Pass2.find(*I);
530 if (PI != Pass2.end()) {
531 const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
535 // Enqueue nodes to the worklist that were marked during pass 1.