ExplodedGraph.h revision 6800ba622e4edf287801ac69c42c61e7e294b06b
1//=-- ExplodedGraph.h - 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//  See "Precise interprocedural dataflow analysis via graph reachability"
13//  by Reps, Horwitz, and Sagiv
14//  (http://portal.acm.org/citation.cfm?id=199462) for the definition of an
15//  exploded graph.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_CLANG_GR_EXPLODEDGRAPH
20#define LLVM_CLANG_GR_EXPLODEDGRAPH
21
22#include "clang/Analysis/ProgramPoint.h"
23#include "clang/Analysis/AnalysisContext.h"
24#include "clang/AST/Decl.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/Support/Allocator.h"
29#include "llvm/ADT/OwningPtr.h"
30#include "llvm/ADT/GraphTraits.h"
31#include "llvm/ADT/DepthFirstIterator.h"
32#include "llvm/Support/Casting.h"
33#include "clang/Analysis/Support/BumpVector.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
35
36namespace clang {
37
38class CFG;
39
40namespace ento {
41
42class ExplodedGraph;
43
44//===----------------------------------------------------------------------===//
45// ExplodedGraph "implementation" classes.  These classes are not typed to
46// contain a specific kind of state.  Typed-specialized versions are defined
47// on top of these classes.
48//===----------------------------------------------------------------------===//
49
50// ExplodedNode is not constified all over the engine because we need to add
51// successors to it at any time after creating it.
52
53class ExplodedNode : public llvm::FoldingSetNode {
54  friend class ExplodedGraph;
55  friend class CoreEngine;
56  friend class NodeBuilder;
57  friend class BranchNodeBuilder;
58  friend class IndirectGotoNodeBuilder;
59  friend class SwitchNodeBuilder;
60  friend class EndOfFunctionNodeBuilder;
61
62  class NodeGroup {
63    enum { Size1 = 0x0, SizeOther = 0x1, AuxFlag = 0x2, Mask = 0x3 };
64    uintptr_t P;
65
66    unsigned getKind() const {
67      return P & 0x1;
68    }
69
70    void *getPtr() const {
71      assert (!getFlag());
72      return reinterpret_cast<void*>(P & ~Mask);
73    }
74
75    ExplodedNode *getNode() const {
76      return reinterpret_cast<ExplodedNode*>(getPtr());
77    }
78
79  public:
80    NodeGroup() : P(0) {}
81
82    ExplodedNode **begin() const;
83
84    ExplodedNode **end() const;
85
86    unsigned size() const;
87
88    bool empty() const { return (P & ~Mask) == 0; }
89
90    void addNode(ExplodedNode *N, ExplodedGraph &G);
91
92    void replaceNode(ExplodedNode *node);
93
94    void setFlag() {
95      assert(P == 0);
96      P = AuxFlag;
97    }
98
99    bool getFlag() const {
100      return P & AuxFlag ? true : false;
101    }
102  };
103
104  /// Location - The program location (within a function body) associated
105  ///  with this node.
106  const ProgramPoint Location;
107
108  /// State - The state associated with this node.
109  const ProgramState *State;
110
111  /// Preds - The predecessors of this node.
112  NodeGroup Preds;
113
114  /// Succs - The successors of this node.
115  NodeGroup Succs;
116
117public:
118
119  explicit ExplodedNode(const ProgramPoint &loc, const ProgramState *state,
120                        bool IsSink)
121    : Location(loc), State(state) {
122    const_cast<ProgramState*>(State)->incrementReferenceCount();
123    if (IsSink)
124      Succs.setFlag();
125  }
126
127  ~ExplodedNode() {
128    const_cast<ProgramState*>(State)->decrementReferenceCount();
129  }
130
131  /// getLocation - Returns the edge associated with the given node.
132  ProgramPoint getLocation() const { return Location; }
133
134  const LocationContext *getLocationContext() const {
135    return getLocation().getLocationContext();
136  }
137
138  const Decl &getCodeDecl() const { return *getLocationContext()->getDecl(); }
139
140  CFG &getCFG() const { return *getLocationContext()->getCFG(); }
141
142  ParentMap &getParentMap() const {return getLocationContext()->getParentMap();}
143
144  template <typename T>
145  T &getAnalysis() const {
146    return *getLocationContext()->getAnalysis<T>();
147  }
148
149  const ProgramState *getState() const { return State; }
150
151  template <typename T>
152  const T* getLocationAs() const { return llvm::dyn_cast<T>(&Location); }
153
154  static void Profile(llvm::FoldingSetNodeID &ID,
155                      const ProgramPoint &Loc,
156                      const ProgramState *state,
157                      bool IsSink) {
158    ID.Add(Loc);
159    ID.AddPointer(state);
160    ID.AddBoolean(IsSink);
161  }
162
163  void Profile(llvm::FoldingSetNodeID& ID) const {
164    Profile(ID, getLocation(), getState(), isSink());
165  }
166
167  /// addPredeccessor - Adds a predecessor to the current node, and
168  ///  in tandem add this node as a successor of the other node.
169  void addPredecessor(ExplodedNode *V, ExplodedGraph &G);
170
171  unsigned succ_size() const { return Succs.size(); }
172  unsigned pred_size() const { return Preds.size(); }
173  bool succ_empty() const { return Succs.empty(); }
174  bool pred_empty() const { return Preds.empty(); }
175
176  bool isSink() const { return Succs.getFlag(); }
177
178  ExplodedNode *getFirstPred() {
179    return pred_empty() ? NULL : *(pred_begin());
180  }
181
182  const ExplodedNode *getFirstPred() const {
183    return const_cast<ExplodedNode*>(this)->getFirstPred();
184  }
185
186  // Iterators over successor and predecessor vertices.
187  typedef ExplodedNode**       succ_iterator;
188  typedef const ExplodedNode* const * const_succ_iterator;
189  typedef ExplodedNode**       pred_iterator;
190  typedef const ExplodedNode* const * const_pred_iterator;
191
192  pred_iterator pred_begin() { return Preds.begin(); }
193  pred_iterator pred_end() { return Preds.end(); }
194
195  const_pred_iterator pred_begin() const {
196    return const_cast<ExplodedNode*>(this)->pred_begin();
197  }
198  const_pred_iterator pred_end() const {
199    return const_cast<ExplodedNode*>(this)->pred_end();
200  }
201
202  succ_iterator succ_begin() { return Succs.begin(); }
203  succ_iterator succ_end() { return Succs.end(); }
204
205  const_succ_iterator succ_begin() const {
206    return const_cast<ExplodedNode*>(this)->succ_begin();
207  }
208  const_succ_iterator succ_end() const {
209    return const_cast<ExplodedNode*>(this)->succ_end();
210  }
211
212  // For debugging.
213
214public:
215
216  class Auditor {
217  public:
218    virtual ~Auditor();
219    virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) = 0;
220  };
221
222  static void SetAuditor(Auditor* A);
223
224private:
225  void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); }
226  void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); }
227};
228
229// FIXME: Is this class necessary?
230class InterExplodedGraphMap {
231  llvm::DenseMap<const ExplodedNode*, ExplodedNode*> M;
232  friend class ExplodedGraph;
233
234public:
235  ExplodedNode *getMappedNode(const ExplodedNode *N) const;
236
237  InterExplodedGraphMap() {}
238  virtual ~InterExplodedGraphMap() {}
239};
240
241class ExplodedGraph {
242protected:
243  friend class CoreEngine;
244
245  // Type definitions.
246  typedef SmallVector<ExplodedNode*,2>    RootsTy;
247  typedef SmallVector<ExplodedNode*,10>   EndNodesTy;
248
249  /// Roots - The roots of the simulation graph. Usually there will be only
250  /// one, but clients are free to establish multiple subgraphs within a single
251  /// SimulGraph. Moreover, these subgraphs can often merge when paths from
252  /// different roots reach the same state at the same program location.
253  RootsTy Roots;
254
255  /// EndNodes - The nodes in the simulation graph which have been
256  ///  specially marked as the endpoint of an abstract simulation path.
257  EndNodesTy EndNodes;
258
259  /// Nodes - The nodes in the graph.
260  llvm::FoldingSet<ExplodedNode> Nodes;
261
262  /// BVC - Allocator and context for allocating nodes and their predecessor
263  /// and successor groups.
264  BumpVectorContext BVC;
265
266  /// NumNodes - The number of nodes in the graph.
267  unsigned NumNodes;
268
269  /// A list of recently allocated nodes that can potentially be recycled.
270  void *recentlyAllocatedNodes;
271
272  /// A list of nodes that can be reused.
273  void *freeNodes;
274
275  /// A flag that indicates whether nodes should be recycled.
276  bool reclaimNodes;
277
278public:
279
280  /// \brief Retrieve the node associated with a (Location,State) pair,
281  ///  where the 'Location' is a ProgramPoint in the CFG.  If no node for
282  ///  this pair exists, it is created. IsNew is set to true if
283  ///  the node was freshly created.
284  ExplodedNode *getNode(const ProgramPoint &L, const ProgramState *State,
285                        bool IsSink = false,
286                        bool* IsNew = 0);
287
288  ExplodedGraph* MakeEmptyGraph() const {
289    return new ExplodedGraph();
290  }
291
292  /// addRoot - Add an untyped node to the set of roots.
293  ExplodedNode *addRoot(ExplodedNode *V) {
294    Roots.push_back(V);
295    return V;
296  }
297
298  /// addEndOfPath - Add an untyped node to the set of EOP nodes.
299  ExplodedNode *addEndOfPath(ExplodedNode *V) {
300    EndNodes.push_back(V);
301    return V;
302  }
303
304  ExplodedGraph()
305    : NumNodes(0), recentlyAllocatedNodes(0),
306      freeNodes(0), reclaimNodes(false) {}
307
308  ~ExplodedGraph();
309
310  unsigned num_roots() const { return Roots.size(); }
311  unsigned num_eops() const { return EndNodes.size(); }
312
313  bool empty() const { return NumNodes == 0; }
314  unsigned size() const { return NumNodes; }
315
316  // Iterators.
317  typedef ExplodedNode                        NodeTy;
318  typedef llvm::FoldingSet<ExplodedNode>      AllNodesTy;
319  typedef NodeTy**                            roots_iterator;
320  typedef NodeTy* const *                     const_roots_iterator;
321  typedef NodeTy**                            eop_iterator;
322  typedef NodeTy* const *                     const_eop_iterator;
323  typedef AllNodesTy::iterator                node_iterator;
324  typedef AllNodesTy::const_iterator          const_node_iterator;
325
326  node_iterator nodes_begin() { return Nodes.begin(); }
327
328  node_iterator nodes_end() { return Nodes.end(); }
329
330  const_node_iterator nodes_begin() const { return Nodes.begin(); }
331
332  const_node_iterator nodes_end() const { return Nodes.end(); }
333
334  roots_iterator roots_begin() { return Roots.begin(); }
335
336  roots_iterator roots_end() { return Roots.end(); }
337
338  const_roots_iterator roots_begin() const { return Roots.begin(); }
339
340  const_roots_iterator roots_end() const { return Roots.end(); }
341
342  eop_iterator eop_begin() { return EndNodes.begin(); }
343
344  eop_iterator eop_end() { return EndNodes.end(); }
345
346  const_eop_iterator eop_begin() const { return EndNodes.begin(); }
347
348  const_eop_iterator eop_end() const { return EndNodes.end(); }
349
350  llvm::BumpPtrAllocator & getAllocator() { return BVC.getAllocator(); }
351  BumpVectorContext &getNodeAllocator() { return BVC; }
352
353  typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> NodeMap;
354
355  std::pair<ExplodedGraph*, InterExplodedGraphMap*>
356  Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd,
357       llvm::DenseMap<const void*, const void*> *InverseMap = 0) const;
358
359  ExplodedGraph* TrimInternal(const ExplodedNode* const * NBeg,
360                              const ExplodedNode* const * NEnd,
361                              InterExplodedGraphMap *M,
362                    llvm::DenseMap<const void*, const void*> *InverseMap) const;
363
364  /// Enable tracking of recently allocated nodes for potential reclamation
365  /// when calling reclaimRecentlyAllocatedNodes().
366  void enableNodeReclamation() { reclaimNodes = true; }
367
368  /// Reclaim "uninteresting" nodes created since the last time this method
369  /// was called.
370  void reclaimRecentlyAllocatedNodes();
371};
372
373class ExplodedNodeSet {
374  typedef llvm::SmallPtrSet<ExplodedNode*,5> ImplTy;
375  ImplTy Impl;
376
377public:
378  ExplodedNodeSet(ExplodedNode *N) {
379    assert (N && !static_cast<ExplodedNode*>(N)->isSink());
380    Impl.insert(N);
381  }
382
383  ExplodedNodeSet() {}
384
385  inline void Add(ExplodedNode *N) {
386    if (N && !static_cast<ExplodedNode*>(N)->isSink()) Impl.insert(N);
387  }
388
389  typedef ImplTy::iterator       iterator;
390  typedef ImplTy::const_iterator const_iterator;
391
392  unsigned size() const { return Impl.size();  }
393  bool empty()    const { return Impl.empty(); }
394  bool erase(ExplodedNode *N) { return Impl.erase(N); }
395
396  void clear() { Impl.clear(); }
397  void insert(const ExplodedNodeSet &S) {
398    assert(&S != this);
399    if (empty())
400      Impl = S.Impl;
401    else
402      Impl.insert(S.begin(), S.end());
403  }
404
405  inline iterator begin() { return Impl.begin(); }
406  inline iterator end()   { return Impl.end();   }
407
408  inline const_iterator begin() const { return Impl.begin(); }
409  inline const_iterator end()   const { return Impl.end();   }
410};
411
412} // end GR namespace
413
414} // end clang namespace
415
416// GraphTraits
417
418namespace llvm {
419  template<> struct GraphTraits<clang::ento::ExplodedNode*> {
420    typedef clang::ento::ExplodedNode NodeType;
421    typedef NodeType::succ_iterator  ChildIteratorType;
422    typedef llvm::df_iterator<NodeType*>      nodes_iterator;
423
424    static inline NodeType* getEntryNode(NodeType* N) {
425      return N;
426    }
427
428    static inline ChildIteratorType child_begin(NodeType* N) {
429      return N->succ_begin();
430    }
431
432    static inline ChildIteratorType child_end(NodeType* N) {
433      return N->succ_end();
434    }
435
436    static inline nodes_iterator nodes_begin(NodeType* N) {
437      return df_begin(N);
438    }
439
440    static inline nodes_iterator nodes_end(NodeType* N) {
441      return df_end(N);
442    }
443  };
444
445  template<> struct GraphTraits<const clang::ento::ExplodedNode*> {
446    typedef const clang::ento::ExplodedNode NodeType;
447    typedef NodeType::const_succ_iterator   ChildIteratorType;
448    typedef llvm::df_iterator<NodeType*>       nodes_iterator;
449
450    static inline NodeType* getEntryNode(NodeType* N) {
451      return N;
452    }
453
454    static inline ChildIteratorType child_begin(NodeType* N) {
455      return N->succ_begin();
456    }
457
458    static inline ChildIteratorType child_end(NodeType* N) {
459      return N->succ_end();
460    }
461
462    static inline nodes_iterator nodes_begin(NodeType* N) {
463      return df_begin(N);
464    }
465
466    static inline nodes_iterator nodes_end(NodeType* N) {
467      return df_end(N);
468    }
469  };
470
471} // end llvm namespace
472
473#endif
474