ExplodedGraph.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. //===- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -------------===//
  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/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/ProgramPoint.h"
  20. #include "clang/Analysis/Support/BumpVector.h"
  21. #include "clang/Basic/LLVM.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. #include "llvm/ADT/FoldingSet.h"
  27. #include "llvm/ADT/Optional.h"
  28. #include "llvm/ADT/PointerUnion.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/Support/Casting.h"
  31. #include <cassert>
  32. #include <memory>
  33. using namespace clang;
  34. using namespace ento;
  35. //===----------------------------------------------------------------------===//
  36. // Node auditing.
  37. //===----------------------------------------------------------------------===//
  38. // An out of line virtual method to provide a home for the class vtable.
  39. ExplodedNode::Auditor::~Auditor() = default;
  40. #ifndef NDEBUG
  41. static ExplodedNode::Auditor* NodeAuditor = nullptr;
  42. #endif
  43. void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
  44. #ifndef NDEBUG
  45. NodeAuditor = A;
  46. #endif
  47. }
  48. //===----------------------------------------------------------------------===//
  49. // Cleanup.
  50. //===----------------------------------------------------------------------===//
  51. ExplodedGraph::ExplodedGraph() = default;
  52. ExplodedGraph::~ExplodedGraph() = default;
  53. //===----------------------------------------------------------------------===//
  54. // Node reclamation.
  55. //===----------------------------------------------------------------------===//
  56. bool ExplodedGraph::isInterestingLValueExpr(const Expr *Ex) {
  57. if (!Ex->isLValue())
  58. return false;
  59. return isa<DeclRefExpr>(Ex) ||
  60. isa<MemberExpr>(Ex) ||
  61. isa<ObjCIvarRefExpr>(Ex);
  62. }
  63. bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
  64. // First, we only consider nodes for reclamation of the following
  65. // conditions apply:
  66. //
  67. // (1) 1 predecessor (that has one successor)
  68. // (2) 1 successor (that has one predecessor)
  69. //
  70. // If a node has no successor it is on the "frontier", while a node
  71. // with no predecessor is a root.
  72. //
  73. // After these prerequisites, we discard all "filler" nodes that
  74. // are used only for intermediate processing, and are not essential
  75. // for analyzer history:
  76. //
  77. // (a) PreStmtPurgeDeadSymbols
  78. //
  79. // We then discard all other nodes where *all* of the following conditions
  80. // apply:
  81. //
  82. // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
  83. // (4) There is no 'tag' for the ProgramPoint.
  84. // (5) The 'store' is the same as the predecessor.
  85. // (6) The 'GDM' is the same as the predecessor.
  86. // (7) The LocationContext is the same as the predecessor.
  87. // (8) Expressions that are *not* lvalue expressions.
  88. // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
  89. // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
  90. // PreImplicitCall (so that we would be able to find it when retrying a
  91. // call with no inlining).
  92. // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
  93. // Conditions 1 and 2.
  94. if (node->pred_size() != 1 || node->succ_size() != 1)
  95. return false;
  96. const ExplodedNode *pred = *(node->pred_begin());
  97. if (pred->succ_size() != 1)
  98. return false;
  99. const ExplodedNode *succ = *(node->succ_begin());
  100. if (succ->pred_size() != 1)
  101. return false;
  102. // Now reclaim any nodes that are (by definition) not essential to
  103. // analysis history and are not consulted by any client code.
  104. ProgramPoint progPoint = node->getLocation();
  105. if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
  106. return !progPoint.getTag();
  107. // Condition 3.
  108. if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
  109. return false;
  110. // Condition 4.
  111. if (progPoint.getTag())
  112. return false;
  113. // Conditions 5, 6, and 7.
  114. ProgramStateRef state = node->getState();
  115. ProgramStateRef pred_state = pred->getState();
  116. if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
  117. progPoint.getLocationContext() != pred->getLocationContext())
  118. return false;
  119. // All further checks require expressions. As per #3, we know that we have
  120. // a PostStmt.
  121. const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
  122. if (!Ex)
  123. return false;
  124. // Condition 8.
  125. // Do not collect nodes for "interesting" lvalue expressions since they are
  126. // used extensively for generating path diagnostics.
  127. if (isInterestingLValueExpr(Ex))
  128. return false;
  129. // Condition 9.
  130. // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
  131. // diagnostic generation; specifically, so that we could anchor arrows
  132. // pointing to the beginning of statements (as written in code).
  133. ParentMap &PM = progPoint.getLocationContext()->getParentMap();
  134. if (!PM.isConsumedExpr(Ex))
  135. return false;
  136. // Condition 10.
  137. const ProgramPoint SuccLoc = succ->getLocation();
  138. if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
  139. if (CallEvent::isCallStmt(SP->getStmt()))
  140. return false;
  141. // Condition 10, continuation.
  142. if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
  143. return false;
  144. return true;
  145. }
  146. void ExplodedGraph::collectNode(ExplodedNode *node) {
  147. // Removing a node means:
  148. // (a) changing the predecessors successor to the successor of this node
  149. // (b) changing the successors predecessor to the predecessor of this node
  150. // (c) Putting 'node' onto freeNodes.
  151. assert(node->pred_size() == 1 || node->succ_size() == 1);
  152. ExplodedNode *pred = *(node->pred_begin());
  153. ExplodedNode *succ = *(node->succ_begin());
  154. pred->replaceSuccessor(succ);
  155. succ->replacePredecessor(pred);
  156. FreeNodes.push_back(node);
  157. Nodes.RemoveNode(node);
  158. --NumNodes;
  159. node->~ExplodedNode();
  160. }
  161. void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
  162. if (ChangedNodes.empty())
  163. return;
  164. // Only periodically reclaim nodes so that we can build up a set of
  165. // nodes that meet the reclamation criteria. Freshly created nodes
  166. // by definition have no successor, and thus cannot be reclaimed (see below).
  167. assert(ReclaimCounter > 0);
  168. if (--ReclaimCounter != 0)
  169. return;
  170. ReclaimCounter = ReclaimNodeInterval;
  171. for (const auto node : ChangedNodes)
  172. if (shouldCollect(node))
  173. collectNode(node);
  174. ChangedNodes.clear();
  175. }
  176. //===----------------------------------------------------------------------===//
  177. // ExplodedNode.
  178. //===----------------------------------------------------------------------===//
  179. // An NodeGroup's storage type is actually very much like a TinyPtrVector:
  180. // it can be either a pointer to a single ExplodedNode, or a pointer to a
  181. // BumpVector allocated with the ExplodedGraph's allocator. This allows the
  182. // common case of single-node NodeGroups to be implemented with no extra memory.
  183. //
  184. // Consequently, each of the NodeGroup methods have up to four cases to handle:
  185. // 1. The flag is set and this group does not actually contain any nodes.
  186. // 2. The group is empty, in which case the storage value is null.
  187. // 3. The group contains a single node.
  188. // 4. The group contains more than one node.
  189. using ExplodedNodeVector = BumpVector<ExplodedNode *>;
  190. using GroupStorage = llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *>;
  191. void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
  192. assert(!V->isSink());
  193. Preds.addNode(V, G);
  194. V->Succs.addNode(this, G);
  195. #ifndef NDEBUG
  196. if (NodeAuditor) NodeAuditor->AddEdge(V, this);
  197. #endif
  198. }
  199. void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
  200. assert(!getFlag());
  201. GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
  202. assert(Storage.is<ExplodedNode *>());
  203. Storage = node;
  204. assert(Storage.is<ExplodedNode *>());
  205. }
  206. void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
  207. assert(!getFlag());
  208. GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
  209. if (Storage.isNull()) {
  210. Storage = N;
  211. assert(Storage.is<ExplodedNode *>());
  212. return;
  213. }
  214. ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
  215. if (!V) {
  216. // Switch from single-node to multi-node representation.
  217. ExplodedNode *Old = Storage.get<ExplodedNode *>();
  218. BumpVectorContext &Ctx = G.getNodeAllocator();
  219. V = G.getAllocator().Allocate<ExplodedNodeVector>();
  220. new (V) ExplodedNodeVector(Ctx, 4);
  221. V->push_back(Old, Ctx);
  222. Storage = V;
  223. assert(!getFlag());
  224. assert(Storage.is<ExplodedNodeVector *>());
  225. }
  226. V->push_back(N, G.getNodeAllocator());
  227. }
  228. unsigned ExplodedNode::NodeGroup::size() const {
  229. if (getFlag())
  230. return 0;
  231. const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
  232. if (Storage.isNull())
  233. return 0;
  234. if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
  235. return V->size();
  236. return 1;
  237. }
  238. ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
  239. if (getFlag())
  240. return nullptr;
  241. const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
  242. if (Storage.isNull())
  243. return nullptr;
  244. if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
  245. return V->begin();
  246. return Storage.getAddrOfPtr1();
  247. }
  248. ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
  249. if (getFlag())
  250. return nullptr;
  251. const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
  252. if (Storage.isNull())
  253. return nullptr;
  254. if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
  255. return V->end();
  256. return Storage.getAddrOfPtr1() + 1;
  257. }
  258. ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
  259. ProgramStateRef State,
  260. bool IsSink,
  261. bool* IsNew) {
  262. // Profile 'State' to determine if we already have an existing node.
  263. llvm::FoldingSetNodeID profile;
  264. void *InsertPos = nullptr;
  265. NodeTy::Profile(profile, L, State, IsSink);
  266. NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
  267. if (!V) {
  268. if (!FreeNodes.empty()) {
  269. V = FreeNodes.back();
  270. FreeNodes.pop_back();
  271. }
  272. else {
  273. // Allocate a new node.
  274. V = (NodeTy*) getAllocator().Allocate<NodeTy>();
  275. }
  276. new (V) NodeTy(L, State, IsSink);
  277. if (ReclaimNodeInterval)
  278. ChangedNodes.push_back(V);
  279. // Insert the node into the node set and return it.
  280. Nodes.InsertNode(V, InsertPos);
  281. ++NumNodes;
  282. if (IsNew) *IsNew = true;
  283. }
  284. else
  285. if (IsNew) *IsNew = false;
  286. return V;
  287. }
  288. ExplodedNode *ExplodedGraph::createUncachedNode(const ProgramPoint &L,
  289. ProgramStateRef State,
  290. bool IsSink) {
  291. NodeTy *V = (NodeTy *) getAllocator().Allocate<NodeTy>();
  292. new (V) NodeTy(L, State, IsSink);
  293. return V;
  294. }
  295. std::unique_ptr<ExplodedGraph>
  296. ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
  297. InterExplodedGraphMap *ForwardMap,
  298. InterExplodedGraphMap *InverseMap) const {
  299. if (Nodes.empty())
  300. return nullptr;
  301. using Pass1Ty = llvm::DenseSet<const ExplodedNode *>;
  302. Pass1Ty Pass1;
  303. using Pass2Ty = InterExplodedGraphMap;
  304. InterExplodedGraphMap Pass2Scratch;
  305. Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
  306. SmallVector<const ExplodedNode*, 10> WL1, WL2;
  307. // ===- Pass 1 (reverse DFS) -===
  308. for (const auto Sink : Sinks)
  309. if (Sink)
  310. WL1.push_back(Sink);
  311. // Process the first worklist until it is empty.
  312. while (!WL1.empty()) {
  313. const ExplodedNode *N = WL1.pop_back_val();
  314. // Have we already visited this node? If so, continue to the next one.
  315. if (!Pass1.insert(N).second)
  316. continue;
  317. // If this is a root enqueue it to the second worklist.
  318. if (N->Preds.empty()) {
  319. WL2.push_back(N);
  320. continue;
  321. }
  322. // Visit our predecessors and enqueue them.
  323. WL1.append(N->Preds.begin(), N->Preds.end());
  324. }
  325. // We didn't hit a root? Return with a null pointer for the new graph.
  326. if (WL2.empty())
  327. return nullptr;
  328. // Create an empty graph.
  329. std::unique_ptr<ExplodedGraph> G = MakeEmptyGraph();
  330. // ===- Pass 2 (forward DFS to construct the new graph) -===
  331. while (!WL2.empty()) {
  332. const ExplodedNode *N = WL2.pop_back_val();
  333. // Skip this node if we have already processed it.
  334. if (Pass2.find(N) != Pass2.end())
  335. continue;
  336. // Create the corresponding node in the new graph and record the mapping
  337. // from the old node to the new node.
  338. ExplodedNode *NewN = G->createUncachedNode(N->getLocation(), N->State, N->isSink());
  339. Pass2[N] = NewN;
  340. // Also record the reverse mapping from the new node to the old node.
  341. if (InverseMap) (*InverseMap)[NewN] = N;
  342. // If this node is a root, designate it as such in the graph.
  343. if (N->Preds.empty())
  344. G->addRoot(NewN);
  345. // In the case that some of the intended predecessors of NewN have already
  346. // been created, we should hook them up as predecessors.
  347. // Walk through the predecessors of 'N' and hook up their corresponding
  348. // nodes in the new graph (if any) to the freshly created node.
  349. for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
  350. I != E; ++I) {
  351. Pass2Ty::iterator PI = Pass2.find(*I);
  352. if (PI == Pass2.end())
  353. continue;
  354. NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
  355. }
  356. // In the case that some of the intended successors of NewN have already
  357. // been created, we should hook them up as successors. Otherwise, enqueue
  358. // the new nodes from the original graph that should have nodes created
  359. // in the new graph.
  360. for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
  361. I != E; ++I) {
  362. Pass2Ty::iterator PI = Pass2.find(*I);
  363. if (PI != Pass2.end()) {
  364. const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
  365. continue;
  366. }
  367. // Enqueue nodes to the worklist that were marked during pass 1.
  368. if (Pass1.count(*I))
  369. WL2.push_back(*I);
  370. }
  371. }
  372. return G;
  373. }