blob: e71f2dfb866a9fb18ac1f1a671aff29764298644 [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 Kremenek351ba912011-02-23 01:52:04 +000018#include "clang/Sema/ScopeInfo.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000019#include "clang/Basic/SourceManager.h"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000020#include "clang/Lex/Preprocessor.h"
John McCall7cd088e2010-08-24 07:21:54 +000021#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000023#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/Analysis/AnalysisContext.h"
28#include "clang/Analysis/CFG.h"
29#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000030#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
31#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000032#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000033#include "llvm/ADT/BitVector.h"
34#include "llvm/Support/Casting.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000035
36using namespace clang;
37
38//===----------------------------------------------------------------------===//
39// Unreachable code analysis.
40//===----------------------------------------------------------------------===//
41
42namespace {
43 class UnreachableCodeHandler : public reachable_code::Callback {
44 Sema &S;
45 public:
46 UnreachableCodeHandler(Sema &s) : S(s) {}
47
48 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
49 S.Diag(L, diag::warn_unreachable) << R1 << R2;
50 }
51 };
52}
53
54/// CheckUnreachable - Check for unreachable code.
55static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
56 UnreachableCodeHandler UC(S);
57 reachable_code::FindUnreachableCode(AC, UC);
58}
59
60//===----------------------------------------------------------------------===//
61// Check for missing return value.
62//===----------------------------------------------------------------------===//
63
John McCall16565aa2010-05-16 09:34:11 +000064enum ControlFlowKind {
65 UnknownFallThrough,
66 NeverFallThrough,
67 MaybeFallThrough,
68 AlwaysFallThrough,
69 NeverFallThroughOrReturn
70};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000071
72/// CheckFallThrough - Check that we don't fall off the end of a
73/// Statement that should return a value.
74///
75/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
76/// MaybeFallThrough iff we might or might not fall off the end,
77/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
78/// return. We assume NeverFallThrough iff we never fall off the end of the
79/// statement but we may return. We assume that functions not marked noreturn
80/// will return.
81static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
82 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000083 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000084
85 // The CFG leaves in dead things, and we don't want the dead code paths to
86 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000087 llvm::BitVector live(cfg->getNumBlockIDs());
88 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
89 live);
90
91 bool AddEHEdges = AC.getAddEHEdges();
92 if (!AddEHEdges && count != cfg->getNumBlockIDs())
93 // When there are things remaining dead, and we didn't add EH edges
94 // from CallExprs to the catch clauses, we have to go back and
95 // mark them as live.
96 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
97 CFGBlock &b = **I;
98 if (!live[b.getBlockID()]) {
99 if (b.pred_begin() == b.pred_end()) {
100 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
101 // When not adding EH edges from calls, catch clauses
102 // can otherwise seem dead. Avoid noting them as dead.
103 count += reachable_code::ScanReachableFromBlock(b, live);
104 continue;
105 }
106 }
107 }
108
109 // Now we know what is live, we check the live precessors of the exit block
110 // and look for fall through paths, being careful to ignore normal returns,
111 // and exceptional paths.
112 bool HasLiveReturn = false;
113 bool HasFakeEdge = false;
114 bool HasPlainEdge = false;
115 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000116
117 // Ignore default cases that aren't likely to be reachable because all
118 // enums in a switch(X) have explicit case statements.
119 CFGBlock::FilterOptions FO;
120 FO.IgnoreDefaultsWithCoveredEnums = 1;
121
122 for (CFGBlock::filtered_pred_iterator
123 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
124 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000125 if (!live[B.getBlockID()])
126 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000127
128 // Destructors can appear after the 'return' in the CFG. This is
129 // normal. We need to look pass the destructors for the return
130 // statement (if it exists).
131 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000132 bool hasNoReturnDtor = false;
133
Ted Kremenek5811f592011-01-26 04:49:52 +0000134 for ( ; ri != re ; ++ri) {
135 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000136
137 // FIXME: The right solution is to just sever the edges in the
138 // CFG itself.
139 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
Ted Kremenekc5aff442011-03-03 01:21:32 +0000140 if (iDtor->isNoReturn(AC.getASTContext())) {
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000141 hasNoReturnDtor = true;
142 HasFakeEdge = true;
143 break;
144 }
145
Ted Kremenek5811f592011-01-26 04:49:52 +0000146 if (isa<CFGStmt>(CE))
147 break;
148 }
149
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000150 if (hasNoReturnDtor)
151 continue;
152
Ted Kremenek5811f592011-01-26 04:49:52 +0000153 // No more CFGElements in the block?
154 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000155 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
156 HasAbnormalEdge = true;
157 continue;
158 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000159 // A labeled empty statement, or the entry block...
160 HasPlainEdge = true;
161 continue;
162 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000163
Ted Kremenek5811f592011-01-26 04:49:52 +0000164 CFGStmt CS = cast<CFGStmt>(*ri);
Zhongxing Xub36cd3e2010-09-16 01:25:47 +0000165 Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000166 if (isa<ReturnStmt>(S)) {
167 HasLiveReturn = true;
168 continue;
169 }
170 if (isa<ObjCAtThrowStmt>(S)) {
171 HasFakeEdge = true;
172 continue;
173 }
174 if (isa<CXXThrowExpr>(S)) {
175 HasFakeEdge = true;
176 continue;
177 }
178 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
179 if (AS->isMSAsm()) {
180 HasFakeEdge = true;
181 HasLiveReturn = true;
182 continue;
183 }
184 }
185 if (isa<CXXTryStmt>(S)) {
186 HasAbnormalEdge = true;
187 continue;
188 }
189
190 bool NoReturnEdge = false;
191 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000192 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
193 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000194 HasAbnormalEdge = true;
195 continue;
196 }
197 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Rafael Espindola264ba482010-03-30 20:24:48 +0000198 if (getFunctionExtInfo(CEE->getType()).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000199 NoReturnEdge = true;
200 HasFakeEdge = true;
201 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
202 ValueDecl *VD = DRE->getDecl();
203 if (VD->hasAttr<NoReturnAttr>()) {
204 NoReturnEdge = true;
205 HasFakeEdge = true;
206 }
207 }
208 }
209 // FIXME: Add noreturn message sends.
210 if (NoReturnEdge == false)
211 HasPlainEdge = true;
212 }
213 if (!HasPlainEdge) {
214 if (HasLiveReturn)
215 return NeverFallThrough;
216 return NeverFallThroughOrReturn;
217 }
218 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
219 return MaybeFallThrough;
220 // This says AlwaysFallThrough for calls to functions that are not marked
221 // noreturn, that don't return. If people would like this warning to be more
222 // accurate, such functions should be marked as noreturn.
223 return AlwaysFallThrough;
224}
225
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000226namespace {
227
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000228struct CheckFallThroughDiagnostics {
229 unsigned diag_MaybeFallThrough_HasNoReturn;
230 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
231 unsigned diag_AlwaysFallThrough_HasNoReturn;
232 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
233 unsigned diag_NeverFallThroughOrReturn;
234 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000235 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000236
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000237 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000238 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000239 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000240 D.diag_MaybeFallThrough_HasNoReturn =
241 diag::warn_falloff_noreturn_function;
242 D.diag_MaybeFallThrough_ReturnsNonVoid =
243 diag::warn_maybe_falloff_nonvoid_function;
244 D.diag_AlwaysFallThrough_HasNoReturn =
245 diag::warn_falloff_noreturn_function;
246 D.diag_AlwaysFallThrough_ReturnsNonVoid =
247 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000248
249 // Don't suggest that virtual functions be marked "noreturn", since they
250 // might be overridden by non-noreturn functions.
251 bool isVirtualMethod = false;
252 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
253 isVirtualMethod = Method->isVirtual();
254
255 if (!isVirtualMethod)
256 D.diag_NeverFallThroughOrReturn =
257 diag::warn_suggest_noreturn_function;
258 else
259 D.diag_NeverFallThroughOrReturn = 0;
260
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000261 D.funMode = true;
262 return D;
263 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000264
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000265 static CheckFallThroughDiagnostics MakeForBlock() {
266 CheckFallThroughDiagnostics D;
267 D.diag_MaybeFallThrough_HasNoReturn =
268 diag::err_noreturn_block_has_return_expr;
269 D.diag_MaybeFallThrough_ReturnsNonVoid =
270 diag::err_maybe_falloff_nonvoid_block;
271 D.diag_AlwaysFallThrough_HasNoReturn =
272 diag::err_noreturn_block_has_return_expr;
273 D.diag_AlwaysFallThrough_ReturnsNonVoid =
274 diag::err_falloff_nonvoid_block;
275 D.diag_NeverFallThroughOrReturn =
276 diag::warn_suggest_noreturn_block;
277 D.funMode = false;
278 return D;
279 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000280
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000281 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
282 bool HasNoReturn) const {
283 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000284 return (ReturnsVoid ||
285 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
286 FuncLoc) == Diagnostic::Ignored)
287 && (!HasNoReturn ||
288 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
289 FuncLoc) == Diagnostic::Ignored)
290 && (!ReturnsVoid ||
291 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
292 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000293 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000294
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000295 // For blocks.
296 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000297 && (!ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
299 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000300 }
301};
302
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000303}
304
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000305/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
306/// function that should return a value. Check that we don't fall off the end
307/// of a noreturn function. We assume that functions and blocks not marked
308/// noreturn will return.
309static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000310 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000311 const CheckFallThroughDiagnostics& CD,
312 AnalysisContext &AC) {
313
314 bool ReturnsVoid = false;
315 bool HasNoReturn = false;
316
317 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
318 ReturnsVoid = FD->getResultType()->isVoidType();
319 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000320 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000321 }
322 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
323 ReturnsVoid = MD->getResultType()->isVoidType();
324 HasNoReturn = MD->hasAttr<NoReturnAttr>();
325 }
326 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000327 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000328 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000329 BlockTy->getPointeeType()->getAs<FunctionType>()) {
330 if (FT->getResultType()->isVoidType())
331 ReturnsVoid = true;
332 if (FT->getNoReturnAttr())
333 HasNoReturn = true;
334 }
335 }
336
337 Diagnostic &Diags = S.getDiagnostics();
338
339 // Short circuit for compilation speed.
340 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
341 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000342
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000343 // FIXME: Function try block
344 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
345 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000346 case UnknownFallThrough:
347 break;
348
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000349 case MaybeFallThrough:
350 if (HasNoReturn)
351 S.Diag(Compound->getRBracLoc(),
352 CD.diag_MaybeFallThrough_HasNoReturn);
353 else if (!ReturnsVoid)
354 S.Diag(Compound->getRBracLoc(),
355 CD.diag_MaybeFallThrough_ReturnsNonVoid);
356 break;
357 case AlwaysFallThrough:
358 if (HasNoReturn)
359 S.Diag(Compound->getRBracLoc(),
360 CD.diag_AlwaysFallThrough_HasNoReturn);
361 else if (!ReturnsVoid)
362 S.Diag(Compound->getRBracLoc(),
363 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
364 break;
365 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000366 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000367 S.Diag(Compound->getLBracLoc(),
368 CD.diag_NeverFallThroughOrReturn);
369 break;
370 case NeverFallThrough:
371 break;
372 }
373 }
374}
375
376//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000377// -Wuninitialized
378//===----------------------------------------------------------------------===//
379
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000380typedef std::pair<const Expr*, bool> UninitUse;
381
Ted Kremenek610068c2011-01-15 02:58:47 +0000382namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000383struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000384 bool operator()(const UninitUse &a, const UninitUse &b) {
385 SourceLocation aLoc = a.first->getLocStart();
386 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000387 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
388 }
389};
390
Ted Kremenek610068c2011-01-15 02:58:47 +0000391class UninitValsDiagReporter : public UninitVariablesHandler {
392 Sema &S;
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000393 typedef llvm::SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000394 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
395 UsesMap *uses;
396
Ted Kremenek610068c2011-01-15 02:58:47 +0000397public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000398 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
399 ~UninitValsDiagReporter() {
400 flushDiagnostics();
401 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000402
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000403 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
404 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000405 if (!uses)
406 uses = new UsesMap();
407
408 UsesVec *&vec = (*uses)[vd];
409 if (!vec)
410 vec = new UsesVec();
411
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000412 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000413 }
414
415 void flushDiagnostics() {
416 if (!uses)
417 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000418
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000419 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
420 const VarDecl *vd = i->first;
421 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000422
423 bool fixitIssued = false;
424
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000425 // Sort the uses by their SourceLocations. While not strictly
426 // guaranteed to produce them in line/column order, this will provide
427 // a stable ordering.
428 std::sort(vec->begin(), vec->end(), SLocSort());
429
430 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve; ++vi)
431 {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000432 const bool isAlwaysUninit = vi->second;
433 if (const DeclRefExpr *dr = dyn_cast<DeclRefExpr>(vi->first)) {
434 S.Diag(dr->getLocStart(),
435 isAlwaysUninit ? diag::warn_uninit_var
436 : diag::warn_maybe_uninit_var)
Ted Kremenek609e3172011-02-02 23:35:53 +0000437 << vd->getDeclName() << dr->getSourceRange();
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000438 }
439 else {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000440 const BlockExpr *be = cast<BlockExpr>(vi->first);
441 S.Diag(be->getLocStart(),
442 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
443 : diag::warn_maybe_uninit_var_captured_by_block)
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000444 << vd->getDeclName();
445 }
Ted Kremenek609e3172011-02-02 23:35:53 +0000446
447 // Report where the variable was declared.
448 S.Diag(vd->getLocStart(), diag::note_uninit_var_def)
449 << vd->getDeclName();
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000450
Ted Kremenek609e3172011-02-02 23:35:53 +0000451 // Only report the fixit once.
452 if (fixitIssued)
453 continue;
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000454
Ted Kremenek609e3172011-02-02 23:35:53 +0000455 fixitIssued = true;
456
457 // Suggest possible initialization (if any).
458 const char *initialization = 0;
459 QualType vdTy = vd->getType().getCanonicalType();
Ted Kremenek09f57b92011-02-05 01:18:18 +0000460
Ted Kremenek609e3172011-02-02 23:35:53 +0000461 if (vdTy->getAs<ObjCObjectPointerType>()) {
462 // Check if 'nil' is defined.
463 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
464 initialization = " = nil";
465 else
466 initialization = " = 0";
467 }
468 else if (vdTy->isRealFloatingType())
469 initialization = " = 0.0";
470 else if (vdTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
471 initialization = " = false";
Ted Kremenek09f57b92011-02-05 01:18:18 +0000472 else if (vdTy->isEnumeralType())
473 continue;
Ted Kremenek609e3172011-02-02 23:35:53 +0000474 else if (vdTy->isScalarType())
Ted Kremenekdcfb3602011-01-21 22:49:49 +0000475 initialization = " = 0";
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000476
Ted Kremenek609e3172011-02-02 23:35:53 +0000477 if (initialization) {
478 SourceLocation loc = S.PP.getLocForEndOfToken(vd->getLocEnd());
479 S.Diag(loc, diag::note_var_fixit_add_initialization)
480 << FixItHint::CreateInsertion(loc, initialization);
481 }
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000482 }
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000483 delete vec;
484 }
485 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000486 }
487};
488}
489
490//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000491// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
492// warnings on a function, method, or block.
493//===----------------------------------------------------------------------===//
494
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000495clang::sema::AnalysisBasedWarnings::Policy::Policy() {
496 enableCheckFallThrough = 1;
497 enableCheckUnreachable = 0;
498}
499
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000500clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
501 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000502 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000503 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
504 Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000505}
506
Ted Kremenek351ba912011-02-23 01:52:04 +0000507static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
508 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
509 i = fscope->PossiblyUnreachableDiags.begin(),
510 e = fscope->PossiblyUnreachableDiags.end();
511 i != e; ++i) {
512 const sema::PossiblyUnreachableDiag &D = *i;
513 S.Diag(D.Loc, D.PD);
514 }
515}
516
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000517void clang::sema::
518AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000519 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000520 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000521
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000522 // We avoid doing analysis-based warnings when there are errors for
523 // two reasons:
524 // (1) The CFGs often can't be constructed (if the body is invalid), so
525 // don't bother trying.
526 // (2) The code already has problems; running the analysis just takes more
527 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000528 Diagnostic &Diags = S.getDiagnostics();
529
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000530 // Do not do any analysis for declarations in system headers if we are
531 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000532 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000533 S.SourceMgr.isInSystemHeader(D->getLocation()))
534 return;
535
John McCalle0054f62010-08-25 05:56:39 +0000536 // For code in dependent contexts, we'll do this at instantiation time.
537 if (cast<DeclContext>(D)->isDependentContext())
538 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000539
Ted Kremenek351ba912011-02-23 01:52:04 +0000540 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
541 // Flush out any possibly unreachable diagnostics.
542 flushDiagnostics(S, fscope);
543 return;
544 }
545
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000546 const Stmt *Body = D->getBody();
547 assert(Body);
548
549 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
550 // explosion for destrutors that can result and the compile time hit.
Chandler Carrutheeef9242011-01-08 06:54:40 +0000551 AnalysisContext AC(D, 0, /*useUnoptimizedCFG=*/false, /*addehedges=*/false,
552 /*addImplicitDtors=*/true, /*addInitializers=*/true);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000553
Ted Kremenek351ba912011-02-23 01:52:04 +0000554 // Emit delayed diagnostics.
555 if (!fscope->PossiblyUnreachableDiags.empty()) {
556 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000557
558 // Register the expressions with the CFGBuilder.
559 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
560 i = fscope->PossiblyUnreachableDiags.begin(),
561 e = fscope->PossiblyUnreachableDiags.end();
562 i != e; ++i) {
563 if (const Stmt *stmt = i->stmt)
564 AC.registerForcedBlockExpression(stmt);
565 }
566
567 if (AC.getCFG()) {
568 analyzed = true;
569 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
570 i = fscope->PossiblyUnreachableDiags.begin(),
571 e = fscope->PossiblyUnreachableDiags.end();
572 i != e; ++i)
573 {
574 const sema::PossiblyUnreachableDiag &D = *i;
575 bool processed = false;
576 if (const Stmt *stmt = i->stmt) {
577 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
578 assert(block);
579 if (CFGReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000580 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000581 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000582 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000583 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000584 }
585 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000586 if (!processed) {
587 // Emit the warning anyway if we cannot map to a basic block.
588 S.Diag(D.Loc, D.PD);
589 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000590 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000591 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000592
593 if (!analyzed)
594 flushDiagnostics(S, fscope);
595 }
596
597
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000598 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000599 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000600 const CheckFallThroughDiagnostics &CD =
601 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000602 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000603 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000604 }
605
606 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000607 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000608 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +0000609
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000610 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000611 != Diagnostic::Ignored) {
Ted Kremenek63b54102011-02-01 17:43:21 +0000612 ASTContext &ctx = D->getASTContext();
613 llvm::OwningPtr<CFG> tmpCFG;
614 bool useAlternateCFG = false;
615 if (ctx.getLangOptions().CPlusPlus) {
616 // Temporary workaround: implicit dtors in the CFG can confuse
617 // the path-sensitivity in the uninitialized values analysis.
618 // For now create (if necessary) a separate CFG without implicit dtors.
619 // FIXME: We should not need to do this, as it results in multiple
620 // CFGs getting constructed.
621 CFG::BuildOptions B;
622 B.AddEHEdges = false;
623 B.AddImplicitDtors = false;
624 B.AddInitializers = true;
625 tmpCFG.reset(CFG::buildCFG(D, AC.getBody(), &ctx, B));
626 useAlternateCFG = true;
627 }
628 CFG *cfg = useAlternateCFG ? tmpCFG.get() : AC.getCFG();
629 if (cfg) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000630 UninitValsDiagReporter reporter(S);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000631 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
632 reporter);
Ted Kremenek610068c2011-01-15 02:58:47 +0000633 }
634 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000635}