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 #include "AnalysisConsumer.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/Analysis/CFG.h"
21 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
22 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
23 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
24 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/TransferFuncs.h"
29 #include "clang/StaticAnalyzer/Core/PathDiagnosticClients.h"
31 #include "clang/Basic/FileManager.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Frontend/AnalyzerOptions.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Program.h"
38 #include "llvm/ADT/OwningPtr.h"
40 using namespace clang;
43 static ExplodedNode::Auditor* CreateUbiViz();
45 //===----------------------------------------------------------------------===//
46 // Special PathDiagnosticClients.
47 //===----------------------------------------------------------------------===//
49 static PathDiagnosticClient*
50 createPlistHTMLDiagnosticClient(const std::string& prefix,
51 const Preprocessor &PP) {
52 PathDiagnosticClient *PD =
53 createHTMLDiagnosticClient(llvm::sys::path::parent_path(prefix), PP);
54 return createPlistDiagnosticClient(prefix, PP, PD);
57 //===----------------------------------------------------------------------===//
58 // AnalysisConsumer declaration.
59 //===----------------------------------------------------------------------===//
63 class AnalysisConsumer : public ASTConsumer {
66 const Preprocessor &PP;
67 const std::string OutDir;
70 // PD is owned by AnalysisManager.
71 PathDiagnosticClient *PD;
73 StoreManagerCreator CreateStoreMgr;
74 ConstraintManagerCreator CreateConstraintMgr;
76 llvm::OwningPtr<CheckerManager> checkerMgr;
77 llvm::OwningPtr<AnalysisManager> Mgr;
79 AnalysisConsumer(const Preprocessor& pp,
80 const std::string& outdir,
81 const AnalyzerOptions& opts)
82 : Ctx(0), PP(pp), OutDir(outdir),
84 DigestAnalyzerOptions();
87 void DigestAnalyzerOptions() {
88 // Create the PathDiagnosticClient.
89 if (!OutDir.empty()) {
90 switch (Opts.AnalysisDiagOpt) {
92 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
93 case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
94 #include "clang/Frontend/Analyses.def"
96 } else if (Opts.AnalysisDiagOpt == PD_TEXT) {
97 // Create the text client even without a specified output file since
98 // it just uses diagnostic notes.
99 PD = createTextPathDiagnosticClient("", PP);
102 // Create the analyzer component creators.
103 switch (Opts.AnalysisStoreOpt) {
105 assert(0 && "Unknown store manager.");
106 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
107 case NAME##Model: CreateStoreMgr = CREATEFN; break;
108 #include "clang/Frontend/Analyses.def"
111 switch (Opts.AnalysisConstraintsOpt) {
113 assert(0 && "Unknown store manager.");
114 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
115 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
116 #include "clang/Frontend/Analyses.def"
120 void DisplayFunction(const Decl *D) {
121 if (!Opts.AnalyzerDisplayProgress)
124 SourceManager &SM = Mgr->getASTContext().getSourceManager();
125 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
127 llvm::errs() << "ANALYZE: " << Loc.getFilename();
129 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
130 const NamedDecl *ND = cast<NamedDecl>(D);
131 llvm::errs() << ' ' << ND << '\n';
133 else if (isa<BlockDecl>(D)) {
134 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
135 << Loc.getColumn() << '\n';
137 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
138 Selector S = MD->getSelector();
139 llvm::errs() << ' ' << S.getAsString();
144 virtual void Initialize(ASTContext &Context) {
146 checkerMgr.reset(registerCheckers(Opts, PP.getLangOptions(),
147 PP.getDiagnostics()));
148 Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
149 PP.getLangOptions(), PD,
150 CreateStoreMgr, CreateConstraintMgr,
153 Opts.MaxNodes, Opts.MaxLoop,
154 Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
155 Opts.PurgeDead, Opts.EagerlyAssume,
156 Opts.TrimGraph, Opts.InlineCall,
157 Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors,
158 Opts.CFGAddInitializers,
159 Opts.EagerlyTrimEGraph));
162 virtual void HandleTranslationUnit(ASTContext &C);
163 void HandleDeclContext(ASTContext &C, DeclContext *dc);
165 void HandleCode(Decl *D);
167 } // end anonymous namespace
169 //===----------------------------------------------------------------------===//
170 // AnalysisConsumer implementation.
171 //===----------------------------------------------------------------------===//
173 void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
174 BugReporter BR(*Mgr);
175 for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
178 checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
180 switch (D->getKind()) {
181 case Decl::Namespace: {
182 HandleDeclContext(C, cast<NamespaceDecl>(D));
185 case Decl::CXXConstructor:
186 case Decl::CXXDestructor:
187 case Decl::CXXConversion:
188 case Decl::CXXMethod:
189 case Decl::Function: {
190 FunctionDecl* FD = cast<FunctionDecl>(D);
191 // We skip function template definitions, as their semantics is
192 // only determined when they are instantiated.
193 if (FD->isThisDeclarationADefinition() &&
194 !FD->isDependentContext()) {
195 if (!Opts.AnalyzeSpecificFunction.empty() &&
196 FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
204 case Decl::ObjCCategoryImpl:
205 case Decl::ObjCImplementation: {
206 ObjCImplDecl* ID = cast<ObjCImplDecl>(*I);
209 for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(),
210 ME = ID->meth_end(); MI != ME; ++MI) {
211 checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
213 if ((*MI)->isThisDeclarationADefinition()) {
214 if (!Opts.AnalyzeSpecificFunction.empty() &&
215 Opts.AnalyzeSpecificFunction !=
216 (*MI)->getSelector().getAsString())
218 DisplayFunction(*MI);
231 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
232 BugReporter BR(*Mgr);
233 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
234 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
235 HandleDeclContext(C, TU);
237 // After all decls handled, run checkers on the entire TranslationUnit.
238 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
240 // Explicitly destroy the PathDiagnosticClient. This will flush its output.
241 // FIXME: This should be replaced with something that doesn't rely on
242 // side-effects in PathDiagnosticClient's destructor. This is required when
243 // used with option -disable-free.
247 static void FindBlocks(DeclContext *D, llvm::SmallVectorImpl<Decl*> &WL) {
248 if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
251 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
253 if (DeclContext *DC = dyn_cast<DeclContext>(*I))
257 static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
260 void AnalysisConsumer::HandleCode(Decl *D) {
262 // Don't run the actions if an error has occurred with parsing the file.
263 Diagnostic &Diags = PP.getDiagnostics();
264 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
267 // Don't run the actions on declarations in header files unless
268 // otherwise specified.
269 SourceManager &SM = Ctx->getSourceManager();
270 SourceLocation SL = SM.getInstantiationLoc(D->getLocation());
271 if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
274 // Clear the AnalysisManager of old AnalysisContexts.
275 Mgr->ClearContexts();
277 // Dispatch on the actions.
278 llvm::SmallVector<Decl*, 10> WL;
281 if (D->hasBody() && Opts.AnalyzeNestedBlocks)
282 FindBlocks(cast<DeclContext>(D), WL);
284 BugReporter BR(*Mgr);
285 for (llvm::SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
287 if ((*WI)->hasBody()) {
288 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
289 if (checkerMgr->hasPathSensitiveCheckers())
290 ActionObjCMemChecker(*this, *Mgr, *WI);
294 //===----------------------------------------------------------------------===//
295 // Path-sensitive checking.
296 //===----------------------------------------------------------------------===//
298 static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr,
302 llvm::OwningPtr<TransferFuncs> TF(tf);
304 // Construct the analysis engine. We first query for the LiveVariables
305 // information to see if the CFG is valid.
306 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
307 if (!mgr.getLiveVariables(D))
309 ExprEngine Eng(mgr, TF.take());
311 // Set the graph auditor.
312 llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
313 if (mgr.shouldVisualizeUbigraph()) {
314 Auditor.reset(CreateUbiViz());
315 ExplodedNode::SetAuditor(Auditor.get());
318 // Execute the worklist algorithm.
319 Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
321 // Release the auditor (if any) so that it doesn't monitor the graph
322 // created BugReporter.
323 ExplodedNode::SetAuditor(0);
325 // Visualize the exploded graph.
326 if (mgr.shouldVisualizeGraphviz())
327 Eng.ViewGraph(mgr.shouldTrimGraph());
330 Eng.getBugReporter().FlushReports();
333 static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
334 Decl *D, bool GCEnabled) {
336 TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
338 mgr.getLangOptions());
340 ActionExprEngine(C, mgr, D, TF);
343 static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
346 switch (mgr.getLangOptions().getGCMode()) {
348 assert (false && "Invalid GC mode.");
349 case LangOptions::NonGC:
350 ActionObjCMemCheckerAux(C, mgr, D, false);
353 case LangOptions::GCOnly:
354 ActionObjCMemCheckerAux(C, mgr, D, true);
357 case LangOptions::HybridGC:
358 ActionObjCMemCheckerAux(C, mgr, D, false);
359 ActionObjCMemCheckerAux(C, mgr, D, true);
364 //===----------------------------------------------------------------------===//
365 // AnalysisConsumer creation.
366 //===----------------------------------------------------------------------===//
368 ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
369 const std::string& OutDir,
370 const AnalyzerOptions& Opts) {
371 llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
373 // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
374 pp.getDiagnostics().setWarningsAsErrors(false);
379 //===----------------------------------------------------------------------===//
380 // Ubigraph Visualization. FIXME: Move to separate file.
381 //===----------------------------------------------------------------------===//
385 class UbigraphViz : public ExplodedNode::Auditor {
386 llvm::OwningPtr<llvm::raw_ostream> Out;
387 llvm::sys::Path Dir, Filename;
390 typedef llvm::DenseMap<void*,unsigned> VMap;
394 UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
395 llvm::sys::Path& filename);
399 virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst);
402 } // end anonymous namespace
404 static ExplodedNode::Auditor* CreateUbiViz() {
407 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
411 llvm::sys::Path Filename = Dir;
412 Filename.appendComponent("llvm_ubi");
413 Filename.makeUnique(true,&ErrMsg);
418 llvm::errs() << "Writing '" << Filename.str() << "'.\n";
420 llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
421 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
426 return new UbigraphViz(Stream.take(), Dir, Filename);
429 void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) {
431 assert (Src != Dst && "Self-edges are not allowed.");
433 // Lookup the Src. If it is a new node, it's a root.
434 VMap::iterator SrcI= M.find(Src);
437 if (SrcI == M.end()) {
438 M[Src] = SrcID = Cntr++;
439 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
442 SrcID = SrcI->second;
445 VMap::iterator DstI= M.find(Dst);
448 if (DstI == M.end()) {
449 M[Dst] = DstID = Cntr++;
450 *Out << "('vertex', " << DstID << ")\n";
453 // We have hit DstID before. Change its style to reflect a cache hit.
454 DstID = DstI->second;
455 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
459 *Out << "('edge', " << SrcID << ", " << DstID
460 << ", ('arrow','true'), ('oriented', 'true'))\n";
463 UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
464 llvm::sys::Path& filename)
465 : Out(out), Dir(dir), Filename(filename), Cntr(0) {
467 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
468 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
469 " ('size', '1.5'))\n";
472 UbigraphViz::~UbigraphViz() {
474 llvm::errs() << "Running 'ubiviz' program... ";
476 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
477 std::vector<const char*> args;
478 args.push_back(Ubiviz.c_str());
479 args.push_back(Filename.c_str());
482 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
483 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
486 // Delete the directory.
487 Dir.eraseFromDisk(true);