blob: 9864072b722893c51802fc3a2a1631a188905d6e [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) {
Richard Trieu658eb682014-01-04 01:57:42 +0000119
120 // Skip function calls which are qualified with a templated class.
121 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
122 CE->getCallee()->IgnoreParenImpCasts())) {
123 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
124 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
125 isa<TemplateSpecializationType>(NNS->getAsType())) {
126 continue;
127 }
128 }
129 }
130
Richard Trieu2f024f42013-12-21 02:33:43 +0000131 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
132 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
133 !MCE->getMethodDecl()->isVirtual()) {
134 State = FoundPath;
135 break;
136 }
137 } else {
138 State = FoundPath;
139 break;
140 }
141 }
142 }
143 }
144
145 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
146 I != E; ++I)
147 if (*I)
148 checkForFunctionCall(S, FD, **I, ExitID, States, State);
149}
150
151static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
152 const Stmt *Body,
153 AnalysisDeclContext &AC) {
154 FD = FD->getCanonicalDecl();
155
156 // Only run on non-templated functions and non-templated members of
157 // templated classes.
158 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
159 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
160 return;
161
162 CFG *cfg = AC.getCFG();
163 if (cfg == 0) return;
164
165 // If the exit block is unreachable, skip processing the function.
166 if (cfg->getExit().pred_empty())
167 return;
168
169 // Mark all nodes as FoundNoPath, then begin processing the entry block.
170 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
171 FoundNoPath);
172 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
173 states, FoundPathWithNoRecursiveCall);
174
175 // Check that the exit block is reachable. This prevents triggering the
176 // warning on functions that do not terminate.
177 if (states[cfg->getExit().getBlockID()] == FoundPath)
178 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
179}
180
181//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000182// Check for missing return value.
183//===----------------------------------------------------------------------===//
184
John McCall5c6ec8c2010-05-16 09:34:11 +0000185enum ControlFlowKind {
186 UnknownFallThrough,
187 NeverFallThrough,
188 MaybeFallThrough,
189 AlwaysFallThrough,
190 NeverFallThroughOrReturn
191};
Ted Kremenek918fe842010-03-20 21:06:02 +0000192
193/// CheckFallThrough - Check that we don't fall off the end of a
194/// Statement that should return a value.
195///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000196/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
197/// MaybeFallThrough iff we might or might not fall off the end,
198/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
199/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000200/// statement but we may return. We assume that functions not marked noreturn
201/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000202static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000203 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000204 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000205
206 // The CFG leaves in dead things, and we don't want the dead code paths to
207 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000208 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000209 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000210 live);
211
212 bool AddEHEdges = AC.getAddEHEdges();
213 if (!AddEHEdges && count != cfg->getNumBlockIDs())
214 // When there are things remaining dead, and we didn't add EH edges
215 // from CallExprs to the catch clauses, we have to go back and
216 // mark them as live.
217 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
218 CFGBlock &b = **I;
219 if (!live[b.getBlockID()]) {
220 if (b.pred_begin() == b.pred_end()) {
221 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
222 // When not adding EH edges from calls, catch clauses
223 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000224 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000225 continue;
226 }
227 }
228 }
229
230 // Now we know what is live, we check the live precessors of the exit block
231 // and look for fall through paths, being careful to ignore normal returns,
232 // and exceptional paths.
233 bool HasLiveReturn = false;
234 bool HasFakeEdge = false;
235 bool HasPlainEdge = false;
236 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000237
238 // Ignore default cases that aren't likely to be reachable because all
239 // enums in a switch(X) have explicit case statements.
240 CFGBlock::FilterOptions FO;
241 FO.IgnoreDefaultsWithCoveredEnums = 1;
242
243 for (CFGBlock::filtered_pred_iterator
244 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
245 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000246 if (!live[B.getBlockID()])
247 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000248
Chandler Carruth03faf782011-09-13 09:53:58 +0000249 // Skip blocks which contain an element marked as no-return. They don't
250 // represent actually viable edges into the exit block, so mark them as
251 // abnormal.
252 if (B.hasNoReturnElement()) {
253 HasAbnormalEdge = true;
254 continue;
255 }
256
Ted Kremenek5d068492011-01-26 04:49:52 +0000257 // Destructors can appear after the 'return' in the CFG. This is
258 // normal. We need to look pass the destructors for the return
259 // statement (if it exists).
260 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000261
Chandler Carruth03faf782011-09-13 09:53:58 +0000262 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000263 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000264 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000265
Ted Kremenek5d068492011-01-26 04:49:52 +0000266 // No more CFGElements in the block?
267 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000268 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
269 HasAbnormalEdge = true;
270 continue;
271 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000272 // A labeled empty statement, or the entry block...
273 HasPlainEdge = true;
274 continue;
275 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000276
David Blaikie2a01f5d2013-02-21 20:58:29 +0000277 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000278 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000279 if (isa<ReturnStmt>(S)) {
280 HasLiveReturn = true;
281 continue;
282 }
283 if (isa<ObjCAtThrowStmt>(S)) {
284 HasFakeEdge = true;
285 continue;
286 }
287 if (isa<CXXThrowExpr>(S)) {
288 HasFakeEdge = true;
289 continue;
290 }
Chad Rosier32503022012-06-11 20:47:18 +0000291 if (isa<MSAsmStmt>(S)) {
292 // TODO: Verify this is correct.
293 HasFakeEdge = true;
294 HasLiveReturn = true;
295 continue;
296 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000297 if (isa<CXXTryStmt>(S)) {
298 HasAbnormalEdge = true;
299 continue;
300 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000301 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
302 == B.succ_end()) {
303 HasAbnormalEdge = true;
304 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000305 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000306
307 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000308 }
309 if (!HasPlainEdge) {
310 if (HasLiveReturn)
311 return NeverFallThrough;
312 return NeverFallThroughOrReturn;
313 }
314 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
315 return MaybeFallThrough;
316 // This says AlwaysFallThrough for calls to functions that are not marked
317 // noreturn, that don't return. If people would like this warning to be more
318 // accurate, such functions should be marked as noreturn.
319 return AlwaysFallThrough;
320}
321
Dan Gohman28ade552010-07-26 21:25:24 +0000322namespace {
323
Ted Kremenek918fe842010-03-20 21:06:02 +0000324struct CheckFallThroughDiagnostics {
325 unsigned diag_MaybeFallThrough_HasNoReturn;
326 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
327 unsigned diag_AlwaysFallThrough_HasNoReturn;
328 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
329 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000330 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000331 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000332
Douglas Gregor24f27692010-04-16 23:28:44 +0000333 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000334 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000335 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000336 D.diag_MaybeFallThrough_HasNoReturn =
337 diag::warn_falloff_noreturn_function;
338 D.diag_MaybeFallThrough_ReturnsNonVoid =
339 diag::warn_maybe_falloff_nonvoid_function;
340 D.diag_AlwaysFallThrough_HasNoReturn =
341 diag::warn_falloff_noreturn_function;
342 D.diag_AlwaysFallThrough_ReturnsNonVoid =
343 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000344
345 // Don't suggest that virtual functions be marked "noreturn", since they
346 // might be overridden by non-noreturn functions.
347 bool isVirtualMethod = false;
348 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
349 isVirtualMethod = Method->isVirtual();
350
Douglas Gregor0de57202011-10-10 18:15:57 +0000351 // Don't suggest that template instantiations be marked "noreturn"
352 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000353 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
354 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000355
356 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000357 D.diag_NeverFallThroughOrReturn =
358 diag::warn_suggest_noreturn_function;
359 else
360 D.diag_NeverFallThroughOrReturn = 0;
361
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000362 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000363 return D;
364 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000365
Ted Kremenek918fe842010-03-20 21:06:02 +0000366 static CheckFallThroughDiagnostics MakeForBlock() {
367 CheckFallThroughDiagnostics D;
368 D.diag_MaybeFallThrough_HasNoReturn =
369 diag::err_noreturn_block_has_return_expr;
370 D.diag_MaybeFallThrough_ReturnsNonVoid =
371 diag::err_maybe_falloff_nonvoid_block;
372 D.diag_AlwaysFallThrough_HasNoReturn =
373 diag::err_noreturn_block_has_return_expr;
374 D.diag_AlwaysFallThrough_ReturnsNonVoid =
375 diag::err_falloff_nonvoid_block;
376 D.diag_NeverFallThroughOrReturn =
377 diag::warn_suggest_noreturn_block;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000378 D.funMode = Block;
379 return D;
380 }
381
382 static CheckFallThroughDiagnostics MakeForLambda() {
383 CheckFallThroughDiagnostics D;
384 D.diag_MaybeFallThrough_HasNoReturn =
385 diag::err_noreturn_lambda_has_return_expr;
386 D.diag_MaybeFallThrough_ReturnsNonVoid =
387 diag::warn_maybe_falloff_nonvoid_lambda;
388 D.diag_AlwaysFallThrough_HasNoReturn =
389 diag::err_noreturn_lambda_has_return_expr;
390 D.diag_AlwaysFallThrough_ReturnsNonVoid =
391 diag::warn_falloff_nonvoid_lambda;
392 D.diag_NeverFallThroughOrReturn = 0;
393 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000394 return D;
395 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000396
David Blaikie9c902b52011-09-25 23:23:43 +0000397 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000398 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000399 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000400 return (ReturnsVoid ||
401 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000402 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000403 && (!HasNoReturn ||
404 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000405 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000406 && (!ReturnsVoid ||
407 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000408 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000409 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000410
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000411 // For blocks / lambdas.
412 return ReturnsVoid && !HasNoReturn
413 && ((funMode == Lambda) ||
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000414 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000415 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000416 }
417};
418
Dan Gohman28ade552010-07-26 21:25:24 +0000419}
420
Ted Kremenek918fe842010-03-20 21:06:02 +0000421/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
422/// function that should return a value. Check that we don't fall off the end
423/// of a noreturn function. We assume that functions and blocks not marked
424/// noreturn will return.
425static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000426 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000427 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000428 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000429
430 bool ReturnsVoid = false;
431 bool HasNoReturn = false;
432
433 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
434 ReturnsVoid = FD->getResultType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000435 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000436 }
437 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
438 ReturnsVoid = MD->getResultType()->isVoidType();
439 HasNoReturn = MD->hasAttr<NoReturnAttr>();
440 }
441 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000442 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000443 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000444 BlockTy->getPointeeType()->getAs<FunctionType>()) {
445 if (FT->getResultType()->isVoidType())
446 ReturnsVoid = true;
447 if (FT->getNoReturnAttr())
448 HasNoReturn = true;
449 }
450 }
451
David Blaikie9c902b52011-09-25 23:23:43 +0000452 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000453
454 // Short circuit for compilation speed.
455 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
456 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000457
Ted Kremenek918fe842010-03-20 21:06:02 +0000458 // FIXME: Function try block
459 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
460 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000461 case UnknownFallThrough:
462 break;
463
Ted Kremenek918fe842010-03-20 21:06:02 +0000464 case MaybeFallThrough:
465 if (HasNoReturn)
466 S.Diag(Compound->getRBracLoc(),
467 CD.diag_MaybeFallThrough_HasNoReturn);
468 else if (!ReturnsVoid)
469 S.Diag(Compound->getRBracLoc(),
470 CD.diag_MaybeFallThrough_ReturnsNonVoid);
471 break;
472 case AlwaysFallThrough:
473 if (HasNoReturn)
474 S.Diag(Compound->getRBracLoc(),
475 CD.diag_AlwaysFallThrough_HasNoReturn);
476 else if (!ReturnsVoid)
477 S.Diag(Compound->getRBracLoc(),
478 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
479 break;
480 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000481 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
482 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
483 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000484 << 0 << FD;
485 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
486 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
487 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000488 } else {
489 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
490 }
491 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000492 break;
493 case NeverFallThrough:
494 break;
495 }
496 }
497}
498
499//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000500// -Wuninitialized
501//===----------------------------------------------------------------------===//
502
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000503namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000504/// ContainsReference - A visitor class to search for references to
505/// a particular declaration (the needle) within any evaluated component of an
506/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000507class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000508 bool FoundReference;
509 const DeclRefExpr *Needle;
510
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000511public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000512 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
513 : EvaluatedExprVisitor<ContainsReference>(Context),
514 FoundReference(false), Needle(Needle) {}
515
516 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000517 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000518 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000519 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000520
521 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000522 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000523
524 void VisitDeclRefExpr(DeclRefExpr *E) {
525 if (E == Needle)
526 FoundReference = true;
527 else
528 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000529 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000530
531 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000532};
533}
534
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000535static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000536 QualType VariableTy = VD->getType().getCanonicalType();
537 if (VariableTy->isBlockPointerType() &&
538 !VD->hasAttr<BlocksAttr>()) {
539 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
540 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
541 return true;
542 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000543
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000544 // Don't issue a fixit if there is already an initializer.
545 if (VD->getInit())
546 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000547
548 // Don't suggest a fixit inside macros.
549 if (VD->getLocEnd().isMacroID())
550 return false;
551
Richard Smith8d06f422012-01-12 23:53:29 +0000552 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000553
554 // Suggest possible initialization (if any).
555 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
556 if (Init.empty())
557 return false;
558
Richard Smith8d06f422012-01-12 23:53:29 +0000559 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
560 << FixItHint::CreateInsertion(Loc, Init);
561 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000562}
563
Richard Smith1bb8edb82012-05-26 06:20:46 +0000564/// Create a fixit to remove an if-like statement, on the assumption that its
565/// condition is CondVal.
566static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
567 const Stmt *Else, bool CondVal,
568 FixItHint &Fixit1, FixItHint &Fixit2) {
569 if (CondVal) {
570 // If condition is always true, remove all but the 'then'.
571 Fixit1 = FixItHint::CreateRemoval(
572 CharSourceRange::getCharRange(If->getLocStart(),
573 Then->getLocStart()));
574 if (Else) {
575 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
576 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
577 Fixit2 = FixItHint::CreateRemoval(
578 SourceRange(ElseKwLoc, Else->getLocEnd()));
579 }
580 } else {
581 // If condition is always false, remove all but the 'else'.
582 if (Else)
583 Fixit1 = FixItHint::CreateRemoval(
584 CharSourceRange::getCharRange(If->getLocStart(),
585 Else->getLocStart()));
586 else
587 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
588 }
589}
590
591/// DiagUninitUse -- Helper function to produce a diagnostic for an
592/// uninitialized use of a variable.
593static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
594 bool IsCapturedByBlock) {
595 bool Diagnosed = false;
596
Richard Smithba8071e2013-09-12 18:49:10 +0000597 switch (Use.getKind()) {
598 case UninitUse::Always:
599 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
600 << VD->getDeclName() << IsCapturedByBlock
601 << Use.getUser()->getSourceRange();
602 return;
603
604 case UninitUse::AfterDecl:
605 case UninitUse::AfterCall:
606 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
607 << VD->getDeclName() << IsCapturedByBlock
608 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
609 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
610 << VD->getSourceRange();
611 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
612 << IsCapturedByBlock << Use.getUser()->getSourceRange();
613 return;
614
615 case UninitUse::Maybe:
616 case UninitUse::Sometimes:
617 // Carry on to report sometimes-uninitialized branches, if possible,
618 // or a 'may be used uninitialized' diagnostic otherwise.
619 break;
620 }
621
Richard Smith1bb8edb82012-05-26 06:20:46 +0000622 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000623 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
624 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000625 assert(Use.getKind() == UninitUse::Sometimes);
626
627 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000628 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000629
630 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000631 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000632 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000633 SourceRange Range;
634
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000635 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000636 // For all binary terminators, branch 0 is taken if the condition is true,
637 // and branch 1 is taken if the condition is false.
638 int RemoveDiagKind = -1;
639 const char *FixitStr =
640 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
641 : (I->Output ? "1" : "0");
642 FixItHint Fixit1, Fixit2;
643
Richard Smithba8071e2013-09-12 18:49:10 +0000644 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000645 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000646 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000647 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000648 continue;
649
650 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000651 case Stmt::IfStmtClass: {
652 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000653 DiagKind = 0;
654 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000655 Range = IS->getCond()->getSourceRange();
656 RemoveDiagKind = 0;
657 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
658 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000659 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000660 }
661 case Stmt::ConditionalOperatorClass: {
662 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000663 DiagKind = 0;
664 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000665 Range = CO->getCond()->getSourceRange();
666 RemoveDiagKind = 0;
667 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
668 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000669 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000670 }
Richard Smith4323bf82012-05-25 02:17:09 +0000671 case Stmt::BinaryOperatorClass: {
672 const BinaryOperator *BO = cast<BinaryOperator>(Term);
673 if (!BO->isLogicalOp())
674 continue;
675 DiagKind = 0;
676 Str = BO->getOpcodeStr();
677 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000678 RemoveDiagKind = 0;
679 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
680 (BO->getOpcode() == BO_LOr && !I->Output))
681 // true && y -> y, false || y -> y.
682 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
683 BO->getOperatorLoc()));
684 else
685 // false && y -> false, true || y -> true.
686 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000687 break;
688 }
689
690 // "loop is entered / loop is exited".
691 case Stmt::WhileStmtClass:
692 DiagKind = 1;
693 Str = "while";
694 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000695 RemoveDiagKind = 1;
696 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000697 break;
698 case Stmt::ForStmtClass:
699 DiagKind = 1;
700 Str = "for";
701 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000702 RemoveDiagKind = 1;
703 if (I->Output)
704 Fixit1 = FixItHint::CreateRemoval(Range);
705 else
706 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000707 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000708 case Stmt::CXXForRangeStmtClass:
709 if (I->Output == 1) {
710 // The use occurs if a range-based for loop's body never executes.
711 // That may be impossible, and there's no syntactic fix for this,
712 // so treat it as a 'may be uninitialized' case.
713 continue;
714 }
715 DiagKind = 1;
716 Str = "for";
717 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
718 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000719
720 // "condition is true / loop is exited".
721 case Stmt::DoStmtClass:
722 DiagKind = 2;
723 Str = "do";
724 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000725 RemoveDiagKind = 1;
726 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000727 break;
728
729 // "switch case is taken".
730 case Stmt::CaseStmtClass:
731 DiagKind = 3;
732 Str = "case";
733 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
734 break;
735 case Stmt::DefaultStmtClass:
736 DiagKind = 3;
737 Str = "default";
738 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
739 break;
740 }
741
Richard Smith1bb8edb82012-05-26 06:20:46 +0000742 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
743 << VD->getDeclName() << IsCapturedByBlock << DiagKind
744 << Str << I->Output << Range;
745 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
746 << IsCapturedByBlock << User->getSourceRange();
747 if (RemoveDiagKind != -1)
748 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
749 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
750
751 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000752 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000753
754 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000755 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000756 << VD->getDeclName() << IsCapturedByBlock
757 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000758}
759
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000760/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
761/// uninitialized variable. This manages the different forms of diagnostic
762/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000763/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000764/// false.
765static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000766 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000767 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000768
Richard Smith4323bf82012-05-25 02:17:09 +0000769 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000770 // Inspect the initializer of the variable declaration which is
771 // being referenced prior to its initialization. We emit
772 // specialized diagnostics for self-initialization, and we
773 // specifically avoid warning about self references which take the
774 // form of:
775 //
776 // int x = x;
777 //
778 // This is used to indicate to GCC that 'x' is intentionally left
779 // uninitialized. Proven code paths which access 'x' in
780 // an uninitialized state after this will still warn.
781 if (const Expr *Initializer = VD->getInit()) {
782 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
783 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000784
Richard Trieu43a2fc72012-05-09 21:08:22 +0000785 ContainsReference CR(S.Context, DRE);
786 CR.Visit(const_cast<Expr*>(Initializer));
787 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000788 S.Diag(DRE->getLocStart(),
789 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000790 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
791 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000792 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000793 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000794
Richard Smith1bb8edb82012-05-26 06:20:46 +0000795 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000796 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000797 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000798 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
799 S.Diag(BE->getLocStart(),
800 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000801 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000802 else
803 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000804 }
805
806 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000807 // the initializer of that declaration & we didn't already suggest
808 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000809 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000810 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
811 << VD->getDeclName();
812
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000813 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000814}
815
Richard Smith84837d52012-05-03 18:27:39 +0000816namespace {
817 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
818 public:
819 FallthroughMapper(Sema &S)
820 : FoundSwitchStatements(false),
821 S(S) {
822 }
823
824 bool foundSwitchStatements() const { return FoundSwitchStatements; }
825
826 void markFallthroughVisited(const AttributedStmt *Stmt) {
827 bool Found = FallthroughStmts.erase(Stmt);
828 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000829 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000830 }
831
832 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
833
834 const AttrStmts &getFallthroughStmts() const {
835 return FallthroughStmts;
836 }
837
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000838 void fillReachableBlocks(CFG *Cfg) {
839 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
840 std::deque<const CFGBlock *> BlockQueue;
841
842 ReachableBlocks.insert(&Cfg->getEntry());
843 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000844 // Mark all case blocks reachable to avoid problems with switching on
845 // constants, covered enums, etc.
846 // These blocks can contain fall-through annotations, and we don't want to
847 // issue a warn_fallthrough_attr_unreachable for them.
848 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
849 const CFGBlock *B = *I;
850 const Stmt *L = B->getLabel();
851 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
852 BlockQueue.push_back(B);
853 }
854
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000855 while (!BlockQueue.empty()) {
856 const CFGBlock *P = BlockQueue.front();
857 BlockQueue.pop_front();
858 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
859 E = P->succ_end();
860 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000861 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000862 BlockQueue.push_back(*I);
863 }
864 }
865 }
866
Richard Smith84837d52012-05-03 18:27:39 +0000867 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000868 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
869
Richard Smith84837d52012-05-03 18:27:39 +0000870 int UnannotatedCnt = 0;
871 AnnotatedCnt = 0;
872
873 std::deque<const CFGBlock*> BlockQueue;
874
875 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
876
877 while (!BlockQueue.empty()) {
878 const CFGBlock *P = BlockQueue.front();
879 BlockQueue.pop_front();
880
881 const Stmt *Term = P->getTerminator();
882 if (Term && isa<SwitchStmt>(Term))
883 continue; // Switch statement, good.
884
885 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
886 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
887 continue; // Previous case label has no statements, good.
888
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000889 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
890 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
891 continue; // Case label is preceded with a normal label, good.
892
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000893 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000894 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
895 ElemEnd = P->rend();
896 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000897 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
898 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000899 S.Diag(AS->getLocStart(),
900 diag::warn_fallthrough_attr_unreachable);
901 markFallthroughVisited(AS);
902 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000903 break;
Richard Smith84837d52012-05-03 18:27:39 +0000904 }
905 // Don't care about other unreachable statements.
906 }
907 }
908 // If there are no unreachable statements, this may be a special
909 // case in CFG:
910 // case X: {
911 // A a; // A has a destructor.
912 // break;
913 // }
914 // // <<<< This place is represented by a 'hanging' CFG block.
915 // case Y:
916 continue;
917 }
918
919 const Stmt *LastStmt = getLastStmt(*P);
920 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
921 markFallthroughVisited(AS);
922 ++AnnotatedCnt;
923 continue; // Fallthrough annotation, good.
924 }
925
926 if (!LastStmt) { // This block contains no executable statements.
927 // Traverse its predecessors.
928 std::copy(P->pred_begin(), P->pred_end(),
929 std::back_inserter(BlockQueue));
930 continue;
931 }
932
933 ++UnannotatedCnt;
934 }
935 return !!UnannotatedCnt;
936 }
937
938 // RecursiveASTVisitor setup.
939 bool shouldWalkTypesOfTypeLocs() const { return false; }
940
941 bool VisitAttributedStmt(AttributedStmt *S) {
942 if (asFallThroughAttr(S))
943 FallthroughStmts.insert(S);
944 return true;
945 }
946
947 bool VisitSwitchStmt(SwitchStmt *S) {
948 FoundSwitchStatements = true;
949 return true;
950 }
951
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000952 // We don't want to traverse local type declarations. We analyze their
953 // methods separately.
954 bool TraverseDecl(Decl *D) { return true; }
955
Richard Smith84837d52012-05-03 18:27:39 +0000956 private:
957
958 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
959 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
960 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
961 return AS;
962 }
963 return 0;
964 }
965
966 static const Stmt *getLastStmt(const CFGBlock &B) {
967 if (const Stmt *Term = B.getTerminator())
968 return Term;
969 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
970 ElemEnd = B.rend();
971 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000972 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
973 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +0000974 }
975 // Workaround to detect a statement thrown out by CFGBuilder:
976 // case X: {} case Y:
977 // case X: ; case Y:
978 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
979 if (!isa<SwitchCase>(SW->getSubStmt()))
980 return SW->getSubStmt();
981
982 return 0;
983 }
984
985 bool FoundSwitchStatements;
986 AttrStmts FallthroughStmts;
987 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000988 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +0000989 };
990}
991
Alexander Kornienko06caf7d2012-06-02 01:01:07 +0000992static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +0000993 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +0000994 // Only perform this analysis when using C++11. There is no good workflow
995 // for this warning when not using C++11. There is no good way to silence
996 // the warning (no attribute is available) unless we are using C++11's support
997 // for generalized attributes. Once could use pragmas to silence the warning,
998 // but as a general solution that is gross and not in the spirit of this
999 // warning.
1000 //
1001 // NOTE: This an intermediate solution. There are on-going discussions on
1002 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001003 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001004 return;
1005
Richard Smith84837d52012-05-03 18:27:39 +00001006 FallthroughMapper FM(S);
1007 FM.TraverseStmt(AC.getBody());
1008
1009 if (!FM.foundSwitchStatements())
1010 return;
1011
Alexis Hunt2178f142012-06-15 21:22:05 +00001012 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001013 return;
1014
Richard Smith84837d52012-05-03 18:27:39 +00001015 CFG *Cfg = AC.getCFG();
1016
1017 if (!Cfg)
1018 return;
1019
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001020 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001021
1022 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001023 const CFGBlock *B = *I;
1024 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001025
1026 if (!Label || !isa<SwitchCase>(Label))
1027 continue;
1028
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001029 int AnnotatedCnt;
1030
Alexander Kornienko55488792013-01-25 15:49:34 +00001031 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001032 continue;
1033
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001034 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001035 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1036 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001037
1038 if (!AnnotatedCnt) {
1039 SourceLocation L = Label->getLocStart();
1040 if (L.isMacroID())
1041 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001042 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001043 const Stmt *Term = B->getTerminator();
1044 // Skip empty cases.
1045 while (B->empty() && !Term && B->succ_size() == 1) {
1046 B = *B->succ_begin();
1047 Term = B->getTerminator();
1048 }
1049 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001050 Preprocessor &PP = S.getPreprocessor();
1051 TokenValue Tokens[] = {
1052 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1053 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1054 tok::r_square, tok::r_square
1055 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001056 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1057 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1058 if (!MacroName.empty())
1059 AnnotationSpelling = MacroName;
1060 SmallString<64> TextToInsert(AnnotationSpelling);
1061 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001062 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001063 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001064 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001065 }
Richard Smith84837d52012-05-03 18:27:39 +00001066 }
1067 S.Diag(L, diag::note_insert_break_fixit) <<
1068 FixItHint::CreateInsertion(L, "break; ");
1069 }
1070 }
1071
1072 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1073 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1074 E = Fallthroughs.end();
1075 I != E; ++I) {
1076 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1077 }
1078
1079}
1080
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001081namespace {
Jordan Rosed61f3b42012-09-28 22:29:02 +00001082typedef std::pair<const Stmt *,
1083 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
1084 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001085
Jordan Rosed61f3b42012-09-28 22:29:02 +00001086class StmtUseSorter {
Jordan Rosed3934582012-09-28 22:21:30 +00001087 const SourceManager &SM;
1088
1089public:
Jordan Rosed61f3b42012-09-28 22:29:02 +00001090 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
Jordan Rosed3934582012-09-28 22:21:30 +00001091
1092 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1093 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1094 RHS.first->getLocStart());
1095 }
1096};
Jordan Rosed61f3b42012-09-28 22:29:02 +00001097}
Jordan Rosed3934582012-09-28 22:21:30 +00001098
Jordan Rose25c0ea82012-10-29 17:46:47 +00001099static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1100 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001101 assert(S);
1102
1103 do {
1104 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001105 case Stmt::ForStmtClass:
1106 case Stmt::WhileStmtClass:
1107 case Stmt::CXXForRangeStmtClass:
1108 case Stmt::ObjCForCollectionStmtClass:
1109 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001110 case Stmt::DoStmtClass: {
1111 const Expr *Cond = cast<DoStmt>(S)->getCond();
1112 llvm::APSInt Val;
1113 if (!Cond->EvaluateAsInt(Val, Ctx))
1114 return true;
1115 return Val.getBoolValue();
1116 }
Jordan Rose76831c62012-10-11 16:10:19 +00001117 default:
1118 break;
1119 }
1120 } while ((S = PM.getParent(S)));
1121
1122 return false;
1123}
1124
Jordan Rosed3934582012-09-28 22:21:30 +00001125
1126static void diagnoseRepeatedUseOfWeak(Sema &S,
1127 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001128 const Decl *D,
1129 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001130 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1131 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1132 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1133
Jordan Rose25c0ea82012-10-29 17:46:47 +00001134 ASTContext &Ctx = S.getASTContext();
1135
Jordan Rosed3934582012-09-28 22:21:30 +00001136 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1137
1138 // Extract all weak objects that are referenced more than once.
1139 SmallVector<StmtUsesPair, 8> UsesByStmt;
1140 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1141 I != E; ++I) {
1142 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001143
1144 // Find the first read of the weak object.
1145 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1146 for ( ; UI != UE; ++UI) {
1147 if (UI->isUnsafe())
1148 break;
1149 }
1150
1151 // If there were only writes to this object, don't warn.
1152 if (UI == UE)
1153 continue;
1154
Jordan Rose76831c62012-10-11 16:10:19 +00001155 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001156 // read is not within a loop, don't warn. Additionally, don't warn in a
1157 // loop if the base object is a local variable -- local variables are often
1158 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001159 if (UI == Uses.begin()) {
1160 WeakUseVector::const_iterator UI2 = UI;
1161 for (++UI2; UI2 != UE; ++UI2)
1162 if (UI2->isUnsafe())
1163 break;
1164
Jordan Rose25c0ea82012-10-29 17:46:47 +00001165 if (UI2 == UE) {
1166 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001167 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001168
1169 const WeakObjectProfileTy &Profile = I->first;
1170 if (!Profile.isExactProfile())
1171 continue;
1172
1173 const NamedDecl *Base = Profile.getBase();
1174 if (!Base)
1175 Base = Profile.getProperty();
1176 assert(Base && "A profile always has a base or property.");
1177
1178 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1179 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1180 continue;
1181 }
Jordan Rose76831c62012-10-11 16:10:19 +00001182 }
1183
Jordan Rosed3934582012-09-28 22:21:30 +00001184 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1185 }
1186
1187 if (UsesByStmt.empty())
1188 return;
1189
1190 // Sort by first use so that we emit the warnings in a deterministic order.
1191 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Jordan Rosed61f3b42012-09-28 22:29:02 +00001192 StmtUseSorter(S.getSourceManager()));
Jordan Rosed3934582012-09-28 22:21:30 +00001193
1194 // Classify the current code body for better warning text.
1195 // This enum should stay in sync with the cases in
1196 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1197 // FIXME: Should we use a common classification enum and the same set of
1198 // possibilities all throughout Sema?
1199 enum {
1200 Function,
1201 Method,
1202 Block,
1203 Lambda
1204 } FunctionKind;
1205
1206 if (isa<sema::BlockScopeInfo>(CurFn))
1207 FunctionKind = Block;
1208 else if (isa<sema::LambdaScopeInfo>(CurFn))
1209 FunctionKind = Lambda;
1210 else if (isa<ObjCMethodDecl>(D))
1211 FunctionKind = Method;
1212 else
1213 FunctionKind = Function;
1214
1215 // Iterate through the sorted problems and emit warnings for each.
1216 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1217 E = UsesByStmt.end();
1218 I != E; ++I) {
1219 const Stmt *FirstRead = I->first;
1220 const WeakObjectProfileTy &Key = I->second->first;
1221 const WeakUseVector &Uses = I->second->second;
1222
Jordan Rose657b5f42012-09-28 22:21:35 +00001223 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1224 // may not contain enough information to determine that these are different
1225 // properties. We can only be 100% sure of a repeated use in certain cases,
1226 // and we adjust the diagnostic kind accordingly so that the less certain
1227 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001228 unsigned DiagKind;
1229 if (Key.isExactProfile())
1230 DiagKind = diag::warn_arc_repeated_use_of_weak;
1231 else
1232 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1233
Jordan Rose657b5f42012-09-28 22:21:35 +00001234 // Classify the weak object being accessed for better warning text.
1235 // This enum should stay in sync with the cases in
1236 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1237 enum {
1238 Variable,
1239 Property,
1240 ImplicitProperty,
1241 Ivar
1242 } ObjectKind;
1243
1244 const NamedDecl *D = Key.getProperty();
1245 if (isa<VarDecl>(D))
1246 ObjectKind = Variable;
1247 else if (isa<ObjCPropertyDecl>(D))
1248 ObjectKind = Property;
1249 else if (isa<ObjCMethodDecl>(D))
1250 ObjectKind = ImplicitProperty;
1251 else if (isa<ObjCIvarDecl>(D))
1252 ObjectKind = Ivar;
1253 else
1254 llvm_unreachable("Unexpected weak object kind!");
1255
Jordan Rosed3934582012-09-28 22:21:30 +00001256 // Show the first time the object was read.
1257 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001258 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001259 << FirstRead->getSourceRange();
1260
1261 // Print all the other accesses as notes.
1262 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1263 UI != UE; ++UI) {
1264 if (UI->getUseExpr() == FirstRead)
1265 continue;
1266 S.Diag(UI->getUseExpr()->getLocStart(),
1267 diag::note_arc_weak_also_accessed_here)
1268 << UI->getUseExpr()->getSourceRange();
1269 }
1270 }
1271}
1272
1273
1274namespace {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001275struct SLocSort {
Ted Kremenekc8c4e5f2011-03-15 04:57:38 +00001276 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith4323bf82012-05-25 02:17:09 +00001277 // Prefer a more confident report over a less confident one.
1278 if (a.getKind() != b.getKind())
1279 return a.getKind() > b.getKind();
1280 SourceLocation aLoc = a.getUser()->getLocStart();
1281 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek39fa0562011-01-21 19:41:41 +00001282 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1283 }
1284};
1285
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001286class UninitValsDiagReporter : public UninitVariablesHandler {
1287 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001288 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001289 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001290 // Prefer using MapVector to DenseMap, so that iteration order will be
1291 // the same as insertion order. This is needed to obtain a deterministic
1292 // order of diagnostics when calling flushDiagnostics().
1293 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001294 UsesMap *uses;
1295
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001296public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001297 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1298 ~UninitValsDiagReporter() {
1299 flushDiagnostics();
1300 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001301
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001302 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001303 if (!uses)
1304 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001305
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001306 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001307 if (!V.getPointer())
1308 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001309
Ted Kremenek596fa162011-10-13 18:50:06 +00001310 return V;
1311 }
1312
Richard Smith4323bf82012-05-25 02:17:09 +00001313 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001314 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001315 }
1316
1317 void handleSelfInit(const VarDecl *vd) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001318 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001319 }
1320
1321 void flushDiagnostics() {
1322 if (!uses)
1323 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001324
Ted Kremenek39fa0562011-01-21 19:41:41 +00001325 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1326 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001327 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001328
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001329 UsesVec *vec = V.getPointer();
1330 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001331
1332 // Specially handle the case where we have uses of an uninitialized
1333 // variable, but the root cause is an idiomatic self-init. We want
1334 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001335 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001336 DiagnoseUninitializedUse(S, vd,
1337 UninitUse(vd->getInit()->IgnoreParenCasts(),
1338 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001339 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001340 else {
1341 // Sort the uses by their SourceLocations. While not strictly
1342 // guaranteed to produce them in line/column order, this will provide
1343 // a stable ordering.
1344 std::sort(vec->begin(), vec->end(), SLocSort());
1345
1346 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1347 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001348 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1349 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1350
1351 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001352 // Skip further diagnostics for this variable. We try to warn only
1353 // on the first point at which a variable is used uninitialized.
1354 break;
1355 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001356 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001357
1358 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001359 delete vec;
1360 }
1361 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001362 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001363
1364private:
1365 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1366 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001367 if (i->getKind() == UninitUse::Always ||
1368 i->getKind() == UninitUse::AfterCall ||
1369 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001370 return true;
1371 }
1372 }
1373 return false;
1374}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001375};
1376}
1377
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001378namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001379namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001380typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001381typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001382typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001383
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001384struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001385 SourceManager &SM;
1386 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001387
1388 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1389 // Although this call will be slow, this is only called when outputting
1390 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001391 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001392 }
1393};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001394}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001395
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001396//===----------------------------------------------------------------------===//
1397// -Wthread-safety
1398//===----------------------------------------------------------------------===//
1399namespace clang {
1400namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001401namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001402class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1403 Sema &S;
1404 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001405 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001406
1407 // Helper functions
1408 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001409 // Gracefully handle rare cases when the analysis can't get a more
1410 // precise source location.
1411 if (!Loc.isValid())
1412 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001413 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1414 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001415 }
1416
1417 public:
Richard Smith92286672012-02-03 04:45:26 +00001418 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1419 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001420
1421 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1422 /// We need to output diagnostics produced while iterating through
1423 /// the lockset in deterministic order, so this function orders diagnostics
1424 /// and outputs them.
1425 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001426 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001427 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001428 I != E; ++I) {
1429 S.Diag(I->first.first, I->first.second);
1430 const OptionalNotes &Notes = I->second;
1431 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1432 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1433 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001434 }
1435
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001436 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001437 PartialDiagnosticAt Warning(Loc,
1438 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1439 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001440 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001441 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1442 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1443 }
1444
1445 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1446 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1447 }
1448
Richard Smith92286672012-02-03 04:45:26 +00001449 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1450 SourceLocation LocEndOfScope,
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001451 LockErrorKind LEK){
1452 unsigned DiagID = 0;
1453 switch (LEK) {
1454 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001455 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001456 break;
1457 case LEK_LockedSomeLoopIterations:
1458 DiagID = diag::warn_expecting_lock_held_on_loop;
1459 break;
1460 case LEK_LockedAtEndOfFunction:
1461 DiagID = diag::warn_no_unlock;
1462 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001463 case LEK_NotLockedAtEndOfFunction:
1464 DiagID = diag::warn_expecting_locked;
1465 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001466 }
Richard Smith92286672012-02-03 04:45:26 +00001467 if (LocEndOfScope.isInvalid())
1468 LocEndOfScope = FunEndLocation;
1469
1470 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001471 if (LocLocked.isValid()) {
1472 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1473 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1474 return;
1475 }
1476 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001477 }
1478
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001479
1480 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1481 SourceLocation Loc2) {
Richard Smith92286672012-02-03 04:45:26 +00001482 PartialDiagnosticAt Warning(
1483 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1484 PartialDiagnosticAt Note(
1485 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1486 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001487 }
1488
1489 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1490 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001491 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1492 && "Only works for variables");
1493 unsigned DiagID = POK == POK_VarAccess?
1494 diag::warn_variable_requires_any_lock:
1495 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001496 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001497 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001498 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001499 }
1500
1501 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001502 Name LockName, LockKind LK, SourceLocation Loc,
1503 Name *PossibleMatch) {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001504 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001505 if (PossibleMatch) {
1506 switch (POK) {
1507 case POK_VarAccess:
1508 DiagID = diag::warn_variable_requires_lock_precise;
1509 break;
1510 case POK_VarDereference:
1511 DiagID = diag::warn_var_deref_requires_lock_precise;
1512 break;
1513 case POK_FunctionCall:
1514 DiagID = diag::warn_fun_requires_lock_precise;
1515 break;
1516 }
1517 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001518 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001519 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1520 << *PossibleMatch);
1521 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1522 } else {
1523 switch (POK) {
1524 case POK_VarAccess:
1525 DiagID = diag::warn_variable_requires_lock;
1526 break;
1527 case POK_VarDereference:
1528 DiagID = diag::warn_var_deref_requires_lock;
1529 break;
1530 case POK_FunctionCall:
1531 DiagID = diag::warn_fun_requires_lock;
1532 break;
1533 }
1534 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001535 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001536 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001537 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001538 }
1539
1540 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001541 PartialDiagnosticAt Warning(Loc,
1542 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1543 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001544 }
1545};
1546}
1547}
David Blaikie68e081d2011-12-20 02:48:34 +00001548}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001549
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001550//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001551// -Wconsumed
1552//===----------------------------------------------------------------------===//
1553
1554namespace clang {
1555namespace consumed {
1556namespace {
1557class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1558
1559 Sema &S;
1560 DiagList Warnings;
1561
1562public:
1563
1564 ConsumedWarningsHandler(Sema &S) : S(S) {}
1565
1566 void emitDiagnostics() {
1567 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1568
1569 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1570 I != E; ++I) {
1571
1572 const OptionalNotes &Notes = I->second;
1573 S.Diag(I->first.first, I->first.second);
1574
1575 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1576 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1577 }
1578 }
1579 }
1580
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001581 void warnLoopStateMismatch(SourceLocation Loc, StringRef VariableName) {
1582 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1583 VariableName);
1584
1585 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1586 }
1587
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001588 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1589 StringRef VariableName,
1590 StringRef ExpectedState,
1591 StringRef ObservedState) {
1592
1593 PartialDiagnosticAt Warning(Loc, S.PDiag(
1594 diag::warn_param_return_typestate_mismatch) << VariableName <<
1595 ExpectedState << ObservedState);
1596
1597 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1598 }
1599
DeLesley Hutchins69391772013-10-17 23:23:53 +00001600 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1601 StringRef ObservedState) {
1602
1603 PartialDiagnosticAt Warning(Loc, S.PDiag(
1604 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1605
1606 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1607 }
1608
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001609 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1610 StringRef TypeName) {
1611 PartialDiagnosticAt Warning(Loc, S.PDiag(
1612 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1613
1614 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1615 }
1616
1617 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1618 StringRef ObservedState) {
1619
1620 PartialDiagnosticAt Warning(Loc, S.PDiag(
1621 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1622
1623 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1624 }
1625
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001626 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1627 SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001628
1629 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001630 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001631
1632 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1633 }
1634
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001635 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1636 StringRef State, SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001637
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001638 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1639 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001640
1641 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1642 }
1643};
1644}}}
1645
1646//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001647// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1648// warnings on a function, method, or block.
1649//===----------------------------------------------------------------------===//
1650
Ted Kremenek0b405322010-03-23 00:13:23 +00001651clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1652 enableCheckFallThrough = 1;
1653 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001654 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001655 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001656}
1657
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001658clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1659 : S(s),
1660 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001661 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001662 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001663 MaxCFGBlocksPerFunction(0),
1664 NumUninitAnalysisFunctions(0),
1665 NumUninitAnalysisVariables(0),
1666 MaxUninitAnalysisVariablesPerFunction(0),
1667 NumUninitAnalysisBlockVisits(0),
1668 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikie9c902b52011-09-25 23:23:43 +00001669 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenek0b405322010-03-23 00:13:23 +00001670 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001671 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001672 DiagnosticsEngine::Ignored);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001673 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1674 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001675 DiagnosticsEngine::Ignored);
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001676 DefaultPolicy.enableConsumedAnalysis = (unsigned)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001677 (D.getDiagnosticLevel(diag::warn_use_in_invalid_state, SourceLocation()) !=
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001678 DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +00001679}
1680
Ted Kremenek3427fac2011-02-23 01:52:04 +00001681static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001682 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001683 i = fscope->PossiblyUnreachableDiags.begin(),
1684 e = fscope->PossiblyUnreachableDiags.end();
1685 i != e; ++i) {
1686 const sema::PossiblyUnreachableDiag &D = *i;
1687 S.Diag(D.Loc, D.PD);
1688 }
1689}
1690
Ted Kremenek0b405322010-03-23 00:13:23 +00001691void clang::sema::
1692AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001693 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001694 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001695
Ted Kremenek918fe842010-03-20 21:06:02 +00001696 // We avoid doing analysis-based warnings when there are errors for
1697 // two reasons:
1698 // (1) The CFGs often can't be constructed (if the body is invalid), so
1699 // don't bother trying.
1700 // (2) The code already has problems; running the analysis just takes more
1701 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001702 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001703
Ted Kremenek0b405322010-03-23 00:13:23 +00001704 // Do not do any analysis for declarations in system headers if we are
1705 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001706 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001707 S.SourceMgr.isInSystemHeader(D->getLocation()))
1708 return;
1709
John McCall1d570a72010-08-25 05:56:39 +00001710 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001711 if (cast<DeclContext>(D)->isDependentContext())
1712 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001713
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001714 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001715 // Flush out any possibly unreachable diagnostics.
1716 flushDiagnostics(S, fscope);
1717 return;
1718 }
1719
Ted Kremenek918fe842010-03-20 21:06:02 +00001720 const Stmt *Body = D->getBody();
1721 assert(Body);
1722
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001723 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001724 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001725
Ted Kremenek918fe842010-03-20 21:06:02 +00001726 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001727 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001728 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1729 AC.getCFGBuildOptions().AddEHEdges = false;
1730 AC.getCFGBuildOptions().AddInitializers = true;
1731 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001732 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001733 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001734
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001735 // Force that certain expressions appear as CFGElements in the CFG. This
1736 // is used to speed up various analyses.
1737 // FIXME: This isn't the right factoring. This is here for initial
1738 // prototyping, but we need a way for analyses to say what expressions they
1739 // expect to always be CFGElements and then fill in the BuildOptions
1740 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001741 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1742 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001743 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001744 AC.getCFGBuildOptions().setAllAlwaysAdd();
1745 }
1746 else {
1747 AC.getCFGBuildOptions()
1748 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001749 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001750 .setAlwaysAdd(Stmt::BlockExprClass)
1751 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1752 .setAlwaysAdd(Stmt::DeclRefExprClass)
1753 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001754 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1755 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001756 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001757
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001758
Ted Kremenek3427fac2011-02-23 01:52:04 +00001759 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001760 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001761 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001762
1763 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001764 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001765 i = fscope->PossiblyUnreachableDiags.begin(),
1766 e = fscope->PossiblyUnreachableDiags.end();
1767 i != e; ++i) {
1768 if (const Stmt *stmt = i->stmt)
1769 AC.registerForcedBlockExpression(stmt);
1770 }
1771
1772 if (AC.getCFG()) {
1773 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001774 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001775 i = fscope->PossiblyUnreachableDiags.begin(),
1776 e = fscope->PossiblyUnreachableDiags.end();
1777 i != e; ++i)
1778 {
1779 const sema::PossiblyUnreachableDiag &D = *i;
1780 bool processed = false;
1781 if (const Stmt *stmt = i->stmt) {
1782 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001783 CFGReverseBlockReachabilityAnalysis *cra =
1784 AC.getCFGReachablityAnalysis();
1785 // FIXME: We should be able to assert that block is non-null, but
1786 // the CFG analysis can skip potentially-evaluated expressions in
1787 // edge cases; see test/Sema/vla-2.c.
1788 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001789 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001790 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001791 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001792 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001793 }
1794 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001795 if (!processed) {
1796 // Emit the warning anyway if we cannot map to a basic block.
1797 S.Diag(D.Loc, D.PD);
1798 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001799 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001800 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001801
1802 if (!analyzed)
1803 flushDiagnostics(S, fscope);
1804 }
1805
1806
Ted Kremenek918fe842010-03-20 21:06:02 +00001807 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001808 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001809 const CheckFallThroughDiagnostics &CD =
1810 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001811 : (isa<CXXMethodDecl>(D) &&
1812 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1813 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1814 ? CheckFallThroughDiagnostics::MakeForLambda()
1815 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001816 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001817 }
1818
1819 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001820 if (P.enableCheckUnreachable) {
1821 // Only check for unreachable code on non-template instantiations.
1822 // Different template instantiations can effectively change the control-flow
1823 // and it is very difficult to prove that a snippet of code in a template
1824 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001825 bool isTemplateInstantiation = false;
1826 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1827 isTemplateInstantiation = Function->isTemplateInstantiation();
1828 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001829 CheckUnreachable(S, AC);
1830 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001831
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001832 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001833 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001834 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001835 SourceLocation FEL = AC.getDecl()->getLocEnd();
1836 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001837 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1838 != DiagnosticsEngine::Ignored)
1839 Reporter.setIssueBetaWarnings(true);
1840
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001841 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1842 Reporter.emitDiagnostics();
1843 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001844
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001845 // Check for violations of consumed properties.
1846 if (P.enableConsumedAnalysis) {
1847 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001848 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001849 Analyzer.run(AC);
1850 }
1851
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001852 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001853 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001854 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1855 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001856 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001857 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001858 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001859 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001860 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001861 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001862 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001863 reporter, stats);
1864
1865 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1866 ++NumUninitAnalysisFunctions;
1867 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1868 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1869 MaxUninitAnalysisVariablesPerFunction =
1870 std::max(MaxUninitAnalysisVariablesPerFunction,
1871 stats.NumVariablesAnalyzed);
1872 MaxUninitAnalysisBlockVisitsPerFunction =
1873 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1874 stats.NumBlockVisits);
1875 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001876 }
1877 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001878
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001879 bool FallThroughDiagFull =
1880 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1881 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001882 bool FallThroughDiagPerFunction =
1883 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001884 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001885 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001886 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001887 }
1888
Jordan Rosed3934582012-09-28 22:21:30 +00001889 if (S.getLangOpts().ObjCARCWeak &&
1890 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1891 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001892 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001893
Richard Trieu2f024f42013-12-21 02:33:43 +00001894
1895 // Check for infinite self-recursion in functions
1896 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1897 D->getLocStart())
1898 != DiagnosticsEngine::Ignored) {
1899 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1900 checkRecursiveFunction(S, FD, Body, AC);
1901 }
1902 }
1903
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001904 // Collect statistics about the CFG if it was built.
1905 if (S.CollectStats && AC.isCFGBuilt()) {
1906 ++NumFunctionsAnalyzed;
1907 if (CFG *cfg = AC.getCFG()) {
1908 // If we successfully built a CFG for this context, record some more
1909 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001910 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001911 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001912 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001913 } else {
1914 ++NumFunctionsWithBadCFGs;
1915 }
1916 }
1917}
1918
1919void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1920 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1921
1922 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1923 unsigned AvgCFGBlocksPerFunction =
1924 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1925 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1926 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1927 << " " << NumCFGBlocks << " CFG blocks built.\n"
1928 << " " << AvgCFGBlocksPerFunction
1929 << " average CFG blocks per function.\n"
1930 << " " << MaxCFGBlocksPerFunction
1931 << " max CFG blocks per function.\n";
1932
1933 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1934 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1935 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1936 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1937 llvm::errs() << NumUninitAnalysisFunctions
1938 << " functions analyzed for uninitialiazed variables\n"
1939 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1940 << " " << AvgUninitVariablesPerFunction
1941 << " average variables per function.\n"
1942 << " " << MaxUninitAnalysisVariablesPerFunction
1943 << " max variables per function.\n"
1944 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1945 << " " << AvgUninitBlockVisitsPerFunction
1946 << " average block visits per function.\n"
1947 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1948 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001949}