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