AnalysisConsumer.cpp revision a603569515eea06e54e6e041b1c690d33086f375
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#define DEBUG_TYPE "AnalysisConsumer"
15
16#include "AnalysisConsumer.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ParentMap.h"
22#include "clang/AST/RecursiveASTVisitor.h"
23#include "clang/Analysis/Analyses/LiveVariables.h"
24#include "clang/Analysis/CFG.h"
25#include "clang/Analysis/CallGraph.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
30#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
31#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
32#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
33#include "clang/StaticAnalyzer/Core/CheckerManager.h"
34#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
35#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
36#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
37#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
38#include "llvm/ADT/DepthFirstIterator.h"
39#include "llvm/ADT/OwningPtr.h"
40#include "llvm/ADT/PostOrderIterator.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
47#include <queue>
48
49using namespace clang;
50using namespace ento;
51using llvm::SmallPtrSet;
52
53static ExplodedNode::Auditor* CreateUbiViz();
54
55STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
56STATISTIC(NumFunctionsAnalyzed,
57                      "The # of functions and blocks analyzed (as top level "
58                      "with inlining turned on).");
59STATISTIC(NumBlocksInAnalyzedFunctions,
60                      "The # of basic blocks in the analyzed functions.");
61STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
62STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
63
64//===----------------------------------------------------------------------===//
65// Special PathDiagnosticConsumers.
66//===----------------------------------------------------------------------===//
67
68static void createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
69                                              PathDiagnosticConsumers &C,
70                                              const std::string &prefix,
71                                              const Preprocessor &PP) {
72  createHTMLDiagnosticConsumer(AnalyzerOpts, C,
73                               llvm::sys::path::parent_path(prefix), PP);
74  createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
75}
76
77namespace {
78class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
79  DiagnosticsEngine &Diag;
80public:
81  ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) : Diag(Diag) {}
82  virtual ~ClangDiagPathDiagConsumer() {}
83  virtual StringRef getName() const { return "ClangDiags"; }
84  virtual PathGenerationScheme getGenerationScheme() const { return None; }
85
86  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
87                            FilesMade *filesMade) {
88    for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
89         E = Diags.end(); I != E; ++I) {
90      const PathDiagnostic *PD = *I;
91      StringRef desc = PD->getShortDescription();
92      SmallString<512> TmpStr;
93      llvm::raw_svector_ostream Out(TmpStr);
94      for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) {
95        if (*I == '%')
96          Out << "%%";
97        else
98          Out << *I;
99      }
100      Out.flush();
101      unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning,
102                                                TmpStr);
103      SourceLocation L = PD->getLocation().asLocation();
104      DiagnosticBuilder diagBuilder = Diag.Report(L, ErrorDiag);
105
106      // Get the ranges from the last point in the path.
107      ArrayRef<SourceRange> Ranges = PD->path.back()->getRanges();
108
109      for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
110                                           E = Ranges.end(); I != E; ++I) {
111        diagBuilder << *I;
112      }
113    }
114  }
115};
116} // end anonymous namespace
117
118//===----------------------------------------------------------------------===//
119// AnalysisConsumer declaration.
120//===----------------------------------------------------------------------===//
121
122namespace {
123
124class AnalysisConsumer : public ASTConsumer,
125                         public RecursiveASTVisitor<AnalysisConsumer> {
126  enum {
127    AM_None = 0,
128    AM_Syntax = 0x1,
129    AM_Path = 0x2
130  };
131  typedef unsigned AnalysisMode;
132
133  /// Mode of the analyzes while recursively visiting Decls.
134  AnalysisMode RecVisitorMode;
135  /// Bug Reporter to use while recursively visiting Decls.
136  BugReporter *RecVisitorBR;
137
138public:
139  ASTContext *Ctx;
140  const Preprocessor &PP;
141  const std::string OutDir;
142  AnalyzerOptionsRef Opts;
143  ArrayRef<std::string> Plugins;
144
145  /// \brief Stores the declarations from the local translation unit.
146  /// Note, we pre-compute the local declarations at parse time as an
147  /// optimization to make sure we do not deserialize everything from disk.
148  /// The local declaration to all declarations ratio might be very small when
149  /// working with a PCH file.
150  SetOfDecls LocalTUDecls;
151
152  // Set of PathDiagnosticConsumers.  Owned by AnalysisManager.
153  PathDiagnosticConsumers PathConsumers;
154
155  StoreManagerCreator CreateStoreMgr;
156  ConstraintManagerCreator CreateConstraintMgr;
157
158  OwningPtr<CheckerManager> checkerMgr;
159  OwningPtr<AnalysisManager> Mgr;
160
161  /// Time the analyzes time of each translation unit.
162  static llvm::Timer* TUTotalTimer;
163
164  /// The information about analyzed functions shared throughout the
165  /// translation unit.
166  FunctionSummariesTy FunctionSummaries;
167
168  AnalysisConsumer(const Preprocessor& pp,
169                   const std::string& outdir,
170                   AnalyzerOptionsRef opts,
171                   ArrayRef<std::string> plugins)
172    : RecVisitorMode(0), RecVisitorBR(0),
173      Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins) {
174    DigestAnalyzerOptions();
175    if (Opts->PrintStats) {
176      llvm::EnableStatistics();
177      TUTotalTimer = new llvm::Timer("Analyzer Total Time");
178    }
179  }
180
181  ~AnalysisConsumer() {
182    if (Opts->PrintStats)
183      delete TUTotalTimer;
184  }
185
186  void DigestAnalyzerOptions() {
187    // Create the PathDiagnosticConsumer.
188    PathConsumers.push_back(new ClangDiagPathDiagConsumer(PP.getDiagnostics()));
189
190    if (!OutDir.empty()) {
191      switch (Opts->AnalysisDiagOpt) {
192      default:
193#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
194        case PD_##NAME: CREATEFN(*Opts.getPtr(), PathConsumers, OutDir, PP);\
195        break;
196#include "clang/StaticAnalyzer/Core/Analyses.def"
197      }
198    } else if (Opts->AnalysisDiagOpt == PD_TEXT) {
199      // Create the text client even without a specified output file since
200      // it just uses diagnostic notes.
201      createTextPathDiagnosticConsumer(*Opts.getPtr(), PathConsumers, "", PP);
202    }
203
204    // Create the analyzer component creators.
205    switch (Opts->AnalysisStoreOpt) {
206    default:
207      llvm_unreachable("Unknown store manager.");
208#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
209      case NAME##Model: CreateStoreMgr = CREATEFN; break;
210#include "clang/StaticAnalyzer/Core/Analyses.def"
211    }
212
213    switch (Opts->AnalysisConstraintsOpt) {
214    default:
215      llvm_unreachable("Unknown constraint manager.");
216#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
217      case NAME##Model: CreateConstraintMgr = CREATEFN; break;
218#include "clang/StaticAnalyzer/Core/Analyses.def"
219    }
220  }
221
222  void DisplayFunction(const Decl *D, AnalysisMode Mode,
223                       ExprEngine::InliningModes IMode) {
224    if (!Opts->AnalyzerDisplayProgress)
225      return;
226
227    SourceManager &SM = Mgr->getASTContext().getSourceManager();
228    PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
229    if (Loc.isValid()) {
230      llvm::errs() << "ANALYZE";
231
232      if (Mode == AM_Syntax)
233        llvm::errs() << " (Syntax)";
234      else if (Mode == AM_Path) {
235        llvm::errs() << " (Path, ";
236        switch (IMode) {
237          case ExprEngine::Inline_Minimal:
238            llvm::errs() << " Inline_Minimal";
239            break;
240          case ExprEngine::Inline_Regular:
241            llvm::errs() << " Inline_Regular";
242            break;
243        }
244        llvm::errs() << ")";
245      }
246      else
247        assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
248
249      llvm::errs() << ": " << Loc.getFilename();
250      if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
251        const NamedDecl *ND = cast<NamedDecl>(D);
252        llvm::errs() << ' ' << *ND << '\n';
253      }
254      else if (isa<BlockDecl>(D)) {
255        llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
256                     << Loc.getColumn() << '\n';
257      }
258      else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
259        Selector S = MD->getSelector();
260        llvm::errs() << ' ' << S.getAsString();
261      }
262    }
263  }
264
265  virtual void Initialize(ASTContext &Context) {
266    Ctx = &Context;
267    checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
268                                          PP.getDiagnostics()));
269    Mgr.reset(new AnalysisManager(*Ctx,
270                                  PP.getDiagnostics(),
271                                  PP.getLangOpts(),
272                                  PathConsumers,
273                                  CreateStoreMgr,
274                                  CreateConstraintMgr,
275                                  checkerMgr.get(),
276                                  *Opts));
277  }
278
279  /// \brief Store the top level decls in the set to be processed later on.
280  /// (Doing this pre-processing avoids deserialization of data from PCH.)
281  virtual bool HandleTopLevelDecl(DeclGroupRef D);
282  virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D);
283
284  virtual void HandleTranslationUnit(ASTContext &C);
285
286  /// \brief Determine which inlining mode should be used when this function is
287  /// analyzed. This allows to redefine the default inlining policies when
288  /// analyzing a given function.
289  ExprEngine::InliningModes
290  getInliningModeForFunction(const Decl *D, SetOfConstDecls Visited);
291
292  /// \brief Build the call graph for all the top level decls of this TU and
293  /// use it to define the order in which the functions should be visited.
294  void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
295
296  /// \brief Run analyzes(syntax or path sensitive) on the given function.
297  /// \param Mode - determines if we are requesting syntax only or path
298  /// sensitive only analysis.
299  /// \param VisitedCallees - The output parameter, which is populated with the
300  /// set of functions which should be considered analyzed after analyzing the
301  /// given root function.
302  void HandleCode(Decl *D, AnalysisMode Mode,
303                  ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
304                  SetOfConstDecls *VisitedCallees = 0);
305
306  void RunPathSensitiveChecks(Decl *D,
307                              ExprEngine::InliningModes IMode,
308                              SetOfConstDecls *VisitedCallees);
309  void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
310                        ExprEngine::InliningModes IMode,
311                        SetOfConstDecls *VisitedCallees);
312
313  /// Visitors for the RecursiveASTVisitor.
314  bool shouldWalkTypesOfTypeLocs() const { return false; }
315
316  /// Handle callbacks for arbitrary Decls.
317  bool VisitDecl(Decl *D) {
318    AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
319    if (Mode & AM_Syntax)
320      checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
321    return true;
322  }
323
324  bool VisitFunctionDecl(FunctionDecl *FD) {
325    IdentifierInfo *II = FD->getIdentifier();
326    if (II && II->getName().startswith("__inline"))
327      return true;
328
329    // We skip function template definitions, as their semantics is
330    // only determined when they are instantiated.
331    if (FD->isThisDeclarationADefinition() &&
332        !FD->isDependentContext()) {
333      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
334      HandleCode(FD, RecVisitorMode);
335    }
336    return true;
337  }
338
339  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
340    if (MD->isThisDeclarationADefinition()) {
341      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
342      HandleCode(MD, RecVisitorMode);
343    }
344    return true;
345  }
346
347  bool VisitBlockDecl(BlockDecl *BD) {
348    if (BD->hasBody()) {
349      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
350      HandleCode(BD, RecVisitorMode);
351    }
352    return true;
353  }
354
355private:
356  void storeTopLevelDecls(DeclGroupRef DG);
357
358  /// \brief Check if we should skip (not analyze) the given function.
359  AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
360
361};
362} // end anonymous namespace
363
364
365//===----------------------------------------------------------------------===//
366// AnalysisConsumer implementation.
367//===----------------------------------------------------------------------===//
368llvm::Timer* AnalysisConsumer::TUTotalTimer = 0;
369
370bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
371  storeTopLevelDecls(DG);
372  return true;
373}
374
375void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
376  storeTopLevelDecls(DG);
377}
378
379void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
380  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
381
382    // Skip ObjCMethodDecl, wait for the objc container to avoid
383    // analyzing twice.
384    if (isa<ObjCMethodDecl>(*I))
385      continue;
386
387    LocalTUDecls.push_back(*I);
388  }
389}
390
391static bool shouldSkipFunction(const Decl *D,
392                               SetOfConstDecls Visited,
393                               SetOfConstDecls VisitedAsTopLevel) {
394  if (VisitedAsTopLevel.count(D))
395    return true;
396
397  // We want to re-analyse the functions as top level in the following cases:
398  // - The 'init' methods should be reanalyzed because
399  //   ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
400  //   'nil' and unless we analyze the 'init' functions as top level, we will
401  //   not catch errors within defensive code.
402  // - We want to reanalyze all ObjC methods as top level to report Retain
403  //   Count naming convention errors more aggressively.
404  if (isa<ObjCMethodDecl>(D))
405    return false;
406
407  // Otherwise, if we visited the function before, do not reanalyze it.
408  return Visited.count(D);
409}
410
411ExprEngine::InliningModes
412AnalysisConsumer::getInliningModeForFunction(const Decl *D,
413                                             SetOfConstDecls Visited) {
414  // We want to reanalyze all ObjC methods as top level to report Retain
415  // Count naming convention errors more aggressively. But we should tune down
416  // inlining when reanalyzing an already inlined function.
417  if (Visited.count(D)) {
418    assert(isa<ObjCMethodDecl>(D) &&
419           "We are only reanalyzing ObjCMethods.");
420    const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
421    if (ObjCM->getMethodFamily() != OMF_init)
422      return ExprEngine::Inline_Minimal;
423  }
424
425  return ExprEngine::Inline_Regular;
426}
427
428void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
429  // Build the Call Graph by adding all the top level declarations to the graph.
430  // Note: CallGraph can trigger deserialization of more items from a pch
431  // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
432  // We rely on random access to add the initially processed Decls to CG.
433  CallGraph CG;
434  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
435    CG.addToCallGraph(LocalTUDecls[i]);
436  }
437
438  // Walk over all of the call graph nodes in topological order, so that we
439  // analyze parents before the children. Skip the functions inlined into
440  // the previously processed functions. Use external Visited set to identify
441  // inlined functions. The topological order allows the "do not reanalyze
442  // previously inlined function" performance heuristic to be triggered more
443  // often.
444  SetOfConstDecls Visited;
445  SetOfConstDecls VisitedAsTopLevel;
446  llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
447  for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
448         I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
449    NumFunctionTopLevel++;
450
451    CallGraphNode *N = *I;
452    Decl *D = N->getDecl();
453
454    // Skip the abstract root node.
455    if (!D)
456      continue;
457
458    // Skip the functions which have been processed already or previously
459    // inlined.
460    if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
461      continue;
462
463    // Analyze the function.
464    SetOfConstDecls VisitedCallees;
465
466    HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
467               (Mgr->options.InliningMode == All ? 0 : &VisitedCallees));
468
469    // Add the visited callees to the global visited set.
470    for (SetOfConstDecls::iterator I = VisitedCallees.begin(),
471                                   E = VisitedCallees.end(); I != E; ++I) {
472        Visited.insert(*I);
473    }
474    VisitedAsTopLevel.insert(D);
475  }
476}
477
478void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
479  // Don't run the actions if an error has occurred with parsing the file.
480  DiagnosticsEngine &Diags = PP.getDiagnostics();
481  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
482    return;
483
484  {
485    if (TUTotalTimer) TUTotalTimer->startTimer();
486
487    // Introduce a scope to destroy BR before Mgr.
488    BugReporter BR(*Mgr);
489    TranslationUnitDecl *TU = C.getTranslationUnitDecl();
490    checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
491
492    // Run the AST-only checks using the order in which functions are defined.
493    // If inlining is not turned on, use the simplest function order for path
494    // sensitive analyzes as well.
495    RecVisitorMode = AM_Syntax;
496    if (!Mgr->shouldInlineCall())
497      RecVisitorMode |= AM_Path;
498    RecVisitorBR = &BR;
499
500    // Process all the top level declarations.
501    //
502    // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
503    // entries.  Thus we don't use an iterator, but rely on LocalTUDecls
504    // random access.  By doing so, we automatically compensate for iterators
505    // possibly being invalidated, although this is a bit slower.
506    const unsigned LocalTUDeclsSize = LocalTUDecls.size();
507    for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
508      TraverseDecl(LocalTUDecls[i]);
509    }
510
511    if (Mgr->shouldInlineCall())
512      HandleDeclsCallGraph(LocalTUDeclsSize);
513
514    // After all decls handled, run checkers on the entire TranslationUnit.
515    checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
516
517    RecVisitorBR = 0;
518  }
519
520  // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
521  // FIXME: This should be replaced with something that doesn't rely on
522  // side-effects in PathDiagnosticConsumer's destructor. This is required when
523  // used with option -disable-free.
524  Mgr.reset(NULL);
525
526  if (TUTotalTimer) TUTotalTimer->stopTimer();
527
528  // Count how many basic blocks we have not covered.
529  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
530  if (NumBlocksInAnalyzedFunctions > 0)
531    PercentReachableBlocks =
532      (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
533        NumBlocksInAnalyzedFunctions;
534
535}
536
537static std::string getFunctionName(const Decl *D) {
538  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
539    return ID->getSelector().getAsString();
540  }
541  if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
542    IdentifierInfo *II = ND->getIdentifier();
543    if (II)
544      return II->getName();
545  }
546  return "";
547}
548
549AnalysisConsumer::AnalysisMode
550AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
551  if (!Opts->AnalyzeSpecificFunction.empty() &&
552      getFunctionName(D) != Opts->AnalyzeSpecificFunction)
553    return AM_None;
554
555  // Unless -analyze-all is specified, treat decls differently depending on
556  // where they came from:
557  // - Main source file: run both path-sensitive and non-path-sensitive checks.
558  // - Header files: run non-path-sensitive checks only.
559  // - System headers: don't run any checks.
560  SourceManager &SM = Ctx->getSourceManager();
561  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
562  if (!Opts->AnalyzeAll && !SM.isFromMainFile(SL)) {
563    if (SL.isInvalid() || SM.isInSystemHeader(SL))
564      return AM_None;
565    return Mode & ~AM_Path;
566  }
567
568  return Mode;
569}
570
571void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
572                                  ExprEngine::InliningModes IMode,
573                                  SetOfConstDecls *VisitedCallees) {
574  if (!D->hasBody())
575    return;
576  Mode = getModeForDecl(D, Mode);
577  if (Mode == AM_None)
578    return;
579
580  DisplayFunction(D, Mode, IMode);
581  CFG *DeclCFG = Mgr->getCFG(D);
582  if (DeclCFG) {
583    unsigned CFGSize = DeclCFG->size();
584    MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
585  }
586
587  // Clear the AnalysisManager of old AnalysisDeclContexts.
588  Mgr->ClearContexts();
589  BugReporter BR(*Mgr);
590
591  if (Mode & AM_Syntax)
592    checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
593  if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
594    RunPathSensitiveChecks(D, IMode, VisitedCallees);
595    if (IMode != ExprEngine::Inline_Minimal)
596      NumFunctionsAnalyzed++;
597  }
598}
599
600//===----------------------------------------------------------------------===//
601// Path-sensitive checking.
602//===----------------------------------------------------------------------===//
603
604void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
605                                        ExprEngine::InliningModes IMode,
606                                        SetOfConstDecls *VisitedCallees) {
607  // Construct the analysis engine.  First check if the CFG is valid.
608  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
609  if (!Mgr->getCFG(D))
610    return;
611
612  // See if the LiveVariables analysis scales.
613  if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
614    return;
615
616  ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
617
618  // Set the graph auditor.
619  OwningPtr<ExplodedNode::Auditor> Auditor;
620  if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
621    Auditor.reset(CreateUbiViz());
622    ExplodedNode::SetAuditor(Auditor.get());
623  }
624
625  // Execute the worklist algorithm.
626  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
627                      Mgr->options.getMaxNodesPerTopLevelFunction());
628
629  // Release the auditor (if any) so that it doesn't monitor the graph
630  // created BugReporter.
631  ExplodedNode::SetAuditor(0);
632
633  // Visualize the exploded graph.
634  if (Mgr->options.visualizeExplodedGraphWithGraphViz)
635    Eng.ViewGraph(Mgr->options.TrimGraph);
636
637  // Display warnings.
638  Eng.getBugReporter().FlushReports();
639}
640
641void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
642                                              ExprEngine::InliningModes IMode,
643                                              SetOfConstDecls *Visited) {
644
645  switch (Mgr->getLangOpts().getGC()) {
646  case LangOptions::NonGC:
647    ActionExprEngine(D, false, IMode, Visited);
648    break;
649
650  case LangOptions::GCOnly:
651    ActionExprEngine(D, true, IMode, Visited);
652    break;
653
654  case LangOptions::HybridGC:
655    ActionExprEngine(D, false, IMode, Visited);
656    ActionExprEngine(D, true, IMode, Visited);
657    break;
658  }
659}
660
661//===----------------------------------------------------------------------===//
662// AnalysisConsumer creation.
663//===----------------------------------------------------------------------===//
664
665ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
666                                          const std::string& outDir,
667                                          AnalyzerOptionsRef opts,
668                                          ArrayRef<std::string> plugins) {
669  // Disable the effects of '-Werror' when using the AnalysisConsumer.
670  pp.getDiagnostics().setWarningsAsErrors(false);
671
672  return new AnalysisConsumer(pp, outDir, opts, plugins);
673}
674
675//===----------------------------------------------------------------------===//
676// Ubigraph Visualization.  FIXME: Move to separate file.
677//===----------------------------------------------------------------------===//
678
679namespace {
680
681class UbigraphViz : public ExplodedNode::Auditor {
682  OwningPtr<raw_ostream> Out;
683  llvm::sys::Path Dir, Filename;
684  unsigned Cntr;
685
686  typedef llvm::DenseMap<void*,unsigned> VMap;
687  VMap M;
688
689public:
690  UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
691              llvm::sys::Path& filename);
692
693  ~UbigraphViz();
694
695  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
696};
697
698} // end anonymous namespace
699
700static ExplodedNode::Auditor* CreateUbiViz() {
701  std::string ErrMsg;
702
703  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
704  if (!ErrMsg.empty())
705    return 0;
706
707  llvm::sys::Path Filename = Dir;
708  Filename.appendComponent("llvm_ubi");
709  Filename.makeUnique(true,&ErrMsg);
710
711  if (!ErrMsg.empty())
712    return 0;
713
714  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
715
716  OwningPtr<llvm::raw_fd_ostream> Stream;
717  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
718
719  if (!ErrMsg.empty())
720    return 0;
721
722  return new UbigraphViz(Stream.take(), Dir, Filename);
723}
724
725void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
726
727  assert (Src != Dst && "Self-edges are not allowed.");
728
729  // Lookup the Src.  If it is a new node, it's a root.
730  VMap::iterator SrcI= M.find(Src);
731  unsigned SrcID;
732
733  if (SrcI == M.end()) {
734    M[Src] = SrcID = Cntr++;
735    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
736  }
737  else
738    SrcID = SrcI->second;
739
740  // Lookup the Dst.
741  VMap::iterator DstI= M.find(Dst);
742  unsigned DstID;
743
744  if (DstI == M.end()) {
745    M[Dst] = DstID = Cntr++;
746    *Out << "('vertex', " << DstID << ")\n";
747  }
748  else {
749    // We have hit DstID before.  Change its style to reflect a cache hit.
750    DstID = DstI->second;
751    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
752  }
753
754  // Add the edge.
755  *Out << "('edge', " << SrcID << ", " << DstID
756       << ", ('arrow','true'), ('oriented', 'true'))\n";
757}
758
759UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
760                         llvm::sys::Path& filename)
761  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
762
763  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
764  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
765          " ('size', '1.5'))\n";
766}
767
768UbigraphViz::~UbigraphViz() {
769  Out.reset(0);
770  llvm::errs() << "Running 'ubiviz' program... ";
771  std::string ErrMsg;
772  llvm::sys::Path Ubiviz = llvm::sys::FindProgramByName("ubiviz");
773  std::vector<const char*> args;
774  args.push_back(Ubiviz.c_str());
775  args.push_back(Filename.c_str());
776  args.push_back(0);
777
778  if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
779    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
780  }
781
782  // Delete the directory.
783  Dir.eraseFromDisk(true);
784}
785