blob: 4594a71492912c81109532c996d265938b86e71c [file] [log] [blame]
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// "Meta" ASTConsumer for running different source analyses.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000015#include "clang/Frontend/PathDiagnosticClients.h"
16#include "clang/Frontend/ManagerRegistry.h"
Ted Kremenekf4381fd2008-07-02 00:03:09 +000017#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "llvm/Support/Compiler.h"
Ted Kremenekf4381fd2008-07-02 00:03:09 +000021#include "llvm/ADT/OwningPtr.h"
22#include "clang/AST/CFG.h"
23#include "clang/Analysis/Analyses/LiveVariables.h"
24#include "clang/Analysis/PathDiagnostic.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/AST/ParentMap.h"
Ted Kremenekdb09a4d2008-07-03 04:29:21 +000028#include "clang/AST/TranslationUnit.h"
Ted Kremenekc0959972008-07-02 21:24:01 +000029#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenekf4381fd2008-07-02 00:03:09 +000030#include "clang/Analysis/Analyses/LiveVariables.h"
31#include "clang/Analysis/LocalCheckers.h"
32#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
33#include "clang/Analysis/PathSensitive/GRExprEngine.h"
Zhongxing Xuff944a82008-12-22 01:52:37 +000034#include "llvm/Support/CommandLine.h"
Ted Kremenek34d77342008-07-02 16:49:11 +000035#include "llvm/Support/Streams.h"
Ted Kremenekf8ce6992008-08-27 22:31:43 +000036#include "llvm/Support/raw_ostream.h"
37#include "llvm/System/Path.h"
Ted Kremenek710ad932008-08-28 03:54:51 +000038#include "llvm/System/Program.h"
Ted Kremenekdb09a4d2008-07-03 04:29:21 +000039#include <vector>
40
Ted Kremenekf4381fd2008-07-02 00:03:09 +000041using namespace clang;
42
Ted Kremenekf8ce6992008-08-27 22:31:43 +000043static ExplodedNodeImpl::Auditor* CreateUbiViz();
Zhongxing Xuff944a82008-12-22 01:52:37 +000044
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +000045//===----------------------------------------------------------------------===//
46// Analyzer Options: available analyses.
47//===----------------------------------------------------------------------===//
48
49/// Analysis - Set of available source code analyses.
50enum Analyses {
51#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE) NAME,
52#include "Analyses.def"
53NumAnalyses
54};
55
56static llvm::cl::list<Analyses>
57AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
58llvm::cl::values(
59#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
60clEnumValN(NAME, CMDFLAG, DESC),
61#include "Analyses.def"
62clEnumValEnd));
63
64//===----------------------------------------------------------------------===//
65// Analyzer Options: store model.
66//===----------------------------------------------------------------------===//
67
68/// AnalysisStores - Set of available analysis store models.
69enum AnalysisStores {
70#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
71#include "Analyses.def"
72NumStores
73};
74
75static llvm::cl::opt<AnalysisStores>
76AnalysisStoreOpt("analyzer-store",
77 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
78 llvm::cl::init(BasicStoreModel),
79 llvm::cl::values(
80#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
81clEnumValN(NAME##Model, CMDFLAG, DESC),
82#include "Analyses.def"
83clEnumValEnd));
84
85//===----------------------------------------------------------------------===//
86// Analyzer Options: constraint engines.
87//===----------------------------------------------------------------------===//
88
89/// AnalysisConstraints - Set of available constraint models.
90enum AnalysisConstraints {
91#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
92#include "Analyses.def"
93NumConstraints
94};
95
96static llvm::cl::opt<AnalysisConstraints>
97AnalysisConstraintsOpt("analyzer-constraints",
98 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
Ted Kremenek9f4ecb32009-02-20 21:49:22 +000099 llvm::cl::init(RangeConstraintsModel),
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000100 llvm::cl::values(
101#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
102clEnumValN(NAME##Model, CMDFLAG, DESC),
103#include "Analyses.def"
104clEnumValEnd));
105
106//===----------------------------------------------------------------------===//
107// Analyzer Options: diagnostic clients.
108//===----------------------------------------------------------------------===//
109
110/// AnalysisDiagClients - Set of available diagnostic clients for rendering
111/// analysis results.
112enum AnalysisDiagClients {
113#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREAT) PD_##NAME,
114#include "Analyses.def"
115NUM_ANALYSIS_DIAG_CLIENTS
116};
117
118static llvm::cl::opt<AnalysisDiagClients>
119AnalysisDiagOpt("analyzer-output",
120 llvm::cl::desc("Source Code Analysis - Output Options"),
121 llvm::cl::init(PD_HTML),
122 llvm::cl::values(
123#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
124clEnumValN(PD_##NAME, CMDFLAG, DESC),
125#include "Analyses.def"
126clEnumValEnd));
127
128//===----------------------------------------------------------------------===//
129// Misc. fun options.
130//===----------------------------------------------------------------------===//
131
132static llvm::cl::opt<bool>
133VisualizeEGDot("analyzer-viz-egraph-graphviz",
134 llvm::cl::desc("Display exploded graph using GraphViz"));
135
136static llvm::cl::opt<bool>
137VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
138 llvm::cl::desc("Display exploded graph using Ubigraph"));
139
140static llvm::cl::opt<bool>
141AnalyzeAll("analyzer-opt-analyze-headers",
142 llvm::cl::desc("Force the static analyzer to analyze "
143 "functions defined in header files"));
144
145static llvm::cl::opt<bool>
146AnalyzerDisplayProgress("analyzer-display-progress",
147 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
148
Zhongxing Xuff944a82008-12-22 01:52:37 +0000149static llvm::cl::opt<bool>
150PurgeDead("analyzer-purge-dead",
151 llvm::cl::init(true),
152 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
153 " processing a statement."));
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000154
Ted Kremenek48af2a92009-02-25 22:32:02 +0000155static llvm::cl::opt<bool>
156EagerlyAssume("analyzer-eagerly-assume",
157 llvm::cl::init(false),
158 llvm::cl::desc("Eagerly assume the truth/falseness of some "
159 "symbolic constraints."));
160
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000161static llvm::cl::opt<std::string>
162AnalyzeSpecificFunction("analyze-function",
163 llvm::cl::desc("Run analysis on specific function"));
164
Ted Kremenek45021952009-02-14 17:08:39 +0000165static llvm::cl::opt<bool>
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000166TrimGraph("trim-egraph",
167 llvm::cl::desc("Only show error-related paths in the analysis graph"));
168
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000169//===----------------------------------------------------------------------===//
170// Basic type definitions.
171//===----------------------------------------------------------------------===//
172
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000173namespace {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000174 class AnalysisManager;
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000175 typedef void (*CodeAction)(AnalysisManager& Mgr);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000176} // end anonymous namespace
177
178//===----------------------------------------------------------------------===//
179// AnalysisConsumer declaration.
180//===----------------------------------------------------------------------===//
181
182namespace {
183
184 class VISIBILITY_HIDDEN AnalysisConsumer : public ASTConsumer {
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000185 typedef std::vector<CodeAction> Actions;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000186 Actions FunctionActions;
187 Actions ObjCMethodActions;
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000188 Actions ObjCImplementationActions;
Ted Kremenekdaac6342008-11-07 02:09:25 +0000189 Actions TranslationUnitActions;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000190
191 public:
Ted Kremenek95c7b002008-10-24 01:04:59 +0000192 const LangOptions& LOpts;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000193 Diagnostic &Diags;
194 ASTContext* Ctx;
195 Preprocessor* PP;
196 PreprocessorFactory* PPF;
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000197 const std::string OutDir;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000198 llvm::OwningPtr<PathDiagnosticClient> PD;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000199
200 AnalysisConsumer(Diagnostic &diags, Preprocessor* pp,
201 PreprocessorFactory* ppf,
202 const LangOptions& lopts,
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000203 const std::string& outdir)
204 : LOpts(lopts), Diags(diags),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000205 Ctx(0), PP(pp), PPF(ppf),
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000206 OutDir(outdir) {}
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000207
208 void addCodeAction(CodeAction action) {
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000209 FunctionActions.push_back(action);
210 ObjCMethodActions.push_back(action);
211 }
212
213 void addObjCImplementationAction(CodeAction action) {
214 ObjCImplementationActions.push_back(action);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000215 }
216
Ted Kremenekdaac6342008-11-07 02:09:25 +0000217 void addTranslationUnitAction(CodeAction action) {
218 TranslationUnitActions.push_back(action);
219 }
220
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000221 virtual void Initialize(ASTContext &Context) {
222 Ctx = &Context;
223 }
224
225 virtual void HandleTopLevelDecl(Decl *D);
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000226 virtual void HandleTranslationUnit(TranslationUnit &TU);
227
Ted Kremenek81922f02009-02-02 20:52:40 +0000228 void HandleCode(Decl* D, Stmt* Body, Actions& actions);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000229 };
230
231
Ted Kremenekc0959972008-07-02 21:24:01 +0000232 class VISIBILITY_HIDDEN AnalysisManager : public BugReporterData {
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000233 Decl* D; Stmt* Body;
234 TranslationUnit* TU;
235
236 enum AnalysisScope { ScopeTU, ScopeDecl } AScope;
237
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000238 AnalysisConsumer& C;
Ted Kremenek34d77342008-07-02 16:49:11 +0000239 bool DisplayedFunction;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000240
241 llvm::OwningPtr<CFG> cfg;
242 llvm::OwningPtr<LiveVariables> liveness;
243 llvm::OwningPtr<ParentMap> PM;
244
Zhongxing Xu22438a82008-11-27 01:55:08 +0000245 // Configurable components creators.
246 StoreManagerCreator CreateStoreMgr;
247 ConstraintManagerCreator CreateConstraintMgr;
248
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000249 public:
Ted Kremenek491918e2009-01-23 20:52:26 +0000250 AnalysisManager(AnalysisConsumer& c, Decl* d, Stmt* b, bool displayProgress)
251 : D(d), Body(b), TU(0), AScope(ScopeDecl), C(c),
252 DisplayedFunction(!displayProgress) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000253 setManagerCreators();
254 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000255
Ted Kremenek491918e2009-01-23 20:52:26 +0000256 AnalysisManager(AnalysisConsumer& c, TranslationUnit* tu,
257 bool displayProgress)
258 : D(0), Body(0), TU(tu), AScope(ScopeTU), C(c),
259 DisplayedFunction(!displayProgress) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000260 setManagerCreators();
261 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000262
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000263 Decl* getCodeDecl() const {
264 assert (AScope == ScopeDecl);
265 return D;
266 }
267
268 Stmt* getBody() const {
269 assert (AScope == ScopeDecl);
270 return Body;
271 }
272
273 TranslationUnit* getTranslationUnit() const {
274 assert (AScope == ScopeTU);
275 return TU;
276 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000277
Zhongxing Xu22438a82008-11-27 01:55:08 +0000278 StoreManagerCreator getStoreManagerCreator() {
279 return CreateStoreMgr;
Ted Kremenek95c7b002008-10-24 01:04:59 +0000280 };
Zhongxing Xu22438a82008-11-27 01:55:08 +0000281
282 ConstraintManagerCreator getConstraintManagerCreator() {
283 return CreateConstraintMgr;
284 }
Ted Kremenek95c7b002008-10-24 01:04:59 +0000285
Ted Kremenek7032f462008-07-03 05:26:14 +0000286 virtual CFG* getCFG() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000287 if (!cfg) cfg.reset(CFG::buildCFG(getBody()));
Ted Kremenek7032f462008-07-03 05:26:14 +0000288 return cfg.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000289 }
290
Ted Kremenekc0959972008-07-02 21:24:01 +0000291 virtual ParentMap& getParentMap() {
Ted Kremeneke2075582008-07-02 23:16:33 +0000292 if (!PM)
293 PM.reset(new ParentMap(getBody()));
Ted Kremenekc0959972008-07-02 21:24:01 +0000294 return *PM.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000295 }
296
Ted Kremenekc0959972008-07-02 21:24:01 +0000297 virtual ASTContext& getContext() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000298 return *C.Ctx;
299 }
300
Ted Kremenekc0959972008-07-02 21:24:01 +0000301 virtual SourceManager& getSourceManager() {
Ted Kremenek235e0312008-07-02 18:11:29 +0000302 return getContext().getSourceManager();
303 }
304
Ted Kremenekc0959972008-07-02 21:24:01 +0000305 virtual Diagnostic& getDiagnostic() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000306 return C.Diags;
307 }
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000308
309 const LangOptions& getLangOptions() const {
310 return C.LOpts;
311 }
312
Ted Kremenekc0959972008-07-02 21:24:01 +0000313 virtual PathDiagnosticClient* getPathDiagnosticClient() {
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000314 if (C.PD.get() == 0 && !C.OutDir.empty()) {
315 switch (AnalysisDiagOpt) {
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000316 default:
Ted Kremenekc472d792009-01-23 20:06:20 +0000317#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000318case PD_##NAME: C.PD.reset(CREATEFN(C.OutDir, C.PP, C.PPF)); break;
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000319#include "Analyses.def"
320 }
321 }
Ted Kremeneke2075582008-07-02 23:16:33 +0000322 return C.PD.get();
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000323 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000324
Ted Kremenek7032f462008-07-03 05:26:14 +0000325 virtual LiveVariables* getLiveVariables() {
Ted Kremenek235e0312008-07-02 18:11:29 +0000326 if (!liveness) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000327 CFG* c = getCFG();
328 if (!c) return 0;
329
Ted Kremenekca9bab02008-12-09 00:17:51 +0000330 liveness.reset(new LiveVariables(getContext(), *c));
Ted Kremenek7032f462008-07-03 05:26:14 +0000331 liveness->runOnCFG(*c);
332 liveness->runOnAllBlocks(*c, 0, true);
Ted Kremenek235e0312008-07-02 18:11:29 +0000333 }
Ted Kremenekc0959972008-07-02 21:24:01 +0000334
Ted Kremenek7032f462008-07-03 05:26:14 +0000335 return liveness.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000336 }
Ted Kremenek34d77342008-07-02 16:49:11 +0000337
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000338 bool shouldVisualizeGraphviz() const { return VisualizeEGDot; }
339
340 bool shouldVisualizeUbigraph() const { return VisualizeEGUbi; }
341
342 bool shouldVisualize() const {
343 return VisualizeEGDot || VisualizeEGUbi;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000344 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000345
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000346 bool shouldTrimGraph() const { return TrimGraph; }
347
Ted Kremenek34d77342008-07-02 16:49:11 +0000348 void DisplayFunction() {
349
350 if (DisplayedFunction)
351 return;
352
353 DisplayedFunction = true;
354
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000355 // FIXME: Is getCodeDecl() always a named decl?
356 if (isa<FunctionDecl>(getCodeDecl()) ||
357 isa<ObjCMethodDecl>(getCodeDecl())) {
358 NamedDecl *ND = cast<NamedDecl>(getCodeDecl());
359 SourceManager &SM = getContext().getSourceManager();
Ted Kremeneka88fcef2008-11-20 16:14:48 +0000360 llvm::cerr << "ANALYZE: "
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000361 << SM.getPresumedLoc(ND->getLocation()).getFilename()
362 << ' ' << ND->getNameAsString() << '\n';
Ted Kremenek34d77342008-07-02 16:49:11 +0000363 }
364 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000365
366 private:
367 /// Set configurable analyzer components creators. First check if there are
368 /// components registered at runtime. Otherwise fall back to builtin
369 /// components.
370 void setManagerCreators() {
371 if (ManagerRegistry::StoreMgrCreator != 0) {
372 CreateStoreMgr = ManagerRegistry::StoreMgrCreator;
373 }
374 else {
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000375 switch (AnalysisStoreOpt) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000376 default:
377 assert(0 && "Unknown store manager.");
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000378#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
379 case NAME##Model: CreateStoreMgr = CREATEFN; break;
Zhongxing Xu22438a82008-11-27 01:55:08 +0000380#include "Analyses.def"
381 }
382 }
383
384 if (ManagerRegistry::ConstraintMgrCreator != 0)
385 CreateConstraintMgr = ManagerRegistry::ConstraintMgrCreator;
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000386 else {
387 switch (AnalysisConstraintsOpt) {
388 default:
389 assert(0 && "Unknown store manager.");
390#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
391 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
392#include "Analyses.def"
393 }
394 }
395
Ted Kremenekc472d792009-01-23 20:06:20 +0000396
397 // Some DiagnosticClients should be created all the time instead of
398 // lazily. Create those now.
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000399 switch (AnalysisDiagOpt) {
Ted Kremenekc472d792009-01-23 20:06:20 +0000400 default: break;
401#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\
402case PD_##NAME: if (AUTOCREATE) getPathDiagnosticClient(); break;
403#include "Analyses.def"
404 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000405 }
406
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000407 };
Zhongxing Xu22438a82008-11-27 01:55:08 +0000408
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000409} // end anonymous namespace
410
411namespace llvm {
412 template <> struct FoldingSetTrait<CodeAction> {
413 static inline void Profile(CodeAction X, FoldingSetNodeID& ID) {
414 ID.AddPointer(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(X)));
415 }
416 };
417}
418
419//===----------------------------------------------------------------------===//
420// AnalysisConsumer implementation.
421//===----------------------------------------------------------------------===//
422
423void AnalysisConsumer::HandleTopLevelDecl(Decl *D) {
424 switch (D->getKind()) {
425 case Decl::Function: {
426 FunctionDecl* FD = cast<FunctionDecl>(D);
Ted Kremenek235e0312008-07-02 18:11:29 +0000427
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000428 if (AnalyzeSpecificFunction.size() > 0 &&
429 AnalyzeSpecificFunction != FD->getIdentifier()->getName())
Ted Kremenek235e0312008-07-02 18:11:29 +0000430 break;
431
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000432 Stmt* Body = FD->getBody();
433 if (Body) HandleCode(FD, Body, FunctionActions);
434 break;
435 }
436
437 case Decl::ObjCMethod: {
438 ObjCMethodDecl* MD = cast<ObjCMethodDecl>(D);
Ted Kremenek235e0312008-07-02 18:11:29 +0000439
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000440 if (AnalyzeSpecificFunction.size() > 0 &&
441 AnalyzeSpecificFunction != MD->getSelector().getAsString())
Ted Kremenek235e0312008-07-02 18:11:29 +0000442 return;
443
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000444 Stmt* Body = MD->getBody();
445 if (Body) HandleCode(MD, Body, ObjCMethodActions);
446 break;
447 }
448
449 default:
450 break;
451 }
452}
453
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000454void AnalysisConsumer::HandleTranslationUnit(TranslationUnit& TU) {
455
Ted Kremenekdaac6342008-11-07 02:09:25 +0000456 if(!TranslationUnitActions.empty()) {
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000457 AnalysisManager mgr(*this, &TU, AnalyzerDisplayProgress);
Ted Kremenekdaac6342008-11-07 02:09:25 +0000458 for (Actions::iterator I = TranslationUnitActions.begin(),
459 E = TranslationUnitActions.end(); I != E; ++I)
460 (*I)(mgr);
461 }
462
Chris Lattnere9077872009-03-28 03:29:40 +0000463 if (!ObjCImplementationActions.empty()) {
464 TranslationUnitDecl *TUD = TU.getContext().getTranslationUnitDecl();
465
466 for (DeclContext::decl_iterator I = TUD->decls_begin(),E = TUD->decls_end();
467 I != E; ++I)
Ted Kremenek4d53a532009-02-13 00:51:30 +0000468 if (ObjCImplementationDecl* ID = dyn_cast<ObjCImplementationDecl>(*I))
469 HandleCode(ID, 0, ObjCImplementationActions);
Chris Lattnere9077872009-03-28 03:29:40 +0000470 }
Ted Kremenek4d53a532009-02-13 00:51:30 +0000471
472 // Delete the PathDiagnosticClient here just in case the AnalysisConsumer
473 // object doesn't get released. This will cause any side-effects in the
474 // destructor of the PathDiagnosticClient to get executed.
475 PD.reset();
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000476}
477
Ted Kremenek81922f02009-02-02 20:52:40 +0000478void AnalysisConsumer::HandleCode(Decl* D, Stmt* Body, Actions& actions) {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000479
480 // Don't run the actions if an error has occured with parsing the file.
481 if (Diags.hasErrorOccurred())
482 return;
Ted Kremenek81922f02009-02-02 20:52:40 +0000483
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000484 // Don't run the actions on declarations in header files unless
485 // otherwise specified.
Ted Kremenek81922f02009-02-02 20:52:40 +0000486 if (!AnalyzeAll && !Ctx->getSourceManager().isFromMainFile(D->getLocation()))
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000487 return;
488
489 // Create an AnalysisManager that will manage the state for analyzing
490 // this method/function.
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000491 AnalysisManager mgr(*this, D, Body, AnalyzerDisplayProgress);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000492
493 // Dispatch on the actions.
Zhongxing Xu3702af52008-10-30 05:03:28 +0000494 for (Actions::iterator I = actions.begin(), E = actions.end(); I != E; ++I)
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000495 (*I)(mgr);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000496}
497
498//===----------------------------------------------------------------------===//
499// Analyses
500//===----------------------------------------------------------------------===//
501
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000502static void ActionWarnDeadStores(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000503 if (LiveVariables* L = mgr.getLiveVariables()) {
504 BugReporter BR(mgr);
505 CheckDeadStores(*L, BR);
506 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000507}
508
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000509static void ActionWarnUninitVals(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000510 if (CFG* c = mgr.getCFG())
511 CheckUninitializedValues(*c, mgr.getContext(), mgr.getDiagnostic());
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000512}
513
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000514
Ted Kremenek78d46242008-07-22 16:21:24 +0000515static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf,
516 bool StandardWarnings = true) {
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000517
Ted Kremenek7032f462008-07-03 05:26:14 +0000518
Ted Kremenekbc46f342008-07-02 16:35:50 +0000519 llvm::OwningPtr<GRTransferFuncs> TF(tf);
Ted Kremenek7032f462008-07-03 05:26:14 +0000520
Ted Kremenek8ffc8a52008-11-24 20:53:32 +0000521 // Display progress.
522 mgr.DisplayFunction();
523
Ted Kremenek7032f462008-07-03 05:26:14 +0000524 // Construct the analysis engine.
525 LiveVariables* L = mgr.getLiveVariables();
526 if (!L) return;
Ted Kremenek8ffc8a52008-11-24 20:53:32 +0000527
Ted Kremenekcf118d42009-02-04 23:49:09 +0000528 GRExprEngine Eng(*mgr.getCFG(), *mgr.getCodeDecl(), mgr.getContext(), *L, mgr,
Ted Kremenek48af2a92009-02-25 22:32:02 +0000529 PurgeDead, EagerlyAssume,
Zhongxing Xu22438a82008-11-27 01:55:08 +0000530 mgr.getStoreManagerCreator(),
531 mgr.getConstraintManagerCreator());
Ted Kremenek95c7b002008-10-24 01:04:59 +0000532
Ted Kremenekbc46f342008-07-02 16:35:50 +0000533 Eng.setTransferFunctions(tf);
534
Ted Kremenek78d46242008-07-22 16:21:24 +0000535 if (StandardWarnings) {
536 Eng.RegisterInternalChecks();
537 RegisterAppleChecks(Eng);
538 }
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000539
540 // Set the graph auditor.
541 llvm::OwningPtr<ExplodedNodeImpl::Auditor> Auditor;
542 if (mgr.shouldVisualizeUbigraph()) {
543 Auditor.reset(CreateUbiViz());
544 ExplodedNodeImpl::SetAuditor(Auditor.get());
545 }
Ted Kremenek78d46242008-07-22 16:21:24 +0000546
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000547 // Execute the worklist algorithm.
548 Eng.ExecuteWorkList();
Ted Kremenekbc46f342008-07-02 16:35:50 +0000549
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000550 // Release the auditor (if any) so that it doesn't monitor the graph
551 // created BugReporter.
552 ExplodedNodeImpl::SetAuditor(0);
Ted Kremenek3df64212009-03-11 01:42:29 +0000553
Ted Kremenek34d77342008-07-02 16:49:11 +0000554 // Visualize the exploded graph.
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000555 if (mgr.shouldVisualizeGraphviz())
Ted Kremenek34d77342008-07-02 16:49:11 +0000556 Eng.ViewGraph(mgr.shouldTrimGraph());
Ted Kremenek3df64212009-03-11 01:42:29 +0000557
558 // Display warnings.
559 Eng.getBugReporter().FlushReports();
Ted Kremenekbc46f342008-07-02 16:35:50 +0000560}
561
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000562static void ActionCheckerCFRefAux(AnalysisManager& mgr, bool GCEnabled,
Ted Kremenek78d46242008-07-22 16:21:24 +0000563 bool StandardWarnings) {
564
Ted Kremenekbc46f342008-07-02 16:35:50 +0000565 GRTransferFuncs* TF = MakeCFRefCountTF(mgr.getContext(),
566 GCEnabled,
Ted Kremenekbc46f342008-07-02 16:35:50 +0000567 mgr.getLangOptions());
568
Ted Kremenek78d46242008-07-22 16:21:24 +0000569 ActionGRExprEngine(mgr, TF, StandardWarnings);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000570}
571
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000572static void ActionCheckerCFRef(AnalysisManager& mgr) {
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000573
574 switch (mgr.getLangOptions().getGCMode()) {
575 default:
576 assert (false && "Invalid GC mode.");
577 case LangOptions::NonGC:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000578 ActionCheckerCFRefAux(mgr, false, true);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000579 break;
580
581 case LangOptions::GCOnly:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000582 ActionCheckerCFRefAux(mgr, true, true);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000583 break;
584
585 case LangOptions::HybridGC:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000586 ActionCheckerCFRefAux(mgr, false, true);
587 ActionCheckerCFRefAux(mgr, true, false);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000588 break;
589 }
590}
591
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000592static void ActionCheckerSimple(AnalysisManager& mgr) {
Ted Kremenekbc46f342008-07-02 16:35:50 +0000593 ActionGRExprEngine(mgr, MakeGRSimpleValsTF());
594}
595
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000596static void ActionDisplayLiveVariables(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000597 if (LiveVariables* L = mgr.getLiveVariables()) {
598 mgr.DisplayFunction();
599 L->dumpBlockLiveness(mgr.getSourceManager());
600 }
Ted Kremenek235e0312008-07-02 18:11:29 +0000601}
602
Ted Kremenek902141f2008-07-02 18:23:21 +0000603static void ActionCFGDump(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000604 if (CFG* c = mgr.getCFG()) {
605 mgr.DisplayFunction();
606 c->dump();
607 }
Ted Kremenek902141f2008-07-02 18:23:21 +0000608}
609
610static void ActionCFGView(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000611 if (CFG* c = mgr.getCFG()) {
612 mgr.DisplayFunction();
613 c->viewCFG();
614 }
Ted Kremenek902141f2008-07-02 18:23:21 +0000615}
616
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000617static void ActionWarnObjCDealloc(AnalysisManager& mgr) {
Ted Kremenek4f4e7e42008-08-04 17:14:10 +0000618 if (mgr.getLangOptions().getGCMode() == LangOptions::GCOnly)
619 return;
620
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000621 BugReporter BR(mgr);
Ted Kremenek3cd483c2008-07-03 14:35:01 +0000622
623 CheckObjCDealloc(cast<ObjCImplementationDecl>(mgr.getCodeDecl()),
624 mgr.getLangOptions(), BR);
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000625}
626
Ted Kremenek395aaf22008-07-23 00:45:26 +0000627static void ActionWarnObjCUnusedIvars(AnalysisManager& mgr) {
628 BugReporter BR(mgr);
629 CheckObjCUnusedIvar(cast<ObjCImplementationDecl>(mgr.getCodeDecl()), BR);
630}
631
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000632static void ActionWarnObjCMethSigs(AnalysisManager& mgr) {
Ted Kremenek0d8019e2008-07-11 22:40:47 +0000633 BugReporter BR(mgr);
634
635 CheckObjCInstMethSignature(cast<ObjCImplementationDecl>(mgr.getCodeDecl()),
636 BR);
637}
638
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000639//===----------------------------------------------------------------------===//
640// AnalysisConsumer creation.
641//===----------------------------------------------------------------------===//
642
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000643ASTConsumer* clang::CreateAnalysisConsumer(Diagnostic &diags, Preprocessor* pp,
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000644 PreprocessorFactory* ppf,
645 const LangOptions& lopts,
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000646 const std::string& OutDir) {
647
648 llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(diags, pp, ppf,
649 lopts, OutDir));
650
651 for (unsigned i = 0; i < AnalysisList.size(); ++i)
652 switch (AnalysisList[i]) {
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000653#define ANALYSIS(NAME, CMD, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000654 case NAME:\
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000655 C->add ## SCOPE ## Action(&Action ## NAME);\
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000656 break;
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000657#include "Analyses.def"
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000658 default: break;
659 }
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000660
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000661 return C.take();
662}
663
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000664//===----------------------------------------------------------------------===//
665// Ubigraph Visualization. FIXME: Move to separate file.
666//===----------------------------------------------------------------------===//
667
668namespace {
669
670class UbigraphViz : public ExplodedNodeImpl::Auditor {
671 llvm::OwningPtr<llvm::raw_ostream> Out;
Ted Kremenek710ad932008-08-28 03:54:51 +0000672 llvm::sys::Path Dir, Filename;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000673 unsigned Cntr;
674
675 typedef llvm::DenseMap<void*,unsigned> VMap;
676 VMap M;
677
678public:
Ted Kremenek710ad932008-08-28 03:54:51 +0000679 UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
Ted Kremenek56b98712008-08-28 05:02:09 +0000680 llvm::sys::Path& filename);
Ted Kremenek710ad932008-08-28 03:54:51 +0000681
682 ~UbigraphViz();
683
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000684 virtual void AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst);
685};
686
687} // end anonymous namespace
688
689static ExplodedNodeImpl::Auditor* CreateUbiViz() {
690 std::string ErrMsg;
691
Ted Kremenek710ad932008-08-28 03:54:51 +0000692 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000693 if (!ErrMsg.empty())
694 return 0;
695
Ted Kremenek710ad932008-08-28 03:54:51 +0000696 llvm::sys::Path Filename = Dir;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000697 Filename.appendComponent("llvm_ubi");
698 Filename.makeUnique(true,&ErrMsg);
699
700 if (!ErrMsg.empty())
701 return 0;
702
703 llvm::cerr << "Writing '" << Filename << "'.\n";
704
705 llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
706 std::string filename = Filename.toString();
Daniel Dunbar26fb2722008-11-13 05:09:21 +0000707 Stream.reset(new llvm::raw_fd_ostream(filename.c_str(), false, ErrMsg));
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000708
709 if (!ErrMsg.empty())
710 return 0;
711
Ted Kremenek710ad932008-08-28 03:54:51 +0000712 return new UbigraphViz(Stream.take(), Dir, Filename);
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000713}
714
715void UbigraphViz::AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst) {
Ted Kremenek45479c82008-08-28 18:34:41 +0000716
717 assert (Src != Dst && "Self-edges are not allowed.");
718
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000719 // Lookup the Src. If it is a new node, it's a root.
720 VMap::iterator SrcI= M.find(Src);
721 unsigned SrcID;
722
723 if (SrcI == M.end()) {
724 M[Src] = SrcID = Cntr++;
725 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
726 }
727 else
728 SrcID = SrcI->second;
729
730 // Lookup the Dst.
731 VMap::iterator DstI= M.find(Dst);
732 unsigned DstID;
733
734 if (DstI == M.end()) {
735 M[Dst] = DstID = Cntr++;
736 *Out << "('vertex', " << DstID << ")\n";
737 }
Ted Kremenek56b98712008-08-28 05:02:09 +0000738 else {
739 // We have hit DstID before. Change its style to reflect a cache hit.
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000740 DstID = DstI->second;
Ted Kremenek56b98712008-08-28 05:02:09 +0000741 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
742 }
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000743
744 // Add the edge.
Ted Kremenekd1289322008-08-27 22:46:55 +0000745 *Out << "('edge', " << SrcID << ", " << DstID
746 << ", ('arrow','true'), ('oriented', 'true'))\n";
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000747}
748
Ted Kremenek56b98712008-08-28 05:02:09 +0000749UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
750 llvm::sys::Path& filename)
751 : Out(out), Dir(dir), Filename(filename), Cntr(0) {
752
753 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
754 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
755 " ('size', '1.5'))\n";
756}
757
Ted Kremenek710ad932008-08-28 03:54:51 +0000758UbigraphViz::~UbigraphViz() {
759 Out.reset(0);
760 llvm::cerr << "Running 'ubiviz' program... ";
761 std::string ErrMsg;
762 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
763 std::vector<const char*> args;
764 args.push_back(Ubiviz.c_str());
765 args.push_back(Filename.c_str());
766 args.push_back(0);
767
768 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
769 llvm::cerr << "Error viewing graph: " << ErrMsg << "\n";
770 }
771
772 // Delete the directory.
773 Dir.eraseFromDisk(true);
Daniel Dunbar932680e2008-08-29 03:45:59 +0000774}