blob: 6a7c5d3dc3a980cc8e6529acde6d46bebfb12c51 [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"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000020#include "clang/Basic/SourceLocation.h"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000021#include "clang/Lex/Preprocessor.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000024#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000029#include "clang/AST/StmtVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000030#include "clang/Analysis/AnalysisContext.h"
31#include "clang/Analysis/CFG.h"
32#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000033#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000034#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000035#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000036#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000037#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000038#include "llvm/ADT/FoldingSet.h"
39#include "llvm/ADT/ImmutableMap.h"
40#include "llvm/ADT/PostOrderIterator.h"
41#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000042#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000043#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000044#include <algorithm>
45#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000046
47using namespace clang;
48
49//===----------------------------------------------------------------------===//
50// Unreachable code analysis.
51//===----------------------------------------------------------------------===//
52
53namespace {
54 class UnreachableCodeHandler : public reachable_code::Callback {
55 Sema &S;
56 public:
57 UnreachableCodeHandler(Sema &s) : S(s) {}
58
59 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
60 S.Diag(L, diag::warn_unreachable) << R1 << R2;
61 }
62 };
63}
64
65/// CheckUnreachable - Check for unreachable code.
66static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
67 UnreachableCodeHandler UC(S);
68 reachable_code::FindUnreachableCode(AC, UC);
69}
70
71//===----------------------------------------------------------------------===//
72// Check for missing return value.
73//===----------------------------------------------------------------------===//
74
John McCall16565aa2010-05-16 09:34:11 +000075enum ControlFlowKind {
76 UnknownFallThrough,
77 NeverFallThrough,
78 MaybeFallThrough,
79 AlwaysFallThrough,
80 NeverFallThroughOrReturn
81};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000082
83/// CheckFallThrough - Check that we don't fall off the end of a
84/// Statement that should return a value.
85///
86/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
87/// MaybeFallThrough iff we might or might not fall off the end,
88/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
89/// return. We assume NeverFallThrough iff we never fall off the end of the
90/// statement but we may return. We assume that functions not marked noreturn
91/// will return.
92static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
93 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000094 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000095
96 // The CFG leaves in dead things, and we don't want the dead code paths to
97 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000098 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +000099 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000100 live);
101
102 bool AddEHEdges = AC.getAddEHEdges();
103 if (!AddEHEdges && count != cfg->getNumBlockIDs())
104 // When there are things remaining dead, and we didn't add EH edges
105 // from CallExprs to the catch clauses, we have to go back and
106 // mark them as live.
107 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
108 CFGBlock &b = **I;
109 if (!live[b.getBlockID()]) {
110 if (b.pred_begin() == b.pred_end()) {
111 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
112 // When not adding EH edges from calls, catch clauses
113 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000114 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000115 continue;
116 }
117 }
118 }
119
120 // Now we know what is live, we check the live precessors of the exit block
121 // and look for fall through paths, being careful to ignore normal returns,
122 // and exceptional paths.
123 bool HasLiveReturn = false;
124 bool HasFakeEdge = false;
125 bool HasPlainEdge = false;
126 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000127
128 // Ignore default cases that aren't likely to be reachable because all
129 // enums in a switch(X) have explicit case statements.
130 CFGBlock::FilterOptions FO;
131 FO.IgnoreDefaultsWithCoveredEnums = 1;
132
133 for (CFGBlock::filtered_pred_iterator
134 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
135 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000136 if (!live[B.getBlockID()])
137 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000138
139 // Destructors can appear after the 'return' in the CFG. This is
140 // normal. We need to look pass the destructors for the return
141 // statement (if it exists).
142 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000143 bool hasNoReturnDtor = false;
144
Ted Kremenek5811f592011-01-26 04:49:52 +0000145 for ( ; ri != re ; ++ri) {
146 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000147
148 // FIXME: The right solution is to just sever the edges in the
149 // CFG itself.
150 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
Ted Kremenekc5aff442011-03-03 01:21:32 +0000151 if (iDtor->isNoReturn(AC.getASTContext())) {
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000152 hasNoReturnDtor = true;
153 HasFakeEdge = true;
154 break;
155 }
156
Ted Kremenek5811f592011-01-26 04:49:52 +0000157 if (isa<CFGStmt>(CE))
158 break;
159 }
160
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000161 if (hasNoReturnDtor)
162 continue;
163
Ted Kremenek5811f592011-01-26 04:49:52 +0000164 // No more CFGElements in the block?
165 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000166 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
167 HasAbnormalEdge = true;
168 continue;
169 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000170 // A labeled empty statement, or the entry block...
171 HasPlainEdge = true;
172 continue;
173 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000174
Ted Kremenek5811f592011-01-26 04:49:52 +0000175 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000176 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000177 if (isa<ReturnStmt>(S)) {
178 HasLiveReturn = true;
179 continue;
180 }
181 if (isa<ObjCAtThrowStmt>(S)) {
182 HasFakeEdge = true;
183 continue;
184 }
185 if (isa<CXXThrowExpr>(S)) {
186 HasFakeEdge = true;
187 continue;
188 }
189 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
190 if (AS->isMSAsm()) {
191 HasFakeEdge = true;
192 HasLiveReturn = true;
193 continue;
194 }
195 }
196 if (isa<CXXTryStmt>(S)) {
197 HasAbnormalEdge = true;
198 continue;
199 }
200
201 bool NoReturnEdge = false;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000202 if (const CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000203 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
204 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000205 HasAbnormalEdge = true;
206 continue;
207 }
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000208 const Expr *CEE = C->getCallee()->IgnoreParenCasts();
John McCall1de85332011-05-11 07:19:11 +0000209 QualType calleeType = CEE->getType();
210 if (calleeType == AC.getASTContext().BoundMemberTy) {
211 calleeType = Expr::findBoundMemberType(CEE);
212 assert(!calleeType.isNull() && "analyzing unresolved call?");
213 }
214 if (getFunctionExtInfo(calleeType).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000215 NoReturnEdge = true;
216 HasFakeEdge = true;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000217 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
218 const ValueDecl *VD = DRE->getDecl();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000219 if (VD->hasAttr<NoReturnAttr>()) {
220 NoReturnEdge = true;
221 HasFakeEdge = true;
222 }
223 }
224 }
225 // FIXME: Add noreturn message sends.
226 if (NoReturnEdge == false)
227 HasPlainEdge = true;
228 }
229 if (!HasPlainEdge) {
230 if (HasLiveReturn)
231 return NeverFallThrough;
232 return NeverFallThroughOrReturn;
233 }
234 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
235 return MaybeFallThrough;
236 // This says AlwaysFallThrough for calls to functions that are not marked
237 // noreturn, that don't return. If people would like this warning to be more
238 // accurate, such functions should be marked as noreturn.
239 return AlwaysFallThrough;
240}
241
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000242namespace {
243
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000244struct CheckFallThroughDiagnostics {
245 unsigned diag_MaybeFallThrough_HasNoReturn;
246 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
247 unsigned diag_AlwaysFallThrough_HasNoReturn;
248 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
249 unsigned diag_NeverFallThroughOrReturn;
250 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000251 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000252
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000253 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000254 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000255 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000256 D.diag_MaybeFallThrough_HasNoReturn =
257 diag::warn_falloff_noreturn_function;
258 D.diag_MaybeFallThrough_ReturnsNonVoid =
259 diag::warn_maybe_falloff_nonvoid_function;
260 D.diag_AlwaysFallThrough_HasNoReturn =
261 diag::warn_falloff_noreturn_function;
262 D.diag_AlwaysFallThrough_ReturnsNonVoid =
263 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000264
265 // Don't suggest that virtual functions be marked "noreturn", since they
266 // might be overridden by non-noreturn functions.
267 bool isVirtualMethod = false;
268 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
269 isVirtualMethod = Method->isVirtual();
270
271 if (!isVirtualMethod)
272 D.diag_NeverFallThroughOrReturn =
273 diag::warn_suggest_noreturn_function;
274 else
275 D.diag_NeverFallThroughOrReturn = 0;
276
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000277 D.funMode = true;
278 return D;
279 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000280
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000281 static CheckFallThroughDiagnostics MakeForBlock() {
282 CheckFallThroughDiagnostics D;
283 D.diag_MaybeFallThrough_HasNoReturn =
284 diag::err_noreturn_block_has_return_expr;
285 D.diag_MaybeFallThrough_ReturnsNonVoid =
286 diag::err_maybe_falloff_nonvoid_block;
287 D.diag_AlwaysFallThrough_HasNoReturn =
288 diag::err_noreturn_block_has_return_expr;
289 D.diag_AlwaysFallThrough_ReturnsNonVoid =
290 diag::err_falloff_nonvoid_block;
291 D.diag_NeverFallThroughOrReturn =
292 diag::warn_suggest_noreturn_block;
293 D.funMode = false;
294 return D;
295 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000296
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000297 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
298 bool HasNoReturn) const {
299 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000300 return (ReturnsVoid ||
301 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
302 FuncLoc) == Diagnostic::Ignored)
303 && (!HasNoReturn ||
304 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
305 FuncLoc) == Diagnostic::Ignored)
306 && (!ReturnsVoid ||
307 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
308 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000309 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000310
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000311 // For blocks.
312 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000313 && (!ReturnsVoid ||
314 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
315 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000316 }
317};
318
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000319}
320
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000321/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
322/// function that should return a value. Check that we don't fall off the end
323/// of a noreturn function. We assume that functions and blocks not marked
324/// noreturn will return.
325static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000326 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000327 const CheckFallThroughDiagnostics& CD,
328 AnalysisContext &AC) {
329
330 bool ReturnsVoid = false;
331 bool HasNoReturn = false;
332
333 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
334 ReturnsVoid = FD->getResultType()->isVoidType();
335 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000336 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000337 }
338 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
339 ReturnsVoid = MD->getResultType()->isVoidType();
340 HasNoReturn = MD->hasAttr<NoReturnAttr>();
341 }
342 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000343 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000344 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000345 BlockTy->getPointeeType()->getAs<FunctionType>()) {
346 if (FT->getResultType()->isVoidType())
347 ReturnsVoid = true;
348 if (FT->getNoReturnAttr())
349 HasNoReturn = true;
350 }
351 }
352
353 Diagnostic &Diags = S.getDiagnostics();
354
355 // Short circuit for compilation speed.
356 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
357 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000358
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000359 // FIXME: Function try block
360 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
361 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000362 case UnknownFallThrough:
363 break;
364
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000365 case MaybeFallThrough:
366 if (HasNoReturn)
367 S.Diag(Compound->getRBracLoc(),
368 CD.diag_MaybeFallThrough_HasNoReturn);
369 else if (!ReturnsVoid)
370 S.Diag(Compound->getRBracLoc(),
371 CD.diag_MaybeFallThrough_ReturnsNonVoid);
372 break;
373 case AlwaysFallThrough:
374 if (HasNoReturn)
375 S.Diag(Compound->getRBracLoc(),
376 CD.diag_AlwaysFallThrough_HasNoReturn);
377 else if (!ReturnsVoid)
378 S.Diag(Compound->getRBracLoc(),
379 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
380 break;
381 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000382 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
383 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
384 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000385 << 0 << FD;
386 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
387 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
388 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000389 } else {
390 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
391 }
392 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000393 break;
394 case NeverFallThrough:
395 break;
396 }
397 }
398}
399
400//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000401// -Wuninitialized
402//===----------------------------------------------------------------------===//
403
Ted Kremenek6f417152011-04-04 20:56:00 +0000404namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000405/// ContainsReference - A visitor class to search for references to
406/// a particular declaration (the needle) within any evaluated component of an
407/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000408class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000409 bool FoundReference;
410 const DeclRefExpr *Needle;
411
Ted Kremenek6f417152011-04-04 20:56:00 +0000412public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000413 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
414 : EvaluatedExprVisitor<ContainsReference>(Context),
415 FoundReference(false), Needle(Needle) {}
416
417 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000418 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000419 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000420 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000421
422 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000423 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000424
425 void VisitDeclRefExpr(DeclRefExpr *E) {
426 if (E == Needle)
427 FoundReference = true;
428 else
429 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000430 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000431
432 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000433};
434}
435
David Blaikie4f4f3492011-09-10 05:35:08 +0000436static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
437 // Don't issue a fixit if there is already an initializer.
438 if (VD->getInit())
439 return false;
440
441 // Suggest possible initialization (if any).
442 const char *initialization = 0;
443 QualType VariableTy = VD->getType().getCanonicalType();
444
445 if (VariableTy->isObjCObjectPointerType() ||
446 VariableTy->isBlockPointerType()) {
447 // Check if 'nil' is defined.
448 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
449 initialization = " = nil";
450 else
451 initialization = " = 0";
452 }
453 else if (VariableTy->isRealFloatingType())
454 initialization = " = 0.0";
455 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
456 initialization = " = false";
457 else if (VariableTy->isEnumeralType())
458 return false;
459 else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType()) {
460 if (S.Context.getLangOptions().CPlusPlus0x)
461 initialization = " = nullptr";
462 // Check if 'NULL' is defined.
463 else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL")))
464 initialization = " = NULL";
465 else
466 initialization = " = 0";
467 }
468 else if (VariableTy->isScalarType())
469 initialization = " = 0";
470
471 if (initialization) {
472 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
473 S.Diag(loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
474 << FixItHint::CreateInsertion(loc, initialization);
475 return true;
476 }
477 return false;
478}
479
Chandler Carruth262d50e2011-04-05 18:27:05 +0000480/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
481/// uninitialized variable. This manages the different forms of diagnostic
482/// emitted for particular types of uses. Returns true if the use was diagnosed
483/// as a warning. If a pariticular use is one we omit warnings for, returns
484/// false.
485static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Chandler Carruth64fb9592011-04-05 18:18:08 +0000486 const Expr *E, bool isAlwaysUninit) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000487 bool isSelfInit = false;
488
489 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
490 if (isAlwaysUninit) {
491 // Inspect the initializer of the variable declaration which is
492 // being referenced prior to its initialization. We emit
493 // specialized diagnostics for self-initialization, and we
494 // specifically avoid warning about self references which take the
495 // form of:
496 //
497 // int x = x;
498 //
499 // This is used to indicate to GCC that 'x' is intentionally left
500 // uninitialized. Proven code paths which access 'x' in
501 // an uninitialized state after this will still warn.
502 //
503 // TODO: Should we suppress maybe-uninitialized warnings for
504 // variables initialized in this way?
505 if (const Expr *Initializer = VD->getInit()) {
506 if (DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000507 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000508
509 ContainsReference CR(S.Context, DRE);
510 CR.Visit(const_cast<Expr*>(Initializer));
511 isSelfInit = CR.doesContainReference();
512 }
513 if (isSelfInit) {
514 S.Diag(DRE->getLocStart(),
515 diag::warn_uninit_self_reference_in_init)
516 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
517 } else {
518 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
519 << VD->getDeclName() << DRE->getSourceRange();
520 }
521 } else {
522 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
523 << VD->getDeclName() << DRE->getSourceRange();
524 }
525 } else {
526 const BlockExpr *BE = cast<BlockExpr>(E);
527 S.Diag(BE->getLocStart(),
528 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
529 : diag::warn_maybe_uninit_var_captured_by_block)
530 << VD->getDeclName();
531 }
532
533 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000534 // the initializer of that declaration & we didn't already suggest
535 // an initialization fixit.
536 if (!isSelfInit && !SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000537 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
538 << VD->getDeclName();
539
Chandler Carruth262d50e2011-04-05 18:27:05 +0000540 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000541}
542
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000543typedef std::pair<const Expr*, bool> UninitUse;
544
Ted Kremenek610068c2011-01-15 02:58:47 +0000545namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000546struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000547 bool operator()(const UninitUse &a, const UninitUse &b) {
548 SourceLocation aLoc = a.first->getLocStart();
549 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000550 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
551 }
552};
553
Ted Kremenek610068c2011-01-15 02:58:47 +0000554class UninitValsDiagReporter : public UninitVariablesHandler {
555 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000556 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000557 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
558 UsesMap *uses;
559
Ted Kremenek610068c2011-01-15 02:58:47 +0000560public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000561 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
562 ~UninitValsDiagReporter() {
563 flushDiagnostics();
564 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000565
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000566 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
567 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000568 if (!uses)
569 uses = new UsesMap();
570
571 UsesVec *&vec = (*uses)[vd];
572 if (!vec)
573 vec = new UsesVec();
574
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000575 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000576 }
577
578 void flushDiagnostics() {
579 if (!uses)
580 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000581
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000582 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
583 const VarDecl *vd = i->first;
584 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000585
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000586 // Sort the uses by their SourceLocations. While not strictly
587 // guaranteed to produce them in line/column order, this will provide
588 // a stable ordering.
589 std::sort(vec->begin(), vec->end(), SLocSort());
590
Chandler Carruth64fb9592011-04-05 18:18:08 +0000591 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
592 ++vi) {
David Blaikie4f4f3492011-09-10 05:35:08 +0000593 if (DiagnoseUninitializedUse(S, vd, vi->first,
Chandler Carruth262d50e2011-04-05 18:27:05 +0000594 /*isAlwaysUninit=*/vi->second))
David Blaikie4f4f3492011-09-10 05:35:08 +0000595 // Skip further diagnostics for this variable. We try to warn only on
596 // the first point at which a variable is used uninitialized.
597 break;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000598 }
Ted Kremenekd40066b2011-04-04 23:29:12 +0000599
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000600 delete vec;
601 }
602 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000603 }
604};
605}
606
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000607
608//===----------------------------------------------------------------------===//
609// -Wthread-safety
610//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000611namespace clang {
612namespace thread_safety {
613typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag;
614typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
615
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000616struct SortDiagBySourceLocation {
617 Sema &S;
618 SortDiagBySourceLocation(Sema &S) : S(S) {}
619
620 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
621 // Although this call will be slow, this is only called when outputting
622 // multiple warnings.
623 return S.getSourceManager().isBeforeInTranslationUnit(left.first,
624 right.first);
625 }
626};
627
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000628class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
629 Sema &S;
630 DiagList Warnings;
631
632 // Helper functions
633 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
634 PartialDiagnostic Warning = S.PDiag(DiagID) << LockName;
635 Warnings.push_back(DelayedDiag(Loc, Warning));
636 }
637
638 public:
639 ThreadSafetyReporter(Sema &S) : S(S) {}
640
641 /// \brief Emit all buffered diagnostics in order of sourcelocation.
642 /// We need to output diagnostics produced while iterating through
643 /// the lockset in deterministic order, so this function orders diagnostics
644 /// and outputs them.
645 void emitDiagnostics() {
646 SortDiagBySourceLocation SortDiagBySL(S);
647 sort(Warnings.begin(), Warnings.end(), SortDiagBySL);
648 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
649 I != E; ++I)
650 S.Diag(I->first, I->second);
651 }
652
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000653 void handleInvalidLockExp(SourceLocation Loc) {
654 PartialDiagnostic Warning = S.PDiag(diag::warn_cannot_resolve_lock) << Loc;
655 Warnings.push_back(DelayedDiag(Loc, Warning));
656 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000657 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
658 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
659 }
660
661 void handleDoubleLock(Name LockName, SourceLocation Loc) {
662 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
663 }
664
665 void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc){
666 warnLockMismatch(diag::warn_lock_at_end_of_scope, LockName, Loc);
667 }
668
669 void handleNoLockLoopEntry(Name LockName, SourceLocation Loc) {
670 warnLockMismatch(diag::warn_expecting_lock_held_on_loop, LockName, Loc);
671 }
672
673 void handleNoUnlock(Name LockName, llvm::StringRef FunName,
674 SourceLocation Loc) {
675 PartialDiagnostic Warning =
676 S.PDiag(diag::warn_no_unlock) << LockName << FunName;
677 Warnings.push_back(DelayedDiag(Loc, Warning));
678 }
679
680 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
681 SourceLocation Loc2) {
682 PartialDiagnostic Warning =
683 S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName;
684 PartialDiagnostic Note =
685 S.PDiag(diag::note_lock_exclusive_and_shared) << LockName;
686 Warnings.push_back(DelayedDiag(Loc1, Warning));
687 Warnings.push_back(DelayedDiag(Loc2, Note));
688 }
689
690 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
691 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskia49d1d82011-09-09 16:07:55 +0000692 // FIXME: It would be nice if this case printed without single quotes around
693 // the phrase 'any mutex'
694 handleMutexNotHeld(D, POK, "any mutex", getLockKindFromAccessKind(AK), Loc);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000695 }
696
697 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
698 Name LockName, LockKind LK, SourceLocation Loc) {
699 unsigned DiagID;
700 switch (POK) {
701 case POK_VarAccess:
702 DiagID = diag::warn_variable_requires_lock;
703 break;
704 case POK_VarDereference:
705 DiagID = diag::warn_var_deref_requires_lock;
706 break;
707 case POK_FunctionCall:
708 DiagID = diag::warn_fun_requires_lock;
709 break;
710 }
711 PartialDiagnostic Warning = S.PDiag(DiagID)
712 << D->getName().str() << LockName << LK;
713 Warnings.push_back(DelayedDiag(Loc, Warning));
714 }
715
716 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
717 PartialDiagnostic Warning =
718 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName;
719 Warnings.push_back(DelayedDiag(Loc, Warning));
720 }
721};
722}
723}
724
Ted Kremenek610068c2011-01-15 02:58:47 +0000725//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000726// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
727// warnings on a function, method, or block.
728//===----------------------------------------------------------------------===//
729
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000730clang::sema::AnalysisBasedWarnings::Policy::Policy() {
731 enableCheckFallThrough = 1;
732 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000733 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000734}
735
Chandler Carruth5d989942011-07-06 16:21:37 +0000736clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
737 : S(s),
738 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000739 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +0000740 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000741 MaxCFGBlocksPerFunction(0),
742 NumUninitAnalysisFunctions(0),
743 NumUninitAnalysisVariables(0),
744 MaxUninitAnalysisVariablesPerFunction(0),
745 NumUninitAnalysisBlockVisits(0),
746 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000747 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000748 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000749 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
750 Diagnostic::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000751 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
752 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
753 Diagnostic::Ignored);
754
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000755}
756
Ted Kremenek351ba912011-02-23 01:52:04 +0000757static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000758 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +0000759 i = fscope->PossiblyUnreachableDiags.begin(),
760 e = fscope->PossiblyUnreachableDiags.end();
761 i != e; ++i) {
762 const sema::PossiblyUnreachableDiag &D = *i;
763 S.Diag(D.Loc, D.PD);
764 }
765}
766
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000767void clang::sema::
768AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000769 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000770 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000771
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000772 // We avoid doing analysis-based warnings when there are errors for
773 // two reasons:
774 // (1) The CFGs often can't be constructed (if the body is invalid), so
775 // don't bother trying.
776 // (2) The code already has problems; running the analysis just takes more
777 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000778 Diagnostic &Diags = S.getDiagnostics();
779
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000780 // Do not do any analysis for declarations in system headers if we are
781 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000782 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000783 S.SourceMgr.isInSystemHeader(D->getLocation()))
784 return;
785
John McCalle0054f62010-08-25 05:56:39 +0000786 // For code in dependent contexts, we'll do this at instantiation time.
787 if (cast<DeclContext>(D)->isDependentContext())
788 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000789
Ted Kremenek351ba912011-02-23 01:52:04 +0000790 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
791 // Flush out any possibly unreachable diagnostics.
792 flushDiagnostics(S, fscope);
793 return;
794 }
795
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000796 const Stmt *Body = D->getBody();
797 assert(Body);
798
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000799 AnalysisContext AC(D, 0);
800
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000801 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
802 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000803 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
804 AC.getCFGBuildOptions().AddEHEdges = false;
805 AC.getCFGBuildOptions().AddInitializers = true;
806 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000807
808 // Force that certain expressions appear as CFGElements in the CFG. This
809 // is used to speed up various analyses.
810 // FIXME: This isn't the right factoring. This is here for initial
811 // prototyping, but we need a way for analyses to say what expressions they
812 // expect to always be CFGElements and then fill in the BuildOptions
813 // appropriately. This is essentially a layering violation.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000814 if (P.enableCheckUnreachable) {
815 // Unreachable code analysis requires a linearized CFG.
816 AC.getCFGBuildOptions().setAllAlwaysAdd();
817 }
818 else {
819 AC.getCFGBuildOptions()
820 .setAlwaysAdd(Stmt::BinaryOperatorClass)
821 .setAlwaysAdd(Stmt::BlockExprClass)
822 .setAlwaysAdd(Stmt::CStyleCastExprClass)
823 .setAlwaysAdd(Stmt::DeclRefExprClass)
824 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
825 .setAlwaysAdd(Stmt::UnaryOperatorClass);
826 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000827
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000828 // Construct the analysis context with the specified CFG build options.
829
Ted Kremenek351ba912011-02-23 01:52:04 +0000830 // Emit delayed diagnostics.
831 if (!fscope->PossiblyUnreachableDiags.empty()) {
832 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000833
834 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000835 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000836 i = fscope->PossiblyUnreachableDiags.begin(),
837 e = fscope->PossiblyUnreachableDiags.end();
838 i != e; ++i) {
839 if (const Stmt *stmt = i->stmt)
840 AC.registerForcedBlockExpression(stmt);
841 }
842
843 if (AC.getCFG()) {
844 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000845 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000846 i = fscope->PossiblyUnreachableDiags.begin(),
847 e = fscope->PossiblyUnreachableDiags.end();
848 i != e; ++i)
849 {
850 const sema::PossiblyUnreachableDiag &D = *i;
851 bool processed = false;
852 if (const Stmt *stmt = i->stmt) {
853 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
854 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000855 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000856 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000857 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000858 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000859 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000860 }
861 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000862 if (!processed) {
863 // Emit the warning anyway if we cannot map to a basic block.
864 S.Diag(D.Loc, D.PD);
865 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000866 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000867 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000868
869 if (!analyzed)
870 flushDiagnostics(S, fscope);
871 }
872
873
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000874 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000875 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000876 const CheckFallThroughDiagnostics &CD =
877 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000878 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000879 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000880 }
881
882 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000883 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000884 CheckUnreachable(S, AC);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000885
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000886 // Check for thread safety violations
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000887 if (P.enableThreadSafetyAnalysis) {
888 thread_safety::ThreadSafetyReporter Reporter(S);
889 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
890 Reporter.emitDiagnostics();
891 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000892
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000893 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +0000894 != Diagnostic::Ignored ||
895 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000896 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000897 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000898 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +0000899 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +0000900 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000901 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +0000902 reporter, stats);
903
904 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
905 ++NumUninitAnalysisFunctions;
906 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
907 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
908 MaxUninitAnalysisVariablesPerFunction =
909 std::max(MaxUninitAnalysisVariablesPerFunction,
910 stats.NumVariablesAnalyzed);
911 MaxUninitAnalysisBlockVisitsPerFunction =
912 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
913 stats.NumBlockVisits);
914 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000915 }
916 }
Chandler Carruth5d989942011-07-06 16:21:37 +0000917
918 // Collect statistics about the CFG if it was built.
919 if (S.CollectStats && AC.isCFGBuilt()) {
920 ++NumFunctionsAnalyzed;
921 if (CFG *cfg = AC.getCFG()) {
922 // If we successfully built a CFG for this context, record some more
923 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000924 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +0000925 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000926 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +0000927 } else {
928 ++NumFunctionsWithBadCFGs;
929 }
930 }
931}
932
933void clang::sema::AnalysisBasedWarnings::PrintStats() const {
934 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
935
936 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
937 unsigned AvgCFGBlocksPerFunction =
938 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
939 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
940 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
941 << " " << NumCFGBlocks << " CFG blocks built.\n"
942 << " " << AvgCFGBlocksPerFunction
943 << " average CFG blocks per function.\n"
944 << " " << MaxCFGBlocksPerFunction
945 << " max CFG blocks per function.\n";
946
947 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
948 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
949 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
950 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
951 llvm::errs() << NumUninitAnalysisFunctions
952 << " functions analyzed for uninitialiazed variables\n"
953 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
954 << " " << AvgUninitVariablesPerFunction
955 << " average variables per function.\n"
956 << " " << MaxUninitAnalysisVariablesPerFunction
957 << " max variables per function.\n"
958 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
959 << " " << AvgUninitBlockVisitsPerFunction
960 << " average block visits per function.\n"
961 << " " << MaxUninitAnalysisBlockVisitsPerFunction
962 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000963}