ExplodedGraph.cpp 13 KB

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