blob: 21dd40b32ee96127922ee37dc3233b42a42a99f0 [file] [log] [blame]
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
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// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
17#include "AnalysisBasedWarnings.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000018#include "clang/Basic/SourceManager.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000019#include "clang/AST/ExprObjC.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/StmtObjC.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/Analysis/AnalysisContext.h"
24#include "clang/Analysis/CFG.h"
25#include "clang/Analysis/Analyses/ReachableCode.h"
26#include "llvm/ADT/BitVector.h"
27#include "llvm/Support/Casting.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000028
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Unreachable code analysis.
33//===----------------------------------------------------------------------===//
34
35namespace {
36 class UnreachableCodeHandler : public reachable_code::Callback {
37 Sema &S;
38 public:
39 UnreachableCodeHandler(Sema &s) : S(s) {}
40
41 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
42 S.Diag(L, diag::warn_unreachable) << R1 << R2;
43 }
44 };
45}
46
47/// CheckUnreachable - Check for unreachable code.
48static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
49 UnreachableCodeHandler UC(S);
50 reachable_code::FindUnreachableCode(AC, UC);
51}
52
53//===----------------------------------------------------------------------===//
54// Check for missing return value.
55//===----------------------------------------------------------------------===//
56
John McCall16565aa2010-05-16 09:34:11 +000057enum ControlFlowKind {
58 UnknownFallThrough,
59 NeverFallThrough,
60 MaybeFallThrough,
61 AlwaysFallThrough,
62 NeverFallThroughOrReturn
63};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000064
65/// CheckFallThrough - Check that we don't fall off the end of a
66/// Statement that should return a value.
67///
68/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
69/// MaybeFallThrough iff we might or might not fall off the end,
70/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
71/// return. We assume NeverFallThrough iff we never fall off the end of the
72/// statement but we may return. We assume that functions not marked noreturn
73/// will return.
74static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
75 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000076 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000077
78 // The CFG leaves in dead things, and we don't want the dead code paths to
79 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000080 llvm::BitVector live(cfg->getNumBlockIDs());
81 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
82 live);
83
84 bool AddEHEdges = AC.getAddEHEdges();
85 if (!AddEHEdges && count != cfg->getNumBlockIDs())
86 // When there are things remaining dead, and we didn't add EH edges
87 // from CallExprs to the catch clauses, we have to go back and
88 // mark them as live.
89 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
90 CFGBlock &b = **I;
91 if (!live[b.getBlockID()]) {
92 if (b.pred_begin() == b.pred_end()) {
93 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
94 // When not adding EH edges from calls, catch clauses
95 // can otherwise seem dead. Avoid noting them as dead.
96 count += reachable_code::ScanReachableFromBlock(b, live);
97 continue;
98 }
99 }
100 }
101
102 // Now we know what is live, we check the live precessors of the exit block
103 // and look for fall through paths, being careful to ignore normal returns,
104 // and exceptional paths.
105 bool HasLiveReturn = false;
106 bool HasFakeEdge = false;
107 bool HasPlainEdge = false;
108 bool HasAbnormalEdge = false;
109 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
110 E = cfg->getExit().pred_end();
111 I != E;
112 ++I) {
113 CFGBlock& B = **I;
114 if (!live[B.getBlockID()])
115 continue;
116 if (B.size() == 0) {
117 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
118 HasAbnormalEdge = true;
119 continue;
120 }
121
122 // A labeled empty statement, or the entry block...
123 HasPlainEdge = true;
124 continue;
125 }
126 Stmt *S = B[B.size()-1];
127 if (isa<ReturnStmt>(S)) {
128 HasLiveReturn = true;
129 continue;
130 }
131 if (isa<ObjCAtThrowStmt>(S)) {
132 HasFakeEdge = true;
133 continue;
134 }
135 if (isa<CXXThrowExpr>(S)) {
136 HasFakeEdge = true;
137 continue;
138 }
139 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
140 if (AS->isMSAsm()) {
141 HasFakeEdge = true;
142 HasLiveReturn = true;
143 continue;
144 }
145 }
146 if (isa<CXXTryStmt>(S)) {
147 HasAbnormalEdge = true;
148 continue;
149 }
150
151 bool NoReturnEdge = false;
152 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000153 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
154 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000155 HasAbnormalEdge = true;
156 continue;
157 }
158 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Rafael Espindola264ba482010-03-30 20:24:48 +0000159 if (getFunctionExtInfo(CEE->getType()).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000160 NoReturnEdge = true;
161 HasFakeEdge = true;
162 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
163 ValueDecl *VD = DRE->getDecl();
164 if (VD->hasAttr<NoReturnAttr>()) {
165 NoReturnEdge = true;
166 HasFakeEdge = true;
167 }
168 }
169 }
170 // FIXME: Add noreturn message sends.
171 if (NoReturnEdge == false)
172 HasPlainEdge = true;
173 }
174 if (!HasPlainEdge) {
175 if (HasLiveReturn)
176 return NeverFallThrough;
177 return NeverFallThroughOrReturn;
178 }
179 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
180 return MaybeFallThrough;
181 // This says AlwaysFallThrough for calls to functions that are not marked
182 // noreturn, that don't return. If people would like this warning to be more
183 // accurate, such functions should be marked as noreturn.
184 return AlwaysFallThrough;
185}
186
187struct CheckFallThroughDiagnostics {
188 unsigned diag_MaybeFallThrough_HasNoReturn;
189 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
190 unsigned diag_AlwaysFallThrough_HasNoReturn;
191 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
192 unsigned diag_NeverFallThroughOrReturn;
193 bool funMode;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000194
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000195 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000196 CheckFallThroughDiagnostics D;
197 D.diag_MaybeFallThrough_HasNoReturn =
198 diag::warn_falloff_noreturn_function;
199 D.diag_MaybeFallThrough_ReturnsNonVoid =
200 diag::warn_maybe_falloff_nonvoid_function;
201 D.diag_AlwaysFallThrough_HasNoReturn =
202 diag::warn_falloff_noreturn_function;
203 D.diag_AlwaysFallThrough_ReturnsNonVoid =
204 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000205
206 // Don't suggest that virtual functions be marked "noreturn", since they
207 // might be overridden by non-noreturn functions.
208 bool isVirtualMethod = false;
209 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
210 isVirtualMethod = Method->isVirtual();
211
212 if (!isVirtualMethod)
213 D.diag_NeverFallThroughOrReturn =
214 diag::warn_suggest_noreturn_function;
215 else
216 D.diag_NeverFallThroughOrReturn = 0;
217
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000218 D.funMode = true;
219 return D;
220 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000221
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000222 static CheckFallThroughDiagnostics MakeForBlock() {
223 CheckFallThroughDiagnostics D;
224 D.diag_MaybeFallThrough_HasNoReturn =
225 diag::err_noreturn_block_has_return_expr;
226 D.diag_MaybeFallThrough_ReturnsNonVoid =
227 diag::err_maybe_falloff_nonvoid_block;
228 D.diag_AlwaysFallThrough_HasNoReturn =
229 diag::err_noreturn_block_has_return_expr;
230 D.diag_AlwaysFallThrough_ReturnsNonVoid =
231 diag::err_falloff_nonvoid_block;
232 D.diag_NeverFallThroughOrReturn =
233 diag::warn_suggest_noreturn_block;
234 D.funMode = false;
235 return D;
236 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000237
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000238 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
239 bool HasNoReturn) const {
240 if (funMode) {
241 return (D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
242 == Diagnostic::Ignored || ReturnsVoid)
243 && (D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
244 == Diagnostic::Ignored || !HasNoReturn)
245 && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
246 == Diagnostic::Ignored || !ReturnsVoid);
247 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000248
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000249 // For blocks.
250 return ReturnsVoid && !HasNoReturn
251 && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
252 == Diagnostic::Ignored || !ReturnsVoid);
253 }
254};
255
256/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
257/// function that should return a value. Check that we don't fall off the end
258/// of a noreturn function. We assume that functions and blocks not marked
259/// noreturn will return.
260static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
261 QualType BlockTy,
262 const CheckFallThroughDiagnostics& CD,
263 AnalysisContext &AC) {
264
265 bool ReturnsVoid = false;
266 bool HasNoReturn = false;
267
268 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
269 ReturnsVoid = FD->getResultType()->isVoidType();
270 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000271 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000272 }
273 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
274 ReturnsVoid = MD->getResultType()->isVoidType();
275 HasNoReturn = MD->hasAttr<NoReturnAttr>();
276 }
277 else if (isa<BlockDecl>(D)) {
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000278 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000279 BlockTy->getPointeeType()->getAs<FunctionType>()) {
280 if (FT->getResultType()->isVoidType())
281 ReturnsVoid = true;
282 if (FT->getNoReturnAttr())
283 HasNoReturn = true;
284 }
285 }
286
287 Diagnostic &Diags = S.getDiagnostics();
288
289 // Short circuit for compilation speed.
290 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
291 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000292
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000293 // FIXME: Function try block
294 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
295 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000296 case UnknownFallThrough:
297 break;
298
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000299 case MaybeFallThrough:
300 if (HasNoReturn)
301 S.Diag(Compound->getRBracLoc(),
302 CD.diag_MaybeFallThrough_HasNoReturn);
303 else if (!ReturnsVoid)
304 S.Diag(Compound->getRBracLoc(),
305 CD.diag_MaybeFallThrough_ReturnsNonVoid);
306 break;
307 case AlwaysFallThrough:
308 if (HasNoReturn)
309 S.Diag(Compound->getRBracLoc(),
310 CD.diag_AlwaysFallThrough_HasNoReturn);
311 else if (!ReturnsVoid)
312 S.Diag(Compound->getRBracLoc(),
313 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
314 break;
315 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000316 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000317 S.Diag(Compound->getLBracLoc(),
318 CD.diag_NeverFallThroughOrReturn);
319 break;
320 case NeverFallThrough:
321 break;
322 }
323 }
324}
325
326//===----------------------------------------------------------------------===//
327// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
328// warnings on a function, method, or block.
329//===----------------------------------------------------------------------===//
330
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000331clang::sema::AnalysisBasedWarnings::Policy::Policy() {
332 enableCheckFallThrough = 1;
333 enableCheckUnreachable = 0;
334}
335
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000336clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
337 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000338 DefaultPolicy.enableCheckUnreachable = (unsigned)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000339 (D.getDiagnosticLevel(diag::warn_unreachable) != Diagnostic::Ignored);
340}
341
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000342void clang::sema::
343AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000344 const Decl *D, QualType BlockTy) {
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000345
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000346 assert(BlockTy.isNull() || isa<BlockDecl>(D));
Ted Kremenekd068aab2010-03-20 21:11:09 +0000347
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000348 // We avoid doing analysis-based warnings when there are errors for
349 // two reasons:
350 // (1) The CFGs often can't be constructed (if the body is invalid), so
351 // don't bother trying.
352 // (2) The code already has problems; running the analysis just takes more
353 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000354 Diagnostic &Diags = S.getDiagnostics();
355
356 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000357 return;
358
359 // Do not do any analysis for declarations in system headers if we are
360 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000361 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000362 S.SourceMgr.isInSystemHeader(D->getLocation()))
363 return;
364
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000365 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
366 // For function templates, class templates and member function templates
367 // we'll do the analysis at instantiation time.
368 if (FD->isDependentContext())
369 return;
370 }
371
372 const Stmt *Body = D->getBody();
373 assert(Body);
374
375 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
376 // explosion for destrutors that can result and the compile time hit.
377 AnalysisContext AC(D, false);
378
379 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000380 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000381 const CheckFallThroughDiagnostics &CD =
382 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000383 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000384 CheckFallThroughForBody(S, D, Body, BlockTy, CD, AC);
385 }
386
387 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000388 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000389 CheckUnreachable(S, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000390}