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