CheckerManager.h revision c41f3652f4e836cff988320bad2d6c5f416ebe1f
1//===--- CheckerManager.h - Static Analyzer Checker Manager -----*- 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// Defines the Static Analyzer Checker Manager.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SA_CORE_CHECKERMANAGER_H
15#define LLVM_CLANG_SA_CORE_CHECKERMANAGER_H
16
17#include "clang/Basic/LangOptions.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/FoldingSet.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
22#include <vector>
23
24namespace clang {
25  class Decl;
26  class Stmt;
27  class CallExpr;
28
29namespace ento {
30  class CheckerBase;
31  class ExprEngine;
32  class AnalysisManager;
33  class BugReporter;
34  class CheckerContext;
35  class ObjCMessage;
36  class SVal;
37  class ExplodedNode;
38  class ExplodedNodeSet;
39  class ExplodedGraph;
40  class ProgramState;
41  class EndOfFunctionNodeBuilder;
42  class BranchNodeBuilder;
43  class MemRegion;
44  class SymbolReaper;
45
46class GraphExpander {
47public:
48  virtual ~GraphExpander();
49  virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) = 0;
50};
51
52template <typename T> class CheckerFn;
53
54template <typename RET, typename P1, typename P2, typename P3, typename P4>
55class CheckerFn<RET(P1, P2, P3, P4)> {
56  typedef RET (*Func)(void *, P1, P2, P3, P4);
57  Func Fn;
58public:
59  CheckerBase *Checker;
60  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
61  RET operator()(P1 p1, P2 p2, P3 p3, P4 p4) const {
62    return Fn(Checker, p1, p2, p3, p4);
63  }
64};
65
66template <typename RET, typename P1, typename P2, typename P3>
67class CheckerFn<RET(P1, P2, P3)> {
68  typedef RET (*Func)(void *, P1, P2, P3);
69  Func Fn;
70public:
71  CheckerBase *Checker;
72  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
73  RET operator()(P1 p1, P2 p2, P3 p3) const { return Fn(Checker, p1, p2, p3); }
74};
75
76template <typename RET, typename P1, typename P2>
77class CheckerFn<RET(P1, P2)> {
78  typedef RET (*Func)(void *, P1, P2);
79  Func Fn;
80public:
81  CheckerBase *Checker;
82  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
83  RET operator()(P1 p1, P2 p2) const { return Fn(Checker, p1, p2); }
84};
85
86template <typename RET, typename P1>
87class CheckerFn<RET(P1)> {
88  typedef RET (*Func)(void *, P1);
89  Func Fn;
90public:
91  CheckerBase *Checker;
92  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
93  RET operator()(P1 p1) const { return Fn(Checker, p1); }
94};
95
96template <typename RET>
97class CheckerFn<RET()> {
98  typedef RET (*Func)(void *);
99  Func Fn;
100public:
101  CheckerBase *Checker;
102  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
103  RET operator()() const { return Fn(Checker); }
104};
105
106class CheckerManager {
107  const LangOptions LangOpts;
108
109public:
110  CheckerManager(const LangOptions &langOpts) : LangOpts(langOpts) { }
111  ~CheckerManager();
112
113  bool hasPathSensitiveCheckers() const;
114
115  void finishedCheckerRegistration();
116
117  const LangOptions &getLangOptions() const { return LangOpts; }
118
119  typedef CheckerBase *CheckerRef;
120  typedef const void *CheckerTag;
121  typedef CheckerFn<void ()> CheckerDtor;
122
123//===----------------------------------------------------------------------===//
124// registerChecker
125//===----------------------------------------------------------------------===//
126
127  /// \brief Used to register checkers.
128  ///
129  /// \returns a pointer to the checker object.
130  template <typename CHECKER>
131  CHECKER *registerChecker() {
132    CheckerTag tag = getTag<CHECKER>();
133    CheckerRef &ref = CheckerTags[tag];
134    if (ref)
135      return static_cast<CHECKER *>(ref); // already registered.
136
137    CHECKER *checker = new CHECKER();
138    CheckerDtors.push_back(CheckerDtor(checker, destruct<CHECKER>));
139    CHECKER::_register(checker, *this);
140    ref = checker;
141    return checker;
142  }
143
144//===----------------------------------------------------------------------===//
145// Functions for running checkers for AST traversing..
146//===----------------------------------------------------------------------===//
147
148  /// \brief Run checkers handling Decls.
149  void runCheckersOnASTDecl(const Decl *D, AnalysisManager& mgr,
150                            BugReporter &BR);
151
152  /// \brief Run checkers handling Decls containing a Stmt body.
153  void runCheckersOnASTBody(const Decl *D, AnalysisManager& mgr,
154                            BugReporter &BR);
155
156//===----------------------------------------------------------------------===//
157// Functions for running checkers for path-sensitive checking.
158//===----------------------------------------------------------------------===//
159
160  /// \brief Run checkers for pre-visiting Stmts.
161  ///
162  /// The notification is performed for every explored CFGElement, which does
163  /// not include the control flow statements such as IfStmt.
164  ///
165  /// \sa runCheckersForBranchCondition, runCheckersForPostStmt
166  void runCheckersForPreStmt(ExplodedNodeSet &Dst,
167                             const ExplodedNodeSet &Src,
168                             const Stmt *S,
169                             ExprEngine &Eng) {
170    runCheckersForStmt(/*isPreVisit=*/true, Dst, Src, S, Eng);
171  }
172
173  /// \brief Run checkers for post-visiting Stmts.
174  ///
175  /// The notification is performed for every explored CFGElement, which does
176  /// not include the control flow statements such as IfStmt.
177  ///
178  /// \sa runCheckersForBranchCondition, runCheckersForPreStmt
179  void runCheckersForPostStmt(ExplodedNodeSet &Dst,
180                              const ExplodedNodeSet &Src,
181                              const Stmt *S,
182                              ExprEngine &Eng) {
183    runCheckersForStmt(/*isPreVisit=*/false, Dst, Src, S, Eng);
184  }
185
186  /// \brief Run checkers for visiting Stmts.
187  void runCheckersForStmt(bool isPreVisit,
188                          ExplodedNodeSet &Dst, const ExplodedNodeSet &Src,
189                          const Stmt *S, ExprEngine &Eng);
190
191  /// \brief Run checkers for pre-visiting obj-c messages.
192  void runCheckersForPreObjCMessage(ExplodedNodeSet &Dst,
193                                    const ExplodedNodeSet &Src,
194                                    const ObjCMessage &msg,
195                                    ExprEngine &Eng) {
196    runCheckersForObjCMessage(/*isPreVisit=*/true, Dst, Src, msg, Eng);
197  }
198
199  /// \brief Run checkers for post-visiting obj-c messages.
200  void runCheckersForPostObjCMessage(ExplodedNodeSet &Dst,
201                                     const ExplodedNodeSet &Src,
202                                     const ObjCMessage &msg,
203                                     ExprEngine &Eng) {
204    runCheckersForObjCMessage(/*isPreVisit=*/false, Dst, Src, msg, Eng);
205  }
206
207  /// \brief Run checkers for visiting obj-c messages.
208  void runCheckersForObjCMessage(bool isPreVisit,
209                                 ExplodedNodeSet &Dst,
210                                 const ExplodedNodeSet &Src,
211                                 const ObjCMessage &msg, ExprEngine &Eng);
212
213  /// \brief Run checkers for load/store of a location.
214  void runCheckersForLocation(ExplodedNodeSet &Dst,
215                              const ExplodedNodeSet &Src,
216                              SVal location, bool isLoad,
217                              const Stmt *S,
218                              ExprEngine &Eng);
219
220  /// \brief Run checkers for binding of a value to a location.
221  void runCheckersForBind(ExplodedNodeSet &Dst,
222                          const ExplodedNodeSet &Src,
223                          SVal location, SVal val,
224                          const Stmt *S, ExprEngine &Eng);
225
226  /// \brief Run checkers for end of analysis.
227  void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR,
228                                 ExprEngine &Eng);
229
230  /// \brief Run checkers for end of path.
231  void runCheckersForEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng);
232
233  /// \brief Run checkers for branch condition.
234  void runCheckersForBranchCondition(const Stmt *condition,
235                                     BranchNodeBuilder &B, ExprEngine &Eng);
236
237  /// \brief Run checkers for live symbols.
238  ///
239  /// Allows modifying SymbolReaper object. For example, checkers can explicitly
240  /// register symbols of interest as live. These symbols will not be marked
241  /// dead and removed.
242  void runCheckersForLiveSymbols(const ProgramState *state,
243                                 SymbolReaper &SymReaper);
244
245  /// \brief Run checkers for dead symbols.
246  ///
247  /// Notifies checkers when symbols become dead. For example, this allows
248  /// checkers to aggressively clean up/reduce the checker state and produce
249  /// precise diagnostics.
250  void runCheckersForDeadSymbols(ExplodedNodeSet &Dst,
251                                 const ExplodedNodeSet &Src,
252                                 SymbolReaper &SymReaper, const Stmt *S,
253                                 ExprEngine &Eng);
254
255  /// \brief True if at least one checker wants to check region changes.
256  bool wantsRegionChangeUpdate(const ProgramState *state);
257
258  /// \brief Run checkers for region changes.
259  ///
260  /// This corresponds to the check::RegionChanges callback.
261  /// \param state The current program state.
262  /// \param invalidated A set of all symbols potentially touched by the change.
263  /// \param ExplicitRegions The regions explicitly requested for invalidation.
264  ///   For example, in the case of a function call, these would be arguments.
265  /// \param Regions The transitive closure of accessible regions,
266  ///   i.e. all regions that may have been touched by this change.
267  const ProgramState *
268  runCheckersForRegionChanges(const ProgramState *state,
269                            const StoreManager::InvalidatedSymbols *invalidated,
270                              ArrayRef<const MemRegion *> ExplicitRegions,
271                              ArrayRef<const MemRegion *> Regions);
272
273  /// \brief Run checkers for handling assumptions on symbolic values.
274  const ProgramState *runCheckersForEvalAssume(const ProgramState *state,
275                                          SVal Cond, bool Assumption);
276
277  /// \brief Run checkers for evaluating a call.
278  void runCheckersForEvalCall(ExplodedNodeSet &Dst,
279                              const ExplodedNodeSet &Src,
280                              const CallExpr *CE, ExprEngine &Eng,
281                              GraphExpander *defaultEval = 0);
282
283  /// \brief Run checkers for the entire Translation Unit.
284  void runCheckersOnEndOfTranslationUnit(const TranslationUnitDecl *TU,
285                                         AnalysisManager &mgr,
286                                         BugReporter &BR);
287
288  /// \brief Run checkers for debug-printing a ProgramState.
289  ///
290  /// Unlike most other callbacks, any checker can simply implement the virtual
291  /// method CheckerBase::printState if it has custom data to print.
292  /// \param Out The output stream
293  /// \param State The state being printed
294  /// \param NL The preferred representation of a newline.
295  /// \param Sep The preferred separator between different kinds of data.
296  void runCheckersForPrintState(raw_ostream &Out, const ProgramState *State,
297                                const char *NL, const char *Sep);
298
299//===----------------------------------------------------------------------===//
300// Internal registration functions for AST traversing.
301//===----------------------------------------------------------------------===//
302
303  // Functions used by the registration mechanism, checkers should not touch
304  // these directly.
305
306  typedef CheckerFn<void (const Decl *, AnalysisManager&, BugReporter &)>
307      CheckDeclFunc;
308
309  typedef bool (*HandlesDeclFunc)(const Decl *D);
310  void _registerForDecl(CheckDeclFunc checkfn, HandlesDeclFunc isForDeclFn);
311
312  void _registerForBody(CheckDeclFunc checkfn);
313
314//===----------------------------------------------------------------------===//
315// Internal registration functions for path-sensitive checking.
316//===----------------------------------------------------------------------===//
317
318  typedef CheckerFn<void (const Stmt *, CheckerContext &)> CheckStmtFunc;
319
320  typedef CheckerFn<void (const ObjCMessage &, CheckerContext &)>
321      CheckObjCMessageFunc;
322
323  typedef CheckerFn<void (const SVal &location, bool isLoad, CheckerContext &)>
324      CheckLocationFunc;
325
326  typedef CheckerFn<void (const SVal &location, const SVal &val,
327                          CheckerContext &)> CheckBindFunc;
328
329  typedef CheckerFn<void (ExplodedGraph &, BugReporter &, ExprEngine &)>
330      CheckEndAnalysisFunc;
331
332  typedef CheckerFn<void (EndOfFunctionNodeBuilder &, ExprEngine &)>
333      CheckEndPathFunc;
334
335  typedef CheckerFn<void (const Stmt *, BranchNodeBuilder &, ExprEngine &)>
336      CheckBranchConditionFunc;
337
338  typedef CheckerFn<void (SymbolReaper &, CheckerContext &)>
339      CheckDeadSymbolsFunc;
340
341  typedef CheckerFn<void (const ProgramState *,SymbolReaper &)> CheckLiveSymbolsFunc;
342
343  typedef CheckerFn<const ProgramState * (const ProgramState *,
344                                const StoreManager::InvalidatedSymbols *symbols,
345                                    ArrayRef<const MemRegion *> ExplicitRegions,
346                                          ArrayRef<const MemRegion *> Regions)>
347      CheckRegionChangesFunc;
348
349  typedef CheckerFn<bool (const ProgramState *)> WantsRegionChangeUpdateFunc;
350
351  typedef CheckerFn<const ProgramState * (const ProgramState *,
352                                          const SVal &cond, bool assumption)>
353      EvalAssumeFunc;
354
355  typedef CheckerFn<bool (const CallExpr *, CheckerContext &)>
356      EvalCallFunc;
357
358  typedef CheckerFn<void (const TranslationUnitDecl *,
359                          AnalysisManager&, BugReporter &)>
360      CheckEndOfTranslationUnit;
361
362  typedef bool (*HandlesStmtFunc)(const Stmt *D);
363  void _registerForPreStmt(CheckStmtFunc checkfn,
364                           HandlesStmtFunc isForStmtFn);
365  void _registerForPostStmt(CheckStmtFunc checkfn,
366                            HandlesStmtFunc isForStmtFn);
367
368  void _registerForPreObjCMessage(CheckObjCMessageFunc checkfn);
369  void _registerForPostObjCMessage(CheckObjCMessageFunc checkfn);
370
371  void _registerForLocation(CheckLocationFunc checkfn);
372
373  void _registerForBind(CheckBindFunc checkfn);
374
375  void _registerForEndAnalysis(CheckEndAnalysisFunc checkfn);
376
377  void _registerForEndPath(CheckEndPathFunc checkfn);
378
379  void _registerForBranchCondition(CheckBranchConditionFunc checkfn);
380
381  void _registerForLiveSymbols(CheckLiveSymbolsFunc checkfn);
382
383  void _registerForDeadSymbols(CheckDeadSymbolsFunc checkfn);
384
385  void _registerForRegionChanges(CheckRegionChangesFunc checkfn,
386                                 WantsRegionChangeUpdateFunc wantUpdateFn);
387
388  void _registerForEvalAssume(EvalAssumeFunc checkfn);
389
390  void _registerForEvalCall(EvalCallFunc checkfn);
391
392  void _registerForEndOfTranslationUnit(CheckEndOfTranslationUnit checkfn);
393
394//===----------------------------------------------------------------------===//
395// Internal registration functions for events.
396//===----------------------------------------------------------------------===//
397
398  typedef void *EventTag;
399  typedef CheckerFn<void (const void *event)> CheckEventFunc;
400
401  template <typename EVENT>
402  void _registerListenerForEvent(CheckEventFunc checkfn) {
403    EventInfo &info = Events[getTag<EVENT>()];
404    info.Checkers.push_back(checkfn);
405  }
406
407  template <typename EVENT>
408  void _registerDispatcherForEvent() {
409    EventInfo &info = Events[getTag<EVENT>()];
410    info.HasDispatcher = true;
411  }
412
413  template <typename EVENT>
414  void _dispatchEvent(const EVENT &event) const {
415    EventsTy::const_iterator I = Events.find(getTag<EVENT>());
416    if (I == Events.end())
417      return;
418    const EventInfo &info = I->second;
419    for (unsigned i = 0, e = info.Checkers.size(); i != e; ++i)
420      info.Checkers[i](&event);
421  }
422
423//===----------------------------------------------------------------------===//
424// Implementation details.
425//===----------------------------------------------------------------------===//
426
427private:
428  template <typename CHECKER>
429  static void destruct(void *obj) { delete static_cast<CHECKER *>(obj); }
430
431  template <typename T>
432  static void *getTag() { static int tag; return &tag; }
433
434  llvm::DenseMap<CheckerTag, CheckerRef> CheckerTags;
435
436  std::vector<CheckerDtor> CheckerDtors;
437
438  struct DeclCheckerInfo {
439    CheckDeclFunc CheckFn;
440    HandlesDeclFunc IsForDeclFn;
441  };
442  std::vector<DeclCheckerInfo> DeclCheckers;
443
444  std::vector<CheckDeclFunc> BodyCheckers;
445
446  typedef SmallVector<CheckDeclFunc, 4> CachedDeclCheckers;
447  typedef llvm::DenseMap<unsigned, CachedDeclCheckers> CachedDeclCheckersMapTy;
448  CachedDeclCheckersMapTy CachedDeclCheckersMap;
449
450  struct StmtCheckerInfo {
451    CheckStmtFunc CheckFn;
452    HandlesStmtFunc IsForStmtFn;
453    bool IsPreVisit;
454  };
455  std::vector<StmtCheckerInfo> StmtCheckers;
456
457  struct CachedStmtCheckersKey {
458    unsigned StmtKind;
459    bool IsPreVisit;
460
461    CachedStmtCheckersKey() : StmtKind(0), IsPreVisit(0) { }
462    CachedStmtCheckersKey(unsigned stmtKind, bool isPreVisit)
463      : StmtKind(stmtKind), IsPreVisit(isPreVisit) { }
464
465    static CachedStmtCheckersKey getSentinel() {
466      return CachedStmtCheckersKey(~0U, 0);
467    }
468    unsigned getHashValue() const {
469      llvm::FoldingSetNodeID ID;
470      ID.AddInteger(StmtKind);
471      ID.AddBoolean(IsPreVisit);
472      return ID.ComputeHash();
473    }
474    bool operator==(const CachedStmtCheckersKey &RHS) const {
475      return StmtKind == RHS.StmtKind && IsPreVisit == RHS.IsPreVisit;
476    }
477  };
478  friend struct llvm::DenseMapInfo<CachedStmtCheckersKey>;
479
480  typedef SmallVector<CheckStmtFunc, 4> CachedStmtCheckers;
481  typedef llvm::DenseMap<CachedStmtCheckersKey, CachedStmtCheckers>
482      CachedStmtCheckersMapTy;
483  CachedStmtCheckersMapTy CachedStmtCheckersMap;
484
485  CachedStmtCheckers *getCachedStmtCheckersFor(const Stmt *S, bool isPreVisit);
486
487  std::vector<CheckObjCMessageFunc> PreObjCMessageCheckers;
488  std::vector<CheckObjCMessageFunc> PostObjCMessageCheckers;
489
490  std::vector<CheckLocationFunc> LocationCheckers;
491
492  std::vector<CheckBindFunc> BindCheckers;
493
494  std::vector<CheckEndAnalysisFunc> EndAnalysisCheckers;
495
496  std::vector<CheckEndPathFunc> EndPathCheckers;
497
498  std::vector<CheckBranchConditionFunc> BranchConditionCheckers;
499
500  std::vector<CheckLiveSymbolsFunc> LiveSymbolsCheckers;
501
502  std::vector<CheckDeadSymbolsFunc> DeadSymbolsCheckers;
503
504  struct RegionChangesCheckerInfo {
505    CheckRegionChangesFunc CheckFn;
506    WantsRegionChangeUpdateFunc WantUpdateFn;
507  };
508  std::vector<RegionChangesCheckerInfo> RegionChangesCheckers;
509
510  std::vector<EvalAssumeFunc> EvalAssumeCheckers;
511
512  std::vector<EvalCallFunc> EvalCallCheckers;
513
514  std::vector<CheckEndOfTranslationUnit> EndOfTranslationUnitCheckers;
515
516  struct EventInfo {
517    SmallVector<CheckEventFunc, 4> Checkers;
518    bool HasDispatcher;
519    EventInfo() : HasDispatcher(false) { }
520  };
521
522  typedef llvm::DenseMap<EventTag, EventInfo> EventsTy;
523  EventsTy Events;
524};
525
526} // end ento namespace
527
528} // end clang namespace
529
530namespace llvm {
531  /// Define DenseMapInfo so that CachedStmtCheckersKey can be used as key
532  /// in DenseMap and DenseSets.
533  template <>
534  struct DenseMapInfo<clang::ento::CheckerManager::CachedStmtCheckersKey> {
535    static inline clang::ento::CheckerManager::CachedStmtCheckersKey
536        getEmptyKey() {
537      return clang::ento::CheckerManager::CachedStmtCheckersKey();
538    }
539    static inline clang::ento::CheckerManager::CachedStmtCheckersKey
540        getTombstoneKey() {
541      return clang::ento::CheckerManager::CachedStmtCheckersKey::getSentinel();
542    }
543
544    static unsigned
545        getHashValue(clang::ento::CheckerManager::CachedStmtCheckersKey S) {
546      return S.getHashValue();
547    }
548
549    static bool isEqual(clang::ento::CheckerManager::CachedStmtCheckersKey LHS,
550                       clang::ento::CheckerManager::CachedStmtCheckersKey RHS) {
551      return LHS == RHS;
552    }
553  };
554} // end namespace llvm
555
556#endif
557