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