blob: 78864ec2852e326162e88c2a77f857aa8b2866ea [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 McCall384aff82010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Roseb5cd1222012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smithe0d3b4c2012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
28#include "clang/Analysis/Analyses/ReachableCode.h"
29#include "clang/Analysis/Analyses/ThreadSafety.h"
30#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000031#include "clang/Analysis/AnalysisContext.h"
32#include "clang/Analysis/CFG.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000033#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000034#include "clang/Basic/SourceLocation.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/Preprocessor.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
Alexander Kornienko66da0ab2012-09-28 22:24:03 +000040#include "llvm/ADT/ArrayRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000041#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000042#include "llvm/ADT/FoldingSet.h"
43#include "llvm/ADT/ImmutableMap.h"
44#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko19523542012-09-29 11:40:46 +000045#include "llvm/ADT/SmallString.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000046#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000047#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000048#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000049#include <algorithm>
Chandler Carruth55fc8732012-12-04 09:13:33 +000050#include <deque>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000051#include <iterator>
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000052#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000053
54using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Unreachable code analysis.
58//===----------------------------------------------------------------------===//
59
60namespace {
61 class UnreachableCodeHandler : public reachable_code::Callback {
62 Sema &S;
63 public:
64 UnreachableCodeHandler(Sema &s) : S(s) {}
65
66 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
67 S.Diag(L, diag::warn_unreachable) << R1 << R2;
68 }
69 };
70}
71
72/// CheckUnreachable - Check for unreachable code.
Ted Kremenek1d26f482011-10-24 01:32:45 +000073static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000074 UnreachableCodeHandler UC(S);
75 reachable_code::FindUnreachableCode(AC, UC);
76}
77
78//===----------------------------------------------------------------------===//
79// Check for missing return value.
80//===----------------------------------------------------------------------===//
81
John McCall16565aa2010-05-16 09:34:11 +000082enum ControlFlowKind {
83 UnknownFallThrough,
84 NeverFallThrough,
85 MaybeFallThrough,
86 AlwaysFallThrough,
87 NeverFallThroughOrReturn
88};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000089
90/// CheckFallThrough - Check that we don't fall off the end of a
91/// Statement that should return a value.
92///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000093/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
94/// MaybeFallThrough iff we might or might not fall off the end,
95/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
96/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000097/// statement but we may return. We assume that functions not marked noreturn
98/// will return.
Ted Kremenek1d26f482011-10-24 01:32:45 +000099static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000100 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +0000101 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000102
103 // The CFG leaves in dead things, and we don't want the dead code paths to
104 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000105 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000106 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000107 live);
108
109 bool AddEHEdges = AC.getAddEHEdges();
110 if (!AddEHEdges && count != cfg->getNumBlockIDs())
111 // When there are things remaining dead, and we didn't add EH edges
112 // from CallExprs to the catch clauses, we have to go back and
113 // mark them as live.
114 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
115 CFGBlock &b = **I;
116 if (!live[b.getBlockID()]) {
117 if (b.pred_begin() == b.pred_end()) {
118 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
119 // When not adding EH edges from calls, catch clauses
120 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000121 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000122 continue;
123 }
124 }
125 }
126
127 // Now we know what is live, we check the live precessors of the exit block
128 // and look for fall through paths, being careful to ignore normal returns,
129 // and exceptional paths.
130 bool HasLiveReturn = false;
131 bool HasFakeEdge = false;
132 bool HasPlainEdge = false;
133 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000134
135 // Ignore default cases that aren't likely to be reachable because all
136 // enums in a switch(X) have explicit case statements.
137 CFGBlock::FilterOptions FO;
138 FO.IgnoreDefaultsWithCoveredEnums = 1;
139
140 for (CFGBlock::filtered_pred_iterator
141 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
142 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000143 if (!live[B.getBlockID()])
144 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000145
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000146 // Skip blocks which contain an element marked as no-return. They don't
147 // represent actually viable edges into the exit block, so mark them as
148 // abnormal.
149 if (B.hasNoReturnElement()) {
150 HasAbnormalEdge = true;
151 continue;
152 }
153
Ted Kremenek5811f592011-01-26 04:49:52 +0000154 // Destructors can appear after the 'return' in the CFG. This is
155 // normal. We need to look pass the destructors for the return
156 // statement (if it exists).
157 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000158
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000159 for ( ; ri != re ; ++ri)
160 if (isa<CFGStmt>(*ri))
Ted Kremenek5811f592011-01-26 04:49:52 +0000161 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000162
Ted Kremenek5811f592011-01-26 04:49:52 +0000163 // No more CFGElements in the block?
164 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000165 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
166 HasAbnormalEdge = true;
167 continue;
168 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000169 // A labeled empty statement, or the entry block...
170 HasPlainEdge = true;
171 continue;
172 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000173
Ted Kremenek5811f592011-01-26 04:49:52 +0000174 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000175 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000176 if (isa<ReturnStmt>(S)) {
177 HasLiveReturn = true;
178 continue;
179 }
180 if (isa<ObjCAtThrowStmt>(S)) {
181 HasFakeEdge = true;
182 continue;
183 }
184 if (isa<CXXThrowExpr>(S)) {
185 HasFakeEdge = true;
186 continue;
187 }
Chad Rosier8cd64b42012-06-11 20:47:18 +0000188 if (isa<MSAsmStmt>(S)) {
189 // TODO: Verify this is correct.
190 HasFakeEdge = true;
191 HasLiveReturn = true;
192 continue;
193 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000194 if (isa<CXXTryStmt>(S)) {
195 HasAbnormalEdge = true;
196 continue;
197 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000198 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
199 == B.succ_end()) {
200 HasAbnormalEdge = true;
201 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000202 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000203
204 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000205 }
206 if (!HasPlainEdge) {
207 if (HasLiveReturn)
208 return NeverFallThrough;
209 return NeverFallThroughOrReturn;
210 }
211 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
212 return MaybeFallThrough;
213 // This says AlwaysFallThrough for calls to functions that are not marked
214 // noreturn, that don't return. If people would like this warning to be more
215 // accurate, such functions should be marked as noreturn.
216 return AlwaysFallThrough;
217}
218
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000219namespace {
220
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000221struct CheckFallThroughDiagnostics {
222 unsigned diag_MaybeFallThrough_HasNoReturn;
223 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
224 unsigned diag_AlwaysFallThrough_HasNoReturn;
225 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
226 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000227 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000228 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000229
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000230 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000231 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000232 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000233 D.diag_MaybeFallThrough_HasNoReturn =
234 diag::warn_falloff_noreturn_function;
235 D.diag_MaybeFallThrough_ReturnsNonVoid =
236 diag::warn_maybe_falloff_nonvoid_function;
237 D.diag_AlwaysFallThrough_HasNoReturn =
238 diag::warn_falloff_noreturn_function;
239 D.diag_AlwaysFallThrough_ReturnsNonVoid =
240 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000241
242 // Don't suggest that virtual functions be marked "noreturn", since they
243 // might be overridden by non-noreturn functions.
244 bool isVirtualMethod = false;
245 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
246 isVirtualMethod = Method->isVirtual();
247
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000248 // Don't suggest that template instantiations be marked "noreturn"
249 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000250 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
251 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000252
253 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000254 D.diag_NeverFallThroughOrReturn =
255 diag::warn_suggest_noreturn_function;
256 else
257 D.diag_NeverFallThroughOrReturn = 0;
258
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000259 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000260 return D;
261 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000262
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000263 static CheckFallThroughDiagnostics MakeForBlock() {
264 CheckFallThroughDiagnostics D;
265 D.diag_MaybeFallThrough_HasNoReturn =
266 diag::err_noreturn_block_has_return_expr;
267 D.diag_MaybeFallThrough_ReturnsNonVoid =
268 diag::err_maybe_falloff_nonvoid_block;
269 D.diag_AlwaysFallThrough_HasNoReturn =
270 diag::err_noreturn_block_has_return_expr;
271 D.diag_AlwaysFallThrough_ReturnsNonVoid =
272 diag::err_falloff_nonvoid_block;
273 D.diag_NeverFallThroughOrReturn =
274 diag::warn_suggest_noreturn_block;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000275 D.funMode = Block;
276 return D;
277 }
278
279 static CheckFallThroughDiagnostics MakeForLambda() {
280 CheckFallThroughDiagnostics D;
281 D.diag_MaybeFallThrough_HasNoReturn =
282 diag::err_noreturn_lambda_has_return_expr;
283 D.diag_MaybeFallThrough_ReturnsNonVoid =
284 diag::warn_maybe_falloff_nonvoid_lambda;
285 D.diag_AlwaysFallThrough_HasNoReturn =
286 diag::err_noreturn_lambda_has_return_expr;
287 D.diag_AlwaysFallThrough_ReturnsNonVoid =
288 diag::warn_falloff_nonvoid_lambda;
289 D.diag_NeverFallThroughOrReturn = 0;
290 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000291 return D;
292 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000293
David Blaikied6471f72011-09-25 23:23:43 +0000294 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000295 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000296 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000297 return (ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000299 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000300 && (!HasNoReturn ||
301 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000302 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000303 && (!ReturnsVoid ||
304 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000305 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000306 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000307
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000308 // For blocks / lambdas.
309 return ReturnsVoid && !HasNoReturn
310 && ((funMode == Lambda) ||
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000311 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000312 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000313 }
314};
315
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000316}
317
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000318/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
319/// function that should return a value. Check that we don't fall off the end
320/// of a noreturn function. We assume that functions and blocks not marked
321/// noreturn will return.
322static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000323 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000324 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000325 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000326
327 bool ReturnsVoid = false;
328 bool HasNoReturn = false;
329
330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
331 ReturnsVoid = FD->getResultType()->isVoidType();
Richard Smithcd8ab512013-01-17 01:30:42 +0000332 HasNoReturn = FD->isNoReturn();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000333 }
334 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
335 ReturnsVoid = MD->getResultType()->isVoidType();
336 HasNoReturn = MD->hasAttr<NoReturnAttr>();
337 }
338 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000339 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000340 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000341 BlockTy->getPointeeType()->getAs<FunctionType>()) {
342 if (FT->getResultType()->isVoidType())
343 ReturnsVoid = true;
344 if (FT->getNoReturnAttr())
345 HasNoReturn = true;
346 }
347 }
348
David Blaikied6471f72011-09-25 23:23:43 +0000349 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000350
351 // Short circuit for compilation speed.
352 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
353 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000354
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000355 // FIXME: Function try block
356 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
357 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000358 case UnknownFallThrough:
359 break;
360
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000361 case MaybeFallThrough:
362 if (HasNoReturn)
363 S.Diag(Compound->getRBracLoc(),
364 CD.diag_MaybeFallThrough_HasNoReturn);
365 else if (!ReturnsVoid)
366 S.Diag(Compound->getRBracLoc(),
367 CD.diag_MaybeFallThrough_ReturnsNonVoid);
368 break;
369 case AlwaysFallThrough:
370 if (HasNoReturn)
371 S.Diag(Compound->getRBracLoc(),
372 CD.diag_AlwaysFallThrough_HasNoReturn);
373 else if (!ReturnsVoid)
374 S.Diag(Compound->getRBracLoc(),
375 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
376 break;
377 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000378 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
379 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
380 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000381 << 0 << FD;
382 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
383 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
384 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000385 } else {
386 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
387 }
388 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000389 break;
390 case NeverFallThrough:
391 break;
392 }
393 }
394}
395
396//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000397// -Wuninitialized
398//===----------------------------------------------------------------------===//
399
Ted Kremenek6f417152011-04-04 20:56:00 +0000400namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000401/// ContainsReference - A visitor class to search for references to
402/// a particular declaration (the needle) within any evaluated component of an
403/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000404class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000405 bool FoundReference;
406 const DeclRefExpr *Needle;
407
Ted Kremenek6f417152011-04-04 20:56:00 +0000408public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000409 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
410 : EvaluatedExprVisitor<ContainsReference>(Context),
411 FoundReference(false), Needle(Needle) {}
412
413 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000414 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000415 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000416 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000417
418 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000419 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000420
421 void VisitDeclRefExpr(DeclRefExpr *E) {
422 if (E == Needle)
423 FoundReference = true;
424 else
425 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000426 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000427
428 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000429};
430}
431
David Blaikie4f4f3492011-09-10 05:35:08 +0000432static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000433 QualType VariableTy = VD->getType().getCanonicalType();
434 if (VariableTy->isBlockPointerType() &&
435 !VD->hasAttr<BlocksAttr>()) {
436 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
437 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
438 return true;
439 }
440
David Blaikie4f4f3492011-09-10 05:35:08 +0000441 // Don't issue a fixit if there is already an initializer.
442 if (VD->getInit())
443 return false;
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000444
David Blaikie4f4f3492011-09-10 05:35:08 +0000445 // Suggest possible initialization (if any).
David Blaikie2c0abf42012-04-30 18:27:22 +0000446 std::string Init = S.getFixItZeroInitializerForType(VariableTy);
447 if (Init.empty())
David Blaikie4f4f3492011-09-10 05:35:08 +0000448 return false;
Richard Trieu7b0a3e32012-05-03 01:09:59 +0000449
450 // Don't suggest a fixit inside macros.
451 if (VD->getLocEnd().isMacroID())
452 return false;
453
Richard Smith7984de32012-01-12 23:53:29 +0000454 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000455
Richard Smith7984de32012-01-12 23:53:29 +0000456 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
457 << FixItHint::CreateInsertion(Loc, Init);
458 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000459}
460
Richard Smithbdb97ff2012-05-26 06:20:46 +0000461/// Create a fixit to remove an if-like statement, on the assumption that its
462/// condition is CondVal.
463static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
464 const Stmt *Else, bool CondVal,
465 FixItHint &Fixit1, FixItHint &Fixit2) {
466 if (CondVal) {
467 // If condition is always true, remove all but the 'then'.
468 Fixit1 = FixItHint::CreateRemoval(
469 CharSourceRange::getCharRange(If->getLocStart(),
470 Then->getLocStart()));
471 if (Else) {
472 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
473 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
474 Fixit2 = FixItHint::CreateRemoval(
475 SourceRange(ElseKwLoc, Else->getLocEnd()));
476 }
477 } else {
478 // If condition is always false, remove all but the 'else'.
479 if (Else)
480 Fixit1 = FixItHint::CreateRemoval(
481 CharSourceRange::getCharRange(If->getLocStart(),
482 Else->getLocStart()));
483 else
484 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
485 }
486}
487
488/// DiagUninitUse -- Helper function to produce a diagnostic for an
489/// uninitialized use of a variable.
490static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
491 bool IsCapturedByBlock) {
492 bool Diagnosed = false;
493
494 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith2815e1a2012-05-25 02:17:09 +0000495 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
496 I != E; ++I) {
Richard Smithbdb97ff2012-05-26 06:20:46 +0000497 assert(Use.getKind() == UninitUse::Sometimes);
498
499 const Expr *User = Use.getUser();
Richard Smith2815e1a2012-05-25 02:17:09 +0000500 const Stmt *Term = I->Terminator;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000501
502 // Information used when building the diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000503 unsigned DiagKind;
David Blaikie0bea8632012-10-08 01:11:04 +0000504 StringRef Str;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000505 SourceRange Range;
506
507 // FixIts to suppress the diagnosic by removing the dead condition.
508 // For all binary terminators, branch 0 is taken if the condition is true,
509 // and branch 1 is taken if the condition is false.
510 int RemoveDiagKind = -1;
511 const char *FixitStr =
512 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
513 : (I->Output ? "1" : "0");
514 FixItHint Fixit1, Fixit2;
515
Richard Smith2815e1a2012-05-25 02:17:09 +0000516 switch (Term->getStmtClass()) {
517 default:
Richard Smithbdb97ff2012-05-26 06:20:46 +0000518 // Don't know how to report this. Just fall back to 'may be used
519 // uninitialized'. This happens for range-based for, which the user
520 // can't explicitly fix.
521 // FIXME: This also happens if the first use of a variable is always
522 // uninitialized, eg "for (int n; n < 10; ++n)". We should report that
523 // with the 'is uninitialized' diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000524 continue;
525
526 // "condition is true / condition is false".
Richard Smithbdb97ff2012-05-26 06:20:46 +0000527 case Stmt::IfStmtClass: {
528 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000529 DiagKind = 0;
530 Str = "if";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000531 Range = IS->getCond()->getSourceRange();
532 RemoveDiagKind = 0;
533 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
534 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000535 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000536 }
537 case Stmt::ConditionalOperatorClass: {
538 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000539 DiagKind = 0;
540 Str = "?:";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000541 Range = CO->getCond()->getSourceRange();
542 RemoveDiagKind = 0;
543 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
544 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000545 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000546 }
Richard Smith2815e1a2012-05-25 02:17:09 +0000547 case Stmt::BinaryOperatorClass: {
548 const BinaryOperator *BO = cast<BinaryOperator>(Term);
549 if (!BO->isLogicalOp())
550 continue;
551 DiagKind = 0;
552 Str = BO->getOpcodeStr();
553 Range = BO->getLHS()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000554 RemoveDiagKind = 0;
555 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
556 (BO->getOpcode() == BO_LOr && !I->Output))
557 // true && y -> y, false || y -> y.
558 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
559 BO->getOperatorLoc()));
560 else
561 // false && y -> false, true || y -> true.
562 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000563 break;
564 }
565
566 // "loop is entered / loop is exited".
567 case Stmt::WhileStmtClass:
568 DiagKind = 1;
569 Str = "while";
570 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000571 RemoveDiagKind = 1;
572 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000573 break;
574 case Stmt::ForStmtClass:
575 DiagKind = 1;
576 Str = "for";
577 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000578 RemoveDiagKind = 1;
579 if (I->Output)
580 Fixit1 = FixItHint::CreateRemoval(Range);
581 else
582 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000583 break;
584
585 // "condition is true / loop is exited".
586 case Stmt::DoStmtClass:
587 DiagKind = 2;
588 Str = "do";
589 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000590 RemoveDiagKind = 1;
591 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000592 break;
593
594 // "switch case is taken".
595 case Stmt::CaseStmtClass:
596 DiagKind = 3;
597 Str = "case";
598 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
599 break;
600 case Stmt::DefaultStmtClass:
601 DiagKind = 3;
602 Str = "default";
603 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
604 break;
605 }
606
Richard Smithbdb97ff2012-05-26 06:20:46 +0000607 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
608 << VD->getDeclName() << IsCapturedByBlock << DiagKind
609 << Str << I->Output << Range;
610 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
611 << IsCapturedByBlock << User->getSourceRange();
612 if (RemoveDiagKind != -1)
613 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
614 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
615
616 Diagnosed = true;
Richard Smith2815e1a2012-05-25 02:17:09 +0000617 }
Richard Smithbdb97ff2012-05-26 06:20:46 +0000618
619 if (!Diagnosed)
620 S.Diag(Use.getUser()->getLocStart(),
621 Use.getKind() == UninitUse::Always ? diag::warn_uninit_var
622 : diag::warn_maybe_uninit_var)
623 << VD->getDeclName() << IsCapturedByBlock
624 << Use.getUser()->getSourceRange();
Richard Smith2815e1a2012-05-25 02:17:09 +0000625}
626
Chandler Carruth262d50e2011-04-05 18:27:05 +0000627/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
628/// uninitialized variable. This manages the different forms of diagnostic
629/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith2815e1a2012-05-25 02:17:09 +0000630/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruth262d50e2011-04-05 18:27:05 +0000631/// false.
632static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith2815e1a2012-05-25 02:17:09 +0000633 const UninitUse &Use,
Ted Kremenek9e761722011-10-13 18:50:06 +0000634 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000635
Richard Smith2815e1a2012-05-25 02:17:09 +0000636 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieuf6278e52012-05-09 21:08:22 +0000637 // Inspect the initializer of the variable declaration which is
638 // being referenced prior to its initialization. We emit
639 // specialized diagnostics for self-initialization, and we
640 // specifically avoid warning about self references which take the
641 // form of:
642 //
643 // int x = x;
644 //
645 // This is used to indicate to GCC that 'x' is intentionally left
646 // uninitialized. Proven code paths which access 'x' in
647 // an uninitialized state after this will still warn.
648 if (const Expr *Initializer = VD->getInit()) {
649 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
650 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000651
Richard Trieuf6278e52012-05-09 21:08:22 +0000652 ContainsReference CR(S.Context, DRE);
653 CR.Visit(const_cast<Expr*>(Initializer));
654 if (CR.doesContainReference()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000655 S.Diag(DRE->getLocStart(),
656 diag::warn_uninit_self_reference_in_init)
Richard Trieuf6278e52012-05-09 21:08:22 +0000657 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
658 return true;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000659 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000660 }
Richard Trieuf6278e52012-05-09 21:08:22 +0000661
Richard Smithbdb97ff2012-05-26 06:20:46 +0000662 DiagUninitUse(S, VD, Use, false);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000663 } else {
Richard Smith2815e1a2012-05-25 02:17:09 +0000664 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smithbdb97ff2012-05-26 06:20:46 +0000665 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
666 S.Diag(BE->getLocStart(),
667 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000668 << VD->getDeclName();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000669 else
670 DiagUninitUse(S, VD, Use, true);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000671 }
672
673 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000674 // the initializer of that declaration & we didn't already suggest
675 // an initialization fixit.
Richard Trieuf6278e52012-05-09 21:08:22 +0000676 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000677 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
678 << VD->getDeclName();
679
Chandler Carruth262d50e2011-04-05 18:27:05 +0000680 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000681}
682
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000683namespace {
684 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
685 public:
686 FallthroughMapper(Sema &S)
687 : FoundSwitchStatements(false),
688 S(S) {
689 }
690
691 bool foundSwitchStatements() const { return FoundSwitchStatements; }
692
693 void markFallthroughVisited(const AttributedStmt *Stmt) {
694 bool Found = FallthroughStmts.erase(Stmt);
695 assert(Found);
Kaelyn Uhrain3bb29942012-05-03 19:46:38 +0000696 (void)Found;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000697 }
698
699 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
700
701 const AttrStmts &getFallthroughStmts() const {
702 return FallthroughStmts;
703 }
704
705 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
706 int UnannotatedCnt = 0;
707 AnnotatedCnt = 0;
708
709 std::deque<const CFGBlock*> BlockQueue;
710
711 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
712
713 while (!BlockQueue.empty()) {
714 const CFGBlock *P = BlockQueue.front();
715 BlockQueue.pop_front();
716
717 const Stmt *Term = P->getTerminator();
718 if (Term && isa<SwitchStmt>(Term))
719 continue; // Switch statement, good.
720
721 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
722 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
723 continue; // Previous case label has no statements, good.
724
725 if (P->pred_begin() == P->pred_end()) { // The block is unreachable.
726 // This only catches trivially unreachable blocks.
727 for (CFGBlock::const_iterator ElIt = P->begin(), ElEnd = P->end();
728 ElIt != ElEnd; ++ElIt) {
729 if (const CFGStmt *CS = ElIt->getAs<CFGStmt>()){
730 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
731 S.Diag(AS->getLocStart(),
732 diag::warn_fallthrough_attr_unreachable);
733 markFallthroughVisited(AS);
734 ++AnnotatedCnt;
735 }
736 // Don't care about other unreachable statements.
737 }
738 }
739 // If there are no unreachable statements, this may be a special
740 // case in CFG:
741 // case X: {
742 // A a; // A has a destructor.
743 // break;
744 // }
745 // // <<<< This place is represented by a 'hanging' CFG block.
746 // case Y:
747 continue;
748 }
749
750 const Stmt *LastStmt = getLastStmt(*P);
751 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
752 markFallthroughVisited(AS);
753 ++AnnotatedCnt;
754 continue; // Fallthrough annotation, good.
755 }
756
757 if (!LastStmt) { // This block contains no executable statements.
758 // Traverse its predecessors.
759 std::copy(P->pred_begin(), P->pred_end(),
760 std::back_inserter(BlockQueue));
761 continue;
762 }
763
764 ++UnannotatedCnt;
765 }
766 return !!UnannotatedCnt;
767 }
768
769 // RecursiveASTVisitor setup.
770 bool shouldWalkTypesOfTypeLocs() const { return false; }
771
772 bool VisitAttributedStmt(AttributedStmt *S) {
773 if (asFallThroughAttr(S))
774 FallthroughStmts.insert(S);
775 return true;
776 }
777
778 bool VisitSwitchStmt(SwitchStmt *S) {
779 FoundSwitchStatements = true;
780 return true;
781 }
782
783 private:
784
785 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
786 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
787 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
788 return AS;
789 }
790 return 0;
791 }
792
793 static const Stmt *getLastStmt(const CFGBlock &B) {
794 if (const Stmt *Term = B.getTerminator())
795 return Term;
796 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
797 ElemEnd = B.rend();
798 ElemIt != ElemEnd; ++ElemIt) {
799 if (const CFGStmt *CS = ElemIt->getAs<CFGStmt>())
800 return CS->getStmt();
801 }
802 // Workaround to detect a statement thrown out by CFGBuilder:
803 // case X: {} case Y:
804 // case X: ; case Y:
805 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
806 if (!isa<SwitchCase>(SW->getSubStmt()))
807 return SW->getSubStmt();
808
809 return 0;
810 }
811
812 bool FoundSwitchStatements;
813 AttrStmts FallthroughStmts;
814 Sema &S;
815 };
816}
817
Alexander Kornienko19736342012-06-02 01:01:07 +0000818static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Sean Huntc2f51cf2012-06-15 21:22:05 +0000819 bool PerFunction) {
Ted Kremenek30783532012-11-12 21:20:48 +0000820 // Only perform this analysis when using C++11. There is no good workflow
821 // for this warning when not using C++11. There is no good way to silence
822 // the warning (no attribute is available) unless we are using C++11's support
823 // for generalized attributes. Once could use pragmas to silence the warning,
824 // but as a general solution that is gross and not in the spirit of this
825 // warning.
826 //
827 // NOTE: This an intermediate solution. There are on-going discussions on
828 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith80ad52f2013-01-02 11:42:31 +0000829 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenek30783532012-11-12 21:20:48 +0000830 return;
831
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000832 FallthroughMapper FM(S);
833 FM.TraverseStmt(AC.getBody());
834
835 if (!FM.foundSwitchStatements())
836 return;
837
Sean Huntc2f51cf2012-06-15 21:22:05 +0000838 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko19736342012-06-02 01:01:07 +0000839 return;
840
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000841 CFG *Cfg = AC.getCFG();
842
843 if (!Cfg)
844 return;
845
846 int AnnotatedCnt;
847
848 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienkoe992ed12013-01-25 15:49:34 +0000849 const CFGBlock *B = *I;
850 const Stmt *Label = B->getLabel();
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000851
852 if (!Label || !isa<SwitchCase>(Label))
853 continue;
854
Alexander Kornienkoe992ed12013-01-25 15:49:34 +0000855 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000856 continue;
857
Alexander Kornienko19736342012-06-02 01:01:07 +0000858 S.Diag(Label->getLocStart(),
Sean Huntc2f51cf2012-06-15 21:22:05 +0000859 PerFunction ? diag::warn_unannotated_fallthrough_per_function
860 : diag::warn_unannotated_fallthrough);
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000861
862 if (!AnnotatedCnt) {
863 SourceLocation L = Label->getLocStart();
864 if (L.isMacroID())
865 continue;
Richard Smith80ad52f2013-01-02 11:42:31 +0000866 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienkoe992ed12013-01-25 15:49:34 +0000867 const Stmt *Term = B->getTerminator();
868 // Skip empty cases.
869 while (B->empty() && !Term && B->succ_size() == 1) {
870 B = *B->succ_begin();
871 Term = B->getTerminator();
872 }
873 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000874 Preprocessor &PP = S.getPreprocessor();
875 TokenValue Tokens[] = {
876 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
877 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
878 tok::r_square, tok::r_square
879 };
Dmitri Gribenko19523542012-09-29 11:40:46 +0000880 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
881 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
882 if (!MacroName.empty())
883 AnnotationSpelling = MacroName;
884 SmallString<64> TextToInsert(AnnotationSpelling);
885 TextToInsert += "; ";
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000886 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000887 AnnotationSpelling <<
Dmitri Gribenko19523542012-09-29 11:40:46 +0000888 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000889 }
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000890 }
891 S.Diag(L, diag::note_insert_break_fixit) <<
892 FixItHint::CreateInsertion(L, "break; ");
893 }
894 }
895
896 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
897 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
898 E = Fallthroughs.end();
899 I != E; ++I) {
900 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
901 }
902
903}
904
Ted Kremenek610068c2011-01-15 02:58:47 +0000905namespace {
Jordan Rose20441c52012-09-28 22:29:02 +0000906typedef std::pair<const Stmt *,
907 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
908 StmtUsesPair;
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000909
Jordan Rose20441c52012-09-28 22:29:02 +0000910class StmtUseSorter {
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000911 const SourceManager &SM;
912
913public:
Jordan Rose20441c52012-09-28 22:29:02 +0000914 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000915
916 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
917 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
918 RHS.first->getLocStart());
919 }
920};
Jordan Rose20441c52012-09-28 22:29:02 +0000921}
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000922
Jordan Rosec0e44452012-10-29 17:46:47 +0000923static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
924 const Stmt *S) {
Jordan Roseb5cd1222012-10-11 16:10:19 +0000925 assert(S);
926
927 do {
928 switch (S->getStmtClass()) {
Jordan Roseb5cd1222012-10-11 16:10:19 +0000929 case Stmt::ForStmtClass:
930 case Stmt::WhileStmtClass:
931 case Stmt::CXXForRangeStmtClass:
932 case Stmt::ObjCForCollectionStmtClass:
933 return true;
Jordan Rosec0e44452012-10-29 17:46:47 +0000934 case Stmt::DoStmtClass: {
935 const Expr *Cond = cast<DoStmt>(S)->getCond();
936 llvm::APSInt Val;
937 if (!Cond->EvaluateAsInt(Val, Ctx))
938 return true;
939 return Val.getBoolValue();
940 }
Jordan Roseb5cd1222012-10-11 16:10:19 +0000941 default:
942 break;
943 }
944 } while ((S = PM.getParent(S)));
945
946 return false;
947}
948
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000949
950static void diagnoseRepeatedUseOfWeak(Sema &S,
951 const sema::FunctionScopeInfo *CurFn,
Jordan Roseb5cd1222012-10-11 16:10:19 +0000952 const Decl *D,
953 const ParentMap &PM) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000954 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
955 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
956 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
957
Jordan Rosec0e44452012-10-29 17:46:47 +0000958 ASTContext &Ctx = S.getASTContext();
959
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000960 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
961
962 // Extract all weak objects that are referenced more than once.
963 SmallVector<StmtUsesPair, 8> UsesByStmt;
964 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
965 I != E; ++I) {
966 const WeakUseVector &Uses = I->second;
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000967
968 // Find the first read of the weak object.
969 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
970 for ( ; UI != UE; ++UI) {
971 if (UI->isUnsafe())
972 break;
973 }
974
975 // If there were only writes to this object, don't warn.
976 if (UI == UE)
977 continue;
978
Jordan Roseb5cd1222012-10-11 16:10:19 +0000979 // If there was only one read, followed by any number of writes, and the
Jordan Rosec0e44452012-10-29 17:46:47 +0000980 // read is not within a loop, don't warn. Additionally, don't warn in a
981 // loop if the base object is a local variable -- local variables are often
982 // changed in loops.
Jordan Roseb5cd1222012-10-11 16:10:19 +0000983 if (UI == Uses.begin()) {
984 WeakUseVector::const_iterator UI2 = UI;
985 for (++UI2; UI2 != UE; ++UI2)
986 if (UI2->isUnsafe())
987 break;
988
Jordan Rosec0e44452012-10-29 17:46:47 +0000989 if (UI2 == UE) {
990 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Roseb5cd1222012-10-11 16:10:19 +0000991 continue;
Jordan Rosec0e44452012-10-29 17:46:47 +0000992
993 const WeakObjectProfileTy &Profile = I->first;
994 if (!Profile.isExactProfile())
995 continue;
996
997 const NamedDecl *Base = Profile.getBase();
998 if (!Base)
999 Base = Profile.getProperty();
1000 assert(Base && "A profile always has a base or property.");
1001
1002 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1003 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1004 continue;
1005 }
Jordan Roseb5cd1222012-10-11 16:10:19 +00001006 }
1007
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001008 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1009 }
1010
1011 if (UsesByStmt.empty())
1012 return;
1013
1014 // Sort by first use so that we emit the warnings in a deterministic order.
1015 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Jordan Rose20441c52012-09-28 22:29:02 +00001016 StmtUseSorter(S.getSourceManager()));
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001017
1018 // Classify the current code body for better warning text.
1019 // This enum should stay in sync with the cases in
1020 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1021 // FIXME: Should we use a common classification enum and the same set of
1022 // possibilities all throughout Sema?
1023 enum {
1024 Function,
1025 Method,
1026 Block,
1027 Lambda
1028 } FunctionKind;
1029
1030 if (isa<sema::BlockScopeInfo>(CurFn))
1031 FunctionKind = Block;
1032 else if (isa<sema::LambdaScopeInfo>(CurFn))
1033 FunctionKind = Lambda;
1034 else if (isa<ObjCMethodDecl>(D))
1035 FunctionKind = Method;
1036 else
1037 FunctionKind = Function;
1038
1039 // Iterate through the sorted problems and emit warnings for each.
1040 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1041 E = UsesByStmt.end();
1042 I != E; ++I) {
1043 const Stmt *FirstRead = I->first;
1044 const WeakObjectProfileTy &Key = I->second->first;
1045 const WeakUseVector &Uses = I->second->second;
1046
Jordan Rose7a270482012-09-28 22:21:35 +00001047 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1048 // may not contain enough information to determine that these are different
1049 // properties. We can only be 100% sure of a repeated use in certain cases,
1050 // and we adjust the diagnostic kind accordingly so that the less certain
1051 // case can be turned off if it is too noisy.
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001052 unsigned DiagKind;
1053 if (Key.isExactProfile())
1054 DiagKind = diag::warn_arc_repeated_use_of_weak;
1055 else
1056 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1057
Jordan Rose7a270482012-09-28 22:21:35 +00001058 // Classify the weak object being accessed for better warning text.
1059 // This enum should stay in sync with the cases in
1060 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1061 enum {
1062 Variable,
1063 Property,
1064 ImplicitProperty,
1065 Ivar
1066 } ObjectKind;
1067
1068 const NamedDecl *D = Key.getProperty();
1069 if (isa<VarDecl>(D))
1070 ObjectKind = Variable;
1071 else if (isa<ObjCPropertyDecl>(D))
1072 ObjectKind = Property;
1073 else if (isa<ObjCMethodDecl>(D))
1074 ObjectKind = ImplicitProperty;
1075 else if (isa<ObjCIvarDecl>(D))
1076 ObjectKind = Ivar;
1077 else
1078 llvm_unreachable("Unexpected weak object kind!");
1079
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001080 // Show the first time the object was read.
1081 S.Diag(FirstRead->getLocStart(), DiagKind)
Jordan Rose7a270482012-09-28 22:21:35 +00001082 << ObjectKind << D << FunctionKind
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001083 << FirstRead->getSourceRange();
1084
1085 // Print all the other accesses as notes.
1086 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1087 UI != UE; ++UI) {
1088 if (UI->getUseExpr() == FirstRead)
1089 continue;
1090 S.Diag(UI->getUseExpr()->getLocStart(),
1091 diag::note_arc_weak_also_accessed_here)
1092 << UI->getUseExpr()->getSourceRange();
1093 }
1094 }
1095}
1096
1097
1098namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001099struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +00001100 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001101 // Prefer a more confident report over a less confident one.
1102 if (a.getKind() != b.getKind())
1103 return a.getKind() > b.getKind();
1104 SourceLocation aLoc = a.getUser()->getLocStart();
1105 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001106 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1107 }
1108};
1109
Ted Kremenek610068c2011-01-15 02:58:47 +00001110class UninitValsDiagReporter : public UninitVariablesHandler {
1111 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001112 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek9e761722011-10-13 18:50:06 +00001113 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001114 UsesMap *uses;
1115
Ted Kremenek610068c2011-01-15 02:58:47 +00001116public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001117 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1118 ~UninitValsDiagReporter() {
1119 flushDiagnostics();
1120 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001121
1122 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001123 if (!uses)
1124 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +00001125
1126 UsesMap::mapped_type &V = (*uses)[vd];
1127 UsesVec *&vec = V.first;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001128 if (!vec)
1129 vec = new UsesVec();
1130
Ted Kremenek9e761722011-10-13 18:50:06 +00001131 return V;
1132 }
1133
Richard Smith2815e1a2012-05-25 02:17:09 +00001134 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
1135 getUses(vd).first->push_back(use);
Ted Kremenek9e761722011-10-13 18:50:06 +00001136 }
1137
1138 void handleSelfInit(const VarDecl *vd) {
1139 getUses(vd).second = true;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001140 }
1141
1142 void flushDiagnostics() {
1143 if (!uses)
1144 return;
Ted Kremenek609e3172011-02-02 23:35:53 +00001145
Richard Smith81891882012-05-24 23:45:35 +00001146 // FIXME: This iteration order, and thus the resulting diagnostic order,
1147 // is nondeterministic.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001148 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1149 const VarDecl *vd = i->first;
Ted Kremenek9e761722011-10-13 18:50:06 +00001150 const UsesMap::mapped_type &V = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +00001151
Ted Kremenek9e761722011-10-13 18:50:06 +00001152 UsesVec *vec = V.first;
1153 bool hasSelfInit = V.second;
1154
1155 // Specially handle the case where we have uses of an uninitialized
1156 // variable, but the root cause is an idiomatic self-init. We want
1157 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001158 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith2815e1a2012-05-25 02:17:09 +00001159 DiagnoseUninitializedUse(S, vd,
1160 UninitUse(vd->getInit()->IgnoreParenCasts(),
1161 /* isAlwaysUninit */ true),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001162 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +00001163 else {
1164 // Sort the uses by their SourceLocations. While not strictly
1165 // guaranteed to produce them in line/column order, this will provide
1166 // a stable ordering.
1167 std::sort(vec->begin(), vec->end(), SLocSort());
1168
1169 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1170 ++vi) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001171 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1172 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1173
1174 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek9e761722011-10-13 18:50:06 +00001175 // Skip further diagnostics for this variable. We try to warn only
1176 // on the first point at which a variable is used uninitialized.
1177 break;
1178 }
Chandler Carruth64fb9592011-04-05 18:18:08 +00001179 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001180
1181 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001182 delete vec;
1183 }
1184 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +00001185 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001186
1187private:
1188 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1189 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001190 if (i->getKind() == UninitUse::Always) {
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001191 return true;
1192 }
1193 }
1194 return false;
1195}
Ted Kremenek610068c2011-01-15 02:58:47 +00001196};
1197}
1198
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001199
1200//===----------------------------------------------------------------------===//
1201// -Wthread-safety
1202//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001203namespace clang {
1204namespace thread_safety {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001205typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith2e515622012-02-03 04:45:26 +00001206typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramerecafd302012-03-26 14:05:40 +00001207typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001208
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001209struct SortDiagBySourceLocation {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001210 SourceManager &SM;
1211 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001212
1213 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1214 // Although this call will be slow, this is only called when outputting
1215 // multiple warnings.
Benjamin Kramerecafd302012-03-26 14:05:40 +00001216 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001217 }
1218};
1219
David Blaikie99ba9e32011-12-20 02:48:34 +00001220namespace {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001221class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1222 Sema &S;
1223 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +00001224 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001225
1226 // Helper functions
1227 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001228 // Gracefully handle rare cases when the analysis can't get a more
1229 // precise source location.
1230 if (!Loc.isValid())
1231 Loc = FunLocation;
Richard Smith2e515622012-02-03 04:45:26 +00001232 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1233 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001234 }
1235
1236 public:
Richard Smith2e515622012-02-03 04:45:26 +00001237 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1238 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001239
1240 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1241 /// We need to output diagnostics produced while iterating through
1242 /// the lockset in deterministic order, so this function orders diagnostics
1243 /// and outputs them.
1244 void emitDiagnostics() {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001245 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001246 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith2e515622012-02-03 04:45:26 +00001247 I != E; ++I) {
1248 S.Diag(I->first.first, I->first.second);
1249 const OptionalNotes &Notes = I->second;
1250 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1251 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1252 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001253 }
1254
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001255 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001256 PartialDiagnosticAt Warning(Loc,
1257 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1258 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001259 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001260 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1261 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1262 }
1263
1264 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1265 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1266 }
1267
Richard Smith2e515622012-02-03 04:45:26 +00001268 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1269 SourceLocation LocEndOfScope,
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001270 LockErrorKind LEK){
1271 unsigned DiagID = 0;
1272 switch (LEK) {
1273 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +00001274 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001275 break;
1276 case LEK_LockedSomeLoopIterations:
1277 DiagID = diag::warn_expecting_lock_held_on_loop;
1278 break;
1279 case LEK_LockedAtEndOfFunction:
1280 DiagID = diag::warn_no_unlock;
1281 break;
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001282 case LEK_NotLockedAtEndOfFunction:
1283 DiagID = diag::warn_expecting_locked;
1284 break;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001285 }
Richard Smith2e515622012-02-03 04:45:26 +00001286 if (LocEndOfScope.isInvalid())
1287 LocEndOfScope = FunEndLocation;
1288
1289 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
1290 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1291 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001292 }
1293
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001294
1295 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1296 SourceLocation Loc2) {
Richard Smith2e515622012-02-03 04:45:26 +00001297 PartialDiagnosticAt Warning(
1298 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1299 PartialDiagnosticAt Note(
1300 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1301 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001302 }
1303
1304 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1305 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +00001306 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1307 && "Only works for variables");
1308 unsigned DiagID = POK == POK_VarAccess?
1309 diag::warn_variable_requires_any_lock:
1310 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +00001311 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001312 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith2e515622012-02-03 04:45:26 +00001313 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001314 }
1315
1316 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001317 Name LockName, LockKind LK, SourceLocation Loc,
1318 Name *PossibleMatch) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +00001319 unsigned DiagID = 0;
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001320 if (PossibleMatch) {
1321 switch (POK) {
1322 case POK_VarAccess:
1323 DiagID = diag::warn_variable_requires_lock_precise;
1324 break;
1325 case POK_VarDereference:
1326 DiagID = diag::warn_var_deref_requires_lock_precise;
1327 break;
1328 case POK_FunctionCall:
1329 DiagID = diag::warn_fun_requires_lock_precise;
1330 break;
1331 }
1332 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001333 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001334 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1335 << *PossibleMatch);
1336 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1337 } else {
1338 switch (POK) {
1339 case POK_VarAccess:
1340 DiagID = diag::warn_variable_requires_lock;
1341 break;
1342 case POK_VarDereference:
1343 DiagID = diag::warn_var_deref_requires_lock;
1344 break;
1345 case POK_FunctionCall:
1346 DiagID = diag::warn_fun_requires_lock;
1347 break;
1348 }
1349 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001350 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001351 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001352 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001353 }
1354
1355 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001356 PartialDiagnosticAt Warning(Loc,
1357 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1358 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001359 }
1360};
1361}
1362}
David Blaikie99ba9e32011-12-20 02:48:34 +00001363}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001364
Ted Kremenek610068c2011-01-15 02:58:47 +00001365//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001366// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1367// warnings on a function, method, or block.
1368//===----------------------------------------------------------------------===//
1369
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001370clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1371 enableCheckFallThrough = 1;
1372 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001373 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001374}
1375
Chandler Carruth5d989942011-07-06 16:21:37 +00001376clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1377 : S(s),
1378 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001379 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001380 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001381 MaxCFGBlocksPerFunction(0),
1382 NumUninitAnalysisFunctions(0),
1383 NumUninitAnalysisVariables(0),
1384 MaxUninitAnalysisVariablesPerFunction(0),
1385 NumUninitAnalysisBlockVisits(0),
1386 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +00001387 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001388 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001389 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001390 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001391 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1392 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001393 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001394
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001395}
1396
Ted Kremenek351ba912011-02-23 01:52:04 +00001397static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001398 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001399 i = fscope->PossiblyUnreachableDiags.begin(),
1400 e = fscope->PossiblyUnreachableDiags.end();
1401 i != e; ++i) {
1402 const sema::PossiblyUnreachableDiag &D = *i;
1403 S.Diag(D.Loc, D.PD);
1404 }
1405}
1406
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001407void clang::sema::
1408AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001409 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001410 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001411
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001412 // We avoid doing analysis-based warnings when there are errors for
1413 // two reasons:
1414 // (1) The CFGs often can't be constructed (if the body is invalid), so
1415 // don't bother trying.
1416 // (2) The code already has problems; running the analysis just takes more
1417 // time.
David Blaikied6471f72011-09-25 23:23:43 +00001418 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +00001419
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001420 // Do not do any analysis for declarations in system headers if we are
1421 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001422 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001423 S.SourceMgr.isInSystemHeader(D->getLocation()))
1424 return;
1425
John McCalle0054f62010-08-25 05:56:39 +00001426 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +00001427 if (cast<DeclContext>(D)->isDependentContext())
1428 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001429
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00001430 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001431 // Flush out any possibly unreachable diagnostics.
1432 flushDiagnostics(S, fscope);
1433 return;
1434 }
1435
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001436 const Stmt *Body = D->getBody();
1437 assert(Body);
1438
Jordy Rosed2001872012-04-28 01:58:08 +00001439 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001440
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001441 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1442 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001443 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1444 AC.getCFGBuildOptions().AddEHEdges = false;
1445 AC.getCFGBuildOptions().AddInitializers = true;
1446 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rosefaadf482012-09-05 23:11:06 +00001447 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1448
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001449 // Force that certain expressions appear as CFGElements in the CFG. This
1450 // is used to speed up various analyses.
1451 // FIXME: This isn't the right factoring. This is here for initial
1452 // prototyping, but we need a way for analyses to say what expressions they
1453 // expect to always be CFGElements and then fill in the BuildOptions
1454 // appropriately. This is essentially a layering violation.
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001455 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
1456 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001457 AC.getCFGBuildOptions().setAllAlwaysAdd();
1458 }
1459 else {
1460 AC.getCFGBuildOptions()
1461 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smith6cfa78f2012-07-17 01:27:33 +00001462 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001463 .setAlwaysAdd(Stmt::BlockExprClass)
1464 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1465 .setAlwaysAdd(Stmt::DeclRefExprClass)
1466 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001467 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1468 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001469 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001470
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001471 // Construct the analysis context with the specified CFG build options.
1472
Ted Kremenek351ba912011-02-23 01:52:04 +00001473 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +00001474 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001475 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001476
1477 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001478 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001479 i = fscope->PossiblyUnreachableDiags.begin(),
1480 e = fscope->PossiblyUnreachableDiags.end();
1481 i != e; ++i) {
1482 if (const Stmt *stmt = i->stmt)
1483 AC.registerForcedBlockExpression(stmt);
1484 }
1485
1486 if (AC.getCFG()) {
1487 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001488 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001489 i = fscope->PossiblyUnreachableDiags.begin(),
1490 e = fscope->PossiblyUnreachableDiags.end();
1491 i != e; ++i)
1492 {
1493 const sema::PossiblyUnreachableDiag &D = *i;
1494 bool processed = false;
1495 if (const Stmt *stmt = i->stmt) {
1496 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +00001497 CFGReverseBlockReachabilityAnalysis *cra =
1498 AC.getCFGReachablityAnalysis();
1499 // FIXME: We should be able to assert that block is non-null, but
1500 // the CFG analysis can skip potentially-evaluated expressions in
1501 // edge cases; see test/Sema/vla-2.c.
1502 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001503 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001504 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001505 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001506 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001507 }
1508 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001509 if (!processed) {
1510 // Emit the warning anyway if we cannot map to a basic block.
1511 S.Diag(D.Loc, D.PD);
1512 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001513 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001514 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001515
1516 if (!analyzed)
1517 flushDiagnostics(S, fscope);
1518 }
1519
1520
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001521 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +00001522 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001523 const CheckFallThroughDiagnostics &CD =
1524 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +00001525 : (isa<CXXMethodDecl>(D) &&
1526 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1527 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1528 ? CheckFallThroughDiagnostics::MakeForLambda()
1529 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001530 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001531 }
1532
1533 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +00001534 if (P.enableCheckUnreachable) {
1535 // Only check for unreachable code on non-template instantiations.
1536 // Different template instantiations can effectively change the control-flow
1537 // and it is very difficult to prove that a snippet of code in a template
1538 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +00001539 bool isTemplateInstantiation = false;
1540 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1541 isTemplateInstantiation = Function->isTemplateInstantiation();
1542 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +00001543 CheckUnreachable(S, AC);
1544 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001545
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001546 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +00001547 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001548 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +00001549 SourceLocation FEL = AC.getDecl()->getLocEnd();
1550 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchinsfb4afc22012-12-05 00:06:15 +00001551 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1552 != DiagnosticsEngine::Ignored)
1553 Reporter.setIssueBetaWarnings(true);
1554
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001555 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1556 Reporter.emitDiagnostics();
1557 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001558
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001559 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001560 != DiagnosticsEngine::Ignored ||
Richard Smith2815e1a2012-05-25 02:17:09 +00001561 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1562 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +00001563 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001564 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001565 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001566 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001567 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001568 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001569 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001570 reporter, stats);
1571
1572 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1573 ++NumUninitAnalysisFunctions;
1574 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1575 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1576 MaxUninitAnalysisVariablesPerFunction =
1577 std::max(MaxUninitAnalysisVariablesPerFunction,
1578 stats.NumVariablesAnalyzed);
1579 MaxUninitAnalysisBlockVisitsPerFunction =
1580 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1581 stats.NumBlockVisits);
1582 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001583 }
1584 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001585
Alexander Kornienko19736342012-06-02 01:01:07 +00001586 bool FallThroughDiagFull =
1587 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1588 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001589 bool FallThroughDiagPerFunction =
1590 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko19736342012-06-02 01:01:07 +00001591 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001592 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko19736342012-06-02 01:01:07 +00001593 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001594 }
1595
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001596 if (S.getLangOpts().ObjCARCWeak &&
1597 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1598 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Roseb5cd1222012-10-11 16:10:19 +00001599 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001600
Chandler Carruth5d989942011-07-06 16:21:37 +00001601 // Collect statistics about the CFG if it was built.
1602 if (S.CollectStats && AC.isCFGBuilt()) {
1603 ++NumFunctionsAnalyzed;
1604 if (CFG *cfg = AC.getCFG()) {
1605 // If we successfully built a CFG for this context, record some more
1606 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001607 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001608 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001609 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001610 } else {
1611 ++NumFunctionsWithBadCFGs;
1612 }
1613 }
1614}
1615
1616void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1617 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1618
1619 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1620 unsigned AvgCFGBlocksPerFunction =
1621 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1622 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1623 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1624 << " " << NumCFGBlocks << " CFG blocks built.\n"
1625 << " " << AvgCFGBlocksPerFunction
1626 << " average CFG blocks per function.\n"
1627 << " " << MaxCFGBlocksPerFunction
1628 << " max CFG blocks per function.\n";
1629
1630 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1631 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1632 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1633 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1634 llvm::errs() << NumUninitAnalysisFunctions
1635 << " functions analyzed for uninitialiazed variables\n"
1636 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1637 << " " << AvgUninitVariablesPerFunction
1638 << " average variables per function.\n"
1639 << " " << MaxUninitAnalysisVariablesPerFunction
1640 << " max variables per function.\n"
1641 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1642 << " " << AvgUninitBlockVisitsPerFunction
1643 << " average block visits per function.\n"
1644 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1645 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001646}