blob: 57c0ac311cdbac51775e8166947e753ee525f65c [file] [log] [blame]
Ted Kremenek918fe842010-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 Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Rose76831c62012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smith84837d52012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-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 Hutchins48a31762013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth3a022472012-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 Kremenek918fe842010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
Ted Kremenek3427fac2011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth3a022472012-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 Kornienkoe61e5622012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenek918fe842010-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 Kremenek81ce1c82011-10-24 01:32:45 +000075static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +000076 UnreachableCodeHandler UC(S);
77 reachable_code::FindUnreachableCode(AC, UC);
78}
79
80//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +000081// Check for infinite self-recursion in functions
82//===----------------------------------------------------------------------===//
83
84// All blocks are in one of three states. States are ordered so that blocks
85// can only move to higher states.
86enum RecursiveState {
87 FoundNoPath,
88 FoundPath,
89 FoundPathWithNoRecursiveCall
90};
91
92static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
93 CFGBlock &Block, unsigned ExitID,
94 llvm::SmallVectorImpl<RecursiveState> &States,
95 RecursiveState State) {
96 unsigned ID = Block.getBlockID();
97
98 // A block's state can only move to a higher state.
99 if (States[ID] >= State)
100 return;
101
102 States[ID] = State;
103
104 // Found a path to the exit node without a recursive call.
105 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
106 return;
107
108 if (State == FoundPathWithNoRecursiveCall) {
109 // If the current state is FoundPathWithNoRecursiveCall, the successors
110 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
111 // which, process all the Stmt's in this block to find any recursive calls.
112 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
113 if (I->getKind() != CFGElement::Statement)
114 continue;
115
116 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
117 if (CE && CE->getCalleeDecl() &&
118 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
119 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
120 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
121 !MCE->getMethodDecl()->isVirtual()) {
122 State = FoundPath;
123 break;
124 }
125 } else {
126 State = FoundPath;
127 break;
128 }
129 }
130 }
131 }
132
133 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
134 I != E; ++I)
135 if (*I)
136 checkForFunctionCall(S, FD, **I, ExitID, States, State);
137}
138
139static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
140 const Stmt *Body,
141 AnalysisDeclContext &AC) {
142 FD = FD->getCanonicalDecl();
143
144 // Only run on non-templated functions and non-templated members of
145 // templated classes.
146 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
147 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
148 return;
149
150 CFG *cfg = AC.getCFG();
151 if (cfg == 0) return;
152
153 // If the exit block is unreachable, skip processing the function.
154 if (cfg->getExit().pred_empty())
155 return;
156
157 // Mark all nodes as FoundNoPath, then begin processing the entry block.
158 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
159 FoundNoPath);
160 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
161 states, FoundPathWithNoRecursiveCall);
162
163 // Check that the exit block is reachable. This prevents triggering the
164 // warning on functions that do not terminate.
165 if (states[cfg->getExit().getBlockID()] == FoundPath)
166 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
167}
168
169//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000170// Check for missing return value.
171//===----------------------------------------------------------------------===//
172
John McCall5c6ec8c2010-05-16 09:34:11 +0000173enum ControlFlowKind {
174 UnknownFallThrough,
175 NeverFallThrough,
176 MaybeFallThrough,
177 AlwaysFallThrough,
178 NeverFallThroughOrReturn
179};
Ted Kremenek918fe842010-03-20 21:06:02 +0000180
181/// CheckFallThrough - Check that we don't fall off the end of a
182/// Statement that should return a value.
183///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000184/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
185/// MaybeFallThrough iff we might or might not fall off the end,
186/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
187/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000188/// statement but we may return. We assume that functions not marked noreturn
189/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000190static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000191 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000192 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000193
194 // The CFG leaves in dead things, and we don't want the dead code paths to
195 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000196 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000197 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000198 live);
199
200 bool AddEHEdges = AC.getAddEHEdges();
201 if (!AddEHEdges && count != cfg->getNumBlockIDs())
202 // When there are things remaining dead, and we didn't add EH edges
203 // from CallExprs to the catch clauses, we have to go back and
204 // mark them as live.
205 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
206 CFGBlock &b = **I;
207 if (!live[b.getBlockID()]) {
208 if (b.pred_begin() == b.pred_end()) {
209 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
210 // When not adding EH edges from calls, catch clauses
211 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000212 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000213 continue;
214 }
215 }
216 }
217
218 // Now we know what is live, we check the live precessors of the exit block
219 // and look for fall through paths, being careful to ignore normal returns,
220 // and exceptional paths.
221 bool HasLiveReturn = false;
222 bool HasFakeEdge = false;
223 bool HasPlainEdge = false;
224 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000225
226 // Ignore default cases that aren't likely to be reachable because all
227 // enums in a switch(X) have explicit case statements.
228 CFGBlock::FilterOptions FO;
229 FO.IgnoreDefaultsWithCoveredEnums = 1;
230
231 for (CFGBlock::filtered_pred_iterator
232 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
233 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000234 if (!live[B.getBlockID()])
235 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000236
Chandler Carruth03faf782011-09-13 09:53:58 +0000237 // Skip blocks which contain an element marked as no-return. They don't
238 // represent actually viable edges into the exit block, so mark them as
239 // abnormal.
240 if (B.hasNoReturnElement()) {
241 HasAbnormalEdge = true;
242 continue;
243 }
244
Ted Kremenek5d068492011-01-26 04:49:52 +0000245 // Destructors can appear after the 'return' in the CFG. This is
246 // normal. We need to look pass the destructors for the return
247 // statement (if it exists).
248 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000249
Chandler Carruth03faf782011-09-13 09:53:58 +0000250 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000251 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000252 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000253
Ted Kremenek5d068492011-01-26 04:49:52 +0000254 // No more CFGElements in the block?
255 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000256 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
257 HasAbnormalEdge = true;
258 continue;
259 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000260 // A labeled empty statement, or the entry block...
261 HasPlainEdge = true;
262 continue;
263 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000264
David Blaikie2a01f5d2013-02-21 20:58:29 +0000265 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000266 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000267 if (isa<ReturnStmt>(S)) {
268 HasLiveReturn = true;
269 continue;
270 }
271 if (isa<ObjCAtThrowStmt>(S)) {
272 HasFakeEdge = true;
273 continue;
274 }
275 if (isa<CXXThrowExpr>(S)) {
276 HasFakeEdge = true;
277 continue;
278 }
Chad Rosier32503022012-06-11 20:47:18 +0000279 if (isa<MSAsmStmt>(S)) {
280 // TODO: Verify this is correct.
281 HasFakeEdge = true;
282 HasLiveReturn = true;
283 continue;
284 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000285 if (isa<CXXTryStmt>(S)) {
286 HasAbnormalEdge = true;
287 continue;
288 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000289 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
290 == B.succ_end()) {
291 HasAbnormalEdge = true;
292 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000293 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000294
295 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000296 }
297 if (!HasPlainEdge) {
298 if (HasLiveReturn)
299 return NeverFallThrough;
300 return NeverFallThroughOrReturn;
301 }
302 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
303 return MaybeFallThrough;
304 // This says AlwaysFallThrough for calls to functions that are not marked
305 // noreturn, that don't return. If people would like this warning to be more
306 // accurate, such functions should be marked as noreturn.
307 return AlwaysFallThrough;
308}
309
Dan Gohman28ade552010-07-26 21:25:24 +0000310namespace {
311
Ted Kremenek918fe842010-03-20 21:06:02 +0000312struct CheckFallThroughDiagnostics {
313 unsigned diag_MaybeFallThrough_HasNoReturn;
314 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
315 unsigned diag_AlwaysFallThrough_HasNoReturn;
316 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
317 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000318 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000319 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000320
Douglas Gregor24f27692010-04-16 23:28:44 +0000321 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000322 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000323 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000324 D.diag_MaybeFallThrough_HasNoReturn =
325 diag::warn_falloff_noreturn_function;
326 D.diag_MaybeFallThrough_ReturnsNonVoid =
327 diag::warn_maybe_falloff_nonvoid_function;
328 D.diag_AlwaysFallThrough_HasNoReturn =
329 diag::warn_falloff_noreturn_function;
330 D.diag_AlwaysFallThrough_ReturnsNonVoid =
331 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000332
333 // Don't suggest that virtual functions be marked "noreturn", since they
334 // might be overridden by non-noreturn functions.
335 bool isVirtualMethod = false;
336 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
337 isVirtualMethod = Method->isVirtual();
338
Douglas Gregor0de57202011-10-10 18:15:57 +0000339 // Don't suggest that template instantiations be marked "noreturn"
340 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000341 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
342 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000343
344 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000345 D.diag_NeverFallThroughOrReturn =
346 diag::warn_suggest_noreturn_function;
347 else
348 D.diag_NeverFallThroughOrReturn = 0;
349
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000350 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000351 return D;
352 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000353
Ted Kremenek918fe842010-03-20 21:06:02 +0000354 static CheckFallThroughDiagnostics MakeForBlock() {
355 CheckFallThroughDiagnostics D;
356 D.diag_MaybeFallThrough_HasNoReturn =
357 diag::err_noreturn_block_has_return_expr;
358 D.diag_MaybeFallThrough_ReturnsNonVoid =
359 diag::err_maybe_falloff_nonvoid_block;
360 D.diag_AlwaysFallThrough_HasNoReturn =
361 diag::err_noreturn_block_has_return_expr;
362 D.diag_AlwaysFallThrough_ReturnsNonVoid =
363 diag::err_falloff_nonvoid_block;
364 D.diag_NeverFallThroughOrReturn =
365 diag::warn_suggest_noreturn_block;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000366 D.funMode = Block;
367 return D;
368 }
369
370 static CheckFallThroughDiagnostics MakeForLambda() {
371 CheckFallThroughDiagnostics D;
372 D.diag_MaybeFallThrough_HasNoReturn =
373 diag::err_noreturn_lambda_has_return_expr;
374 D.diag_MaybeFallThrough_ReturnsNonVoid =
375 diag::warn_maybe_falloff_nonvoid_lambda;
376 D.diag_AlwaysFallThrough_HasNoReturn =
377 diag::err_noreturn_lambda_has_return_expr;
378 D.diag_AlwaysFallThrough_ReturnsNonVoid =
379 diag::warn_falloff_nonvoid_lambda;
380 D.diag_NeverFallThroughOrReturn = 0;
381 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000382 return D;
383 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000384
David Blaikie9c902b52011-09-25 23:23:43 +0000385 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000386 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000387 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000388 return (ReturnsVoid ||
389 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000390 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000391 && (!HasNoReturn ||
392 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000393 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000394 && (!ReturnsVoid ||
395 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000396 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000397 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000398
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000399 // For blocks / lambdas.
400 return ReturnsVoid && !HasNoReturn
401 && ((funMode == Lambda) ||
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000402 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000403 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000404 }
405};
406
Dan Gohman28ade552010-07-26 21:25:24 +0000407}
408
Ted Kremenek918fe842010-03-20 21:06:02 +0000409/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
410/// function that should return a value. Check that we don't fall off the end
411/// of a noreturn function. We assume that functions and blocks not marked
412/// noreturn will return.
413static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000414 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000415 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000416 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000417
418 bool ReturnsVoid = false;
419 bool HasNoReturn = false;
420
421 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422 ReturnsVoid = FD->getResultType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000423 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000424 }
425 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 ReturnsVoid = MD->getResultType()->isVoidType();
427 HasNoReturn = MD->hasAttr<NoReturnAttr>();
428 }
429 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000430 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000431 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000432 BlockTy->getPointeeType()->getAs<FunctionType>()) {
433 if (FT->getResultType()->isVoidType())
434 ReturnsVoid = true;
435 if (FT->getNoReturnAttr())
436 HasNoReturn = true;
437 }
438 }
439
David Blaikie9c902b52011-09-25 23:23:43 +0000440 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000441
442 // Short circuit for compilation speed.
443 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
444 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000445
Ted Kremenek918fe842010-03-20 21:06:02 +0000446 // FIXME: Function try block
447 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
448 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000449 case UnknownFallThrough:
450 break;
451
Ted Kremenek918fe842010-03-20 21:06:02 +0000452 case MaybeFallThrough:
453 if (HasNoReturn)
454 S.Diag(Compound->getRBracLoc(),
455 CD.diag_MaybeFallThrough_HasNoReturn);
456 else if (!ReturnsVoid)
457 S.Diag(Compound->getRBracLoc(),
458 CD.diag_MaybeFallThrough_ReturnsNonVoid);
459 break;
460 case AlwaysFallThrough:
461 if (HasNoReturn)
462 S.Diag(Compound->getRBracLoc(),
463 CD.diag_AlwaysFallThrough_HasNoReturn);
464 else if (!ReturnsVoid)
465 S.Diag(Compound->getRBracLoc(),
466 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
467 break;
468 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000469 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
470 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
471 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000472 << 0 << FD;
473 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
474 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
475 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000476 } else {
477 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
478 }
479 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000480 break;
481 case NeverFallThrough:
482 break;
483 }
484 }
485}
486
487//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000488// -Wuninitialized
489//===----------------------------------------------------------------------===//
490
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000491namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000492/// ContainsReference - A visitor class to search for references to
493/// a particular declaration (the needle) within any evaluated component of an
494/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000495class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000496 bool FoundReference;
497 const DeclRefExpr *Needle;
498
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000499public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000500 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
501 : EvaluatedExprVisitor<ContainsReference>(Context),
502 FoundReference(false), Needle(Needle) {}
503
504 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000505 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000506 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000507 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000508
509 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000510 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000511
512 void VisitDeclRefExpr(DeclRefExpr *E) {
513 if (E == Needle)
514 FoundReference = true;
515 else
516 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000517 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000518
519 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000520};
521}
522
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000523static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000524 QualType VariableTy = VD->getType().getCanonicalType();
525 if (VariableTy->isBlockPointerType() &&
526 !VD->hasAttr<BlocksAttr>()) {
527 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
528 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
529 return true;
530 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000531
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000532 // Don't issue a fixit if there is already an initializer.
533 if (VD->getInit())
534 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000535
536 // Don't suggest a fixit inside macros.
537 if (VD->getLocEnd().isMacroID())
538 return false;
539
Richard Smith8d06f422012-01-12 23:53:29 +0000540 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000541
542 // Suggest possible initialization (if any).
543 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
544 if (Init.empty())
545 return false;
546
Richard Smith8d06f422012-01-12 23:53:29 +0000547 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
548 << FixItHint::CreateInsertion(Loc, Init);
549 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000550}
551
Richard Smith1bb8edb82012-05-26 06:20:46 +0000552/// Create a fixit to remove an if-like statement, on the assumption that its
553/// condition is CondVal.
554static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
555 const Stmt *Else, bool CondVal,
556 FixItHint &Fixit1, FixItHint &Fixit2) {
557 if (CondVal) {
558 // If condition is always true, remove all but the 'then'.
559 Fixit1 = FixItHint::CreateRemoval(
560 CharSourceRange::getCharRange(If->getLocStart(),
561 Then->getLocStart()));
562 if (Else) {
563 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
564 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
565 Fixit2 = FixItHint::CreateRemoval(
566 SourceRange(ElseKwLoc, Else->getLocEnd()));
567 }
568 } else {
569 // If condition is always false, remove all but the 'else'.
570 if (Else)
571 Fixit1 = FixItHint::CreateRemoval(
572 CharSourceRange::getCharRange(If->getLocStart(),
573 Else->getLocStart()));
574 else
575 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
576 }
577}
578
579/// DiagUninitUse -- Helper function to produce a diagnostic for an
580/// uninitialized use of a variable.
581static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
582 bool IsCapturedByBlock) {
583 bool Diagnosed = false;
584
Richard Smithba8071e2013-09-12 18:49:10 +0000585 switch (Use.getKind()) {
586 case UninitUse::Always:
587 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
588 << VD->getDeclName() << IsCapturedByBlock
589 << Use.getUser()->getSourceRange();
590 return;
591
592 case UninitUse::AfterDecl:
593 case UninitUse::AfterCall:
594 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
595 << VD->getDeclName() << IsCapturedByBlock
596 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
597 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
598 << VD->getSourceRange();
599 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
600 << IsCapturedByBlock << Use.getUser()->getSourceRange();
601 return;
602
603 case UninitUse::Maybe:
604 case UninitUse::Sometimes:
605 // Carry on to report sometimes-uninitialized branches, if possible,
606 // or a 'may be used uninitialized' diagnostic otherwise.
607 break;
608 }
609
Richard Smith1bb8edb82012-05-26 06:20:46 +0000610 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000611 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
612 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000613 assert(Use.getKind() == UninitUse::Sometimes);
614
615 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000616 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000617
618 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000619 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000620 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000621 SourceRange Range;
622
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000623 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000624 // For all binary terminators, branch 0 is taken if the condition is true,
625 // and branch 1 is taken if the condition is false.
626 int RemoveDiagKind = -1;
627 const char *FixitStr =
628 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
629 : (I->Output ? "1" : "0");
630 FixItHint Fixit1, Fixit2;
631
Richard Smithba8071e2013-09-12 18:49:10 +0000632 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000633 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000634 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000635 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000636 continue;
637
638 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000639 case Stmt::IfStmtClass: {
640 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000641 DiagKind = 0;
642 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000643 Range = IS->getCond()->getSourceRange();
644 RemoveDiagKind = 0;
645 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
646 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000647 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000648 }
649 case Stmt::ConditionalOperatorClass: {
650 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000651 DiagKind = 0;
652 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000653 Range = CO->getCond()->getSourceRange();
654 RemoveDiagKind = 0;
655 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
656 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000657 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000658 }
Richard Smith4323bf82012-05-25 02:17:09 +0000659 case Stmt::BinaryOperatorClass: {
660 const BinaryOperator *BO = cast<BinaryOperator>(Term);
661 if (!BO->isLogicalOp())
662 continue;
663 DiagKind = 0;
664 Str = BO->getOpcodeStr();
665 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000666 RemoveDiagKind = 0;
667 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
668 (BO->getOpcode() == BO_LOr && !I->Output))
669 // true && y -> y, false || y -> y.
670 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
671 BO->getOperatorLoc()));
672 else
673 // false && y -> false, true || y -> true.
674 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000675 break;
676 }
677
678 // "loop is entered / loop is exited".
679 case Stmt::WhileStmtClass:
680 DiagKind = 1;
681 Str = "while";
682 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000683 RemoveDiagKind = 1;
684 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000685 break;
686 case Stmt::ForStmtClass:
687 DiagKind = 1;
688 Str = "for";
689 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000690 RemoveDiagKind = 1;
691 if (I->Output)
692 Fixit1 = FixItHint::CreateRemoval(Range);
693 else
694 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000695 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000696 case Stmt::CXXForRangeStmtClass:
697 if (I->Output == 1) {
698 // The use occurs if a range-based for loop's body never executes.
699 // That may be impossible, and there's no syntactic fix for this,
700 // so treat it as a 'may be uninitialized' case.
701 continue;
702 }
703 DiagKind = 1;
704 Str = "for";
705 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
706 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000707
708 // "condition is true / loop is exited".
709 case Stmt::DoStmtClass:
710 DiagKind = 2;
711 Str = "do";
712 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000713 RemoveDiagKind = 1;
714 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000715 break;
716
717 // "switch case is taken".
718 case Stmt::CaseStmtClass:
719 DiagKind = 3;
720 Str = "case";
721 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
722 break;
723 case Stmt::DefaultStmtClass:
724 DiagKind = 3;
725 Str = "default";
726 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
727 break;
728 }
729
Richard Smith1bb8edb82012-05-26 06:20:46 +0000730 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
731 << VD->getDeclName() << IsCapturedByBlock << DiagKind
732 << Str << I->Output << Range;
733 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
734 << IsCapturedByBlock << User->getSourceRange();
735 if (RemoveDiagKind != -1)
736 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
737 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
738
739 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000740 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000741
742 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000743 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000744 << VD->getDeclName() << IsCapturedByBlock
745 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000746}
747
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000748/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
749/// uninitialized variable. This manages the different forms of diagnostic
750/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000751/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000752/// false.
753static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000754 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000755 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000756
Richard Smith4323bf82012-05-25 02:17:09 +0000757 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000758 // Inspect the initializer of the variable declaration which is
759 // being referenced prior to its initialization. We emit
760 // specialized diagnostics for self-initialization, and we
761 // specifically avoid warning about self references which take the
762 // form of:
763 //
764 // int x = x;
765 //
766 // This is used to indicate to GCC that 'x' is intentionally left
767 // uninitialized. Proven code paths which access 'x' in
768 // an uninitialized state after this will still warn.
769 if (const Expr *Initializer = VD->getInit()) {
770 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
771 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000772
Richard Trieu43a2fc72012-05-09 21:08:22 +0000773 ContainsReference CR(S.Context, DRE);
774 CR.Visit(const_cast<Expr*>(Initializer));
775 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000776 S.Diag(DRE->getLocStart(),
777 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000778 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
779 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000780 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000781 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000782
Richard Smith1bb8edb82012-05-26 06:20:46 +0000783 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000784 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000785 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000786 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
787 S.Diag(BE->getLocStart(),
788 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000789 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000790 else
791 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000792 }
793
794 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000795 // the initializer of that declaration & we didn't already suggest
796 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000797 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000798 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
799 << VD->getDeclName();
800
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000801 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000802}
803
Richard Smith84837d52012-05-03 18:27:39 +0000804namespace {
805 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
806 public:
807 FallthroughMapper(Sema &S)
808 : FoundSwitchStatements(false),
809 S(S) {
810 }
811
812 bool foundSwitchStatements() const { return FoundSwitchStatements; }
813
814 void markFallthroughVisited(const AttributedStmt *Stmt) {
815 bool Found = FallthroughStmts.erase(Stmt);
816 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000817 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000818 }
819
820 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
821
822 const AttrStmts &getFallthroughStmts() const {
823 return FallthroughStmts;
824 }
825
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000826 void fillReachableBlocks(CFG *Cfg) {
827 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
828 std::deque<const CFGBlock *> BlockQueue;
829
830 ReachableBlocks.insert(&Cfg->getEntry());
831 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000832 // Mark all case blocks reachable to avoid problems with switching on
833 // constants, covered enums, etc.
834 // These blocks can contain fall-through annotations, and we don't want to
835 // issue a warn_fallthrough_attr_unreachable for them.
836 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
837 const CFGBlock *B = *I;
838 const Stmt *L = B->getLabel();
839 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
840 BlockQueue.push_back(B);
841 }
842
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000843 while (!BlockQueue.empty()) {
844 const CFGBlock *P = BlockQueue.front();
845 BlockQueue.pop_front();
846 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
847 E = P->succ_end();
848 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000849 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000850 BlockQueue.push_back(*I);
851 }
852 }
853 }
854
Richard Smith84837d52012-05-03 18:27:39 +0000855 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000856 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
857
Richard Smith84837d52012-05-03 18:27:39 +0000858 int UnannotatedCnt = 0;
859 AnnotatedCnt = 0;
860
861 std::deque<const CFGBlock*> BlockQueue;
862
863 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
864
865 while (!BlockQueue.empty()) {
866 const CFGBlock *P = BlockQueue.front();
867 BlockQueue.pop_front();
868
869 const Stmt *Term = P->getTerminator();
870 if (Term && isa<SwitchStmt>(Term))
871 continue; // Switch statement, good.
872
873 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
874 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
875 continue; // Previous case label has no statements, good.
876
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000877 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
878 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
879 continue; // Case label is preceded with a normal label, good.
880
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000881 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000882 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
883 ElemEnd = P->rend();
884 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000885 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
886 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000887 S.Diag(AS->getLocStart(),
888 diag::warn_fallthrough_attr_unreachable);
889 markFallthroughVisited(AS);
890 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000891 break;
Richard Smith84837d52012-05-03 18:27:39 +0000892 }
893 // Don't care about other unreachable statements.
894 }
895 }
896 // If there are no unreachable statements, this may be a special
897 // case in CFG:
898 // case X: {
899 // A a; // A has a destructor.
900 // break;
901 // }
902 // // <<<< This place is represented by a 'hanging' CFG block.
903 // case Y:
904 continue;
905 }
906
907 const Stmt *LastStmt = getLastStmt(*P);
908 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
909 markFallthroughVisited(AS);
910 ++AnnotatedCnt;
911 continue; // Fallthrough annotation, good.
912 }
913
914 if (!LastStmt) { // This block contains no executable statements.
915 // Traverse its predecessors.
916 std::copy(P->pred_begin(), P->pred_end(),
917 std::back_inserter(BlockQueue));
918 continue;
919 }
920
921 ++UnannotatedCnt;
922 }
923 return !!UnannotatedCnt;
924 }
925
926 // RecursiveASTVisitor setup.
927 bool shouldWalkTypesOfTypeLocs() const { return false; }
928
929 bool VisitAttributedStmt(AttributedStmt *S) {
930 if (asFallThroughAttr(S))
931 FallthroughStmts.insert(S);
932 return true;
933 }
934
935 bool VisitSwitchStmt(SwitchStmt *S) {
936 FoundSwitchStatements = true;
937 return true;
938 }
939
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000940 // We don't want to traverse local type declarations. We analyze their
941 // methods separately.
942 bool TraverseDecl(Decl *D) { return true; }
943
Richard Smith84837d52012-05-03 18:27:39 +0000944 private:
945
946 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
947 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
948 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
949 return AS;
950 }
951 return 0;
952 }
953
954 static const Stmt *getLastStmt(const CFGBlock &B) {
955 if (const Stmt *Term = B.getTerminator())
956 return Term;
957 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
958 ElemEnd = B.rend();
959 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000960 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
961 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +0000962 }
963 // Workaround to detect a statement thrown out by CFGBuilder:
964 // case X: {} case Y:
965 // case X: ; case Y:
966 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
967 if (!isa<SwitchCase>(SW->getSubStmt()))
968 return SW->getSubStmt();
969
970 return 0;
971 }
972
973 bool FoundSwitchStatements;
974 AttrStmts FallthroughStmts;
975 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000976 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +0000977 };
978}
979
Alexander Kornienko06caf7d2012-06-02 01:01:07 +0000980static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +0000981 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +0000982 // Only perform this analysis when using C++11. There is no good workflow
983 // for this warning when not using C++11. There is no good way to silence
984 // the warning (no attribute is available) unless we are using C++11's support
985 // for generalized attributes. Once could use pragmas to silence the warning,
986 // but as a general solution that is gross and not in the spirit of this
987 // warning.
988 //
989 // NOTE: This an intermediate solution. There are on-going discussions on
990 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000991 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +0000992 return;
993
Richard Smith84837d52012-05-03 18:27:39 +0000994 FallthroughMapper FM(S);
995 FM.TraverseStmt(AC.getBody());
996
997 if (!FM.foundSwitchStatements())
998 return;
999
Alexis Hunt2178f142012-06-15 21:22:05 +00001000 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001001 return;
1002
Richard Smith84837d52012-05-03 18:27:39 +00001003 CFG *Cfg = AC.getCFG();
1004
1005 if (!Cfg)
1006 return;
1007
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001008 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001009
1010 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001011 const CFGBlock *B = *I;
1012 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001013
1014 if (!Label || !isa<SwitchCase>(Label))
1015 continue;
1016
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001017 int AnnotatedCnt;
1018
Alexander Kornienko55488792013-01-25 15:49:34 +00001019 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001020 continue;
1021
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001022 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001023 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1024 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001025
1026 if (!AnnotatedCnt) {
1027 SourceLocation L = Label->getLocStart();
1028 if (L.isMacroID())
1029 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001030 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001031 const Stmt *Term = B->getTerminator();
1032 // Skip empty cases.
1033 while (B->empty() && !Term && B->succ_size() == 1) {
1034 B = *B->succ_begin();
1035 Term = B->getTerminator();
1036 }
1037 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001038 Preprocessor &PP = S.getPreprocessor();
1039 TokenValue Tokens[] = {
1040 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1041 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1042 tok::r_square, tok::r_square
1043 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001044 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1045 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1046 if (!MacroName.empty())
1047 AnnotationSpelling = MacroName;
1048 SmallString<64> TextToInsert(AnnotationSpelling);
1049 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001050 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001051 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001052 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001053 }
Richard Smith84837d52012-05-03 18:27:39 +00001054 }
1055 S.Diag(L, diag::note_insert_break_fixit) <<
1056 FixItHint::CreateInsertion(L, "break; ");
1057 }
1058 }
1059
1060 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1061 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1062 E = Fallthroughs.end();
1063 I != E; ++I) {
1064 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1065 }
1066
1067}
1068
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001069namespace {
Jordan Rosed61f3b42012-09-28 22:29:02 +00001070typedef std::pair<const Stmt *,
1071 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
1072 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001073
Jordan Rosed61f3b42012-09-28 22:29:02 +00001074class StmtUseSorter {
Jordan Rosed3934582012-09-28 22:21:30 +00001075 const SourceManager &SM;
1076
1077public:
Jordan Rosed61f3b42012-09-28 22:29:02 +00001078 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
Jordan Rosed3934582012-09-28 22:21:30 +00001079
1080 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1081 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1082 RHS.first->getLocStart());
1083 }
1084};
Jordan Rosed61f3b42012-09-28 22:29:02 +00001085}
Jordan Rosed3934582012-09-28 22:21:30 +00001086
Jordan Rose25c0ea82012-10-29 17:46:47 +00001087static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1088 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001089 assert(S);
1090
1091 do {
1092 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001093 case Stmt::ForStmtClass:
1094 case Stmt::WhileStmtClass:
1095 case Stmt::CXXForRangeStmtClass:
1096 case Stmt::ObjCForCollectionStmtClass:
1097 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001098 case Stmt::DoStmtClass: {
1099 const Expr *Cond = cast<DoStmt>(S)->getCond();
1100 llvm::APSInt Val;
1101 if (!Cond->EvaluateAsInt(Val, Ctx))
1102 return true;
1103 return Val.getBoolValue();
1104 }
Jordan Rose76831c62012-10-11 16:10:19 +00001105 default:
1106 break;
1107 }
1108 } while ((S = PM.getParent(S)));
1109
1110 return false;
1111}
1112
Jordan Rosed3934582012-09-28 22:21:30 +00001113
1114static void diagnoseRepeatedUseOfWeak(Sema &S,
1115 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001116 const Decl *D,
1117 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001118 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1119 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1120 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1121
Jordan Rose25c0ea82012-10-29 17:46:47 +00001122 ASTContext &Ctx = S.getASTContext();
1123
Jordan Rosed3934582012-09-28 22:21:30 +00001124 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1125
1126 // Extract all weak objects that are referenced more than once.
1127 SmallVector<StmtUsesPair, 8> UsesByStmt;
1128 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1129 I != E; ++I) {
1130 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001131
1132 // Find the first read of the weak object.
1133 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1134 for ( ; UI != UE; ++UI) {
1135 if (UI->isUnsafe())
1136 break;
1137 }
1138
1139 // If there were only writes to this object, don't warn.
1140 if (UI == UE)
1141 continue;
1142
Jordan Rose76831c62012-10-11 16:10:19 +00001143 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001144 // read is not within a loop, don't warn. Additionally, don't warn in a
1145 // loop if the base object is a local variable -- local variables are often
1146 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001147 if (UI == Uses.begin()) {
1148 WeakUseVector::const_iterator UI2 = UI;
1149 for (++UI2; UI2 != UE; ++UI2)
1150 if (UI2->isUnsafe())
1151 break;
1152
Jordan Rose25c0ea82012-10-29 17:46:47 +00001153 if (UI2 == UE) {
1154 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001155 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001156
1157 const WeakObjectProfileTy &Profile = I->first;
1158 if (!Profile.isExactProfile())
1159 continue;
1160
1161 const NamedDecl *Base = Profile.getBase();
1162 if (!Base)
1163 Base = Profile.getProperty();
1164 assert(Base && "A profile always has a base or property.");
1165
1166 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1167 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1168 continue;
1169 }
Jordan Rose76831c62012-10-11 16:10:19 +00001170 }
1171
Jordan Rosed3934582012-09-28 22:21:30 +00001172 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1173 }
1174
1175 if (UsesByStmt.empty())
1176 return;
1177
1178 // Sort by first use so that we emit the warnings in a deterministic order.
1179 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Jordan Rosed61f3b42012-09-28 22:29:02 +00001180 StmtUseSorter(S.getSourceManager()));
Jordan Rosed3934582012-09-28 22:21:30 +00001181
1182 // Classify the current code body for better warning text.
1183 // This enum should stay in sync with the cases in
1184 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1185 // FIXME: Should we use a common classification enum and the same set of
1186 // possibilities all throughout Sema?
1187 enum {
1188 Function,
1189 Method,
1190 Block,
1191 Lambda
1192 } FunctionKind;
1193
1194 if (isa<sema::BlockScopeInfo>(CurFn))
1195 FunctionKind = Block;
1196 else if (isa<sema::LambdaScopeInfo>(CurFn))
1197 FunctionKind = Lambda;
1198 else if (isa<ObjCMethodDecl>(D))
1199 FunctionKind = Method;
1200 else
1201 FunctionKind = Function;
1202
1203 // Iterate through the sorted problems and emit warnings for each.
1204 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1205 E = UsesByStmt.end();
1206 I != E; ++I) {
1207 const Stmt *FirstRead = I->first;
1208 const WeakObjectProfileTy &Key = I->second->first;
1209 const WeakUseVector &Uses = I->second->second;
1210
Jordan Rose657b5f42012-09-28 22:21:35 +00001211 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1212 // may not contain enough information to determine that these are different
1213 // properties. We can only be 100% sure of a repeated use in certain cases,
1214 // and we adjust the diagnostic kind accordingly so that the less certain
1215 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001216 unsigned DiagKind;
1217 if (Key.isExactProfile())
1218 DiagKind = diag::warn_arc_repeated_use_of_weak;
1219 else
1220 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1221
Jordan Rose657b5f42012-09-28 22:21:35 +00001222 // Classify the weak object being accessed for better warning text.
1223 // This enum should stay in sync with the cases in
1224 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1225 enum {
1226 Variable,
1227 Property,
1228 ImplicitProperty,
1229 Ivar
1230 } ObjectKind;
1231
1232 const NamedDecl *D = Key.getProperty();
1233 if (isa<VarDecl>(D))
1234 ObjectKind = Variable;
1235 else if (isa<ObjCPropertyDecl>(D))
1236 ObjectKind = Property;
1237 else if (isa<ObjCMethodDecl>(D))
1238 ObjectKind = ImplicitProperty;
1239 else if (isa<ObjCIvarDecl>(D))
1240 ObjectKind = Ivar;
1241 else
1242 llvm_unreachable("Unexpected weak object kind!");
1243
Jordan Rosed3934582012-09-28 22:21:30 +00001244 // Show the first time the object was read.
1245 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001246 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001247 << FirstRead->getSourceRange();
1248
1249 // Print all the other accesses as notes.
1250 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1251 UI != UE; ++UI) {
1252 if (UI->getUseExpr() == FirstRead)
1253 continue;
1254 S.Diag(UI->getUseExpr()->getLocStart(),
1255 diag::note_arc_weak_also_accessed_here)
1256 << UI->getUseExpr()->getSourceRange();
1257 }
1258 }
1259}
1260
1261
1262namespace {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001263struct SLocSort {
Ted Kremenekc8c4e5f2011-03-15 04:57:38 +00001264 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith4323bf82012-05-25 02:17:09 +00001265 // Prefer a more confident report over a less confident one.
1266 if (a.getKind() != b.getKind())
1267 return a.getKind() > b.getKind();
1268 SourceLocation aLoc = a.getUser()->getLocStart();
1269 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek39fa0562011-01-21 19:41:41 +00001270 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1271 }
1272};
1273
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001274class UninitValsDiagReporter : public UninitVariablesHandler {
1275 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001276 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001277 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001278 // Prefer using MapVector to DenseMap, so that iteration order will be
1279 // the same as insertion order. This is needed to obtain a deterministic
1280 // order of diagnostics when calling flushDiagnostics().
1281 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001282 UsesMap *uses;
1283
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001284public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001285 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1286 ~UninitValsDiagReporter() {
1287 flushDiagnostics();
1288 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001289
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001290 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001291 if (!uses)
1292 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001293
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001294 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001295 if (!V.getPointer())
1296 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001297
Ted Kremenek596fa162011-10-13 18:50:06 +00001298 return V;
1299 }
1300
Richard Smith4323bf82012-05-25 02:17:09 +00001301 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001302 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001303 }
1304
1305 void handleSelfInit(const VarDecl *vd) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001306 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001307 }
1308
1309 void flushDiagnostics() {
1310 if (!uses)
1311 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001312
Ted Kremenek39fa0562011-01-21 19:41:41 +00001313 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1314 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001315 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001316
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001317 UsesVec *vec = V.getPointer();
1318 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001319
1320 // Specially handle the case where we have uses of an uninitialized
1321 // variable, but the root cause is an idiomatic self-init. We want
1322 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001323 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001324 DiagnoseUninitializedUse(S, vd,
1325 UninitUse(vd->getInit()->IgnoreParenCasts(),
1326 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001327 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001328 else {
1329 // Sort the uses by their SourceLocations. While not strictly
1330 // guaranteed to produce them in line/column order, this will provide
1331 // a stable ordering.
1332 std::sort(vec->begin(), vec->end(), SLocSort());
1333
1334 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1335 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001336 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1337 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1338
1339 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001340 // Skip further diagnostics for this variable. We try to warn only
1341 // on the first point at which a variable is used uninitialized.
1342 break;
1343 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001344 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001345
1346 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001347 delete vec;
1348 }
1349 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001350 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001351
1352private:
1353 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1354 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001355 if (i->getKind() == UninitUse::Always ||
1356 i->getKind() == UninitUse::AfterCall ||
1357 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001358 return true;
1359 }
1360 }
1361 return false;
1362}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001363};
1364}
1365
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001366namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001367namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001368typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001369typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001370typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001371
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001372struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001373 SourceManager &SM;
1374 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001375
1376 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1377 // Although this call will be slow, this is only called when outputting
1378 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001379 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001380 }
1381};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001382}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001383
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001384//===----------------------------------------------------------------------===//
1385// -Wthread-safety
1386//===----------------------------------------------------------------------===//
1387namespace clang {
1388namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001389namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001390class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1391 Sema &S;
1392 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001393 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001394
1395 // Helper functions
1396 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001397 // Gracefully handle rare cases when the analysis can't get a more
1398 // precise source location.
1399 if (!Loc.isValid())
1400 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001401 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1402 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001403 }
1404
1405 public:
Richard Smith92286672012-02-03 04:45:26 +00001406 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1407 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001408
1409 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1410 /// We need to output diagnostics produced while iterating through
1411 /// the lockset in deterministic order, so this function orders diagnostics
1412 /// and outputs them.
1413 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001414 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001415 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001416 I != E; ++I) {
1417 S.Diag(I->first.first, I->first.second);
1418 const OptionalNotes &Notes = I->second;
1419 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1420 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1421 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001422 }
1423
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001424 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001425 PartialDiagnosticAt Warning(Loc,
1426 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1427 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001428 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001429 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1430 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1431 }
1432
1433 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1434 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1435 }
1436
Richard Smith92286672012-02-03 04:45:26 +00001437 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1438 SourceLocation LocEndOfScope,
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001439 LockErrorKind LEK){
1440 unsigned DiagID = 0;
1441 switch (LEK) {
1442 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001443 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001444 break;
1445 case LEK_LockedSomeLoopIterations:
1446 DiagID = diag::warn_expecting_lock_held_on_loop;
1447 break;
1448 case LEK_LockedAtEndOfFunction:
1449 DiagID = diag::warn_no_unlock;
1450 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001451 case LEK_NotLockedAtEndOfFunction:
1452 DiagID = diag::warn_expecting_locked;
1453 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001454 }
Richard Smith92286672012-02-03 04:45:26 +00001455 if (LocEndOfScope.isInvalid())
1456 LocEndOfScope = FunEndLocation;
1457
1458 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001459 if (LocLocked.isValid()) {
1460 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1461 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1462 return;
1463 }
1464 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001465 }
1466
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001467
1468 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1469 SourceLocation Loc2) {
Richard Smith92286672012-02-03 04:45:26 +00001470 PartialDiagnosticAt Warning(
1471 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1472 PartialDiagnosticAt Note(
1473 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1474 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001475 }
1476
1477 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1478 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001479 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1480 && "Only works for variables");
1481 unsigned DiagID = POK == POK_VarAccess?
1482 diag::warn_variable_requires_any_lock:
1483 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001484 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001485 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001486 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001487 }
1488
1489 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001490 Name LockName, LockKind LK, SourceLocation Loc,
1491 Name *PossibleMatch) {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001492 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001493 if (PossibleMatch) {
1494 switch (POK) {
1495 case POK_VarAccess:
1496 DiagID = diag::warn_variable_requires_lock_precise;
1497 break;
1498 case POK_VarDereference:
1499 DiagID = diag::warn_var_deref_requires_lock_precise;
1500 break;
1501 case POK_FunctionCall:
1502 DiagID = diag::warn_fun_requires_lock_precise;
1503 break;
1504 }
1505 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001506 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001507 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1508 << *PossibleMatch);
1509 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1510 } else {
1511 switch (POK) {
1512 case POK_VarAccess:
1513 DiagID = diag::warn_variable_requires_lock;
1514 break;
1515 case POK_VarDereference:
1516 DiagID = diag::warn_var_deref_requires_lock;
1517 break;
1518 case POK_FunctionCall:
1519 DiagID = diag::warn_fun_requires_lock;
1520 break;
1521 }
1522 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001523 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001524 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001525 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001526 }
1527
1528 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001529 PartialDiagnosticAt Warning(Loc,
1530 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1531 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001532 }
1533};
1534}
1535}
David Blaikie68e081d2011-12-20 02:48:34 +00001536}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001537
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001538//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001539// -Wconsumed
1540//===----------------------------------------------------------------------===//
1541
1542namespace clang {
1543namespace consumed {
1544namespace {
1545class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1546
1547 Sema &S;
1548 DiagList Warnings;
1549
1550public:
1551
1552 ConsumedWarningsHandler(Sema &S) : S(S) {}
1553
1554 void emitDiagnostics() {
1555 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1556
1557 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1558 I != E; ++I) {
1559
1560 const OptionalNotes &Notes = I->second;
1561 S.Diag(I->first.first, I->first.second);
1562
1563 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1564 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1565 }
1566 }
1567 }
1568
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001569 void warnLoopStateMismatch(SourceLocation Loc, StringRef VariableName) {
1570 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1571 VariableName);
1572
1573 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1574 }
1575
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001576 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1577 StringRef VariableName,
1578 StringRef ExpectedState,
1579 StringRef ObservedState) {
1580
1581 PartialDiagnosticAt Warning(Loc, S.PDiag(
1582 diag::warn_param_return_typestate_mismatch) << VariableName <<
1583 ExpectedState << ObservedState);
1584
1585 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1586 }
1587
DeLesley Hutchins69391772013-10-17 23:23:53 +00001588 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1589 StringRef ObservedState) {
1590
1591 PartialDiagnosticAt Warning(Loc, S.PDiag(
1592 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1593
1594 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1595 }
1596
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001597 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1598 StringRef TypeName) {
1599 PartialDiagnosticAt Warning(Loc, S.PDiag(
1600 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1601
1602 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1603 }
1604
1605 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1606 StringRef ObservedState) {
1607
1608 PartialDiagnosticAt Warning(Loc, S.PDiag(
1609 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1610
1611 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1612 }
1613
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001614 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1615 SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001616
1617 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001618 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001619
1620 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1621 }
1622
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001623 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1624 StringRef State, SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001625
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001626 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1627 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001628
1629 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1630 }
1631};
1632}}}
1633
1634//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001635// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1636// warnings on a function, method, or block.
1637//===----------------------------------------------------------------------===//
1638
Ted Kremenek0b405322010-03-23 00:13:23 +00001639clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1640 enableCheckFallThrough = 1;
1641 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001642 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001643 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001644}
1645
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001646clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1647 : S(s),
1648 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001649 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001650 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001651 MaxCFGBlocksPerFunction(0),
1652 NumUninitAnalysisFunctions(0),
1653 NumUninitAnalysisVariables(0),
1654 MaxUninitAnalysisVariablesPerFunction(0),
1655 NumUninitAnalysisBlockVisits(0),
1656 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikie9c902b52011-09-25 23:23:43 +00001657 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenek0b405322010-03-23 00:13:23 +00001658 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001659 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001660 DiagnosticsEngine::Ignored);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001661 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1662 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001663 DiagnosticsEngine::Ignored);
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001664 DefaultPolicy.enableConsumedAnalysis = (unsigned)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001665 (D.getDiagnosticLevel(diag::warn_use_in_invalid_state, SourceLocation()) !=
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001666 DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +00001667}
1668
Ted Kremenek3427fac2011-02-23 01:52:04 +00001669static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001670 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001671 i = fscope->PossiblyUnreachableDiags.begin(),
1672 e = fscope->PossiblyUnreachableDiags.end();
1673 i != e; ++i) {
1674 const sema::PossiblyUnreachableDiag &D = *i;
1675 S.Diag(D.Loc, D.PD);
1676 }
1677}
1678
Ted Kremenek0b405322010-03-23 00:13:23 +00001679void clang::sema::
1680AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001681 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001682 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001683
Ted Kremenek918fe842010-03-20 21:06:02 +00001684 // We avoid doing analysis-based warnings when there are errors for
1685 // two reasons:
1686 // (1) The CFGs often can't be constructed (if the body is invalid), so
1687 // don't bother trying.
1688 // (2) The code already has problems; running the analysis just takes more
1689 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001690 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001691
Ted Kremenek0b405322010-03-23 00:13:23 +00001692 // Do not do any analysis for declarations in system headers if we are
1693 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001694 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001695 S.SourceMgr.isInSystemHeader(D->getLocation()))
1696 return;
1697
John McCall1d570a72010-08-25 05:56:39 +00001698 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001699 if (cast<DeclContext>(D)->isDependentContext())
1700 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001701
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001702 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001703 // Flush out any possibly unreachable diagnostics.
1704 flushDiagnostics(S, fscope);
1705 return;
1706 }
1707
Ted Kremenek918fe842010-03-20 21:06:02 +00001708 const Stmt *Body = D->getBody();
1709 assert(Body);
1710
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001711 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001712 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001713
Ted Kremenek918fe842010-03-20 21:06:02 +00001714 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001715 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001716 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1717 AC.getCFGBuildOptions().AddEHEdges = false;
1718 AC.getCFGBuildOptions().AddInitializers = true;
1719 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001720 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1721
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001722 // Force that certain expressions appear as CFGElements in the CFG. This
1723 // is used to speed up various analyses.
1724 // FIXME: This isn't the right factoring. This is here for initial
1725 // prototyping, but we need a way for analyses to say what expressions they
1726 // expect to always be CFGElements and then fill in the BuildOptions
1727 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001728 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1729 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001730 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001731 AC.getCFGBuildOptions().setAllAlwaysAdd();
1732 }
1733 else {
1734 AC.getCFGBuildOptions()
1735 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001736 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001737 .setAlwaysAdd(Stmt::BlockExprClass)
1738 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1739 .setAlwaysAdd(Stmt::DeclRefExprClass)
1740 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001741 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1742 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001743 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001744
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001745
Ted Kremenek3427fac2011-02-23 01:52:04 +00001746 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001747 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001748 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001749
1750 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001751 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001752 i = fscope->PossiblyUnreachableDiags.begin(),
1753 e = fscope->PossiblyUnreachableDiags.end();
1754 i != e; ++i) {
1755 if (const Stmt *stmt = i->stmt)
1756 AC.registerForcedBlockExpression(stmt);
1757 }
1758
1759 if (AC.getCFG()) {
1760 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001761 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001762 i = fscope->PossiblyUnreachableDiags.begin(),
1763 e = fscope->PossiblyUnreachableDiags.end();
1764 i != e; ++i)
1765 {
1766 const sema::PossiblyUnreachableDiag &D = *i;
1767 bool processed = false;
1768 if (const Stmt *stmt = i->stmt) {
1769 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001770 CFGReverseBlockReachabilityAnalysis *cra =
1771 AC.getCFGReachablityAnalysis();
1772 // FIXME: We should be able to assert that block is non-null, but
1773 // the CFG analysis can skip potentially-evaluated expressions in
1774 // edge cases; see test/Sema/vla-2.c.
1775 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001776 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001777 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001778 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001779 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001780 }
1781 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001782 if (!processed) {
1783 // Emit the warning anyway if we cannot map to a basic block.
1784 S.Diag(D.Loc, D.PD);
1785 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001786 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001787 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001788
1789 if (!analyzed)
1790 flushDiagnostics(S, fscope);
1791 }
1792
1793
Ted Kremenek918fe842010-03-20 21:06:02 +00001794 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001795 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001796 const CheckFallThroughDiagnostics &CD =
1797 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001798 : (isa<CXXMethodDecl>(D) &&
1799 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1800 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1801 ? CheckFallThroughDiagnostics::MakeForLambda()
1802 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001803 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001804 }
1805
1806 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001807 if (P.enableCheckUnreachable) {
1808 // Only check for unreachable code on non-template instantiations.
1809 // Different template instantiations can effectively change the control-flow
1810 // and it is very difficult to prove that a snippet of code in a template
1811 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001812 bool isTemplateInstantiation = false;
1813 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1814 isTemplateInstantiation = Function->isTemplateInstantiation();
1815 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001816 CheckUnreachable(S, AC);
1817 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001818
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001819 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001820 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001821 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001822 SourceLocation FEL = AC.getDecl()->getLocEnd();
1823 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001824 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1825 != DiagnosticsEngine::Ignored)
1826 Reporter.setIssueBetaWarnings(true);
1827
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001828 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1829 Reporter.emitDiagnostics();
1830 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001831
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001832 // Check for violations of consumed properties.
1833 if (P.enableConsumedAnalysis) {
1834 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001835 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001836 Analyzer.run(AC);
1837 }
1838
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001839 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001840 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001841 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1842 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001843 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001844 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001845 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001846 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001847 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001848 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001849 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001850 reporter, stats);
1851
1852 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1853 ++NumUninitAnalysisFunctions;
1854 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1855 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1856 MaxUninitAnalysisVariablesPerFunction =
1857 std::max(MaxUninitAnalysisVariablesPerFunction,
1858 stats.NumVariablesAnalyzed);
1859 MaxUninitAnalysisBlockVisitsPerFunction =
1860 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1861 stats.NumBlockVisits);
1862 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001863 }
1864 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001865
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001866 bool FallThroughDiagFull =
1867 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1868 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001869 bool FallThroughDiagPerFunction =
1870 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001871 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001872 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001873 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001874 }
1875
Jordan Rosed3934582012-09-28 22:21:30 +00001876 if (S.getLangOpts().ObjCARCWeak &&
1877 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1878 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001879 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001880
Richard Trieu2f024f42013-12-21 02:33:43 +00001881
1882 // Check for infinite self-recursion in functions
1883 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1884 D->getLocStart())
1885 != DiagnosticsEngine::Ignored) {
1886 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1887 checkRecursiveFunction(S, FD, Body, AC);
1888 }
1889 }
1890
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001891 // Collect statistics about the CFG if it was built.
1892 if (S.CollectStats && AC.isCFGBuilt()) {
1893 ++NumFunctionsAnalyzed;
1894 if (CFG *cfg = AC.getCFG()) {
1895 // If we successfully built a CFG for this context, record some more
1896 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001897 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001898 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001899 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001900 } else {
1901 ++NumFunctionsWithBadCFGs;
1902 }
1903 }
1904}
1905
1906void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1907 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1908
1909 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1910 unsigned AvgCFGBlocksPerFunction =
1911 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1912 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1913 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1914 << " " << NumCFGBlocks << " CFG blocks built.\n"
1915 << " " << AvgCFGBlocksPerFunction
1916 << " average CFG blocks per function.\n"
1917 << " " << MaxCFGBlocksPerFunction
1918 << " max CFG blocks per function.\n";
1919
1920 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1921 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1922 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1923 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1924 llvm::errs() << NumUninitAnalysisFunctions
1925 << " functions analyzed for uninitialiazed variables\n"
1926 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1927 << " " << AvgUninitVariablesPerFunction
1928 << " average variables per function.\n"
1929 << " " << MaxUninitAnalysisVariablesPerFunction
1930 << " max variables per function.\n"
1931 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1932 << " " << AvgUninitBlockVisitsPerFunction
1933 << " average block visits per function.\n"
1934 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1935 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001936}