1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // "Meta" ASTConsumer for running different source analyses.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "AnalysisConsumer"
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/FileSystem.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Program.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
50 using namespace clang;
52 using llvm::SmallPtrSet;
54 static ExplodedNode::Auditor* CreateUbiViz();
56 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
57 STATISTIC(NumFunctionsAnalyzed,
58 "The # of functions and blocks analyzed (as top level "
59 "with inlining turned on).");
60 STATISTIC(NumBlocksInAnalyzedFunctions,
61 "The # of basic blocks in the analyzed functions.");
62 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
63 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
65 //===----------------------------------------------------------------------===//
66 // Special PathDiagnosticConsumers.
67 //===----------------------------------------------------------------------===//
69 void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
70 PathDiagnosticConsumers &C,
71 const std::string &prefix,
72 const Preprocessor &PP) {
73 createHTMLDiagnosticConsumer(AnalyzerOpts, C,
74 llvm::sys::path::parent_path(prefix), PP);
75 createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
78 void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
79 PathDiagnosticConsumers &C,
80 const std::string &Prefix,
81 const clang::Preprocessor &PP) {
82 llvm_unreachable("'text' consumer should be enabled on ClangDiags");
86 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
87 DiagnosticsEngine &Diag;
90 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
91 : Diag(Diag), IncludePath(false) {}
92 virtual ~ClangDiagPathDiagConsumer() {}
93 virtual StringRef getName() const { return "ClangDiags"; }
95 virtual bool supportsLogicalOpControlFlow() const { return true; }
96 virtual bool supportsCrossFileDiagnostics() const { return true; }
98 virtual PathGenerationScheme getGenerationScheme() const {
99 return IncludePath ? Minimal : None;
106 void emitDiag(SourceLocation L, unsigned DiagID,
107 ArrayRef<SourceRange> Ranges) {
108 DiagnosticBuilder DiagBuilder = Diag.Report(L, DiagID);
110 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
116 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
117 FilesMade *filesMade) {
118 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
119 E = Diags.end(); I != E; ++I) {
120 const PathDiagnostic *PD = *I;
121 StringRef desc = PD->getShortDescription();
122 SmallString<512> TmpStr;
123 llvm::raw_svector_ostream Out(TmpStr);
124 for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) {
131 unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning,
133 SourceLocation L = PD->getLocation().asLocation();
134 emitDiag(L, ErrorDiag, PD->path.back()->getRanges());
139 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
140 for (PathPieces::const_iterator PI = FlatPath.begin(),
143 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note,
146 SourceLocation NoteLoc = (*PI)->getLocation().asLocation();
147 emitDiag(NoteLoc, NoteID, (*PI)->getRanges());
152 } // end anonymous namespace
154 //===----------------------------------------------------------------------===//
155 // AnalysisConsumer declaration.
156 //===----------------------------------------------------------------------===//
160 class AnalysisConsumer : public ASTConsumer,
161 public RecursiveASTVisitor<AnalysisConsumer> {
167 typedef unsigned AnalysisMode;
169 /// Mode of the analyzes while recursively visiting Decls.
170 AnalysisMode RecVisitorMode;
171 /// Bug Reporter to use while recursively visiting Decls.
172 BugReporter *RecVisitorBR;
176 const Preprocessor &PP;
177 const std::string OutDir;
178 AnalyzerOptionsRef Opts;
179 ArrayRef<std::string> Plugins;
181 /// \brief Stores the declarations from the local translation unit.
182 /// Note, we pre-compute the local declarations at parse time as an
183 /// optimization to make sure we do not deserialize everything from disk.
184 /// The local declaration to all declarations ratio might be very small when
185 /// working with a PCH file.
186 SetOfDecls LocalTUDecls;
188 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
189 PathDiagnosticConsumers PathConsumers;
191 StoreManagerCreator CreateStoreMgr;
192 ConstraintManagerCreator CreateConstraintMgr;
194 OwningPtr<CheckerManager> checkerMgr;
195 OwningPtr<AnalysisManager> Mgr;
197 /// Time the analyzes time of each translation unit.
198 static llvm::Timer* TUTotalTimer;
200 /// The information about analyzed functions shared throughout the
201 /// translation unit.
202 FunctionSummariesTy FunctionSummaries;
204 AnalysisConsumer(const Preprocessor& pp,
205 const std::string& outdir,
206 AnalyzerOptionsRef opts,
207 ArrayRef<std::string> plugins)
208 : RecVisitorMode(0), RecVisitorBR(0),
209 Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins) {
210 DigestAnalyzerOptions();
211 if (Opts->PrintStats) {
212 llvm::EnableStatistics();
213 TUTotalTimer = new llvm::Timer("Analyzer Total Time");
217 ~AnalysisConsumer() {
218 if (Opts->PrintStats)
222 void DigestAnalyzerOptions() {
223 // Create the PathDiagnosticConsumer.
224 ClangDiagPathDiagConsumer *clangDiags =
225 new ClangDiagPathDiagConsumer(PP.getDiagnostics());
226 PathConsumers.push_back(clangDiags);
228 if (Opts->AnalysisDiagOpt == PD_TEXT) {
229 clangDiags->enablePaths();
231 } else if (!OutDir.empty()) {
232 switch (Opts->AnalysisDiagOpt) {
234 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
235 case PD_##NAME: CREATEFN(*Opts.getPtr(), PathConsumers, OutDir, PP);\
237 #include "clang/StaticAnalyzer/Core/Analyses.def"
241 // Create the analyzer component creators.
242 switch (Opts->AnalysisStoreOpt) {
244 llvm_unreachable("Unknown store manager.");
245 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
246 case NAME##Model: CreateStoreMgr = CREATEFN; break;
247 #include "clang/StaticAnalyzer/Core/Analyses.def"
250 switch (Opts->AnalysisConstraintsOpt) {
252 llvm_unreachable("Unknown constraint manager.");
253 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
254 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
255 #include "clang/StaticAnalyzer/Core/Analyses.def"
259 void DisplayFunction(const Decl *D, AnalysisMode Mode,
260 ExprEngine::InliningModes IMode) {
261 if (!Opts->AnalyzerDisplayProgress)
264 SourceManager &SM = Mgr->getASTContext().getSourceManager();
265 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
267 llvm::errs() << "ANALYZE";
269 if (Mode == AM_Syntax)
270 llvm::errs() << " (Syntax)";
271 else if (Mode == AM_Path) {
272 llvm::errs() << " (Path, ";
274 case ExprEngine::Inline_Minimal:
275 llvm::errs() << " Inline_Minimal";
277 case ExprEngine::Inline_Regular:
278 llvm::errs() << " Inline_Regular";
284 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
286 llvm::errs() << ": " << Loc.getFilename();
287 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
288 const NamedDecl *ND = cast<NamedDecl>(D);
289 llvm::errs() << ' ' << *ND << '\n';
291 else if (isa<BlockDecl>(D)) {
292 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
293 << Loc.getColumn() << '\n';
295 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
296 Selector S = MD->getSelector();
297 llvm::errs() << ' ' << S.getAsString();
302 virtual void Initialize(ASTContext &Context) {
304 checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
305 PP.getDiagnostics()));
306 Mgr.reset(new AnalysisManager(*Ctx,
316 /// \brief Store the top level decls in the set to be processed later on.
317 /// (Doing this pre-processing avoids deserialization of data from PCH.)
318 virtual bool HandleTopLevelDecl(DeclGroupRef D);
319 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D);
321 virtual void HandleTranslationUnit(ASTContext &C);
323 /// \brief Determine which inlining mode should be used when this function is
324 /// analyzed. This allows to redefine the default inlining policies when
325 /// analyzing a given function.
326 ExprEngine::InliningModes
327 getInliningModeForFunction(const Decl *D, SetOfConstDecls Visited);
329 /// \brief Build the call graph for all the top level decls of this TU and
330 /// use it to define the order in which the functions should be visited.
331 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
333 /// \brief Run analyzes(syntax or path sensitive) on the given function.
334 /// \param Mode - determines if we are requesting syntax only or path
335 /// sensitive only analysis.
336 /// \param VisitedCallees - The output parameter, which is populated with the
337 /// set of functions which should be considered analyzed after analyzing the
338 /// given root function.
339 void HandleCode(Decl *D, AnalysisMode Mode,
340 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
341 SetOfConstDecls *VisitedCallees = 0);
343 void RunPathSensitiveChecks(Decl *D,
344 ExprEngine::InliningModes IMode,
345 SetOfConstDecls *VisitedCallees);
346 void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
347 ExprEngine::InliningModes IMode,
348 SetOfConstDecls *VisitedCallees);
350 /// Visitors for the RecursiveASTVisitor.
351 bool shouldWalkTypesOfTypeLocs() const { return false; }
353 /// Handle callbacks for arbitrary Decls.
354 bool VisitDecl(Decl *D) {
355 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
356 if (Mode & AM_Syntax)
357 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
361 bool VisitFunctionDecl(FunctionDecl *FD) {
362 IdentifierInfo *II = FD->getIdentifier();
363 if (II && II->getName().startswith("__inline"))
366 // We skip function template definitions, as their semantics is
367 // only determined when they are instantiated.
368 if (FD->isThisDeclarationADefinition() &&
369 !FD->isDependentContext()) {
370 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
371 HandleCode(FD, RecVisitorMode);
376 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
377 if (MD->isThisDeclarationADefinition()) {
378 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
379 HandleCode(MD, RecVisitorMode);
384 bool VisitBlockDecl(BlockDecl *BD) {
386 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
387 HandleCode(BD, RecVisitorMode);
393 void storeTopLevelDecls(DeclGroupRef DG);
395 /// \brief Check if we should skip (not analyze) the given function.
396 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
399 } // end anonymous namespace
402 //===----------------------------------------------------------------------===//
403 // AnalysisConsumer implementation.
404 //===----------------------------------------------------------------------===//
405 llvm::Timer* AnalysisConsumer::TUTotalTimer = 0;
407 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
408 storeTopLevelDecls(DG);
412 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
413 storeTopLevelDecls(DG);
416 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
417 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
419 // Skip ObjCMethodDecl, wait for the objc container to avoid
421 if (isa<ObjCMethodDecl>(*I))
424 LocalTUDecls.push_back(*I);
428 static bool shouldSkipFunction(const Decl *D,
429 SetOfConstDecls Visited,
430 SetOfConstDecls VisitedAsTopLevel) {
431 if (VisitedAsTopLevel.count(D))
434 // We want to re-analyse the functions as top level in the following cases:
435 // - The 'init' methods should be reanalyzed because
436 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
437 // 'nil' and unless we analyze the 'init' functions as top level, we will
438 // not catch errors within defensive code.
439 // - We want to reanalyze all ObjC methods as top level to report Retain
440 // Count naming convention errors more aggressively.
441 if (isa<ObjCMethodDecl>(D))
444 // Otherwise, if we visited the function before, do not reanalyze it.
445 return Visited.count(D);
448 ExprEngine::InliningModes
449 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
450 SetOfConstDecls Visited) {
451 // We want to reanalyze all ObjC methods as top level to report Retain
452 // Count naming convention errors more aggressively. But we should tune down
453 // inlining when reanalyzing an already inlined function.
454 if (Visited.count(D)) {
455 assert(isa<ObjCMethodDecl>(D) &&
456 "We are only reanalyzing ObjCMethods.");
457 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
458 if (ObjCM->getMethodFamily() != OMF_init)
459 return ExprEngine::Inline_Minimal;
462 return ExprEngine::Inline_Regular;
465 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
466 // Build the Call Graph by adding all the top level declarations to the graph.
467 // Note: CallGraph can trigger deserialization of more items from a pch
468 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
469 // We rely on random access to add the initially processed Decls to CG.
471 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
472 CG.addToCallGraph(LocalTUDecls[i]);
475 // Walk over all of the call graph nodes in topological order, so that we
476 // analyze parents before the children. Skip the functions inlined into
477 // the previously processed functions. Use external Visited set to identify
478 // inlined functions. The topological order allows the "do not reanalyze
479 // previously inlined function" performance heuristic to be triggered more
481 SetOfConstDecls Visited;
482 SetOfConstDecls VisitedAsTopLevel;
483 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
484 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
485 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
486 NumFunctionTopLevel++;
488 CallGraphNode *N = *I;
489 Decl *D = N->getDecl();
491 // Skip the abstract root node.
495 // Skip the functions which have been processed already or previously
497 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
500 // Analyze the function.
501 SetOfConstDecls VisitedCallees;
503 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
504 (Mgr->options.InliningMode == All ? 0 : &VisitedCallees));
506 // Add the visited callees to the global visited set.
507 for (SetOfConstDecls::iterator I = VisitedCallees.begin(),
508 E = VisitedCallees.end(); I != E; ++I) {
511 VisitedAsTopLevel.insert(D);
515 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
516 // Don't run the actions if an error has occurred with parsing the file.
517 DiagnosticsEngine &Diags = PP.getDiagnostics();
518 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
522 if (TUTotalTimer) TUTotalTimer->startTimer();
524 // Introduce a scope to destroy BR before Mgr.
525 BugReporter BR(*Mgr);
526 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
527 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
529 // Run the AST-only checks using the order in which functions are defined.
530 // If inlining is not turned on, use the simplest function order for path
531 // sensitive analyzes as well.
532 RecVisitorMode = AM_Syntax;
533 if (!Mgr->shouldInlineCall())
534 RecVisitorMode |= AM_Path;
537 // Process all the top level declarations.
539 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
540 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
541 // random access. By doing so, we automatically compensate for iterators
542 // possibly being invalidated, although this is a bit slower.
543 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
544 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
545 TraverseDecl(LocalTUDecls[i]);
548 if (Mgr->shouldInlineCall())
549 HandleDeclsCallGraph(LocalTUDeclsSize);
551 // After all decls handled, run checkers on the entire TranslationUnit.
552 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
557 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
558 // FIXME: This should be replaced with something that doesn't rely on
559 // side-effects in PathDiagnosticConsumer's destructor. This is required when
560 // used with option -disable-free.
563 if (TUTotalTimer) TUTotalTimer->stopTimer();
565 // Count how many basic blocks we have not covered.
566 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
567 if (NumBlocksInAnalyzedFunctions > 0)
568 PercentReachableBlocks =
569 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
570 NumBlocksInAnalyzedFunctions;
574 static std::string getFunctionName(const Decl *D) {
575 if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
576 return ID->getSelector().getAsString();
578 if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
579 IdentifierInfo *II = ND->getIdentifier();
581 return II->getName();
586 AnalysisConsumer::AnalysisMode
587 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
588 if (!Opts->AnalyzeSpecificFunction.empty() &&
589 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
592 // Unless -analyze-all is specified, treat decls differently depending on
593 // where they came from:
594 // - Main source file: run both path-sensitive and non-path-sensitive checks.
595 // - Header files: run non-path-sensitive checks only.
596 // - System headers: don't run any checks.
597 SourceManager &SM = Ctx->getSourceManager();
598 SourceLocation SL = SM.getExpansionLoc(D->getLocation());
599 if (!Opts->AnalyzeAll && !SM.isInMainFile(SL)) {
600 if (SL.isInvalid() || SM.isInSystemHeader(SL))
602 return Mode & ~AM_Path;
608 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
609 ExprEngine::InliningModes IMode,
610 SetOfConstDecls *VisitedCallees) {
613 Mode = getModeForDecl(D, Mode);
617 DisplayFunction(D, Mode, IMode);
618 CFG *DeclCFG = Mgr->getCFG(D);
620 unsigned CFGSize = DeclCFG->size();
621 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
624 // Clear the AnalysisManager of old AnalysisDeclContexts.
625 Mgr->ClearContexts();
626 BugReporter BR(*Mgr);
628 if (Mode & AM_Syntax)
629 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
630 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
631 RunPathSensitiveChecks(D, IMode, VisitedCallees);
632 if (IMode != ExprEngine::Inline_Minimal)
633 NumFunctionsAnalyzed++;
637 //===----------------------------------------------------------------------===//
638 // Path-sensitive checking.
639 //===----------------------------------------------------------------------===//
641 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
642 ExprEngine::InliningModes IMode,
643 SetOfConstDecls *VisitedCallees) {
644 // Construct the analysis engine. First check if the CFG is valid.
645 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
649 // See if the LiveVariables analysis scales.
650 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
653 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
655 // Set the graph auditor.
656 OwningPtr<ExplodedNode::Auditor> Auditor;
657 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
658 Auditor.reset(CreateUbiViz());
659 ExplodedNode::SetAuditor(Auditor.get());
662 // Execute the worklist algorithm.
663 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
664 Mgr->options.getMaxNodesPerTopLevelFunction());
666 // Release the auditor (if any) so that it doesn't monitor the graph
667 // created BugReporter.
668 ExplodedNode::SetAuditor(0);
670 // Visualize the exploded graph.
671 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
672 Eng.ViewGraph(Mgr->options.TrimGraph);
675 Eng.getBugReporter().FlushReports();
678 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
679 ExprEngine::InliningModes IMode,
680 SetOfConstDecls *Visited) {
682 switch (Mgr->getLangOpts().getGC()) {
683 case LangOptions::NonGC:
684 ActionExprEngine(D, false, IMode, Visited);
687 case LangOptions::GCOnly:
688 ActionExprEngine(D, true, IMode, Visited);
691 case LangOptions::HybridGC:
692 ActionExprEngine(D, false, IMode, Visited);
693 ActionExprEngine(D, true, IMode, Visited);
698 //===----------------------------------------------------------------------===//
699 // AnalysisConsumer creation.
700 //===----------------------------------------------------------------------===//
702 ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
703 const std::string& outDir,
704 AnalyzerOptionsRef opts,
705 ArrayRef<std::string> plugins) {
706 // Disable the effects of '-Werror' when using the AnalysisConsumer.
707 pp.getDiagnostics().setWarningsAsErrors(false);
709 return new AnalysisConsumer(pp, outDir, opts, plugins);
712 //===----------------------------------------------------------------------===//
713 // Ubigraph Visualization. FIXME: Move to separate file.
714 //===----------------------------------------------------------------------===//
718 class UbigraphViz : public ExplodedNode::Auditor {
719 OwningPtr<raw_ostream> Out;
720 std::string Filename;
723 typedef llvm::DenseMap<void*,unsigned> VMap;
727 UbigraphViz(raw_ostream *Out, StringRef Filename);
731 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
734 } // end anonymous namespace
736 static ExplodedNode::Auditor* CreateUbiViz() {
739 llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P);
740 llvm::errs() << "Writing '" << P.str() << "'.\n";
742 OwningPtr<llvm::raw_fd_ostream> Stream;
743 Stream.reset(new llvm::raw_fd_ostream(FD, true));
745 return new UbigraphViz(Stream.take(), P);
748 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
750 assert (Src != Dst && "Self-edges are not allowed.");
752 // Lookup the Src. If it is a new node, it's a root.
753 VMap::iterator SrcI= M.find(Src);
756 if (SrcI == M.end()) {
757 M[Src] = SrcID = Cntr++;
758 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
761 SrcID = SrcI->second;
764 VMap::iterator DstI= M.find(Dst);
767 if (DstI == M.end()) {
768 M[Dst] = DstID = Cntr++;
769 *Out << "('vertex', " << DstID << ")\n";
772 // We have hit DstID before. Change its style to reflect a cache hit.
773 DstID = DstI->second;
774 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
778 *Out << "('edge', " << SrcID << ", " << DstID
779 << ", ('arrow','true'), ('oriented', 'true'))\n";
782 UbigraphViz::UbigraphViz(raw_ostream *Out, StringRef Filename)
783 : Out(Out), Filename(Filename), Cntr(0) {
785 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
786 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
787 " ('size', '1.5'))\n";
790 UbigraphViz::~UbigraphViz() {
792 llvm::errs() << "Running 'ubiviz' program... ";
794 std::string Ubiviz = llvm::sys::FindProgramByName("ubiviz");
795 std::vector<const char*> args;
796 args.push_back(Ubiviz.c_str());
797 args.push_back(Filename.c_str());
800 if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], 0, 0, 0, 0, &ErrMsg)) {
801 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
805 llvm::sys::fs::remove(Filename);