AnalysisConsumer.cpp revision 17a38e2636a8b1ce473fc6504c4b16cb09db29f4
158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//
358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//                     The LLVM Compiler Infrastructure
458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//
558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source
658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)// License. See LICENSE.TXT for details.
758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//
858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//===----------------------------------------------------------------------===//
958537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//
1058537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)// "Meta" ASTConsumer for running different source analyses.
1158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//
1258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//===----------------------------------------------------------------------===//
1358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
1458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "AnalysisConsumer.h"
1558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/AST/ASTConsumer.h"
1658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/AST/Decl.h"
1758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/AST/DeclCXX.h"
1858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/AST/DeclObjC.h"
19f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/AST/ParentMap.h"
2058537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/Analysis/CFG.h"
2158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
2258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/CheckerManager.h"
2358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
2458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
2558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
2658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
2758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
2858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/TransferFuncs.h"
2958537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathDiagnosticClients.h"
3058537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
3158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/Basic/FileManager.h"
3258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/Basic/SourceManager.h"
3358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/Frontend/AnalyzerOptions.h"
3458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "clang/Lex/Preprocessor.h"
3558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "llvm/Support/raw_ostream.h"
3658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "llvm/Support/Path.h"
3758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "llvm/Support/Program.h"
3858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "llvm/ADT/OwningPtr.h"
3958537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
4058537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)using namespace clang;
4158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)using namespace ento;
4258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
4358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)static ExplodedNode::Auditor* CreateUbiViz();
4458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
4558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//===----------------------------------------------------------------------===//
4658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)// Special PathDiagnosticClients.
4758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//===----------------------------------------------------------------------===//
4858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
4958537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)static PathDiagnosticClient*
5058537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)createPlistHTMLDiagnosticClient(const std::string& prefix,
5158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)                                const Preprocessor &PP) {
5258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  PathDiagnosticClient *PD =
5358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)    createHTMLDiagnosticClient(llvm::sys::path::parent_path(prefix), PP);
5458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  return createPlistDiagnosticClient(prefix, PP, PD);
5558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)}
5658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
5758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//===----------------------------------------------------------------------===//
5858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)// AnalysisConsumer declaration.
5958537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)//===----------------------------------------------------------------------===//
6058537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
6158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)namespace {
6258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
6358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)class AnalysisConsumer : public ASTConsumer {
6458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)public:
6558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  ASTContext *Ctx;
6658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  const Preprocessor &PP;
6758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  const std::string OutDir;
68  AnalyzerOptions Opts;
69  ArrayRef<std::string> Plugins;
70
71  // PD is owned by AnalysisManager.
72  PathDiagnosticClient *PD;
73
74  StoreManagerCreator CreateStoreMgr;
75  ConstraintManagerCreator CreateConstraintMgr;
76
77  llvm::OwningPtr<CheckerManager> checkerMgr;
78  llvm::OwningPtr<AnalysisManager> Mgr;
79
80  AnalysisConsumer(const Preprocessor& pp,
81                   const std::string& outdir,
82                   const AnalyzerOptions& opts,
83                   ArrayRef<std::string> plugins)
84    : Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins), PD(0) {
85    DigestAnalyzerOptions();
86  }
87
88  void DigestAnalyzerOptions() {
89    // Create the PathDiagnosticClient.
90    if (!OutDir.empty()) {
91      switch (Opts.AnalysisDiagOpt) {
92      default:
93#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
94        case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
95#include "clang/Frontend/Analyses.def"
96      }
97    } else if (Opts.AnalysisDiagOpt == PD_TEXT) {
98      // Create the text client even without a specified output file since
99      // it just uses diagnostic notes.
100      PD = createTextPathDiagnosticClient("", PP);
101    }
102
103    // Create the analyzer component creators.
104    switch (Opts.AnalysisStoreOpt) {
105    default:
106      assert(0 && "Unknown store manager.");
107#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
108      case NAME##Model: CreateStoreMgr = CREATEFN; break;
109#include "clang/Frontend/Analyses.def"
110    }
111
112    switch (Opts.AnalysisConstraintsOpt) {
113    default:
114      assert(0 && "Unknown store manager.");
115#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
116      case NAME##Model: CreateConstraintMgr = CREATEFN; break;
117#include "clang/Frontend/Analyses.def"
118    }
119  }
120
121  void DisplayFunction(const Decl *D) {
122    if (!Opts.AnalyzerDisplayProgress)
123      return;
124
125    SourceManager &SM = Mgr->getASTContext().getSourceManager();
126    PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
127    if (Loc.isValid()) {
128      llvm::errs() << "ANALYZE: " << Loc.getFilename();
129
130      if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
131        const NamedDecl *ND = cast<NamedDecl>(D);
132        llvm::errs() << ' ' << ND << '\n';
133      }
134      else if (isa<BlockDecl>(D)) {
135        llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
136                     << Loc.getColumn() << '\n';
137      }
138      else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
139        Selector S = MD->getSelector();
140        llvm::errs() << ' ' << S.getAsString();
141      }
142    }
143  }
144
145  virtual void Initialize(ASTContext &Context) {
146    Ctx = &Context;
147    checkerMgr.reset(createCheckerManager(Opts, PP.getLangOptions(), Plugins,
148                                          PP.getDiagnostics()));
149    Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
150                                  PP.getLangOptions(), PD,
151                                  CreateStoreMgr, CreateConstraintMgr,
152                                  checkerMgr.get(),
153                                  /* Indexer */ 0,
154                                  Opts.MaxNodes, Opts.MaxLoop,
155                                  Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
156                                  Opts.PurgeDead, Opts.EagerlyAssume,
157                                  Opts.TrimGraph, Opts.InlineCall,
158                                  Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors,
159                                  Opts.CFGAddInitializers,
160                                  Opts.EagerlyTrimEGraph));
161  }
162
163  virtual void HandleTranslationUnit(ASTContext &C);
164  void HandleDeclContext(ASTContext &C, DeclContext *dc);
165  void HandleDeclContextDecl(ASTContext &C, Decl *D);
166
167  void HandleCode(Decl *D);
168};
169} // end anonymous namespace
170
171//===----------------------------------------------------------------------===//
172// AnalysisConsumer implementation.
173//===----------------------------------------------------------------------===//
174
175void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
176  for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
177       I != E; ++I) {
178    HandleDeclContextDecl(C, *I);
179  }
180}
181
182void AnalysisConsumer::HandleDeclContextDecl(ASTContext &C, Decl *D) {
183  { // Handle callbacks for arbitrary decls.
184    BugReporter BR(*Mgr);
185    checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
186  }
187
188  switch (D->getKind()) {
189    case Decl::Namespace: {
190      HandleDeclContext(C, cast<NamespaceDecl>(D));
191      break;
192    }
193    case Decl::CXXConstructor:
194    case Decl::CXXDestructor:
195    case Decl::CXXConversion:
196    case Decl::CXXMethod:
197    case Decl::Function: {
198      FunctionDecl *FD = cast<FunctionDecl>(D);
199      // We skip function template definitions, as their semantics is
200      // only determined when they are instantiated.
201      if (FD->isThisDeclarationADefinition() &&
202          !FD->isDependentContext()) {
203        if (!Opts.AnalyzeSpecificFunction.empty() &&
204            FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
205          break;
206        DisplayFunction(FD);
207        HandleCode(FD);
208      }
209      break;
210    }
211
212    case Decl::ObjCCategoryImpl:
213    case Decl::ObjCImplementation: {
214      ObjCImplDecl *ID = cast<ObjCImplDecl>(D);
215      HandleCode(ID);
216
217      for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(),
218           ME = ID->meth_end(); MI != ME; ++MI) {
219        BugReporter BR(*Mgr);
220        checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
221
222        if ((*MI)->isThisDeclarationADefinition()) {
223          if (!Opts.AnalyzeSpecificFunction.empty() &&
224              Opts.AnalyzeSpecificFunction !=
225                (*MI)->getSelector().getAsString())
226            break;
227          DisplayFunction(*MI);
228          HandleCode(*MI);
229        }
230      }
231      break;
232    }
233
234    default:
235      break;
236  }
237}
238
239void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
240  BugReporter BR(*Mgr);
241  TranslationUnitDecl *TU = C.getTranslationUnitDecl();
242  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
243  HandleDeclContext(C, TU);
244
245  // After all decls handled, run checkers on the entire TranslationUnit.
246  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
247
248  // Explicitly destroy the PathDiagnosticClient.  This will flush its output.
249  // FIXME: This should be replaced with something that doesn't rely on
250  // side-effects in PathDiagnosticClient's destructor. This is required when
251  // used with option -disable-free.
252  Mgr.reset(NULL);
253}
254
255static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
256  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
257    WL.push_back(BD);
258
259  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
260       I!=E; ++I)
261    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
262      FindBlocks(DC, WL);
263}
264
265static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
266                                   Decl *D);
267
268void AnalysisConsumer::HandleCode(Decl *D) {
269
270  // Don't run the actions if an error has occurred with parsing the file.
271  Diagnostic &Diags = PP.getDiagnostics();
272  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
273    return;
274
275  // Don't run the actions on declarations in header files unless
276  // otherwise specified.
277  SourceManager &SM = Ctx->getSourceManager();
278  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
279  if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
280    return;
281
282  // Clear the AnalysisManager of old AnalysisContexts.
283  Mgr->ClearContexts();
284
285  // Dispatch on the actions.
286  SmallVector<Decl*, 10> WL;
287  WL.push_back(D);
288
289  if (D->hasBody() && Opts.AnalyzeNestedBlocks)
290    FindBlocks(cast<DeclContext>(D), WL);
291
292  BugReporter BR(*Mgr);
293  for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
294       WI != WE; ++WI)
295    if ((*WI)->hasBody()) {
296      checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
297      if (checkerMgr->hasPathSensitiveCheckers())
298        RunPathSensitiveChecks(*this, *Mgr, *WI);
299    }
300}
301
302//===----------------------------------------------------------------------===//
303// Path-sensitive checking.
304//===----------------------------------------------------------------------===//
305
306static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager &mgr,
307                             Decl *D, bool ObjCGCEnabled) {
308  // Construct the analysis engine.  We first query for the LiveVariables
309  // information to see if the CFG is valid.
310  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
311  if (!mgr.getLiveVariables(D))
312    return;
313  ExprEngine Eng(mgr, ObjCGCEnabled);
314
315  // Set the graph auditor.
316  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
317  if (mgr.shouldVisualizeUbigraph()) {
318    Auditor.reset(CreateUbiViz());
319    ExplodedNode::SetAuditor(Auditor.get());
320  }
321
322  // Execute the worklist algorithm.
323  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
324
325  // Release the auditor (if any) so that it doesn't monitor the graph
326  // created BugReporter.
327  ExplodedNode::SetAuditor(0);
328
329  // Visualize the exploded graph.
330  if (mgr.shouldVisualizeGraphviz())
331    Eng.ViewGraph(mgr.shouldTrimGraph());
332
333  // Display warnings.
334  Eng.getBugReporter().FlushReports();
335}
336
337static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
338                                   Decl *D) {
339
340  switch (mgr.getLangOptions().getGCMode()) {
341  default:
342    llvm_unreachable("Invalid GC mode.");
343  case LangOptions::NonGC:
344    ActionExprEngine(C, mgr, D, false);
345    break;
346
347  case LangOptions::GCOnly:
348    ActionExprEngine(C, mgr, D, true);
349    break;
350
351  case LangOptions::HybridGC:
352    ActionExprEngine(C, mgr, D, false);
353    ActionExprEngine(C, mgr, D, true);
354    break;
355  }
356}
357
358//===----------------------------------------------------------------------===//
359// AnalysisConsumer creation.
360//===----------------------------------------------------------------------===//
361
362ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
363                                          const std::string& outDir,
364                                          const AnalyzerOptions& opts,
365                                          ArrayRef<std::string> plugins) {
366  // Disable the effects of '-Werror' when using the AnalysisConsumer.
367  pp.getDiagnostics().setWarningsAsErrors(false);
368
369  return new AnalysisConsumer(pp, outDir, opts, plugins);
370}
371
372//===----------------------------------------------------------------------===//
373// Ubigraph Visualization.  FIXME: Move to separate file.
374//===----------------------------------------------------------------------===//
375
376namespace {
377
378class UbigraphViz : public ExplodedNode::Auditor {
379  llvm::OwningPtr<raw_ostream> Out;
380  llvm::sys::Path Dir, Filename;
381  unsigned Cntr;
382
383  typedef llvm::DenseMap<void*,unsigned> VMap;
384  VMap M;
385
386public:
387  UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
388              llvm::sys::Path& filename);
389
390  ~UbigraphViz();
391
392  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
393};
394
395} // end anonymous namespace
396
397static ExplodedNode::Auditor* CreateUbiViz() {
398  std::string ErrMsg;
399
400  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
401  if (!ErrMsg.empty())
402    return 0;
403
404  llvm::sys::Path Filename = Dir;
405  Filename.appendComponent("llvm_ubi");
406  Filename.makeUnique(true,&ErrMsg);
407
408  if (!ErrMsg.empty())
409    return 0;
410
411  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
412
413  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
414  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
415
416  if (!ErrMsg.empty())
417    return 0;
418
419  return new UbigraphViz(Stream.take(), Dir, Filename);
420}
421
422void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
423
424  assert (Src != Dst && "Self-edges are not allowed.");
425
426  // Lookup the Src.  If it is a new node, it's a root.
427  VMap::iterator SrcI= M.find(Src);
428  unsigned SrcID;
429
430  if (SrcI == M.end()) {
431    M[Src] = SrcID = Cntr++;
432    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
433  }
434  else
435    SrcID = SrcI->second;
436
437  // Lookup the Dst.
438  VMap::iterator DstI= M.find(Dst);
439  unsigned DstID;
440
441  if (DstI == M.end()) {
442    M[Dst] = DstID = Cntr++;
443    *Out << "('vertex', " << DstID << ")\n";
444  }
445  else {
446    // We have hit DstID before.  Change its style to reflect a cache hit.
447    DstID = DstI->second;
448    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
449  }
450
451  // Add the edge.
452  *Out << "('edge', " << SrcID << ", " << DstID
453       << ", ('arrow','true'), ('oriented', 'true'))\n";
454}
455
456UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
457                         llvm::sys::Path& filename)
458  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
459
460  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
461  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
462          " ('size', '1.5'))\n";
463}
464
465UbigraphViz::~UbigraphViz() {
466  Out.reset(0);
467  llvm::errs() << "Running 'ubiviz' program... ";
468  std::string ErrMsg;
469  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
470  std::vector<const char*> args;
471  args.push_back(Ubiviz.c_str());
472  args.push_back(Filename.c_str());
473  args.push_back(0);
474
475  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
476    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
477  }
478
479  // Delete the directory.
480  Dir.eraseFromDisk(true);
481}
482