AnalysisConsumer.cpp revision 08b86531ade68727c56918f162816075b87c864a
1//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
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// "Meta" ASTConsumer for running different source analyses.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AnalysisConsumer.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/Analysis/CFG.h"
21#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
22#include "clang/StaticAnalyzer/Core/CheckerManager.h"
23#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
26#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/TransferFuncs.h"
29#include "clang/StaticAnalyzer/Core/PathDiagnosticClients.h"
30
31#include "clang/Basic/FileManager.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Frontend/AnalyzerOptions.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/Support/raw_ostream.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Program.h"
38#include "llvm/ADT/OwningPtr.h"
39
40using namespace clang;
41using namespace ento;
42
43static ExplodedNode::Auditor* CreateUbiViz();
44
45//===----------------------------------------------------------------------===//
46// Special PathDiagnosticClients.
47//===----------------------------------------------------------------------===//
48
49static PathDiagnosticClient*
50createPlistHTMLDiagnosticClient(const std::string& prefix,
51                                const Preprocessor &PP) {
52  PathDiagnosticClient *PD =
53    createHTMLDiagnosticClient(llvm::sys::path::parent_path(prefix), PP);
54  return createPlistDiagnosticClient(prefix, PP, PD);
55}
56
57//===----------------------------------------------------------------------===//
58// AnalysisConsumer declaration.
59//===----------------------------------------------------------------------===//
60
61namespace {
62
63class AnalysisConsumer : public ASTConsumer {
64public:
65  ASTContext *Ctx;
66  const Preprocessor &PP;
67  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
166  void HandleCode(Decl *D);
167};
168} // end anonymous namespace
169
170//===----------------------------------------------------------------------===//
171// AnalysisConsumer implementation.
172//===----------------------------------------------------------------------===//
173
174void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
175  BugReporter BR(*Mgr);
176  for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
177       I != E; ++I) {
178    Decl *D = *I;
179    checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
180
181    switch (D->getKind()) {
182      case Decl::Namespace: {
183        HandleDeclContext(C, cast<NamespaceDecl>(D));
184        break;
185      }
186      case Decl::CXXConstructor:
187      case Decl::CXXDestructor:
188      case Decl::CXXConversion:
189      case Decl::CXXMethod:
190      case Decl::Function: {
191        FunctionDecl *FD = cast<FunctionDecl>(D);
192        // We skip function template definitions, as their semantics is
193        // only determined when they are instantiated.
194        if (FD->isThisDeclarationADefinition() &&
195            !FD->isDependentContext()) {
196          if (!Opts.AnalyzeSpecificFunction.empty() &&
197              FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
198            break;
199          DisplayFunction(FD);
200          HandleCode(FD);
201        }
202        break;
203      }
204
205      case Decl::ObjCCategoryImpl:
206      case Decl::ObjCImplementation: {
207        ObjCImplDecl *ID = cast<ObjCImplDecl>(*I);
208        HandleCode(ID);
209
210        for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(),
211             ME = ID->meth_end(); MI != ME; ++MI) {
212          checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
213
214          if ((*MI)->isThisDeclarationADefinition()) {
215            if (!Opts.AnalyzeSpecificFunction.empty() &&
216                Opts.AnalyzeSpecificFunction !=
217                  (*MI)->getSelector().getAsString())
218              break;
219            DisplayFunction(*MI);
220            HandleCode(*MI);
221          }
222        }
223        break;
224      }
225
226      default:
227        break;
228    }
229  }
230}
231
232void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
233  BugReporter BR(*Mgr);
234  TranslationUnitDecl *TU = C.getTranslationUnitDecl();
235  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
236  HandleDeclContext(C, TU);
237
238  // After all decls handled, run checkers on the entire TranslationUnit.
239  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
240
241  // Explicitly destroy the PathDiagnosticClient.  This will flush its output.
242  // FIXME: This should be replaced with something that doesn't rely on
243  // side-effects in PathDiagnosticClient's destructor. This is required when
244  // used with option -disable-free.
245  Mgr.reset(NULL);
246}
247
248static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
249  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
250    WL.push_back(BD);
251
252  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
253       I!=E; ++I)
254    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
255      FindBlocks(DC, WL);
256}
257
258static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
259                                 Decl *D);
260
261void AnalysisConsumer::HandleCode(Decl *D) {
262
263  // Don't run the actions if an error has occurred with parsing the file.
264  Diagnostic &Diags = PP.getDiagnostics();
265  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
266    return;
267
268  // Don't run the actions on declarations in header files unless
269  // otherwise specified.
270  SourceManager &SM = Ctx->getSourceManager();
271  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
272  if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
273    return;
274
275  // Clear the AnalysisManager of old AnalysisContexts.
276  Mgr->ClearContexts();
277
278  // Dispatch on the actions.
279  SmallVector<Decl*, 10> WL;
280  WL.push_back(D);
281
282  if (D->hasBody() && Opts.AnalyzeNestedBlocks)
283    FindBlocks(cast<DeclContext>(D), WL);
284
285  BugReporter BR(*Mgr);
286  for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
287       WI != WE; ++WI)
288    if ((*WI)->hasBody()) {
289      checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
290      if (checkerMgr->hasPathSensitiveCheckers())
291        ActionObjCMemChecker(*this, *Mgr, *WI);
292    }
293}
294
295//===----------------------------------------------------------------------===//
296// Path-sensitive checking.
297//===----------------------------------------------------------------------===//
298
299static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr,
300                               Decl *D,
301                               TransferFuncs* tf) {
302
303  llvm::OwningPtr<TransferFuncs> TF(tf);
304
305  // Construct the analysis engine.  We first query for the LiveVariables
306  // information to see if the CFG is valid.
307  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
308  if (!mgr.getLiveVariables(D))
309    return;
310  ExprEngine Eng(mgr, TF.take());
311
312  // Set the graph auditor.
313  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
314  if (mgr.shouldVisualizeUbigraph()) {
315    Auditor.reset(CreateUbiViz());
316    ExplodedNode::SetAuditor(Auditor.get());
317  }
318
319  // Execute the worklist algorithm.
320  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
321
322  // Release the auditor (if any) so that it doesn't monitor the graph
323  // created BugReporter.
324  ExplodedNode::SetAuditor(0);
325
326  // Visualize the exploded graph.
327  if (mgr.shouldVisualizeGraphviz())
328    Eng.ViewGraph(mgr.shouldTrimGraph());
329
330  // Display warnings.
331  Eng.getBugReporter().FlushReports();
332}
333
334static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
335                                  Decl *D, bool GCEnabled) {
336
337  TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
338                                         GCEnabled,
339                                         mgr.getLangOptions());
340
341  ActionExprEngine(C, mgr, D, TF);
342}
343
344static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
345                               Decl *D) {
346
347 switch (mgr.getLangOptions().getGCMode()) {
348 default:
349   assert (false && "Invalid GC mode.");
350 case LangOptions::NonGC:
351   ActionObjCMemCheckerAux(C, mgr, D, false);
352   break;
353
354 case LangOptions::GCOnly:
355   ActionObjCMemCheckerAux(C, mgr, D, true);
356   break;
357
358 case LangOptions::HybridGC:
359   ActionObjCMemCheckerAux(C, mgr, D, false);
360   ActionObjCMemCheckerAux(C, mgr, D, true);
361   break;
362 }
363}
364
365//===----------------------------------------------------------------------===//
366// AnalysisConsumer creation.
367//===----------------------------------------------------------------------===//
368
369ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
370                                          const std::string& outDir,
371                                          const AnalyzerOptions& opts,
372                                          ArrayRef<std::string> plugins) {
373  // Disable the effects of '-Werror' when using the AnalysisConsumer.
374  pp.getDiagnostics().setWarningsAsErrors(false);
375
376  return new AnalysisConsumer(pp, outDir, opts, plugins);
377}
378
379//===----------------------------------------------------------------------===//
380// Ubigraph Visualization.  FIXME: Move to separate file.
381//===----------------------------------------------------------------------===//
382
383namespace {
384
385class UbigraphViz : public ExplodedNode::Auditor {
386  llvm::OwningPtr<raw_ostream> Out;
387  llvm::sys::Path Dir, Filename;
388  unsigned Cntr;
389
390  typedef llvm::DenseMap<void*,unsigned> VMap;
391  VMap M;
392
393public:
394  UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
395              llvm::sys::Path& filename);
396
397  ~UbigraphViz();
398
399  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
400};
401
402} // end anonymous namespace
403
404static ExplodedNode::Auditor* CreateUbiViz() {
405  std::string ErrMsg;
406
407  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
408  if (!ErrMsg.empty())
409    return 0;
410
411  llvm::sys::Path Filename = Dir;
412  Filename.appendComponent("llvm_ubi");
413  Filename.makeUnique(true,&ErrMsg);
414
415  if (!ErrMsg.empty())
416    return 0;
417
418  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
419
420  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
421  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
422
423  if (!ErrMsg.empty())
424    return 0;
425
426  return new UbigraphViz(Stream.take(), Dir, Filename);
427}
428
429void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
430
431  assert (Src != Dst && "Self-edges are not allowed.");
432
433  // Lookup the Src.  If it is a new node, it's a root.
434  VMap::iterator SrcI= M.find(Src);
435  unsigned SrcID;
436
437  if (SrcI == M.end()) {
438    M[Src] = SrcID = Cntr++;
439    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
440  }
441  else
442    SrcID = SrcI->second;
443
444  // Lookup the Dst.
445  VMap::iterator DstI= M.find(Dst);
446  unsigned DstID;
447
448  if (DstI == M.end()) {
449    M[Dst] = DstID = Cntr++;
450    *Out << "('vertex', " << DstID << ")\n";
451  }
452  else {
453    // We have hit DstID before.  Change its style to reflect a cache hit.
454    DstID = DstI->second;
455    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
456  }
457
458  // Add the edge.
459  *Out << "('edge', " << SrcID << ", " << DstID
460       << ", ('arrow','true'), ('oriented', 'true'))\n";
461}
462
463UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
464                         llvm::sys::Path& filename)
465  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
466
467  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
468  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
469          " ('size', '1.5'))\n";
470}
471
472UbigraphViz::~UbigraphViz() {
473  Out.reset(0);
474  llvm::errs() << "Running 'ubiviz' program... ";
475  std::string ErrMsg;
476  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
477  std::vector<const char*> args;
478  args.push_back(Ubiviz.c_str());
479  args.push_back(Filename.c_str());
480  args.push_back(0);
481
482  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
483    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
484  }
485
486  // Delete the directory.
487  Dir.eraseFromDisk(true);
488}
489