blob: a46755bbd99a640f41820ebad086d58188d265b4 [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
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000018#include "clang/Basic/SourceManager.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000020#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000021#include "clang/AST/ExprObjC.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/Analysis/AnalysisContext.h"
26#include "clang/Analysis/CFG.h"
27#include "clang/Analysis/Analyses/ReachableCode.h"
28#include "llvm/ADT/BitVector.h"
29#include "llvm/Support/Casting.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000030
31using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// Unreachable code analysis.
35//===----------------------------------------------------------------------===//
36
37namespace {
38 class UnreachableCodeHandler : public reachable_code::Callback {
39 Sema &S;
40 public:
41 UnreachableCodeHandler(Sema &s) : S(s) {}
42
43 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
44 S.Diag(L, diag::warn_unreachable) << R1 << R2;
45 }
46 };
47}
48
49/// CheckUnreachable - Check for unreachable code.
50static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
51 UnreachableCodeHandler UC(S);
52 reachable_code::FindUnreachableCode(AC, UC);
53}
54
55//===----------------------------------------------------------------------===//
56// Check for missing return value.
57//===----------------------------------------------------------------------===//
58
John McCall16565aa2010-05-16 09:34:11 +000059enum ControlFlowKind {
60 UnknownFallThrough,
61 NeverFallThrough,
62 MaybeFallThrough,
63 AlwaysFallThrough,
64 NeverFallThroughOrReturn
65};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000066
67/// CheckFallThrough - Check that we don't fall off the end of a
68/// Statement that should return a value.
69///
70/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
71/// MaybeFallThrough iff we might or might not fall off the end,
72/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
73/// return. We assume NeverFallThrough iff we never fall off the end of the
74/// statement but we may return. We assume that functions not marked noreturn
75/// will return.
76static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
77 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000078 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000079
80 // The CFG leaves in dead things, and we don't want the dead code paths to
81 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000082 llvm::BitVector live(cfg->getNumBlockIDs());
83 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
84 live);
85
86 bool AddEHEdges = AC.getAddEHEdges();
87 if (!AddEHEdges && count != cfg->getNumBlockIDs())
88 // When there are things remaining dead, and we didn't add EH edges
89 // from CallExprs to the catch clauses, we have to go back and
90 // mark them as live.
91 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
92 CFGBlock &b = **I;
93 if (!live[b.getBlockID()]) {
94 if (b.pred_begin() == b.pred_end()) {
95 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
96 // When not adding EH edges from calls, catch clauses
97 // can otherwise seem dead. Avoid noting them as dead.
98 count += reachable_code::ScanReachableFromBlock(b, live);
99 continue;
100 }
101 }
102 }
103
104 // Now we know what is live, we check the live precessors of the exit block
105 // and look for fall through paths, being careful to ignore normal returns,
106 // and exceptional paths.
107 bool HasLiveReturn = false;
108 bool HasFakeEdge = false;
109 bool HasPlainEdge = false;
110 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000111
112 // Ignore default cases that aren't likely to be reachable because all
113 // enums in a switch(X) have explicit case statements.
114 CFGBlock::FilterOptions FO;
115 FO.IgnoreDefaultsWithCoveredEnums = 1;
116
117 for (CFGBlock::filtered_pred_iterator
118 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
119 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000120 if (!live[B.getBlockID()])
121 continue;
122 if (B.size() == 0) {
123 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
124 HasAbnormalEdge = true;
125 continue;
126 }
127
128 // A labeled empty statement, or the entry block...
129 HasPlainEdge = true;
130 continue;
131 }
132 Stmt *S = B[B.size()-1];
133 if (isa<ReturnStmt>(S)) {
134 HasLiveReturn = true;
135 continue;
136 }
137 if (isa<ObjCAtThrowStmt>(S)) {
138 HasFakeEdge = true;
139 continue;
140 }
141 if (isa<CXXThrowExpr>(S)) {
142 HasFakeEdge = true;
143 continue;
144 }
145 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
146 if (AS->isMSAsm()) {
147 HasFakeEdge = true;
148 HasLiveReturn = true;
149 continue;
150 }
151 }
152 if (isa<CXXTryStmt>(S)) {
153 HasAbnormalEdge = true;
154 continue;
155 }
156
157 bool NoReturnEdge = false;
158 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000159 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
160 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000161 HasAbnormalEdge = true;
162 continue;
163 }
164 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Rafael Espindola264ba482010-03-30 20:24:48 +0000165 if (getFunctionExtInfo(CEE->getType()).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000166 NoReturnEdge = true;
167 HasFakeEdge = true;
168 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
169 ValueDecl *VD = DRE->getDecl();
170 if (VD->hasAttr<NoReturnAttr>()) {
171 NoReturnEdge = true;
172 HasFakeEdge = true;
173 }
174 }
175 }
Chandler Carruth00e9cbb2010-05-17 23:51:52 +0000176 // FIXME: Remove this hack once temporaries and their destructors are
177 // modeled correctly by the CFG.
178 if (CXXExprWithTemporaries *E = dyn_cast<CXXExprWithTemporaries>(S)) {
179 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) {
180 const FunctionDecl *FD = E->getTemporary(I)->getDestructor();
181 if (FD->hasAttr<NoReturnAttr>() ||
182 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) {
183 NoReturnEdge = true;
184 HasFakeEdge = true;
185 break;
186 }
187 }
188 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000189 // FIXME: Add noreturn message sends.
190 if (NoReturnEdge == false)
191 HasPlainEdge = true;
192 }
193 if (!HasPlainEdge) {
194 if (HasLiveReturn)
195 return NeverFallThrough;
196 return NeverFallThroughOrReturn;
197 }
198 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
199 return MaybeFallThrough;
200 // This says AlwaysFallThrough for calls to functions that are not marked
201 // noreturn, that don't return. If people would like this warning to be more
202 // accurate, such functions should be marked as noreturn.
203 return AlwaysFallThrough;
204}
205
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000206namespace {
207
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000208struct CheckFallThroughDiagnostics {
209 unsigned diag_MaybeFallThrough_HasNoReturn;
210 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
211 unsigned diag_AlwaysFallThrough_HasNoReturn;
212 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
213 unsigned diag_NeverFallThroughOrReturn;
214 bool funMode;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000215
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000216 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000217 CheckFallThroughDiagnostics D;
218 D.diag_MaybeFallThrough_HasNoReturn =
219 diag::warn_falloff_noreturn_function;
220 D.diag_MaybeFallThrough_ReturnsNonVoid =
221 diag::warn_maybe_falloff_nonvoid_function;
222 D.diag_AlwaysFallThrough_HasNoReturn =
223 diag::warn_falloff_noreturn_function;
224 D.diag_AlwaysFallThrough_ReturnsNonVoid =
225 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000226
227 // Don't suggest that virtual functions be marked "noreturn", since they
228 // might be overridden by non-noreturn functions.
229 bool isVirtualMethod = false;
230 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
231 isVirtualMethod = Method->isVirtual();
232
233 if (!isVirtualMethod)
234 D.diag_NeverFallThroughOrReturn =
235 diag::warn_suggest_noreturn_function;
236 else
237 D.diag_NeverFallThroughOrReturn = 0;
238
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000239 D.funMode = true;
240 return D;
241 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000242
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000243 static CheckFallThroughDiagnostics MakeForBlock() {
244 CheckFallThroughDiagnostics D;
245 D.diag_MaybeFallThrough_HasNoReturn =
246 diag::err_noreturn_block_has_return_expr;
247 D.diag_MaybeFallThrough_ReturnsNonVoid =
248 diag::err_maybe_falloff_nonvoid_block;
249 D.diag_AlwaysFallThrough_HasNoReturn =
250 diag::err_noreturn_block_has_return_expr;
251 D.diag_AlwaysFallThrough_ReturnsNonVoid =
252 diag::err_falloff_nonvoid_block;
253 D.diag_NeverFallThroughOrReturn =
254 diag::warn_suggest_noreturn_block;
255 D.funMode = false;
256 return D;
257 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000258
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000259 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
260 bool HasNoReturn) const {
261 if (funMode) {
262 return (D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
263 == Diagnostic::Ignored || ReturnsVoid)
264 && (D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
265 == Diagnostic::Ignored || !HasNoReturn)
266 && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
267 == Diagnostic::Ignored || !ReturnsVoid);
268 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000269
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000270 // For blocks.
271 return ReturnsVoid && !HasNoReturn
272 && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
273 == Diagnostic::Ignored || !ReturnsVoid);
274 }
275};
276
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000277}
278
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000279/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
280/// function that should return a value. Check that we don't fall off the end
281/// of a noreturn function. We assume that functions and blocks not marked
282/// noreturn will return.
283static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
284 QualType BlockTy,
285 const CheckFallThroughDiagnostics& CD,
286 AnalysisContext &AC) {
287
288 bool ReturnsVoid = false;
289 bool HasNoReturn = false;
290
291 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
292 ReturnsVoid = FD->getResultType()->isVoidType();
293 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000294 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000295 }
296 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
297 ReturnsVoid = MD->getResultType()->isVoidType();
298 HasNoReturn = MD->hasAttr<NoReturnAttr>();
299 }
300 else if (isa<BlockDecl>(D)) {
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000301 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000302 BlockTy->getPointeeType()->getAs<FunctionType>()) {
303 if (FT->getResultType()->isVoidType())
304 ReturnsVoid = true;
305 if (FT->getNoReturnAttr())
306 HasNoReturn = true;
307 }
308 }
309
310 Diagnostic &Diags = S.getDiagnostics();
311
312 // Short circuit for compilation speed.
313 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
314 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000315
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000316 // FIXME: Function try block
317 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
318 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000319 case UnknownFallThrough:
320 break;
321
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000322 case MaybeFallThrough:
323 if (HasNoReturn)
324 S.Diag(Compound->getRBracLoc(),
325 CD.diag_MaybeFallThrough_HasNoReturn);
326 else if (!ReturnsVoid)
327 S.Diag(Compound->getRBracLoc(),
328 CD.diag_MaybeFallThrough_ReturnsNonVoid);
329 break;
330 case AlwaysFallThrough:
331 if (HasNoReturn)
332 S.Diag(Compound->getRBracLoc(),
333 CD.diag_AlwaysFallThrough_HasNoReturn);
334 else if (!ReturnsVoid)
335 S.Diag(Compound->getRBracLoc(),
336 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
337 break;
338 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000339 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000340 S.Diag(Compound->getLBracLoc(),
341 CD.diag_NeverFallThroughOrReturn);
342 break;
343 case NeverFallThrough:
344 break;
345 }
346 }
347}
348
349//===----------------------------------------------------------------------===//
350// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
351// warnings on a function, method, or block.
352//===----------------------------------------------------------------------===//
353
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000354clang::sema::AnalysisBasedWarnings::Policy::Policy() {
355 enableCheckFallThrough = 1;
356 enableCheckUnreachable = 0;
357}
358
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000359clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
360 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000361 DefaultPolicy.enableCheckUnreachable = (unsigned)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000362 (D.getDiagnosticLevel(diag::warn_unreachable) != Diagnostic::Ignored);
363}
364
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000365void clang::sema::
366AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000367 const Decl *D, QualType BlockTy) {
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000368
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000369 assert(BlockTy.isNull() || isa<BlockDecl>(D));
Ted Kremenekd068aab2010-03-20 21:11:09 +0000370
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000371 // We avoid doing analysis-based warnings when there are errors for
372 // two reasons:
373 // (1) The CFGs often can't be constructed (if the body is invalid), so
374 // don't bother trying.
375 // (2) The code already has problems; running the analysis just takes more
376 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000377 Diagnostic &Diags = S.getDiagnostics();
378
379 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000380 return;
381
382 // Do not do any analysis for declarations in system headers if we are
383 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000384 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000385 S.SourceMgr.isInSystemHeader(D->getLocation()))
386 return;
387
John McCalle0054f62010-08-25 05:56:39 +0000388 // For code in dependent contexts, we'll do this at instantiation time.
389 if (cast<DeclContext>(D)->isDependentContext())
390 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000391
392 const Stmt *Body = D->getBody();
393 assert(Body);
394
395 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
396 // explosion for destrutors that can result and the compile time hit.
Zhongxing Xu7a420542010-07-19 13:16:50 +0000397 AnalysisContext AC(D, 0, false);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000398
399 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000400 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000401 const CheckFallThroughDiagnostics &CD =
402 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000403 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000404 CheckFallThroughForBody(S, D, Body, BlockTy, CD, AC);
405 }
406
407 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000408 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000409 CheckUnreachable(S, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000410}
John McCalle0054f62010-08-25 05:56:39 +0000411
412void clang::sema::
413AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
414 const BlockExpr *E) {
415 return IssueWarnings(P, E->getBlockDecl(), E->getType());
416}
417
418void clang::sema::
419AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
420 const ObjCMethodDecl *D) {
421 return IssueWarnings(P, D, QualType());
422}
423
424void clang::sema::
425AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
426 const FunctionDecl *D) {
427 return IssueWarnings(P, D, QualType());
428}