AnalysisConsumer.cpp revision 75f31c4862643ab09479c979fabf754e7ffe1460
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(CallGraphNode *N,
274                             SmallPtrSet<CallGraphNode*,24> Visited);
275
276  /// \brief Build the call graph for all the top level decls of this TU and
277  /// use it to define the order in which the functions should be visited.
278  void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
279
280  /// \brief Run analyzes(syntax or path sensitive) on the given function.
281  /// \param Mode - determines if we are requesting syntax only or path
282  /// sensitive only analysis.
283  /// \param VisitedCallees - The output parameter, which is populated with the
284  /// set of functions which should be considered analyzed after analyzing the
285  /// given root function.
286  void HandleCode(Decl *D, AnalysisMode Mode,
287                  ExprEngine::InliningModes IMode = ExprEngine::Inline_None,
288                  SetOfConstDecls *VisitedCallees = 0);
289
290  void RunPathSensitiveChecks(Decl *D,
291                              ExprEngine::InliningModes IMode,
292                              SetOfConstDecls *VisitedCallees);
293  void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
294                        ExprEngine::InliningModes IMode,
295                        SetOfConstDecls *VisitedCallees);
296
297  /// Visitors for the RecursiveASTVisitor.
298  bool shouldWalkTypesOfTypeLocs() const { return false; }
299
300  /// Handle callbacks for arbitrary Decls.
301  bool VisitDecl(Decl *D) {
302    AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
303    if (Mode & AM_Syntax)
304      checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
305    return true;
306  }
307
308  bool VisitFunctionDecl(FunctionDecl *FD) {
309    IdentifierInfo *II = FD->getIdentifier();
310    if (II && II->getName().startswith("__inline"))
311      return true;
312
313    // We skip function template definitions, as their semantics is
314    // only determined when they are instantiated.
315    if (FD->isThisDeclarationADefinition() &&
316        !FD->isDependentContext()) {
317      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
318      HandleCode(FD, RecVisitorMode);
319    }
320    return true;
321  }
322
323  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
324    if (MD->isThisDeclarationADefinition()) {
325      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
326      HandleCode(MD, RecVisitorMode);
327    }
328    return true;
329  }
330
331private:
332  void storeTopLevelDecls(DeclGroupRef DG);
333
334  /// \brief Check if we should skip (not analyze) the given function.
335  AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
336
337};
338} // end anonymous namespace
339
340
341//===----------------------------------------------------------------------===//
342// AnalysisConsumer implementation.
343//===----------------------------------------------------------------------===//
344llvm::Timer* AnalysisConsumer::TUTotalTimer = 0;
345
346bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
347  storeTopLevelDecls(DG);
348  return true;
349}
350
351void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
352  storeTopLevelDecls(DG);
353}
354
355void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
356  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
357
358    // Skip ObjCMethodDecl, wait for the objc container to avoid
359    // analyzing twice.
360    if (isa<ObjCMethodDecl>(*I))
361      continue;
362
363    LocalTUDecls.push_back(*I);
364  }
365}
366
367static bool shouldSkipFunction(CallGraphNode *N,
368                             SmallPtrSet<CallGraphNode*,24> Visited,
369                             SmallPtrSet<CallGraphNode*,24> VisitedAsTopLevel) {
370  if (VisitedAsTopLevel.count(N))
371    return true;
372
373  // We want to re-analyse the functions as top level in the following cases:
374  // - The 'init' methods should be reanalyzed because
375  //   ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
376  //   'nil' and unless we analyze the 'init' functions as top level, we will
377  //   not catch errors within defensive code.
378  // - We want to reanalyze all ObjC methods as top level to report Retain
379  //   Count naming convention errors more aggressively.
380  if (isa<ObjCMethodDecl>(N->getDecl()))
381    return false;
382
383  // Otherwise, if we visited the function before, do not reanalyze it.
384  return Visited.count(N);
385}
386
387ExprEngine::InliningModes
388AnalysisConsumer::getInliningModeForFunction(CallGraphNode *N,
389                                       SmallPtrSet<CallGraphNode*,24> Visited) {
390  ExprEngine::InliningModes HowToInline =
391      (Mgr->shouldInlineCall()) ? ExprEngine::Inline_All :
392                                  ExprEngine::Inline_None;
393
394  // We want to reanalyze all ObjC methods as top level to report Retain
395  // Count naming convention errors more aggressively. But we can turn off
396  // inlining when reanalyzing an already inlined function.
397  if (Visited.count(N)) {
398    assert(isa<ObjCMethodDecl>(N->getDecl()) &&
399           "We are only reanalyzing ObjCMethods.");
400    ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(N->getDecl());
401    if (ObjCM->getMethodFamily() != OMF_init)
402      HowToInline = ExprEngine::Inline_None;
403  }
404
405  return HowToInline;
406}
407
408void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
409  // Otherwise, use the Callgraph to derive the order.
410  // Build the Call Graph.
411  CallGraph CG;
412
413  // Add all the top level declarations to the graph.
414  // Note: CallGraph can trigger deserialization of more items from a pch
415  // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
416  // We rely on random access to add the initially processed Decls to CG.
417  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
418    CG.addToCallGraph(LocalTUDecls[i]);
419  }
420
421  // Find the top level nodes - children of root + the unreachable (parentless)
422  // nodes.
423  llvm::SmallVector<CallGraphNode*, 24> TopLevelFunctions;
424  for (CallGraph::nodes_iterator TI = CG.parentless_begin(),
425                                 TE = CG.parentless_end(); TI != TE; ++TI) {
426    TopLevelFunctions.push_back(*TI);
427    NumFunctionTopLevel++;
428  }
429  CallGraphNode *Entry = CG.getRoot();
430  for (CallGraphNode::iterator I = Entry->begin(),
431                               E = Entry->end(); I != E; ++I) {
432    TopLevelFunctions.push_back(*I);
433    NumFunctionTopLevel++;
434  }
435
436  // Make sure the nodes are sorted in order reverse of their definition in the
437  // translation unit. This step is very important for performance. It ensures
438  // that we analyze the root functions before the externally available
439  // subroutines.
440  std::deque<CallGraphNode*> BFSQueue;
441  for (llvm::SmallVector<CallGraphNode*, 24>::reverse_iterator
442         TI = TopLevelFunctions.rbegin(), TE = TopLevelFunctions.rend();
443         TI != TE; ++TI)
444    BFSQueue.push_back(*TI);
445
446  // BFS over all of the functions, while skipping the ones inlined into
447  // the previously processed functions. Use external Visited set, which is
448  // also modified when we inline a function.
449  SmallPtrSet<CallGraphNode*,24> Visited;
450  SmallPtrSet<CallGraphNode*,24> VisitedAsTopLevel;
451  while(!BFSQueue.empty()) {
452    CallGraphNode *N = BFSQueue.front();
453    BFSQueue.pop_front();
454
455    // Push the children into the queue.
456    for (CallGraphNode::const_iterator CI = N->begin(),
457         CE = N->end(); CI != CE; ++CI) {
458      if (!shouldSkipFunction(*CI, Visited, VisitedAsTopLevel))
459        BFSQueue.push_back(*CI);
460    }
461
462    // Skip the functions which have been processed already or previously
463    // inlined.
464    if (shouldSkipFunction(N, Visited, VisitedAsTopLevel))
465      continue;
466
467    // Analyze the function.
468    SetOfConstDecls VisitedCallees;
469    Decl *D = N->getDecl();
470    assert(D);
471
472    HandleCode(D, AM_Path, getInliningModeForFunction(N, 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      CallGraphNode *VN = CG.getNode(*I);
479      if (VN)
480        Visited.insert(VN);
481    }
482    VisitedAsTopLevel.insert(N);
483  }
484}
485
486void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
487  // Don't run the actions if an error has occurred with parsing the file.
488  DiagnosticsEngine &Diags = PP.getDiagnostics();
489  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
490    return;
491
492  {
493    if (TUTotalTimer) TUTotalTimer->startTimer();
494
495    // Introduce a scope to destroy BR before Mgr.
496    BugReporter BR(*Mgr);
497    TranslationUnitDecl *TU = C.getTranslationUnitDecl();
498    checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
499
500    // Run the AST-only checks using the order in which functions are defined.
501    // If inlining is not turned on, use the simplest function order for path
502    // sensitive analyzes as well.
503    RecVisitorMode = AM_Syntax;
504    if (!Mgr->shouldInlineCall())
505      RecVisitorMode |= AM_Path;
506    RecVisitorBR = &BR;
507
508    // Process all the top level declarations.
509    //
510    // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
511    // entries.  Thus we don't use an iterator, but rely on LocalTUDecls
512    // random access.  By doing so, we automatically compensate for iterators
513    // possibly being invalidated, although this is a bit slower.
514    const unsigned LocalTUDeclsSize = LocalTUDecls.size();
515    for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
516      TraverseDecl(LocalTUDecls[i]);
517    }
518
519    if (Mgr->shouldInlineCall())
520      HandleDeclsCallGraph(LocalTUDeclsSize);
521
522    // After all decls handled, run checkers on the entire TranslationUnit.
523    checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
524
525    RecVisitorBR = 0;
526  }
527
528  // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
529  // FIXME: This should be replaced with something that doesn't rely on
530  // side-effects in PathDiagnosticConsumer's destructor. This is required when
531  // used with option -disable-free.
532  Mgr.reset(NULL);
533
534  if (TUTotalTimer) TUTotalTimer->stopTimer();
535
536  // Count how many basic blocks we have not covered.
537  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
538  if (NumBlocksInAnalyzedFunctions > 0)
539    PercentReachableBlocks =
540      (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
541        NumBlocksInAnalyzedFunctions;
542
543}
544
545static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
546  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
547    WL.push_back(BD);
548
549  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
550       I!=E; ++I)
551    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
552      FindBlocks(DC, WL);
553}
554
555static std::string getFunctionName(const Decl *D) {
556  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
557    return ID->getSelector().getAsString();
558  }
559  if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
560    IdentifierInfo *II = ND->getIdentifier();
561    if (II)
562      return II->getName();
563  }
564  return "";
565}
566
567AnalysisConsumer::AnalysisMode
568AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
569  if (!Opts->AnalyzeSpecificFunction.empty() &&
570      getFunctionName(D) != Opts->AnalyzeSpecificFunction)
571    return AM_None;
572
573  // Unless -analyze-all is specified, treat decls differently depending on
574  // where they came from:
575  // - Main source file: run both path-sensitive and non-path-sensitive checks.
576  // - Header files: run non-path-sensitive checks only.
577  // - System headers: don't run any checks.
578  SourceManager &SM = Ctx->getSourceManager();
579  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
580  if (!Opts->AnalyzeAll && !SM.isFromMainFile(SL)) {
581    if (SL.isInvalid() || SM.isInSystemHeader(SL))
582      return AM_None;
583    return Mode & ~AM_Path;
584  }
585
586  return Mode;
587}
588
589void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
590                                  ExprEngine::InliningModes IMode,
591                                  SetOfConstDecls *VisitedCallees) {
592  Mode = getModeForDecl(D, Mode);
593  if (Mode == AM_None)
594    return;
595
596  DisplayFunction(D, Mode);
597  CFG *DeclCFG = Mgr->getCFG(D);
598  if (DeclCFG) {
599    unsigned CFGSize = DeclCFG->size();
600    MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
601  }
602
603
604  // Clear the AnalysisManager of old AnalysisDeclContexts.
605  Mgr->ClearContexts();
606
607  // Dispatch on the actions.
608  SmallVector<Decl*, 10> WL;
609  WL.push_back(D);
610
611  if (D->hasBody() && Opts->AnalyzeNestedBlocks)
612    FindBlocks(cast<DeclContext>(D), WL);
613
614  BugReporter BR(*Mgr);
615  for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
616       WI != WE; ++WI)
617    if ((*WI)->hasBody()) {
618      if (Mode & AM_Syntax)
619        checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
620      if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
621        RunPathSensitiveChecks(*WI, IMode, VisitedCallees);
622        NumFunctionsAnalyzed++;
623      }
624    }
625}
626
627//===----------------------------------------------------------------------===//
628// Path-sensitive checking.
629//===----------------------------------------------------------------------===//
630
631void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
632                                        ExprEngine::InliningModes IMode,
633                                        SetOfConstDecls *VisitedCallees) {
634  // Construct the analysis engine.  First check if the CFG is valid.
635  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
636  if (!Mgr->getCFG(D))
637    return;
638
639  // See if the LiveVariables analysis scales.
640  if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
641    return;
642
643  ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
644
645  // Set the graph auditor.
646  OwningPtr<ExplodedNode::Auditor> Auditor;
647  if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
648    Auditor.reset(CreateUbiViz());
649    ExplodedNode::SetAuditor(Auditor.get());
650  }
651
652  // Execute the worklist algorithm.
653  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
654                      Mgr->options.MaxNodes);
655
656  // Release the auditor (if any) so that it doesn't monitor the graph
657  // created BugReporter.
658  ExplodedNode::SetAuditor(0);
659
660  // Visualize the exploded graph.
661  if (Mgr->options.visualizeExplodedGraphWithGraphViz)
662    Eng.ViewGraph(Mgr->options.TrimGraph);
663
664  // Display warnings.
665  Eng.getBugReporter().FlushReports();
666}
667
668void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
669                                              ExprEngine::InliningModes IMode,
670                                              SetOfConstDecls *Visited) {
671
672  switch (Mgr->getLangOpts().getGC()) {
673  case LangOptions::NonGC:
674    ActionExprEngine(D, false, IMode, Visited);
675    break;
676
677  case LangOptions::GCOnly:
678    ActionExprEngine(D, true, IMode, Visited);
679    break;
680
681  case LangOptions::HybridGC:
682    ActionExprEngine(D, false, IMode, Visited);
683    ActionExprEngine(D, true, IMode, Visited);
684    break;
685  }
686}
687
688//===----------------------------------------------------------------------===//
689// AnalysisConsumer creation.
690//===----------------------------------------------------------------------===//
691
692ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
693                                          const std::string& outDir,
694                                          AnalyzerOptionsRef opts,
695                                          ArrayRef<std::string> plugins) {
696  // Disable the effects of '-Werror' when using the AnalysisConsumer.
697  pp.getDiagnostics().setWarningsAsErrors(false);
698
699  return new AnalysisConsumer(pp, outDir, opts, plugins);
700}
701
702//===----------------------------------------------------------------------===//
703// Ubigraph Visualization.  FIXME: Move to separate file.
704//===----------------------------------------------------------------------===//
705
706namespace {
707
708class UbigraphViz : public ExplodedNode::Auditor {
709  OwningPtr<raw_ostream> Out;
710  llvm::sys::Path Dir, Filename;
711  unsigned Cntr;
712
713  typedef llvm::DenseMap<void*,unsigned> VMap;
714  VMap M;
715
716public:
717  UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
718              llvm::sys::Path& filename);
719
720  ~UbigraphViz();
721
722  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
723};
724
725} // end anonymous namespace
726
727static ExplodedNode::Auditor* CreateUbiViz() {
728  std::string ErrMsg;
729
730  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
731  if (!ErrMsg.empty())
732    return 0;
733
734  llvm::sys::Path Filename = Dir;
735  Filename.appendComponent("llvm_ubi");
736  Filename.makeUnique(true,&ErrMsg);
737
738  if (!ErrMsg.empty())
739    return 0;
740
741  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
742
743  OwningPtr<llvm::raw_fd_ostream> Stream;
744  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
745
746  if (!ErrMsg.empty())
747    return 0;
748
749  return new UbigraphViz(Stream.take(), Dir, Filename);
750}
751
752void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
753
754  assert (Src != Dst && "Self-edges are not allowed.");
755
756  // Lookup the Src.  If it is a new node, it's a root.
757  VMap::iterator SrcI= M.find(Src);
758  unsigned SrcID;
759
760  if (SrcI == M.end()) {
761    M[Src] = SrcID = Cntr++;
762    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
763  }
764  else
765    SrcID = SrcI->second;
766
767  // Lookup the Dst.
768  VMap::iterator DstI= M.find(Dst);
769  unsigned DstID;
770
771  if (DstI == M.end()) {
772    M[Dst] = DstID = Cntr++;
773    *Out << "('vertex', " << DstID << ")\n";
774  }
775  else {
776    // We have hit DstID before.  Change its style to reflect a cache hit.
777    DstID = DstI->second;
778    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
779  }
780
781  // Add the edge.
782  *Out << "('edge', " << SrcID << ", " << DstID
783       << ", ('arrow','true'), ('oriented', 'true'))\n";
784}
785
786UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
787                         llvm::sys::Path& filename)
788  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
789
790  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
791  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
792          " ('size', '1.5'))\n";
793}
794
795UbigraphViz::~UbigraphViz() {
796  Out.reset(0);
797  llvm::errs() << "Running 'ubiviz' program... ";
798  std::string ErrMsg;
799  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
800  std::vector<const char*> args;
801  args.push_back(Ubiviz.c_str());
802  args.push_back(Filename.c_str());
803  args.push_back(0);
804
805  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
806    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
807  }
808
809  // Delete the directory.
810  Dir.eraseFromDisk(true);
811}
812