AnalysisConsumer.cpp revision 402785357ab053dd53f4fdd858b9630a5e0f8bad
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
70  // PD is owned by AnalysisManager.
71  PathDiagnosticClient *PD;
72
73  StoreManagerCreator CreateStoreMgr;
74  ConstraintManagerCreator CreateConstraintMgr;
75
76  llvm::OwningPtr<CheckerManager> checkerMgr;
77  llvm::OwningPtr<AnalysisManager> Mgr;
78
79  AnalysisConsumer(const Preprocessor& pp,
80                   const std::string& outdir,
81                   const AnalyzerOptions& opts)
82    : Ctx(0), PP(pp), OutDir(outdir),
83      Opts(opts), PD(0) {
84    DigestAnalyzerOptions();
85  }
86
87  void DigestAnalyzerOptions() {
88    // Create the PathDiagnosticClient.
89    if (!OutDir.empty()) {
90      switch (Opts.AnalysisDiagOpt) {
91      default:
92#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
93        case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
94#include "clang/Frontend/Analyses.def"
95      }
96    } else if (Opts.AnalysisDiagOpt == PD_TEXT) {
97      // Create the text client even without a specified output file since
98      // it just uses diagnostic notes.
99      PD = createTextPathDiagnosticClient("", PP);
100    }
101
102    // Create the analyzer component creators.
103    switch (Opts.AnalysisStoreOpt) {
104    default:
105      assert(0 && "Unknown store manager.");
106#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
107      case NAME##Model: CreateStoreMgr = CREATEFN; break;
108#include "clang/Frontend/Analyses.def"
109    }
110
111    switch (Opts.AnalysisConstraintsOpt) {
112    default:
113      assert(0 && "Unknown store manager.");
114#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
115      case NAME##Model: CreateConstraintMgr = CREATEFN; break;
116#include "clang/Frontend/Analyses.def"
117    }
118  }
119
120  void DisplayFunction(const Decl *D) {
121    if (!Opts.AnalyzerDisplayProgress)
122      return;
123
124    SourceManager &SM = Mgr->getASTContext().getSourceManager();
125    PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
126    if (Loc.isValid()) {
127      llvm::errs() << "ANALYZE: " << Loc.getFilename();
128
129      if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
130        const NamedDecl *ND = cast<NamedDecl>(D);
131        llvm::errs() << ' ' << ND << '\n';
132      }
133      else if (isa<BlockDecl>(D)) {
134        llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
135                     << Loc.getColumn() << '\n';
136      }
137      else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
138        Selector S = MD->getSelector();
139        llvm::errs() << ' ' << S.getAsString();
140      }
141    }
142  }
143
144  virtual void Initialize(ASTContext &Context) {
145    Ctx = &Context;
146    checkerMgr.reset(registerCheckers(Opts, PP.getLangOptions(),
147                                      PP.getDiagnostics()));
148    Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
149                                  PP.getLangOptions(), PD,
150                                  CreateStoreMgr, CreateConstraintMgr,
151                                  checkerMgr.get(),
152                                  /* Indexer */ 0,
153                                  Opts.MaxNodes, Opts.MaxLoop,
154                                  Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
155                                  Opts.PurgeDead, Opts.EagerlyAssume,
156                                  Opts.TrimGraph, Opts.InlineCall,
157                                  Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors,
158                                  Opts.CFGAddInitializers,
159                                  Opts.EagerlyTrimEGraph));
160  }
161
162  virtual void HandleTranslationUnit(ASTContext &C);
163  void HandleDeclContext(ASTContext &C, DeclContext *dc);
164
165  void HandleCode(Decl *D);
166};
167} // end anonymous namespace
168
169//===----------------------------------------------------------------------===//
170// AnalysisConsumer implementation.
171//===----------------------------------------------------------------------===//
172
173void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
174  BugReporter BR(*Mgr);
175  for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
176       I != E; ++I) {
177    Decl *D = *I;
178    checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
179
180    switch (D->getKind()) {
181      case Decl::Namespace: {
182        HandleDeclContext(C, cast<NamespaceDecl>(D));
183        break;
184      }
185      case Decl::CXXConstructor:
186      case Decl::CXXDestructor:
187      case Decl::CXXConversion:
188      case Decl::CXXMethod:
189      case Decl::Function: {
190        FunctionDecl* FD = cast<FunctionDecl>(D);
191        // We skip function template definitions, as their semantics is
192        // only determined when they are instantiated.
193        if (FD->isThisDeclarationADefinition() &&
194            !FD->isDependentContext()) {
195          if (!Opts.AnalyzeSpecificFunction.empty() &&
196              FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
197            break;
198          DisplayFunction(FD);
199          HandleCode(FD);
200        }
201        break;
202      }
203
204      case Decl::ObjCCategoryImpl:
205      case Decl::ObjCImplementation: {
206        ObjCImplDecl* ID = cast<ObjCImplDecl>(*I);
207        HandleCode(ID);
208
209        for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(),
210             ME = ID->meth_end(); MI != ME; ++MI) {
211          checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
212
213          if ((*MI)->isThisDeclarationADefinition()) {
214            if (!Opts.AnalyzeSpecificFunction.empty() &&
215                Opts.AnalyzeSpecificFunction !=
216                  (*MI)->getSelector().getAsString())
217              break;
218            DisplayFunction(*MI);
219            HandleCode(*MI);
220          }
221        }
222        break;
223      }
224
225      default:
226        break;
227    }
228  }
229}
230
231void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
232  BugReporter BR(*Mgr);
233  TranslationUnitDecl *TU = C.getTranslationUnitDecl();
234  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
235  HandleDeclContext(C, TU);
236
237  // After all decls handled, run checkers on the entire TranslationUnit.
238  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
239
240  // Explicitly destroy the PathDiagnosticClient.  This will flush its output.
241  // FIXME: This should be replaced with something that doesn't rely on
242  // side-effects in PathDiagnosticClient's destructor. This is required when
243  // used with option -disable-free.
244  Mgr.reset(NULL);
245}
246
247static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
248  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
249    WL.push_back(BD);
250
251  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
252       I!=E; ++I)
253    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
254      FindBlocks(DC, WL);
255}
256
257static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
258                                 Decl *D);
259
260void AnalysisConsumer::HandleCode(Decl *D) {
261
262  // Don't run the actions if an error has occurred with parsing the file.
263  Diagnostic &Diags = PP.getDiagnostics();
264  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
265    return;
266
267  // Don't run the actions on declarations in header files unless
268  // otherwise specified.
269  SourceManager &SM = Ctx->getSourceManager();
270  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
271  if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
272    return;
273
274  // Clear the AnalysisManager of old AnalysisContexts.
275  Mgr->ClearContexts();
276
277  // Dispatch on the actions.
278  SmallVector<Decl*, 10> WL;
279  WL.push_back(D);
280
281  if (D->hasBody() && Opts.AnalyzeNestedBlocks)
282    FindBlocks(cast<DeclContext>(D), WL);
283
284  BugReporter BR(*Mgr);
285  for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
286       WI != WE; ++WI)
287    if ((*WI)->hasBody()) {
288      checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
289      if (checkerMgr->hasPathSensitiveCheckers())
290        ActionObjCMemChecker(*this, *Mgr, *WI);
291    }
292}
293
294//===----------------------------------------------------------------------===//
295// Path-sensitive checking.
296//===----------------------------------------------------------------------===//
297
298static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr,
299                               Decl *D,
300                               TransferFuncs* tf) {
301
302  llvm::OwningPtr<TransferFuncs> TF(tf);
303
304  // Construct the analysis engine.  We first query for the LiveVariables
305  // information to see if the CFG is valid.
306  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
307  if (!mgr.getLiveVariables(D))
308    return;
309  ExprEngine Eng(mgr, TF.take());
310
311  // Set the graph auditor.
312  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
313  if (mgr.shouldVisualizeUbigraph()) {
314    Auditor.reset(CreateUbiViz());
315    ExplodedNode::SetAuditor(Auditor.get());
316  }
317
318  // Execute the worklist algorithm.
319  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
320
321  // Release the auditor (if any) so that it doesn't monitor the graph
322  // created BugReporter.
323  ExplodedNode::SetAuditor(0);
324
325  // Visualize the exploded graph.
326  if (mgr.shouldVisualizeGraphviz())
327    Eng.ViewGraph(mgr.shouldTrimGraph());
328
329  // Display warnings.
330  Eng.getBugReporter().FlushReports();
331}
332
333static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
334                                  Decl *D, bool GCEnabled) {
335
336  TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
337                                         GCEnabled,
338                                         mgr.getLangOptions());
339
340  ActionExprEngine(C, mgr, D, TF);
341}
342
343static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
344                               Decl *D) {
345
346 switch (mgr.getLangOptions().getGCMode()) {
347 default:
348   assert (false && "Invalid GC mode.");
349 case LangOptions::NonGC:
350   ActionObjCMemCheckerAux(C, mgr, D, false);
351   break;
352
353 case LangOptions::GCOnly:
354   ActionObjCMemCheckerAux(C, mgr, D, true);
355   break;
356
357 case LangOptions::HybridGC:
358   ActionObjCMemCheckerAux(C, mgr, D, false);
359   ActionObjCMemCheckerAux(C, mgr, D, true);
360   break;
361 }
362}
363
364//===----------------------------------------------------------------------===//
365// AnalysisConsumer creation.
366//===----------------------------------------------------------------------===//
367
368ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
369                                           const std::string& OutDir,
370                                           const AnalyzerOptions& Opts) {
371  llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
372
373  // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
374  pp.getDiagnostics().setWarningsAsErrors(false);
375
376  return C.take();
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