ExplodedGraph.cpp revision 1e548f12f7cd6631a3e688a9580ede92898d9e69
1//=-- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -*- C++ -*------=// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the template classes ExplodedNode and ExplodedGraph, 11// which represent a path-sensitive, intra-procedural "exploded graph." 12// 13//===----------------------------------------------------------------------===// 14#define DEBUG_TYPE "CoreEngine" 15 16#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" 17#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 18#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 19#include "clang/AST/Stmt.h" 20#include "clang/AST/ParentMap.h" 21#include "llvm/ADT/DenseSet.h" 22#include "llvm/ADT/DenseMap.h" 23#include "llvm/ADT/SmallVector.h" 24#include "llvm/ADT/Statistic.h" 25#include <vector> 26 27using namespace clang; 28using namespace ento; 29 30STATISTIC(NumNodesWithMoreThanTwoSucc, 31 "The # of nodes with more than 2 successors."); 32 33//===----------------------------------------------------------------------===// 34// Node auditing. 35//===----------------------------------------------------------------------===// 36 37// An out of line virtual method to provide a home for the class vtable. 38ExplodedNode::Auditor::~Auditor() {} 39 40#ifndef NDEBUG 41static ExplodedNode::Auditor* NodeAuditor = 0; 42#endif 43 44void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) { 45#ifndef NDEBUG 46 NodeAuditor = A; 47#endif 48} 49 50//===----------------------------------------------------------------------===// 51// Cleanup. 52//===----------------------------------------------------------------------===// 53 54static const unsigned CounterTop = 1000; 55 56ExplodedGraph::ExplodedGraph() 57 : NumNodes(0), reclaimNodes(false), reclaimCounter(CounterTop) {} 58 59ExplodedGraph::~ExplodedGraph() {} 60 61//===----------------------------------------------------------------------===// 62// Node reclamation. 63//===----------------------------------------------------------------------===// 64 65bool ExplodedGraph::shouldCollect(const ExplodedNode *node) { 66 // Reclaim all nodes that match *all* the following criteria: 67 // 68 // (1) 1 predecessor (that has one successor) 69 // (2) 1 successor (that has one predecessor) 70 // (3) The ProgramPoint is for a PostStmt. 71 // (4) There is no 'tag' for the ProgramPoint. 72 // (5) The 'store' is the same as the predecessor. 73 // (6) The 'GDM' is the same as the predecessor. 74 // (7) The LocationContext is the same as the predecessor. 75 // (8) The PostStmt is for a non-consumed Stmt or Expr. 76 // (9) The successor is a CallExpr StmtPoint (so that we would be able to 77 // find it when retrying a call with no inlining). 78 79 // Conditions 1 and 2. 80 if (node->pred_size() != 1 || node->succ_size() != 1) 81 return false; 82 83 const ExplodedNode *pred = *(node->pred_begin()); 84 if (pred->succ_size() != 1) 85 return false; 86 87 const ExplodedNode *succ = *(node->succ_begin()); 88 if (succ->pred_size() != 1) 89 return false; 90 91 // Condition 3. 92 ProgramPoint progPoint = node->getLocation(); 93 if (!isa<PostStmt>(progPoint) || 94 (isa<CallEnter>(progPoint) || 95 isa<CallExitBegin>(progPoint) || isa<CallExitEnd>(progPoint))) 96 return false; 97 98 // Condition 4. 99 PostStmt ps = cast<PostStmt>(progPoint); 100 if (ps.getTag()) 101 return false; 102 103 if (isa<BinaryOperator>(ps.getStmt())) 104 return false; 105 106 // Conditions 5, 6, and 7. 107 ProgramStateRef state = node->getState(); 108 ProgramStateRef pred_state = pred->getState(); 109 if (state->store != pred_state->store || state->GDM != pred_state->GDM || 110 progPoint.getLocationContext() != pred->getLocationContext()) 111 return false; 112 113 // Condition 8. 114 if (const Expr *Ex = dyn_cast<Expr>(ps.getStmt())) { 115 ParentMap &PM = progPoint.getLocationContext()->getParentMap(); 116 if (!PM.isConsumedExpr(Ex)) 117 return false; 118 } 119 120 // Condition 9. 121 const ProgramPoint SuccLoc = succ->getLocation(); 122 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&SuccLoc)) 123 if (CallOrObjCMessage::canBeInlined(SP->getStmt())) 124 return false; 125 126 return true; 127} 128 129void ExplodedGraph::collectNode(ExplodedNode *node) { 130 // Removing a node means: 131 // (a) changing the predecessors successor to the successor of this node 132 // (b) changing the successors predecessor to the predecessor of this node 133 // (c) Putting 'node' onto freeNodes. 134 assert(node->pred_size() == 1 || node->succ_size() == 1); 135 ExplodedNode *pred = *(node->pred_begin()); 136 ExplodedNode *succ = *(node->succ_begin()); 137 pred->replaceSuccessor(succ); 138 succ->replacePredecessor(pred); 139 FreeNodes.push_back(node); 140 Nodes.RemoveNode(node); 141 --NumNodes; 142 node->~ExplodedNode(); 143} 144 145void ExplodedGraph::reclaimRecentlyAllocatedNodes() { 146 if (ChangedNodes.empty()) 147 return; 148 149 // Only periodically relcaim nodes so that we can build up a set of 150 // nodes that meet the reclamation criteria. Freshly created nodes 151 // by definition have no successor, and thus cannot be reclaimed (see below). 152 assert(reclaimCounter > 0); 153 if (--reclaimCounter != 0) 154 return; 155 reclaimCounter = CounterTop; 156 157 for (NodeVector::iterator it = ChangedNodes.begin(), et = ChangedNodes.end(); 158 it != et; ++it) { 159 ExplodedNode *node = *it; 160 if (shouldCollect(node)) 161 collectNode(node); 162 } 163 ChangedNodes.clear(); 164} 165 166//===----------------------------------------------------------------------===// 167// ExplodedNode. 168//===----------------------------------------------------------------------===// 169 170static inline BumpVector<ExplodedNode*>& getVector(void *P) { 171 return *reinterpret_cast<BumpVector<ExplodedNode*>*>(P); 172} 173 174void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) { 175 assert (!V->isSink()); 176 Preds.addNode(V, G); 177 V->Succs.addNode(this, G); 178 if (V->Succs.size() == 3) 179 NumNodesWithMoreThanTwoSucc++; 180#ifndef NDEBUG 181 if (NodeAuditor) NodeAuditor->AddEdge(V, this); 182#endif 183} 184 185void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) { 186 assert(getKind() == Size1); 187 P = reinterpret_cast<uintptr_t>(node); 188 assert(getKind() == Size1); 189} 190 191void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) { 192 assert((reinterpret_cast<uintptr_t>(N) & Mask) == 0x0); 193 assert(!getFlag()); 194 195 if (getKind() == Size1) { 196 if (ExplodedNode *NOld = getNode()) { 197 BumpVectorContext &Ctx = G.getNodeAllocator(); 198 BumpVector<ExplodedNode*> *V = 199 G.getAllocator().Allocate<BumpVector<ExplodedNode*> >(); 200 new (V) BumpVector<ExplodedNode*>(Ctx, 4); 201 202 assert((reinterpret_cast<uintptr_t>(V) & Mask) == 0x0); 203 V->push_back(NOld, Ctx); 204 V->push_back(N, Ctx); 205 P = reinterpret_cast<uintptr_t>(V) | SizeOther; 206 assert(getPtr() == (void*) V); 207 assert(getKind() == SizeOther); 208 } 209 else { 210 P = reinterpret_cast<uintptr_t>(N); 211 assert(getKind() == Size1); 212 } 213 } 214 else { 215 assert(getKind() == SizeOther); 216 getVector(getPtr()).push_back(N, G.getNodeAllocator()); 217 } 218} 219 220unsigned ExplodedNode::NodeGroup::size() const { 221 if (getFlag()) 222 return 0; 223 224 if (getKind() == Size1) 225 return getNode() ? 1 : 0; 226 else 227 return getVector(getPtr()).size(); 228} 229 230ExplodedNode **ExplodedNode::NodeGroup::begin() const { 231 if (getFlag()) 232 return NULL; 233 234 if (getKind() == Size1) 235 return (ExplodedNode**) (getPtr() ? &P : NULL); 236 else 237 return const_cast<ExplodedNode**>(&*(getVector(getPtr()).begin())); 238} 239 240ExplodedNode** ExplodedNode::NodeGroup::end() const { 241 if (getFlag()) 242 return NULL; 243 244 if (getKind() == Size1) 245 return (ExplodedNode**) (getPtr() ? &P+1 : NULL); 246 else { 247 // Dereferencing end() is undefined behaviour. The vector is not empty, so 248 // we can dereference the last elem and then add 1 to the result. 249 return const_cast<ExplodedNode**>(getVector(getPtr()).end()); 250 } 251} 252 253ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L, 254 ProgramStateRef State, 255 bool IsSink, 256 bool* IsNew) { 257 // Profile 'State' to determine if we already have an existing node. 258 llvm::FoldingSetNodeID profile; 259 void *InsertPos = 0; 260 261 NodeTy::Profile(profile, L, State, IsSink); 262 NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos); 263 264 if (!V) { 265 if (!FreeNodes.empty()) { 266 V = FreeNodes.back(); 267 FreeNodes.pop_back(); 268 } 269 else { 270 // Allocate a new node. 271 V = (NodeTy*) getAllocator().Allocate<NodeTy>(); 272 } 273 274 new (V) NodeTy(L, State, IsSink); 275 276 if (reclaimNodes) 277 ChangedNodes.push_back(V); 278 279 // Insert the node into the node set and return it. 280 Nodes.InsertNode(V, InsertPos); 281 ++NumNodes; 282 283 if (IsNew) *IsNew = true; 284 } 285 else 286 if (IsNew) *IsNew = false; 287 288 return V; 289} 290 291std::pair<ExplodedGraph*, InterExplodedGraphMap*> 292ExplodedGraph::Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd, 293 llvm::DenseMap<const void*, const void*> *InverseMap) const { 294 295 if (NBeg == NEnd) 296 return std::make_pair((ExplodedGraph*) 0, 297 (InterExplodedGraphMap*) 0); 298 299 assert (NBeg < NEnd); 300 301 OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap()); 302 303 ExplodedGraph* G = TrimInternal(NBeg, NEnd, M.get(), InverseMap); 304 305 return std::make_pair(static_cast<ExplodedGraph*>(G), M.take()); 306} 307 308ExplodedGraph* 309ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources, 310 const ExplodedNode* const* EndSources, 311 InterExplodedGraphMap* M, 312 llvm::DenseMap<const void*, const void*> *InverseMap) const { 313 314 typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty; 315 Pass1Ty Pass1; 316 317 typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> Pass2Ty; 318 Pass2Ty& Pass2 = M->M; 319 320 SmallVector<const ExplodedNode*, 10> WL1, WL2; 321 322 // ===- Pass 1 (reverse DFS) -=== 323 for (const ExplodedNode* const* I = BeginSources; I != EndSources; ++I) { 324 assert(*I); 325 WL1.push_back(*I); 326 } 327 328 // Process the first worklist until it is empty. Because it is a std::list 329 // it acts like a FIFO queue. 330 while (!WL1.empty()) { 331 const ExplodedNode *N = WL1.back(); 332 WL1.pop_back(); 333 334 // Have we already visited this node? If so, continue to the next one. 335 if (Pass1.count(N)) 336 continue; 337 338 // Otherwise, mark this node as visited. 339 Pass1.insert(N); 340 341 // If this is a root enqueue it to the second worklist. 342 if (N->Preds.empty()) { 343 WL2.push_back(N); 344 continue; 345 } 346 347 // Visit our predecessors and enqueue them. 348 for (ExplodedNode** I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) 349 WL1.push_back(*I); 350 } 351 352 // We didn't hit a root? Return with a null pointer for the new graph. 353 if (WL2.empty()) 354 return 0; 355 356 // Create an empty graph. 357 ExplodedGraph* G = MakeEmptyGraph(); 358 359 // ===- Pass 2 (forward DFS to construct the new graph) -=== 360 while (!WL2.empty()) { 361 const ExplodedNode *N = WL2.back(); 362 WL2.pop_back(); 363 364 // Skip this node if we have already processed it. 365 if (Pass2.find(N) != Pass2.end()) 366 continue; 367 368 // Create the corresponding node in the new graph and record the mapping 369 // from the old node to the new node. 370 ExplodedNode *NewN = G->getNode(N->getLocation(), N->State, N->isSink(), 0); 371 Pass2[N] = NewN; 372 373 // Also record the reverse mapping from the new node to the old node. 374 if (InverseMap) (*InverseMap)[NewN] = N; 375 376 // If this node is a root, designate it as such in the graph. 377 if (N->Preds.empty()) 378 G->addRoot(NewN); 379 380 // In the case that some of the intended predecessors of NewN have already 381 // been created, we should hook them up as predecessors. 382 383 // Walk through the predecessors of 'N' and hook up their corresponding 384 // nodes in the new graph (if any) to the freshly created node. 385 for (ExplodedNode **I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) { 386 Pass2Ty::iterator PI = Pass2.find(*I); 387 if (PI == Pass2.end()) 388 continue; 389 390 NewN->addPredecessor(PI->second, *G); 391 } 392 393 // In the case that some of the intended successors of NewN have already 394 // been created, we should hook them up as successors. Otherwise, enqueue 395 // the new nodes from the original graph that should have nodes created 396 // in the new graph. 397 for (ExplodedNode **I=N->Succs.begin(), **E=N->Succs.end(); I!=E; ++I) { 398 Pass2Ty::iterator PI = Pass2.find(*I); 399 if (PI != Pass2.end()) { 400 PI->second->addPredecessor(NewN, *G); 401 continue; 402 } 403 404 // Enqueue nodes to the worklist that were marked during pass 1. 405 if (Pass1.count(*I)) 406 WL2.push_back(*I); 407 } 408 } 409 410 return G; 411} 412 413void InterExplodedGraphMap::anchor() { } 414 415ExplodedNode* 416InterExplodedGraphMap::getMappedNode(const ExplodedNode *N) const { 417 llvm::DenseMap<const ExplodedNode*, ExplodedNode*>::const_iterator I = 418 M.find(N); 419 420 return I == M.end() ? 0 : I->second; 421} 422 423