blob: 54b791e6f62106aae7b1cc661712143bb0e0b977 [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"
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/ReachableCode.h"
30#include "clang/Analysis/Analyses/ThreadSafety.h"
31#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000035#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
Alexander Kornienko66da0ab2012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella3285c782013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko19523542012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth55fc8732012-12-04 09:13:33 +000052#include <deque>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000055
56using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Unreachable code analysis.
60//===----------------------------------------------------------------------===//
61
62namespace {
63 class UnreachableCodeHandler : public reachable_code::Callback {
64 Sema &S;
65 public:
66 UnreachableCodeHandler(Sema &s) : S(s) {}
67
68 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
69 S.Diag(L, diag::warn_unreachable) << R1 << R2;
70 }
71 };
72}
73
74/// CheckUnreachable - Check for unreachable code.
Ted Kremenek1d26f482011-10-24 01:32:45 +000075static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000076 UnreachableCodeHandler UC(S);
77 reachable_code::FindUnreachableCode(AC, UC);
78}
79
80//===----------------------------------------------------------------------===//
81// Check for missing return value.
82//===----------------------------------------------------------------------===//
83
John McCall16565aa2010-05-16 09:34:11 +000084enum ControlFlowKind {
85 UnknownFallThrough,
86 NeverFallThrough,
87 MaybeFallThrough,
88 AlwaysFallThrough,
89 NeverFallThroughOrReturn
90};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000091
92/// CheckFallThrough - Check that we don't fall off the end of a
93/// Statement that should return a value.
94///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000095/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
96/// MaybeFallThrough iff we might or might not fall off the end,
97/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
98/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000099/// statement but we may return. We assume that functions not marked noreturn
100/// will return.
Ted Kremenek1d26f482011-10-24 01:32:45 +0000101static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000102 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +0000103 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000104
105 // The CFG leaves in dead things, and we don't want the dead code paths to
106 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000107 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000108 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000109 live);
110
111 bool AddEHEdges = AC.getAddEHEdges();
112 if (!AddEHEdges && count != cfg->getNumBlockIDs())
113 // When there are things remaining dead, and we didn't add EH edges
114 // from CallExprs to the catch clauses, we have to go back and
115 // mark them as live.
116 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
117 CFGBlock &b = **I;
118 if (!live[b.getBlockID()]) {
119 if (b.pred_begin() == b.pred_end()) {
120 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
121 // When not adding EH edges from calls, catch clauses
122 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000123 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000124 continue;
125 }
126 }
127 }
128
129 // Now we know what is live, we check the live precessors of the exit block
130 // and look for fall through paths, being careful to ignore normal returns,
131 // and exceptional paths.
132 bool HasLiveReturn = false;
133 bool HasFakeEdge = false;
134 bool HasPlainEdge = false;
135 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000136
137 // Ignore default cases that aren't likely to be reachable because all
138 // enums in a switch(X) have explicit case statements.
139 CFGBlock::FilterOptions FO;
140 FO.IgnoreDefaultsWithCoveredEnums = 1;
141
142 for (CFGBlock::filtered_pred_iterator
143 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
144 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000145 if (!live[B.getBlockID()])
146 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000147
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000148 // Skip blocks which contain an element marked as no-return. They don't
149 // represent actually viable edges into the exit block, so mark them as
150 // abnormal.
151 if (B.hasNoReturnElement()) {
152 HasAbnormalEdge = true;
153 continue;
154 }
155
Ted Kremenek5811f592011-01-26 04:49:52 +0000156 // Destructors can appear after the 'return' in the CFG. This is
157 // normal. We need to look pass the destructors for the return
158 // statement (if it exists).
159 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000160
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000161 for ( ; ri != re ; ++ri)
David Blaikiefdf6a272013-02-21 20:58:29 +0000162 if (ri->getAs<CFGStmt>())
Ted Kremenek5811f592011-01-26 04:49:52 +0000163 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000164
Ted Kremenek5811f592011-01-26 04:49:52 +0000165 // No more CFGElements in the block?
166 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000167 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
168 HasAbnormalEdge = true;
169 continue;
170 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000171 // A labeled empty statement, or the entry block...
172 HasPlainEdge = true;
173 continue;
174 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000175
David Blaikiefdf6a272013-02-21 20:58:29 +0000176 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000177 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000178 if (isa<ReturnStmt>(S)) {
179 HasLiveReturn = true;
180 continue;
181 }
182 if (isa<ObjCAtThrowStmt>(S)) {
183 HasFakeEdge = true;
184 continue;
185 }
186 if (isa<CXXThrowExpr>(S)) {
187 HasFakeEdge = true;
188 continue;
189 }
Chad Rosier8cd64b42012-06-11 20:47:18 +0000190 if (isa<MSAsmStmt>(S)) {
191 // TODO: Verify this is correct.
192 HasFakeEdge = true;
193 HasLiveReturn = true;
194 continue;
195 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000196 if (isa<CXXTryStmt>(S)) {
197 HasAbnormalEdge = true;
198 continue;
199 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000200 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
201 == B.succ_end()) {
202 HasAbnormalEdge = true;
203 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000204 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000205
206 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000207 }
208 if (!HasPlainEdge) {
209 if (HasLiveReturn)
210 return NeverFallThrough;
211 return NeverFallThroughOrReturn;
212 }
213 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
214 return MaybeFallThrough;
215 // This says AlwaysFallThrough for calls to functions that are not marked
216 // noreturn, that don't return. If people would like this warning to be more
217 // accurate, such functions should be marked as noreturn.
218 return AlwaysFallThrough;
219}
220
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000221namespace {
222
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000223struct CheckFallThroughDiagnostics {
224 unsigned diag_MaybeFallThrough_HasNoReturn;
225 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
226 unsigned diag_AlwaysFallThrough_HasNoReturn;
227 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
228 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000229 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000230 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000231
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000232 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000233 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000234 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000235 D.diag_MaybeFallThrough_HasNoReturn =
236 diag::warn_falloff_noreturn_function;
237 D.diag_MaybeFallThrough_ReturnsNonVoid =
238 diag::warn_maybe_falloff_nonvoid_function;
239 D.diag_AlwaysFallThrough_HasNoReturn =
240 diag::warn_falloff_noreturn_function;
241 D.diag_AlwaysFallThrough_ReturnsNonVoid =
242 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000243
244 // Don't suggest that virtual functions be marked "noreturn", since they
245 // might be overridden by non-noreturn functions.
246 bool isVirtualMethod = false;
247 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
248 isVirtualMethod = Method->isVirtual();
249
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000250 // Don't suggest that template instantiations be marked "noreturn"
251 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000252 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
253 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000254
255 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000256 D.diag_NeverFallThroughOrReturn =
257 diag::warn_suggest_noreturn_function;
258 else
259 D.diag_NeverFallThroughOrReturn = 0;
260
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000261 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000262 return D;
263 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000264
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000265 static CheckFallThroughDiagnostics MakeForBlock() {
266 CheckFallThroughDiagnostics D;
267 D.diag_MaybeFallThrough_HasNoReturn =
268 diag::err_noreturn_block_has_return_expr;
269 D.diag_MaybeFallThrough_ReturnsNonVoid =
270 diag::err_maybe_falloff_nonvoid_block;
271 D.diag_AlwaysFallThrough_HasNoReturn =
272 diag::err_noreturn_block_has_return_expr;
273 D.diag_AlwaysFallThrough_ReturnsNonVoid =
274 diag::err_falloff_nonvoid_block;
275 D.diag_NeverFallThroughOrReturn =
276 diag::warn_suggest_noreturn_block;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000277 D.funMode = Block;
278 return D;
279 }
280
281 static CheckFallThroughDiagnostics MakeForLambda() {
282 CheckFallThroughDiagnostics D;
283 D.diag_MaybeFallThrough_HasNoReturn =
284 diag::err_noreturn_lambda_has_return_expr;
285 D.diag_MaybeFallThrough_ReturnsNonVoid =
286 diag::warn_maybe_falloff_nonvoid_lambda;
287 D.diag_AlwaysFallThrough_HasNoReturn =
288 diag::err_noreturn_lambda_has_return_expr;
289 D.diag_AlwaysFallThrough_ReturnsNonVoid =
290 diag::warn_falloff_nonvoid_lambda;
291 D.diag_NeverFallThroughOrReturn = 0;
292 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000293 return D;
294 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000295
David Blaikied6471f72011-09-25 23:23:43 +0000296 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000297 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000298 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000299 return (ReturnsVoid ||
300 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000301 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000302 && (!HasNoReturn ||
303 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000304 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000305 && (!ReturnsVoid ||
306 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000307 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000308 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000309
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000310 // For blocks / lambdas.
311 return ReturnsVoid && !HasNoReturn
312 && ((funMode == Lambda) ||
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000313 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000314 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000315 }
316};
317
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000318}
319
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000320/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
321/// function that should return a value. Check that we don't fall off the end
322/// of a noreturn function. We assume that functions and blocks not marked
323/// noreturn will return.
324static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000325 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000326 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000327 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000328
329 bool ReturnsVoid = false;
330 bool HasNoReturn = false;
331
332 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
333 ReturnsVoid = FD->getResultType()->isVoidType();
Richard Smithcd8ab512013-01-17 01:30:42 +0000334 HasNoReturn = FD->isNoReturn();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000335 }
336 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
337 ReturnsVoid = MD->getResultType()->isVoidType();
338 HasNoReturn = MD->hasAttr<NoReturnAttr>();
339 }
340 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000341 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000342 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000343 BlockTy->getPointeeType()->getAs<FunctionType>()) {
344 if (FT->getResultType()->isVoidType())
345 ReturnsVoid = true;
346 if (FT->getNoReturnAttr())
347 HasNoReturn = true;
348 }
349 }
350
David Blaikied6471f72011-09-25 23:23:43 +0000351 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000352
353 // Short circuit for compilation speed.
354 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
355 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000356
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000357 // FIXME: Function try block
358 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
359 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000360 case UnknownFallThrough:
361 break;
362
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000363 case MaybeFallThrough:
364 if (HasNoReturn)
365 S.Diag(Compound->getRBracLoc(),
366 CD.diag_MaybeFallThrough_HasNoReturn);
367 else if (!ReturnsVoid)
368 S.Diag(Compound->getRBracLoc(),
369 CD.diag_MaybeFallThrough_ReturnsNonVoid);
370 break;
371 case AlwaysFallThrough:
372 if (HasNoReturn)
373 S.Diag(Compound->getRBracLoc(),
374 CD.diag_AlwaysFallThrough_HasNoReturn);
375 else if (!ReturnsVoid)
376 S.Diag(Compound->getRBracLoc(),
377 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
378 break;
379 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000380 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
381 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
382 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000383 << 0 << FD;
384 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
385 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
386 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000387 } else {
388 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
389 }
390 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000391 break;
392 case NeverFallThrough:
393 break;
394 }
395 }
396}
397
398//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000399// -Wuninitialized
400//===----------------------------------------------------------------------===//
401
Ted Kremenek6f417152011-04-04 20:56:00 +0000402namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000403/// ContainsReference - A visitor class to search for references to
404/// a particular declaration (the needle) within any evaluated component of an
405/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000406class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000407 bool FoundReference;
408 const DeclRefExpr *Needle;
409
Ted Kremenek6f417152011-04-04 20:56:00 +0000410public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000411 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
412 : EvaluatedExprVisitor<ContainsReference>(Context),
413 FoundReference(false), Needle(Needle) {}
414
415 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000416 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000417 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000418 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000419
420 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000421 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000422
423 void VisitDeclRefExpr(DeclRefExpr *E) {
424 if (E == Needle)
425 FoundReference = true;
426 else
427 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000428 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000429
430 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000431};
432}
433
David Blaikie4f4f3492011-09-10 05:35:08 +0000434static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000435 QualType VariableTy = VD->getType().getCanonicalType();
436 if (VariableTy->isBlockPointerType() &&
437 !VD->hasAttr<BlocksAttr>()) {
438 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
439 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
440 return true;
441 }
442
David Blaikie4f4f3492011-09-10 05:35:08 +0000443 // Don't issue a fixit if there is already an initializer.
444 if (VD->getInit())
445 return false;
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000446
David Blaikie4f4f3492011-09-10 05:35:08 +0000447 // Suggest possible initialization (if any).
David Blaikie2c0abf42012-04-30 18:27:22 +0000448 std::string Init = S.getFixItZeroInitializerForType(VariableTy);
449 if (Init.empty())
David Blaikie4f4f3492011-09-10 05:35:08 +0000450 return false;
Richard Trieu7b0a3e32012-05-03 01:09:59 +0000451
452 // Don't suggest a fixit inside macros.
453 if (VD->getLocEnd().isMacroID())
454 return false;
455
Richard Smith7984de32012-01-12 23:53:29 +0000456 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000457
Richard Smith7984de32012-01-12 23:53:29 +0000458 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
459 << FixItHint::CreateInsertion(Loc, Init);
460 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000461}
462
Richard Smithbdb97ff2012-05-26 06:20:46 +0000463/// Create a fixit to remove an if-like statement, on the assumption that its
464/// condition is CondVal.
465static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
466 const Stmt *Else, bool CondVal,
467 FixItHint &Fixit1, FixItHint &Fixit2) {
468 if (CondVal) {
469 // If condition is always true, remove all but the 'then'.
470 Fixit1 = FixItHint::CreateRemoval(
471 CharSourceRange::getCharRange(If->getLocStart(),
472 Then->getLocStart()));
473 if (Else) {
474 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
475 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
476 Fixit2 = FixItHint::CreateRemoval(
477 SourceRange(ElseKwLoc, Else->getLocEnd()));
478 }
479 } else {
480 // If condition is always false, remove all but the 'else'.
481 if (Else)
482 Fixit1 = FixItHint::CreateRemoval(
483 CharSourceRange::getCharRange(If->getLocStart(),
484 Else->getLocStart()));
485 else
486 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
487 }
488}
489
490/// DiagUninitUse -- Helper function to produce a diagnostic for an
491/// uninitialized use of a variable.
492static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
493 bool IsCapturedByBlock) {
494 bool Diagnosed = false;
495
496 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith2815e1a2012-05-25 02:17:09 +0000497 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
498 I != E; ++I) {
Richard Smithbdb97ff2012-05-26 06:20:46 +0000499 assert(Use.getKind() == UninitUse::Sometimes);
500
501 const Expr *User = Use.getUser();
Richard Smith2815e1a2012-05-25 02:17:09 +0000502 const Stmt *Term = I->Terminator;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000503
504 // Information used when building the diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000505 unsigned DiagKind;
David Blaikie0bea8632012-10-08 01:11:04 +0000506 StringRef Str;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000507 SourceRange Range;
508
Stefanus Du Toitfc093362013-03-01 21:41:22 +0000509 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smithbdb97ff2012-05-26 06:20:46 +0000510 // For all binary terminators, branch 0 is taken if the condition is true,
511 // and branch 1 is taken if the condition is false.
512 int RemoveDiagKind = -1;
513 const char *FixitStr =
514 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
515 : (I->Output ? "1" : "0");
516 FixItHint Fixit1, Fixit2;
517
Richard Smith2815e1a2012-05-25 02:17:09 +0000518 switch (Term->getStmtClass()) {
519 default:
Richard Smithbdb97ff2012-05-26 06:20:46 +0000520 // Don't know how to report this. Just fall back to 'may be used
521 // uninitialized'. This happens for range-based for, which the user
522 // can't explicitly fix.
523 // FIXME: This also happens if the first use of a variable is always
524 // uninitialized, eg "for (int n; n < 10; ++n)". We should report that
525 // with the 'is uninitialized' diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000526 continue;
527
528 // "condition is true / condition is false".
Richard Smithbdb97ff2012-05-26 06:20:46 +0000529 case Stmt::IfStmtClass: {
530 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000531 DiagKind = 0;
532 Str = "if";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000533 Range = IS->getCond()->getSourceRange();
534 RemoveDiagKind = 0;
535 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
536 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000537 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000538 }
539 case Stmt::ConditionalOperatorClass: {
540 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000541 DiagKind = 0;
542 Str = "?:";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000543 Range = CO->getCond()->getSourceRange();
544 RemoveDiagKind = 0;
545 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
546 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000547 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000548 }
Richard Smith2815e1a2012-05-25 02:17:09 +0000549 case Stmt::BinaryOperatorClass: {
550 const BinaryOperator *BO = cast<BinaryOperator>(Term);
551 if (!BO->isLogicalOp())
552 continue;
553 DiagKind = 0;
554 Str = BO->getOpcodeStr();
555 Range = BO->getLHS()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000556 RemoveDiagKind = 0;
557 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
558 (BO->getOpcode() == BO_LOr && !I->Output))
559 // true && y -> y, false || y -> y.
560 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
561 BO->getOperatorLoc()));
562 else
563 // false && y -> false, true || y -> true.
564 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000565 break;
566 }
567
568 // "loop is entered / loop is exited".
569 case Stmt::WhileStmtClass:
570 DiagKind = 1;
571 Str = "while";
572 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000573 RemoveDiagKind = 1;
574 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000575 break;
576 case Stmt::ForStmtClass:
577 DiagKind = 1;
578 Str = "for";
579 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000580 RemoveDiagKind = 1;
581 if (I->Output)
582 Fixit1 = FixItHint::CreateRemoval(Range);
583 else
584 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000585 break;
586
587 // "condition is true / loop is exited".
588 case Stmt::DoStmtClass:
589 DiagKind = 2;
590 Str = "do";
591 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000592 RemoveDiagKind = 1;
593 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000594 break;
595
596 // "switch case is taken".
597 case Stmt::CaseStmtClass:
598 DiagKind = 3;
599 Str = "case";
600 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
601 break;
602 case Stmt::DefaultStmtClass:
603 DiagKind = 3;
604 Str = "default";
605 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
606 break;
607 }
608
Richard Smithbdb97ff2012-05-26 06:20:46 +0000609 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
610 << VD->getDeclName() << IsCapturedByBlock << DiagKind
611 << Str << I->Output << Range;
612 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
613 << IsCapturedByBlock << User->getSourceRange();
614 if (RemoveDiagKind != -1)
615 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
616 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
617
618 Diagnosed = true;
Richard Smith2815e1a2012-05-25 02:17:09 +0000619 }
Richard Smithbdb97ff2012-05-26 06:20:46 +0000620
621 if (!Diagnosed)
622 S.Diag(Use.getUser()->getLocStart(),
623 Use.getKind() == UninitUse::Always ? diag::warn_uninit_var
624 : diag::warn_maybe_uninit_var)
625 << VD->getDeclName() << IsCapturedByBlock
626 << Use.getUser()->getSourceRange();
Richard Smith2815e1a2012-05-25 02:17:09 +0000627}
628
Chandler Carruth262d50e2011-04-05 18:27:05 +0000629/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
630/// uninitialized variable. This manages the different forms of diagnostic
631/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith2815e1a2012-05-25 02:17:09 +0000632/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruth262d50e2011-04-05 18:27:05 +0000633/// false.
634static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith2815e1a2012-05-25 02:17:09 +0000635 const UninitUse &Use,
Ted Kremenek9e761722011-10-13 18:50:06 +0000636 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000637
Richard Smith2815e1a2012-05-25 02:17:09 +0000638 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieuf6278e52012-05-09 21:08:22 +0000639 // Inspect the initializer of the variable declaration which is
640 // being referenced prior to its initialization. We emit
641 // specialized diagnostics for self-initialization, and we
642 // specifically avoid warning about self references which take the
643 // form of:
644 //
645 // int x = x;
646 //
647 // This is used to indicate to GCC that 'x' is intentionally left
648 // uninitialized. Proven code paths which access 'x' in
649 // an uninitialized state after this will still warn.
650 if (const Expr *Initializer = VD->getInit()) {
651 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
652 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000653
Richard Trieuf6278e52012-05-09 21:08:22 +0000654 ContainsReference CR(S.Context, DRE);
655 CR.Visit(const_cast<Expr*>(Initializer));
656 if (CR.doesContainReference()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000657 S.Diag(DRE->getLocStart(),
658 diag::warn_uninit_self_reference_in_init)
Richard Trieuf6278e52012-05-09 21:08:22 +0000659 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
660 return true;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000661 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000662 }
Richard Trieuf6278e52012-05-09 21:08:22 +0000663
Richard Smithbdb97ff2012-05-26 06:20:46 +0000664 DiagUninitUse(S, VD, Use, false);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000665 } else {
Richard Smith2815e1a2012-05-25 02:17:09 +0000666 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smithbdb97ff2012-05-26 06:20:46 +0000667 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
668 S.Diag(BE->getLocStart(),
669 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000670 << VD->getDeclName();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000671 else
672 DiagUninitUse(S, VD, Use, true);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000673 }
674
675 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000676 // the initializer of that declaration & we didn't already suggest
677 // an initialization fixit.
Richard Trieuf6278e52012-05-09 21:08:22 +0000678 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000679 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
680 << VD->getDeclName();
681
Chandler Carruth262d50e2011-04-05 18:27:05 +0000682 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000683}
684
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000685namespace {
686 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
687 public:
688 FallthroughMapper(Sema &S)
689 : FoundSwitchStatements(false),
690 S(S) {
691 }
692
693 bool foundSwitchStatements() const { return FoundSwitchStatements; }
694
695 void markFallthroughVisited(const AttributedStmt *Stmt) {
696 bool Found = FallthroughStmts.erase(Stmt);
697 assert(Found);
Kaelyn Uhrain3bb29942012-05-03 19:46:38 +0000698 (void)Found;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000699 }
700
701 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
702
703 const AttrStmts &getFallthroughStmts() const {
704 return FallthroughStmts;
705 }
706
Alexander Kornienko4874a812013-01-30 03:49:44 +0000707 void fillReachableBlocks(CFG *Cfg) {
708 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
709 std::deque<const CFGBlock *> BlockQueue;
710
711 ReachableBlocks.insert(&Cfg->getEntry());
712 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000713 // Mark all case blocks reachable to avoid problems with switching on
714 // constants, covered enums, etc.
715 // These blocks can contain fall-through annotations, and we don't want to
716 // issue a warn_fallthrough_attr_unreachable for them.
717 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
718 const CFGBlock *B = *I;
719 const Stmt *L = B->getLabel();
720 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
721 BlockQueue.push_back(B);
722 }
723
Alexander Kornienko4874a812013-01-30 03:49:44 +0000724 while (!BlockQueue.empty()) {
725 const CFGBlock *P = BlockQueue.front();
726 BlockQueue.pop_front();
727 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
728 E = P->succ_end();
729 I != E; ++I) {
Alexander Kornienko0162b832013-02-01 15:39:20 +0000730 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienko4874a812013-01-30 03:49:44 +0000731 BlockQueue.push_back(*I);
732 }
733 }
734 }
735
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000736 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienko4874a812013-01-30 03:49:44 +0000737 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
738
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000739 int UnannotatedCnt = 0;
740 AnnotatedCnt = 0;
741
742 std::deque<const CFGBlock*> BlockQueue;
743
744 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
745
746 while (!BlockQueue.empty()) {
747 const CFGBlock *P = BlockQueue.front();
748 BlockQueue.pop_front();
749
750 const Stmt *Term = P->getTerminator();
751 if (Term && isa<SwitchStmt>(Term))
752 continue; // Switch statement, good.
753
754 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
755 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
756 continue; // Previous case label has no statements, good.
757
Alexander Kornienkoc6dcea92013-01-25 20:44:56 +0000758 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
759 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
760 continue; // Case label is preceded with a normal label, good.
761
Alexander Kornienko4874a812013-01-30 03:49:44 +0000762 if (!ReachableBlocks.count(P)) {
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000763 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
764 ElemEnd = P->rend();
765 ElemIt != ElemEnd; ++ElemIt) {
David Blaikieb0780542013-02-23 00:29:34 +0000766 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
767 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000768 S.Diag(AS->getLocStart(),
769 diag::warn_fallthrough_attr_unreachable);
770 markFallthroughVisited(AS);
771 ++AnnotatedCnt;
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000772 break;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000773 }
774 // Don't care about other unreachable statements.
775 }
776 }
777 // If there are no unreachable statements, this may be a special
778 // case in CFG:
779 // case X: {
780 // A a; // A has a destructor.
781 // break;
782 // }
783 // // <<<< This place is represented by a 'hanging' CFG block.
784 // case Y:
785 continue;
786 }
787
788 const Stmt *LastStmt = getLastStmt(*P);
789 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
790 markFallthroughVisited(AS);
791 ++AnnotatedCnt;
792 continue; // Fallthrough annotation, good.
793 }
794
795 if (!LastStmt) { // This block contains no executable statements.
796 // Traverse its predecessors.
797 std::copy(P->pred_begin(), P->pred_end(),
798 std::back_inserter(BlockQueue));
799 continue;
800 }
801
802 ++UnannotatedCnt;
803 }
804 return !!UnannotatedCnt;
805 }
806
807 // RecursiveASTVisitor setup.
808 bool shouldWalkTypesOfTypeLocs() const { return false; }
809
810 bool VisitAttributedStmt(AttributedStmt *S) {
811 if (asFallThroughAttr(S))
812 FallthroughStmts.insert(S);
813 return true;
814 }
815
816 bool VisitSwitchStmt(SwitchStmt *S) {
817 FoundSwitchStatements = true;
818 return true;
819 }
820
Alexander Kornienkob0707c92013-04-02 15:20:32 +0000821 // We don't want to traverse local type declarations. We analyze their
822 // methods separately.
823 bool TraverseDecl(Decl *D) { return true; }
824
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000825 private:
826
827 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
828 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
829 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
830 return AS;
831 }
832 return 0;
833 }
834
835 static const Stmt *getLastStmt(const CFGBlock &B) {
836 if (const Stmt *Term = B.getTerminator())
837 return Term;
838 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
839 ElemEnd = B.rend();
840 ElemIt != ElemEnd; ++ElemIt) {
David Blaikieb0780542013-02-23 00:29:34 +0000841 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
842 return CS->getStmt();
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000843 }
844 // Workaround to detect a statement thrown out by CFGBuilder:
845 // case X: {} case Y:
846 // case X: ; case Y:
847 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
848 if (!isa<SwitchCase>(SW->getSubStmt()))
849 return SW->getSubStmt();
850
851 return 0;
852 }
853
854 bool FoundSwitchStatements;
855 AttrStmts FallthroughStmts;
856 Sema &S;
Alexander Kornienko4874a812013-01-30 03:49:44 +0000857 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000858 };
859}
860
Alexander Kornienko19736342012-06-02 01:01:07 +0000861static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Sean Huntc2f51cf2012-06-15 21:22:05 +0000862 bool PerFunction) {
Ted Kremenek30783532012-11-12 21:20:48 +0000863 // Only perform this analysis when using C++11. There is no good workflow
864 // for this warning when not using C++11. There is no good way to silence
865 // the warning (no attribute is available) unless we are using C++11's support
866 // for generalized attributes. Once could use pragmas to silence the warning,
867 // but as a general solution that is gross and not in the spirit of this
868 // warning.
869 //
870 // NOTE: This an intermediate solution. There are on-going discussions on
871 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith80ad52f2013-01-02 11:42:31 +0000872 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenek30783532012-11-12 21:20:48 +0000873 return;
874
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000875 FallthroughMapper FM(S);
876 FM.TraverseStmt(AC.getBody());
877
878 if (!FM.foundSwitchStatements())
879 return;
880
Sean Huntc2f51cf2012-06-15 21:22:05 +0000881 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko19736342012-06-02 01:01:07 +0000882 return;
883
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000884 CFG *Cfg = AC.getCFG();
885
886 if (!Cfg)
887 return;
888
Alexander Kornienko4874a812013-01-30 03:49:44 +0000889 FM.fillReachableBlocks(Cfg);
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000890
891 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienkoe992ed12013-01-25 15:49:34 +0000892 const CFGBlock *B = *I;
893 const Stmt *Label = B->getLabel();
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000894
895 if (!Label || !isa<SwitchCase>(Label))
896 continue;
897
Alexander Kornienko4874a812013-01-30 03:49:44 +0000898 int AnnotatedCnt;
899
Alexander Kornienkoe992ed12013-01-25 15:49:34 +0000900 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000901 continue;
902
Alexander Kornienko19736342012-06-02 01:01:07 +0000903 S.Diag(Label->getLocStart(),
Sean Huntc2f51cf2012-06-15 21:22:05 +0000904 PerFunction ? diag::warn_unannotated_fallthrough_per_function
905 : diag::warn_unannotated_fallthrough);
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000906
907 if (!AnnotatedCnt) {
908 SourceLocation L = Label->getLocStart();
909 if (L.isMacroID())
910 continue;
Richard Smith80ad52f2013-01-02 11:42:31 +0000911 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienkoe992ed12013-01-25 15:49:34 +0000912 const Stmt *Term = B->getTerminator();
913 // Skip empty cases.
914 while (B->empty() && !Term && B->succ_size() == 1) {
915 B = *B->succ_begin();
916 Term = B->getTerminator();
917 }
918 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000919 Preprocessor &PP = S.getPreprocessor();
920 TokenValue Tokens[] = {
921 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
922 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
923 tok::r_square, tok::r_square
924 };
Dmitri Gribenko19523542012-09-29 11:40:46 +0000925 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
926 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
927 if (!MacroName.empty())
928 AnnotationSpelling = MacroName;
929 SmallString<64> TextToInsert(AnnotationSpelling);
930 TextToInsert += "; ";
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000931 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000932 AnnotationSpelling <<
Dmitri Gribenko19523542012-09-29 11:40:46 +0000933 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000934 }
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000935 }
936 S.Diag(L, diag::note_insert_break_fixit) <<
937 FixItHint::CreateInsertion(L, "break; ");
938 }
939 }
940
941 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
942 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
943 E = Fallthroughs.end();
944 I != E; ++I) {
945 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
946 }
947
948}
949
Ted Kremenek610068c2011-01-15 02:58:47 +0000950namespace {
Jordan Rose20441c52012-09-28 22:29:02 +0000951typedef std::pair<const Stmt *,
952 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
953 StmtUsesPair;
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000954
Jordan Rose20441c52012-09-28 22:29:02 +0000955class StmtUseSorter {
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000956 const SourceManager &SM;
957
958public:
Jordan Rose20441c52012-09-28 22:29:02 +0000959 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000960
961 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
962 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
963 RHS.first->getLocStart());
964 }
965};
Jordan Rose20441c52012-09-28 22:29:02 +0000966}
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000967
Jordan Rosec0e44452012-10-29 17:46:47 +0000968static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
969 const Stmt *S) {
Jordan Roseb5cd1222012-10-11 16:10:19 +0000970 assert(S);
971
972 do {
973 switch (S->getStmtClass()) {
Jordan Roseb5cd1222012-10-11 16:10:19 +0000974 case Stmt::ForStmtClass:
975 case Stmt::WhileStmtClass:
976 case Stmt::CXXForRangeStmtClass:
977 case Stmt::ObjCForCollectionStmtClass:
978 return true;
Jordan Rosec0e44452012-10-29 17:46:47 +0000979 case Stmt::DoStmtClass: {
980 const Expr *Cond = cast<DoStmt>(S)->getCond();
981 llvm::APSInt Val;
982 if (!Cond->EvaluateAsInt(Val, Ctx))
983 return true;
984 return Val.getBoolValue();
985 }
Jordan Roseb5cd1222012-10-11 16:10:19 +0000986 default:
987 break;
988 }
989 } while ((S = PM.getParent(S)));
990
991 return false;
992}
993
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000994
995static void diagnoseRepeatedUseOfWeak(Sema &S,
996 const sema::FunctionScopeInfo *CurFn,
Jordan Roseb5cd1222012-10-11 16:10:19 +0000997 const Decl *D,
998 const ParentMap &PM) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000999 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1000 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1001 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1002
Jordan Rosec0e44452012-10-29 17:46:47 +00001003 ASTContext &Ctx = S.getASTContext();
1004
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001005 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1006
1007 // Extract all weak objects that are referenced more than once.
1008 SmallVector<StmtUsesPair, 8> UsesByStmt;
1009 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1010 I != E; ++I) {
1011 const WeakUseVector &Uses = I->second;
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001012
1013 // Find the first read of the weak object.
1014 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1015 for ( ; UI != UE; ++UI) {
1016 if (UI->isUnsafe())
1017 break;
1018 }
1019
1020 // If there were only writes to this object, don't warn.
1021 if (UI == UE)
1022 continue;
1023
Jordan Roseb5cd1222012-10-11 16:10:19 +00001024 // If there was only one read, followed by any number of writes, and the
Jordan Rosec0e44452012-10-29 17:46:47 +00001025 // read is not within a loop, don't warn. Additionally, don't warn in a
1026 // loop if the base object is a local variable -- local variables are often
1027 // changed in loops.
Jordan Roseb5cd1222012-10-11 16:10:19 +00001028 if (UI == Uses.begin()) {
1029 WeakUseVector::const_iterator UI2 = UI;
1030 for (++UI2; UI2 != UE; ++UI2)
1031 if (UI2->isUnsafe())
1032 break;
1033
Jordan Rosec0e44452012-10-29 17:46:47 +00001034 if (UI2 == UE) {
1035 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Roseb5cd1222012-10-11 16:10:19 +00001036 continue;
Jordan Rosec0e44452012-10-29 17:46:47 +00001037
1038 const WeakObjectProfileTy &Profile = I->first;
1039 if (!Profile.isExactProfile())
1040 continue;
1041
1042 const NamedDecl *Base = Profile.getBase();
1043 if (!Base)
1044 Base = Profile.getProperty();
1045 assert(Base && "A profile always has a base or property.");
1046
1047 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1048 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1049 continue;
1050 }
Jordan Roseb5cd1222012-10-11 16:10:19 +00001051 }
1052
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001053 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1054 }
1055
1056 if (UsesByStmt.empty())
1057 return;
1058
1059 // Sort by first use so that we emit the warnings in a deterministic order.
1060 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Jordan Rose20441c52012-09-28 22:29:02 +00001061 StmtUseSorter(S.getSourceManager()));
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001062
1063 // Classify the current code body for better warning text.
1064 // This enum should stay in sync with the cases in
1065 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1066 // FIXME: Should we use a common classification enum and the same set of
1067 // possibilities all throughout Sema?
1068 enum {
1069 Function,
1070 Method,
1071 Block,
1072 Lambda
1073 } FunctionKind;
1074
1075 if (isa<sema::BlockScopeInfo>(CurFn))
1076 FunctionKind = Block;
1077 else if (isa<sema::LambdaScopeInfo>(CurFn))
1078 FunctionKind = Lambda;
1079 else if (isa<ObjCMethodDecl>(D))
1080 FunctionKind = Method;
1081 else
1082 FunctionKind = Function;
1083
1084 // Iterate through the sorted problems and emit warnings for each.
1085 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1086 E = UsesByStmt.end();
1087 I != E; ++I) {
1088 const Stmt *FirstRead = I->first;
1089 const WeakObjectProfileTy &Key = I->second->first;
1090 const WeakUseVector &Uses = I->second->second;
1091
Jordan Rose7a270482012-09-28 22:21:35 +00001092 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1093 // may not contain enough information to determine that these are different
1094 // properties. We can only be 100% sure of a repeated use in certain cases,
1095 // and we adjust the diagnostic kind accordingly so that the less certain
1096 // case can be turned off if it is too noisy.
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001097 unsigned DiagKind;
1098 if (Key.isExactProfile())
1099 DiagKind = diag::warn_arc_repeated_use_of_weak;
1100 else
1101 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1102
Jordan Rose7a270482012-09-28 22:21:35 +00001103 // Classify the weak object being accessed for better warning text.
1104 // This enum should stay in sync with the cases in
1105 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1106 enum {
1107 Variable,
1108 Property,
1109 ImplicitProperty,
1110 Ivar
1111 } ObjectKind;
1112
1113 const NamedDecl *D = Key.getProperty();
1114 if (isa<VarDecl>(D))
1115 ObjectKind = Variable;
1116 else if (isa<ObjCPropertyDecl>(D))
1117 ObjectKind = Property;
1118 else if (isa<ObjCMethodDecl>(D))
1119 ObjectKind = ImplicitProperty;
1120 else if (isa<ObjCIvarDecl>(D))
1121 ObjectKind = Ivar;
1122 else
1123 llvm_unreachable("Unexpected weak object kind!");
1124
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001125 // Show the first time the object was read.
1126 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenberger73484542013-06-26 21:31:47 +00001127 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001128 << FirstRead->getSourceRange();
1129
1130 // Print all the other accesses as notes.
1131 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1132 UI != UE; ++UI) {
1133 if (UI->getUseExpr() == FirstRead)
1134 continue;
1135 S.Diag(UI->getUseExpr()->getLocStart(),
1136 diag::note_arc_weak_also_accessed_here)
1137 << UI->getUseExpr()->getSourceRange();
1138 }
1139 }
1140}
1141
1142
1143namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001144struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +00001145 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001146 // Prefer a more confident report over a less confident one.
1147 if (a.getKind() != b.getKind())
1148 return a.getKind() > b.getKind();
1149 SourceLocation aLoc = a.getUser()->getLocStart();
1150 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001151 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1152 }
1153};
1154
Ted Kremenek610068c2011-01-15 02:58:47 +00001155class UninitValsDiagReporter : public UninitVariablesHandler {
1156 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001157 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramere1039792013-06-29 17:52:13 +00001158 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella3285c782013-02-15 20:09:55 +00001159 // Prefer using MapVector to DenseMap, so that iteration order will be
1160 // the same as insertion order. This is needed to obtain a deterministic
1161 // order of diagnostics when calling flushDiagnostics().
1162 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001163 UsesMap *uses;
1164
Ted Kremenek610068c2011-01-15 02:58:47 +00001165public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001166 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1167 ~UninitValsDiagReporter() {
1168 flushDiagnostics();
1169 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001170
Enea Zaffanella3285c782013-02-15 20:09:55 +00001171 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001172 if (!uses)
1173 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +00001174
Enea Zaffanella3285c782013-02-15 20:09:55 +00001175 MappedType &V = (*uses)[vd];
Benjamin Kramere1039792013-06-29 17:52:13 +00001176 if (!V.getPointer())
1177 V.setPointer(new UsesVec());
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001178
Ted Kremenek9e761722011-10-13 18:50:06 +00001179 return V;
1180 }
1181
Richard Smith2815e1a2012-05-25 02:17:09 +00001182 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
Benjamin Kramere1039792013-06-29 17:52:13 +00001183 getUses(vd).getPointer()->push_back(use);
Ted Kremenek9e761722011-10-13 18:50:06 +00001184 }
1185
1186 void handleSelfInit(const VarDecl *vd) {
Benjamin Kramere1039792013-06-29 17:52:13 +00001187 getUses(vd).setInt(true);
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001188 }
1189
1190 void flushDiagnostics() {
1191 if (!uses)
1192 return;
Enea Zaffanella3285c782013-02-15 20:09:55 +00001193
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001194 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1195 const VarDecl *vd = i->first;
Enea Zaffanella3285c782013-02-15 20:09:55 +00001196 const MappedType &V = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +00001197
Benjamin Kramere1039792013-06-29 17:52:13 +00001198 UsesVec *vec = V.getPointer();
1199 bool hasSelfInit = V.getInt();
Ted Kremenek9e761722011-10-13 18:50:06 +00001200
1201 // Specially handle the case where we have uses of an uninitialized
1202 // variable, but the root cause is an idiomatic self-init. We want
1203 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001204 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith2815e1a2012-05-25 02:17:09 +00001205 DiagnoseUninitializedUse(S, vd,
1206 UninitUse(vd->getInit()->IgnoreParenCasts(),
1207 /* isAlwaysUninit */ true),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001208 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +00001209 else {
1210 // Sort the uses by their SourceLocations. While not strictly
1211 // guaranteed to produce them in line/column order, this will provide
1212 // a stable ordering.
1213 std::sort(vec->begin(), vec->end(), SLocSort());
1214
1215 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1216 ++vi) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001217 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1218 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1219
1220 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek9e761722011-10-13 18:50:06 +00001221 // Skip further diagnostics for this variable. We try to warn only
1222 // on the first point at which a variable is used uninitialized.
1223 break;
1224 }
Chandler Carruth64fb9592011-04-05 18:18:08 +00001225 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001226
1227 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001228 delete vec;
1229 }
1230 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +00001231 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001232
1233private:
1234 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1235 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001236 if (i->getKind() == UninitUse::Always) {
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001237 return true;
1238 }
1239 }
1240 return false;
1241}
Ted Kremenek610068c2011-01-15 02:58:47 +00001242};
1243}
1244
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001245namespace clang {
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001246namespace {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001247typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith2e515622012-02-03 04:45:26 +00001248typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramerecafd302012-03-26 14:05:40 +00001249typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001250
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001251struct SortDiagBySourceLocation {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001252 SourceManager &SM;
1253 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001254
1255 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1256 // Although this call will be slow, this is only called when outputting
1257 // multiple warnings.
Benjamin Kramerecafd302012-03-26 14:05:40 +00001258 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001259 }
1260};
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001261}}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001262
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001263//===----------------------------------------------------------------------===//
1264// -Wthread-safety
1265//===----------------------------------------------------------------------===//
1266namespace clang {
1267namespace thread_safety {
David Blaikie99ba9e32011-12-20 02:48:34 +00001268namespace {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001269class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1270 Sema &S;
1271 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +00001272 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001273
1274 // Helper functions
1275 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001276 // Gracefully handle rare cases when the analysis can't get a more
1277 // precise source location.
1278 if (!Loc.isValid())
1279 Loc = FunLocation;
Richard Smith2e515622012-02-03 04:45:26 +00001280 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1281 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001282 }
1283
1284 public:
Richard Smith2e515622012-02-03 04:45:26 +00001285 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1286 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001287
1288 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1289 /// We need to output diagnostics produced while iterating through
1290 /// the lockset in deterministic order, so this function orders diagnostics
1291 /// and outputs them.
1292 void emitDiagnostics() {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001293 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001294 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith2e515622012-02-03 04:45:26 +00001295 I != E; ++I) {
1296 S.Diag(I->first.first, I->first.second);
1297 const OptionalNotes &Notes = I->second;
1298 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1299 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1300 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001301 }
1302
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001303 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001304 PartialDiagnosticAt Warning(Loc,
1305 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1306 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001307 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001308 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1309 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1310 }
1311
1312 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1313 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1314 }
1315
Richard Smith2e515622012-02-03 04:45:26 +00001316 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1317 SourceLocation LocEndOfScope,
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001318 LockErrorKind LEK){
1319 unsigned DiagID = 0;
1320 switch (LEK) {
1321 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +00001322 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001323 break;
1324 case LEK_LockedSomeLoopIterations:
1325 DiagID = diag::warn_expecting_lock_held_on_loop;
1326 break;
1327 case LEK_LockedAtEndOfFunction:
1328 DiagID = diag::warn_no_unlock;
1329 break;
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001330 case LEK_NotLockedAtEndOfFunction:
1331 DiagID = diag::warn_expecting_locked;
1332 break;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001333 }
Richard Smith2e515622012-02-03 04:45:26 +00001334 if (LocEndOfScope.isInvalid())
1335 LocEndOfScope = FunEndLocation;
1336
1337 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchins56968842013-04-08 20:11:11 +00001338 if (LocLocked.isValid()) {
1339 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1340 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1341 return;
1342 }
1343 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001344 }
1345
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001346
1347 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1348 SourceLocation Loc2) {
Richard Smith2e515622012-02-03 04:45:26 +00001349 PartialDiagnosticAt Warning(
1350 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1351 PartialDiagnosticAt Note(
1352 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1353 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001354 }
1355
1356 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1357 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +00001358 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1359 && "Only works for variables");
1360 unsigned DiagID = POK == POK_VarAccess?
1361 diag::warn_variable_requires_any_lock:
1362 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +00001363 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001364 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith2e515622012-02-03 04:45:26 +00001365 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001366 }
1367
1368 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001369 Name LockName, LockKind LK, SourceLocation Loc,
1370 Name *PossibleMatch) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +00001371 unsigned DiagID = 0;
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001372 if (PossibleMatch) {
1373 switch (POK) {
1374 case POK_VarAccess:
1375 DiagID = diag::warn_variable_requires_lock_precise;
1376 break;
1377 case POK_VarDereference:
1378 DiagID = diag::warn_var_deref_requires_lock_precise;
1379 break;
1380 case POK_FunctionCall:
1381 DiagID = diag::warn_fun_requires_lock_precise;
1382 break;
1383 }
1384 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001385 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001386 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1387 << *PossibleMatch);
1388 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1389 } else {
1390 switch (POK) {
1391 case POK_VarAccess:
1392 DiagID = diag::warn_variable_requires_lock;
1393 break;
1394 case POK_VarDereference:
1395 DiagID = diag::warn_var_deref_requires_lock;
1396 break;
1397 case POK_FunctionCall:
1398 DiagID = diag::warn_fun_requires_lock;
1399 break;
1400 }
1401 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001402 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001403 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001404 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001405 }
1406
1407 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001408 PartialDiagnosticAt Warning(Loc,
1409 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1410 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001411 }
1412};
1413}
1414}
David Blaikie99ba9e32011-12-20 02:48:34 +00001415}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001416
Ted Kremenek610068c2011-01-15 02:58:47 +00001417//===----------------------------------------------------------------------===//
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001418// -Wconsumed
1419//===----------------------------------------------------------------------===//
1420
1421namespace clang {
1422namespace consumed {
1423namespace {
1424class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1425
1426 Sema &S;
1427 DiagList Warnings;
1428
1429public:
1430
1431 ConsumedWarningsHandler(Sema &S) : S(S) {}
1432
1433 void emitDiagnostics() {
1434 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1435
1436 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1437 I != E; ++I) {
1438
1439 const OptionalNotes &Notes = I->second;
1440 S.Diag(I->first.first, I->first.second);
1441
1442 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1443 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1444 }
1445 }
1446 }
1447
1448 /// Warn about unnecessary-test errors.
1449 /// \param VariableName -- The name of the variable that holds the unique
1450 /// value.
1451 ///
1452 /// \param Loc -- The SourceLocation of the unnecessary test.
1453 void warnUnnecessaryTest(StringRef VariableName, StringRef VariableState,
1454 SourceLocation Loc) {
1455
1456 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unnecessary_test) <<
1457 VariableName << VariableState);
1458
1459 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1460 }
1461
1462 /// Warn about use-while-consumed errors.
1463 /// \param MethodName -- The name of the method that was incorrectly
1464 /// invoked.
1465 ///
1466 /// \param VariableName -- The name of the variable that holds the unique
1467 /// value.
1468 ///
1469 /// \param Loc -- The SourceLocation of the method invocation.
1470 void warnUseOfTempWhileConsumed(StringRef MethodName, SourceLocation Loc) {
1471
1472 PartialDiagnosticAt Warning(Loc, S.PDiag(
1473 diag::warn_use_of_temp_while_consumed) << MethodName);
1474
1475 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1476 }
1477
1478 /// Warn about use-in-unknown-state errors.
1479 /// \param MethodName -- The name of the method that was incorrectly
1480 /// invoked.
1481 ///
1482 /// \param VariableName -- The name of the variable that holds the unique
1483 /// value.
1484 ///
1485 /// \param Loc -- The SourceLocation of the method invocation.
1486 void warnUseOfTempInUnknownState(StringRef MethodName, SourceLocation Loc) {
1487
1488 PartialDiagnosticAt Warning(Loc, S.PDiag(
1489 diag::warn_use_of_temp_in_unknown_state) << MethodName);
1490
1491 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1492 }
1493
1494 /// Warn about use-while-consumed errors.
1495 /// \param MethodName -- The name of the method that was incorrectly
1496 /// invoked.
1497 ///
1498 /// \param VariableName -- The name of the variable that holds the unique
1499 /// value.
1500 ///
1501 /// \param Loc -- The SourceLocation of the method invocation.
1502 void warnUseWhileConsumed(StringRef MethodName, StringRef VariableName,
1503 SourceLocation Loc) {
1504
1505 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_while_consumed) <<
1506 MethodName << VariableName);
1507
1508 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1509 }
1510
1511 /// Warn about use-in-unknown-state errors.
1512 /// \param MethodName -- The name of the method that was incorrectly
1513 /// invoked.
1514 ///
1515 /// \param VariableName -- The name of the variable that holds the unique
1516 /// value.
1517 ///
1518 /// \param Loc -- The SourceLocation of the method invocation.
1519 void warnUseInUnknownState(StringRef MethodName, StringRef VariableName,
1520 SourceLocation Loc) {
1521
1522 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_unknown_state) <<
1523 MethodName << VariableName);
1524
1525 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1526 }
1527};
1528}}}
1529
1530//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001531// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1532// warnings on a function, method, or block.
1533//===----------------------------------------------------------------------===//
1534
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001535clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1536 enableCheckFallThrough = 1;
1537 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001538 enableThreadSafetyAnalysis = 0;
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001539 enableConsumedAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001540}
1541
Chandler Carruth5d989942011-07-06 16:21:37 +00001542clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1543 : S(s),
1544 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001545 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001546 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001547 MaxCFGBlocksPerFunction(0),
1548 NumUninitAnalysisFunctions(0),
1549 NumUninitAnalysisVariables(0),
1550 MaxUninitAnalysisVariablesPerFunction(0),
1551 NumUninitAnalysisBlockVisits(0),
1552 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +00001553 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001554 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001555 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001556 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001557 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1558 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001559 DiagnosticsEngine::Ignored);
Reid Kleckner2d84f6b2013-08-12 23:49:39 +00001560 DefaultPolicy.enableConsumedAnalysis =
1561 (unsigned)(D.getDiagnosticLevel(diag::warn_use_while_consumed,
1562 SourceLocation()) !=
1563 DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001564}
1565
Ted Kremenek351ba912011-02-23 01:52:04 +00001566static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001567 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001568 i = fscope->PossiblyUnreachableDiags.begin(),
1569 e = fscope->PossiblyUnreachableDiags.end();
1570 i != e; ++i) {
1571 const sema::PossiblyUnreachableDiag &D = *i;
1572 S.Diag(D.Loc, D.PD);
1573 }
1574}
1575
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001576void clang::sema::
1577AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001578 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001579 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001580
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001581 // We avoid doing analysis-based warnings when there are errors for
1582 // two reasons:
1583 // (1) The CFGs often can't be constructed (if the body is invalid), so
1584 // don't bother trying.
1585 // (2) The code already has problems; running the analysis just takes more
1586 // time.
David Blaikied6471f72011-09-25 23:23:43 +00001587 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +00001588
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001589 // Do not do any analysis for declarations in system headers if we are
1590 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001591 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001592 S.SourceMgr.isInSystemHeader(D->getLocation()))
1593 return;
1594
John McCalle0054f62010-08-25 05:56:39 +00001595 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +00001596 if (cast<DeclContext>(D)->isDependentContext())
1597 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001598
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00001599 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001600 // Flush out any possibly unreachable diagnostics.
1601 flushDiagnostics(S, fscope);
1602 return;
1603 }
1604
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001605 const Stmt *Body = D->getBody();
1606 assert(Body);
1607
Jordy Rosed2001872012-04-28 01:58:08 +00001608 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001609
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001610 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1611 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001612 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1613 AC.getCFGBuildOptions().AddEHEdges = false;
1614 AC.getCFGBuildOptions().AddInitializers = true;
1615 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rosefaadf482012-09-05 23:11:06 +00001616 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1617
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001618 // Force that certain expressions appear as CFGElements in the CFG. This
1619 // is used to speed up various analyses.
1620 // FIXME: This isn't the right factoring. This is here for initial
1621 // prototyping, but we need a way for analyses to say what expressions they
1622 // expect to always be CFGElements and then fill in the BuildOptions
1623 // appropriately. This is essentially a layering violation.
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001624 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1625 P.enableConsumedAnalysis) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001626 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001627 AC.getCFGBuildOptions().setAllAlwaysAdd();
1628 }
1629 else {
1630 AC.getCFGBuildOptions()
1631 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smith6cfa78f2012-07-17 01:27:33 +00001632 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001633 .setAlwaysAdd(Stmt::BlockExprClass)
1634 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1635 .setAlwaysAdd(Stmt::DeclRefExprClass)
1636 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001637 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1638 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001639 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001640
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001641 // Construct the analysis context with the specified CFG build options.
1642
Ted Kremenek351ba912011-02-23 01:52:04 +00001643 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +00001644 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001645 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001646
1647 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001648 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001649 i = fscope->PossiblyUnreachableDiags.begin(),
1650 e = fscope->PossiblyUnreachableDiags.end();
1651 i != e; ++i) {
1652 if (const Stmt *stmt = i->stmt)
1653 AC.registerForcedBlockExpression(stmt);
1654 }
1655
1656 if (AC.getCFG()) {
1657 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001658 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001659 i = fscope->PossiblyUnreachableDiags.begin(),
1660 e = fscope->PossiblyUnreachableDiags.end();
1661 i != e; ++i)
1662 {
1663 const sema::PossiblyUnreachableDiag &D = *i;
1664 bool processed = false;
1665 if (const Stmt *stmt = i->stmt) {
1666 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +00001667 CFGReverseBlockReachabilityAnalysis *cra =
1668 AC.getCFGReachablityAnalysis();
1669 // FIXME: We should be able to assert that block is non-null, but
1670 // the CFG analysis can skip potentially-evaluated expressions in
1671 // edge cases; see test/Sema/vla-2.c.
1672 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001673 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001674 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001675 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001676 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001677 }
1678 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001679 if (!processed) {
1680 // Emit the warning anyway if we cannot map to a basic block.
1681 S.Diag(D.Loc, D.PD);
1682 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001683 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001684 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001685
1686 if (!analyzed)
1687 flushDiagnostics(S, fscope);
1688 }
1689
1690
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001691 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +00001692 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001693 const CheckFallThroughDiagnostics &CD =
1694 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +00001695 : (isa<CXXMethodDecl>(D) &&
1696 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1697 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1698 ? CheckFallThroughDiagnostics::MakeForLambda()
1699 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001700 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001701 }
1702
1703 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +00001704 if (P.enableCheckUnreachable) {
1705 // Only check for unreachable code on non-template instantiations.
1706 // Different template instantiations can effectively change the control-flow
1707 // and it is very difficult to prove that a snippet of code in a template
1708 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +00001709 bool isTemplateInstantiation = false;
1710 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1711 isTemplateInstantiation = Function->isTemplateInstantiation();
1712 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +00001713 CheckUnreachable(S, AC);
1714 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001715
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001716 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +00001717 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001718 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +00001719 SourceLocation FEL = AC.getDecl()->getLocEnd();
1720 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchinsfb4afc22012-12-05 00:06:15 +00001721 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1722 != DiagnosticsEngine::Ignored)
1723 Reporter.setIssueBetaWarnings(true);
1724
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001725 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1726 Reporter.emitDiagnostics();
1727 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001728
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001729 // Check for violations of consumed properties.
1730 if (P.enableConsumedAnalysis) {
1731 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Kleckner2d84f6b2013-08-12 23:49:39 +00001732 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001733 Analyzer.run(AC);
1734 }
1735
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001736 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001737 != DiagnosticsEngine::Ignored ||
Richard Smith2815e1a2012-05-25 02:17:09 +00001738 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1739 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +00001740 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001741 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001742 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001743 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001744 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001745 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001746 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001747 reporter, stats);
1748
1749 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1750 ++NumUninitAnalysisFunctions;
1751 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1752 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1753 MaxUninitAnalysisVariablesPerFunction =
1754 std::max(MaxUninitAnalysisVariablesPerFunction,
1755 stats.NumVariablesAnalyzed);
1756 MaxUninitAnalysisBlockVisitsPerFunction =
1757 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1758 stats.NumBlockVisits);
1759 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001760 }
1761 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001762
Alexander Kornienko19736342012-06-02 01:01:07 +00001763 bool FallThroughDiagFull =
1764 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1765 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001766 bool FallThroughDiagPerFunction =
1767 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko19736342012-06-02 01:01:07 +00001768 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001769 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko19736342012-06-02 01:01:07 +00001770 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001771 }
1772
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001773 if (S.getLangOpts().ObjCARCWeak &&
1774 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1775 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Roseb5cd1222012-10-11 16:10:19 +00001776 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001777
Chandler Carruth5d989942011-07-06 16:21:37 +00001778 // Collect statistics about the CFG if it was built.
1779 if (S.CollectStats && AC.isCFGBuilt()) {
1780 ++NumFunctionsAnalyzed;
1781 if (CFG *cfg = AC.getCFG()) {
1782 // If we successfully built a CFG for this context, record some more
1783 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001784 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001785 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001786 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001787 } else {
1788 ++NumFunctionsWithBadCFGs;
1789 }
1790 }
1791}
1792
1793void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1794 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1795
1796 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1797 unsigned AvgCFGBlocksPerFunction =
1798 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1799 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1800 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1801 << " " << NumCFGBlocks << " CFG blocks built.\n"
1802 << " " << AvgCFGBlocksPerFunction
1803 << " average CFG blocks per function.\n"
1804 << " " << MaxCFGBlocksPerFunction
1805 << " max CFG blocks per function.\n";
1806
1807 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1808 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1809 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1810 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1811 llvm::errs() << NumUninitAnalysisFunctions
1812 << " functions analyzed for uninitialiazed variables\n"
1813 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1814 << " " << AvgUninitVariablesPerFunction
1815 << " average variables per function.\n"
1816 << " " << MaxUninitAnalysisVariablesPerFunction
1817 << " max variables per function.\n"
1818 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1819 << " " << AvgUninitBlockVisitsPerFunction
1820 << " average block visits per function.\n"
1821 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1822 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001823}