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/Path.h"
44 #include "llvm/Support/Program.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
49 using namespace clang;
51 using llvm::SmallPtrSet;
53 static ExplodedNode::Auditor* CreateUbiViz();
55 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
56 STATISTIC(NumFunctionsAnalyzed,
57 "The # of functions and blocks analyzed (as top level "
58 "with inlining turned on).");
59 STATISTIC(NumBlocksInAnalyzedFunctions,
60 "The # of basic blocks in the analyzed functions.");
61 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
62 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
64 //===----------------------------------------------------------------------===//
65 // Special PathDiagnosticConsumers.
66 //===----------------------------------------------------------------------===//
68 static 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);
78 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
79 DiagnosticsEngine &Diag;
81 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) : Diag(Diag) {}
82 virtual ~ClangDiagPathDiagConsumer() {}
83 virtual StringRef getName() const { return "ClangDiags"; }
84 virtual PathGenerationScheme getGenerationScheme() const { return None; }
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) {
101 unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning,
103 SourceLocation L = PD->getLocation().asLocation();
104 DiagnosticBuilder diagBuilder = Diag.Report(L, ErrorDiag);
106 // Get the ranges from the last point in the path.
107 ArrayRef<SourceRange> Ranges = PD->path.back()->getRanges();
109 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
110 E = Ranges.end(); I != E; ++I) {
116 } // end anonymous namespace
118 //===----------------------------------------------------------------------===//
119 // AnalysisConsumer declaration.
120 //===----------------------------------------------------------------------===//
124 class AnalysisConsumer : public ASTConsumer,
125 public RecursiveASTVisitor<AnalysisConsumer> {
131 typedef unsigned AnalysisMode;
133 /// Mode of the analyzes while recursively visiting Decls.
134 AnalysisMode RecVisitorMode;
135 /// Bug Reporter to use while recursively visiting Decls.
136 BugReporter *RecVisitorBR;
140 const Preprocessor &PP;
141 const std::string OutDir;
142 AnalyzerOptionsRef Opts;
143 ArrayRef<std::string> Plugins;
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;
152 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
153 PathDiagnosticConsumers PathConsumers;
155 StoreManagerCreator CreateStoreMgr;
156 ConstraintManagerCreator CreateConstraintMgr;
158 OwningPtr<CheckerManager> checkerMgr;
159 OwningPtr<AnalysisManager> Mgr;
161 /// Time the analyzes time of each translation unit.
162 static llvm::Timer* TUTotalTimer;
164 /// The information about analyzed functions shared throughout the
165 /// translation unit.
166 FunctionSummariesTy FunctionSummaries;
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");
181 ~AnalysisConsumer() {
182 if (Opts->PrintStats)
186 void DigestAnalyzerOptions() {
187 // Create the PathDiagnosticConsumer.
188 PathConsumers.push_back(new ClangDiagPathDiagConsumer(PP.getDiagnostics()));
190 if (!OutDir.empty()) {
191 switch (Opts->AnalysisDiagOpt) {
193 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
194 case PD_##NAME: CREATEFN(*Opts.getPtr(), PathConsumers, OutDir, PP);\
196 #include "clang/StaticAnalyzer/Core/Analyses.def"
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);
204 // Create the analyzer component creators.
205 switch (Opts->AnalysisStoreOpt) {
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"
213 switch (Opts->AnalysisConstraintsOpt) {
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"
222 void DisplayFunction(const Decl *D, AnalysisMode Mode,
223 ExprEngine::InliningModes IMode) {
224 if (!Opts->AnalyzerDisplayProgress)
227 SourceManager &SM = Mgr->getASTContext().getSourceManager();
228 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
230 llvm::errs() << "ANALYZE";
232 if (Mode == AM_Syntax)
233 llvm::errs() << " (Syntax)";
234 else if (Mode == AM_Path) {
235 llvm::errs() << " (Path, ";
237 case ExprEngine::Inline_Minimal:
238 llvm::errs() << " Inline_Minimal";
240 case ExprEngine::Inline_Regular:
241 llvm::errs() << " Inline_Regular";
247 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
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';
254 else if (isa<BlockDecl>(D)) {
255 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
256 << Loc.getColumn() << '\n';
258 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
259 Selector S = MD->getSelector();
260 llvm::errs() << ' ' << S.getAsString();
265 virtual void Initialize(ASTContext &Context) {
267 checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
268 PP.getDiagnostics()));
269 Mgr.reset(new AnalysisManager(*Ctx,
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);
284 virtual void HandleTranslationUnit(ASTContext &C);
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);
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);
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);
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);
313 /// Visitors for the RecursiveASTVisitor.
314 bool shouldWalkTypesOfTypeLocs() const { return false; }
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);
324 bool VisitFunctionDecl(FunctionDecl *FD) {
325 IdentifierInfo *II = FD->getIdentifier();
326 if (II && II->getName().startswith("__inline"))
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);
339 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
340 if (MD->isThisDeclarationADefinition()) {
341 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
342 HandleCode(MD, RecVisitorMode);
347 bool VisitBlockDecl(BlockDecl *BD) {
349 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
350 HandleCode(BD, RecVisitorMode);
356 void storeTopLevelDecls(DeclGroupRef DG);
358 /// \brief Check if we should skip (not analyze) the given function.
359 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
362 } // end anonymous namespace
365 //===----------------------------------------------------------------------===//
366 // AnalysisConsumer implementation.
367 //===----------------------------------------------------------------------===//
368 llvm::Timer* AnalysisConsumer::TUTotalTimer = 0;
370 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
371 storeTopLevelDecls(DG);
375 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
376 storeTopLevelDecls(DG);
379 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
380 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
382 // Skip ObjCMethodDecl, wait for the objc container to avoid
384 if (isa<ObjCMethodDecl>(*I))
387 LocalTUDecls.push_back(*I);
391 static bool shouldSkipFunction(const Decl *D,
392 SetOfConstDecls Visited,
393 SetOfConstDecls VisitedAsTopLevel) {
394 if (VisitedAsTopLevel.count(D))
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))
407 // Otherwise, if we visited the function before, do not reanalyze it.
408 return Visited.count(D);
411 ExprEngine::InliningModes
412 AnalysisConsumer::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;
425 return ExprEngine::Inline_Regular;
428 void 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.
434 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
435 CG.addToCallGraph(LocalTUDecls[i]);
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
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++;
451 CallGraphNode *N = *I;
452 Decl *D = N->getDecl();
454 // Skip the abstract root node.
458 // Skip the functions which have been processed already or previously
460 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
463 // Analyze the function.
464 SetOfConstDecls VisitedCallees;
466 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
467 (Mgr->options.InliningMode == All ? 0 : &VisitedCallees));
469 // Add the visited callees to the global visited set.
470 for (SetOfConstDecls::iterator I = VisitedCallees.begin(),
471 E = VisitedCallees.end(); I != E; ++I) {
474 VisitedAsTopLevel.insert(D);
478 void 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())
485 if (TUTotalTimer) TUTotalTimer->startTimer();
487 // Introduce a scope to destroy BR before Mgr.
488 BugReporter BR(*Mgr);
489 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
490 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
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;
500 // Process all the top level declarations.
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]);
511 if (Mgr->shouldInlineCall())
512 HandleDeclsCallGraph(LocalTUDeclsSize);
514 // After all decls handled, run checkers on the entire TranslationUnit.
515 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
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.
526 if (TUTotalTimer) TUTotalTimer->stopTimer();
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;
537 static std::string getFunctionName(const Decl *D) {
538 if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
539 return ID->getSelector().getAsString();
541 if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
542 IdentifierInfo *II = ND->getIdentifier();
544 return II->getName();
549 AnalysisConsumer::AnalysisMode
550 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
551 if (!Opts->AnalyzeSpecificFunction.empty() &&
552 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
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))
565 return Mode & ~AM_Path;
571 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
572 ExprEngine::InliningModes IMode,
573 SetOfConstDecls *VisitedCallees) {
576 Mode = getModeForDecl(D, Mode);
580 DisplayFunction(D, Mode, IMode);
581 CFG *DeclCFG = Mgr->getCFG(D);
583 unsigned CFGSize = DeclCFG->size();
584 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
587 // Clear the AnalysisManager of old AnalysisDeclContexts.
588 Mgr->ClearContexts();
589 BugReporter BR(*Mgr);
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++;
600 //===----------------------------------------------------------------------===//
601 // Path-sensitive checking.
602 //===----------------------------------------------------------------------===//
604 void 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.
612 // See if the LiveVariables analysis scales.
613 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
616 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
618 // Set the graph auditor.
619 OwningPtr<ExplodedNode::Auditor> Auditor;
620 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
621 Auditor.reset(CreateUbiViz());
622 ExplodedNode::SetAuditor(Auditor.get());
625 // Execute the worklist algorithm.
626 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
627 Mgr->options.getMaxNodesPerTopLevelFunction());
629 // Release the auditor (if any) so that it doesn't monitor the graph
630 // created BugReporter.
631 ExplodedNode::SetAuditor(0);
633 // Visualize the exploded graph.
634 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
635 Eng.ViewGraph(Mgr->options.TrimGraph);
638 Eng.getBugReporter().FlushReports();
641 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
642 ExprEngine::InliningModes IMode,
643 SetOfConstDecls *Visited) {
645 switch (Mgr->getLangOpts().getGC()) {
646 case LangOptions::NonGC:
647 ActionExprEngine(D, false, IMode, Visited);
650 case LangOptions::GCOnly:
651 ActionExprEngine(D, true, IMode, Visited);
654 case LangOptions::HybridGC:
655 ActionExprEngine(D, false, IMode, Visited);
656 ActionExprEngine(D, true, IMode, Visited);
661 //===----------------------------------------------------------------------===//
662 // AnalysisConsumer creation.
663 //===----------------------------------------------------------------------===//
665 ASTConsumer* 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);
672 return new AnalysisConsumer(pp, outDir, opts, plugins);
675 //===----------------------------------------------------------------------===//
676 // Ubigraph Visualization. FIXME: Move to separate file.
677 //===----------------------------------------------------------------------===//
681 class UbigraphViz : public ExplodedNode::Auditor {
682 OwningPtr<raw_ostream> Out;
683 llvm::sys::Path Dir, Filename;
686 typedef llvm::DenseMap<void*,unsigned> VMap;
690 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
691 llvm::sys::Path& filename);
695 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
698 } // end anonymous namespace
700 static ExplodedNode::Auditor* CreateUbiViz() {
703 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
707 llvm::sys::Path Filename = Dir;
708 Filename.appendComponent("llvm_ubi");
709 Filename.makeUnique(true,&ErrMsg);
714 llvm::errs() << "Writing '" << Filename.str() << "'.\n";
716 OwningPtr<llvm::raw_fd_ostream> Stream;
717 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
722 return new UbigraphViz(Stream.take(), Dir, Filename);
725 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
727 assert (Src != Dst && "Self-edges are not allowed.");
729 // Lookup the Src. If it is a new node, it's a root.
730 VMap::iterator SrcI= M.find(Src);
733 if (SrcI == M.end()) {
734 M[Src] = SrcID = Cntr++;
735 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
738 SrcID = SrcI->second;
741 VMap::iterator DstI= M.find(Dst);
744 if (DstI == M.end()) {
745 M[Dst] = DstID = Cntr++;
746 *Out << "('vertex', " << DstID << ")\n";
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";
755 *Out << "('edge', " << SrcID << ", " << DstID
756 << ", ('arrow','true'), ('oriented', 'true'))\n";
759 UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
760 llvm::sys::Path& filename)
761 : Out(out), Dir(dir), Filename(filename), Cntr(0) {
763 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
764 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
765 " ('size', '1.5'))\n";
768 UbigraphViz::~UbigraphViz() {
770 llvm::errs() << "Running 'ubiviz' program... ";
772 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
773 std::vector<const char*> args;
774 args.push_back(Ubiviz.c_str());
775 args.push_back(Filename.c_str());
778 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
779 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
782 // Delete the directory.
783 Dir.eraseFromDisk(true);