blob: 099ef253736c878f93afd4854d70c3d59b63a07a [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 Kremenekc1b28752014-02-25 22:35:37 +000076 // As a heuristic prune all diagnostics not in the main file. Currently
77 // the majority of warnings in headers are false positives. These
78 // are largely caused by configuration state, e.g. preprocessor
79 // defined code, etc.
80 //
81 // Note that this is also a performance optimization. Analyzing
82 // headers many times can be expensive.
83 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
84 return;
85
Ted Kremenek918fe842010-03-20 21:06:02 +000086 UnreachableCodeHandler UC(S);
87 reachable_code::FindUnreachableCode(AC, UC);
88}
89
90//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +000091// Check for infinite self-recursion in functions
92//===----------------------------------------------------------------------===//
93
94// All blocks are in one of three states. States are ordered so that blocks
95// can only move to higher states.
96enum RecursiveState {
97 FoundNoPath,
98 FoundPath,
99 FoundPathWithNoRecursiveCall
100};
101
102static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
103 CFGBlock &Block, unsigned ExitID,
104 llvm::SmallVectorImpl<RecursiveState> &States,
105 RecursiveState State) {
106 unsigned ID = Block.getBlockID();
107
108 // A block's state can only move to a higher state.
109 if (States[ID] >= State)
110 return;
111
112 States[ID] = State;
113
114 // Found a path to the exit node without a recursive call.
115 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
116 return;
117
118 if (State == FoundPathWithNoRecursiveCall) {
119 // If the current state is FoundPathWithNoRecursiveCall, the successors
120 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
121 // which, process all the Stmt's in this block to find any recursive calls.
122 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
123 if (I->getKind() != CFGElement::Statement)
124 continue;
125
126 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
127 if (CE && CE->getCalleeDecl() &&
128 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000129
130 // Skip function calls which are qualified with a templated class.
131 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
132 CE->getCallee()->IgnoreParenImpCasts())) {
133 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
134 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
135 isa<TemplateSpecializationType>(NNS->getAsType())) {
136 continue;
137 }
138 }
139 }
140
Richard Trieu2f024f42013-12-21 02:33:43 +0000141 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
142 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
143 !MCE->getMethodDecl()->isVirtual()) {
144 State = FoundPath;
145 break;
146 }
147 } else {
148 State = FoundPath;
149 break;
150 }
151 }
152 }
153 }
154
155 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
156 I != E; ++I)
157 if (*I)
158 checkForFunctionCall(S, FD, **I, ExitID, States, State);
159}
160
161static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
162 const Stmt *Body,
163 AnalysisDeclContext &AC) {
164 FD = FD->getCanonicalDecl();
165
166 // Only run on non-templated functions and non-templated members of
167 // templated classes.
168 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
169 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
170 return;
171
172 CFG *cfg = AC.getCFG();
173 if (cfg == 0) return;
174
175 // If the exit block is unreachable, skip processing the function.
176 if (cfg->getExit().pred_empty())
177 return;
178
179 // Mark all nodes as FoundNoPath, then begin processing the entry block.
180 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
181 FoundNoPath);
182 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
183 states, FoundPathWithNoRecursiveCall);
184
185 // Check that the exit block is reachable. This prevents triggering the
186 // warning on functions that do not terminate.
187 if (states[cfg->getExit().getBlockID()] == FoundPath)
188 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
189}
190
191//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000192// Check for missing return value.
193//===----------------------------------------------------------------------===//
194
John McCall5c6ec8c2010-05-16 09:34:11 +0000195enum ControlFlowKind {
196 UnknownFallThrough,
197 NeverFallThrough,
198 MaybeFallThrough,
199 AlwaysFallThrough,
200 NeverFallThroughOrReturn
201};
Ted Kremenek918fe842010-03-20 21:06:02 +0000202
203/// CheckFallThrough - Check that we don't fall off the end of a
204/// Statement that should return a value.
205///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000206/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
207/// MaybeFallThrough iff we might or might not fall off the end,
208/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
209/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000210/// statement but we may return. We assume that functions not marked noreturn
211/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000212static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000213 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000214 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000215
216 // The CFG leaves in dead things, and we don't want the dead code paths to
217 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000218 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000219 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000220 live);
221
222 bool AddEHEdges = AC.getAddEHEdges();
223 if (!AddEHEdges && count != cfg->getNumBlockIDs())
224 // When there are things remaining dead, and we didn't add EH edges
225 // from CallExprs to the catch clauses, we have to go back and
226 // mark them as live.
227 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
228 CFGBlock &b = **I;
229 if (!live[b.getBlockID()]) {
230 if (b.pred_begin() == b.pred_end()) {
231 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
232 // When not adding EH edges from calls, catch clauses
233 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000234 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000235 continue;
236 }
237 }
238 }
239
240 // Now we know what is live, we check the live precessors of the exit block
241 // and look for fall through paths, being careful to ignore normal returns,
242 // and exceptional paths.
243 bool HasLiveReturn = false;
244 bool HasFakeEdge = false;
245 bool HasPlainEdge = false;
246 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000247
248 // Ignore default cases that aren't likely to be reachable because all
249 // enums in a switch(X) have explicit case statements.
250 CFGBlock::FilterOptions FO;
251 FO.IgnoreDefaultsWithCoveredEnums = 1;
252
253 for (CFGBlock::filtered_pred_iterator
254 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
255 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000256 if (!live[B.getBlockID()])
257 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000258
Chandler Carruth03faf782011-09-13 09:53:58 +0000259 // Skip blocks which contain an element marked as no-return. They don't
260 // represent actually viable edges into the exit block, so mark them as
261 // abnormal.
262 if (B.hasNoReturnElement()) {
263 HasAbnormalEdge = true;
264 continue;
265 }
266
Ted Kremenek5d068492011-01-26 04:49:52 +0000267 // Destructors can appear after the 'return' in the CFG. This is
268 // normal. We need to look pass the destructors for the return
269 // statement (if it exists).
270 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000271
Chandler Carruth03faf782011-09-13 09:53:58 +0000272 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000273 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000274 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000275
Ted Kremenek5d068492011-01-26 04:49:52 +0000276 // No more CFGElements in the block?
277 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000278 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
279 HasAbnormalEdge = true;
280 continue;
281 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000282 // A labeled empty statement, or the entry block...
283 HasPlainEdge = true;
284 continue;
285 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000286
David Blaikie2a01f5d2013-02-21 20:58:29 +0000287 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000288 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000289 if (isa<ReturnStmt>(S)) {
290 HasLiveReturn = true;
291 continue;
292 }
293 if (isa<ObjCAtThrowStmt>(S)) {
294 HasFakeEdge = true;
295 continue;
296 }
297 if (isa<CXXThrowExpr>(S)) {
298 HasFakeEdge = true;
299 continue;
300 }
Chad Rosier32503022012-06-11 20:47:18 +0000301 if (isa<MSAsmStmt>(S)) {
302 // TODO: Verify this is correct.
303 HasFakeEdge = true;
304 HasLiveReturn = true;
305 continue;
306 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000307 if (isa<CXXTryStmt>(S)) {
308 HasAbnormalEdge = true;
309 continue;
310 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000311 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
312 == B.succ_end()) {
313 HasAbnormalEdge = true;
314 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000315 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000316
317 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000318 }
319 if (!HasPlainEdge) {
320 if (HasLiveReturn)
321 return NeverFallThrough;
322 return NeverFallThroughOrReturn;
323 }
324 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
325 return MaybeFallThrough;
326 // This says AlwaysFallThrough for calls to functions that are not marked
327 // noreturn, that don't return. If people would like this warning to be more
328 // accurate, such functions should be marked as noreturn.
329 return AlwaysFallThrough;
330}
331
Dan Gohman28ade552010-07-26 21:25:24 +0000332namespace {
333
Ted Kremenek918fe842010-03-20 21:06:02 +0000334struct CheckFallThroughDiagnostics {
335 unsigned diag_MaybeFallThrough_HasNoReturn;
336 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
337 unsigned diag_AlwaysFallThrough_HasNoReturn;
338 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
339 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000340 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000341 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000342
Douglas Gregor24f27692010-04-16 23:28:44 +0000343 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000344 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000345 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000346 D.diag_MaybeFallThrough_HasNoReturn =
347 diag::warn_falloff_noreturn_function;
348 D.diag_MaybeFallThrough_ReturnsNonVoid =
349 diag::warn_maybe_falloff_nonvoid_function;
350 D.diag_AlwaysFallThrough_HasNoReturn =
351 diag::warn_falloff_noreturn_function;
352 D.diag_AlwaysFallThrough_ReturnsNonVoid =
353 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000354
355 // Don't suggest that virtual functions be marked "noreturn", since they
356 // might be overridden by non-noreturn functions.
357 bool isVirtualMethod = false;
358 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
359 isVirtualMethod = Method->isVirtual();
360
Douglas Gregor0de57202011-10-10 18:15:57 +0000361 // Don't suggest that template instantiations be marked "noreturn"
362 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000363 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
364 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000365
366 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000367 D.diag_NeverFallThroughOrReturn =
368 diag::warn_suggest_noreturn_function;
369 else
370 D.diag_NeverFallThroughOrReturn = 0;
371
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000372 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000373 return D;
374 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000375
Ted Kremenek918fe842010-03-20 21:06:02 +0000376 static CheckFallThroughDiagnostics MakeForBlock() {
377 CheckFallThroughDiagnostics D;
378 D.diag_MaybeFallThrough_HasNoReturn =
379 diag::err_noreturn_block_has_return_expr;
380 D.diag_MaybeFallThrough_ReturnsNonVoid =
381 diag::err_maybe_falloff_nonvoid_block;
382 D.diag_AlwaysFallThrough_HasNoReturn =
383 diag::err_noreturn_block_has_return_expr;
384 D.diag_AlwaysFallThrough_ReturnsNonVoid =
385 diag::err_falloff_nonvoid_block;
386 D.diag_NeverFallThroughOrReturn =
387 diag::warn_suggest_noreturn_block;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000388 D.funMode = Block;
389 return D;
390 }
391
392 static CheckFallThroughDiagnostics MakeForLambda() {
393 CheckFallThroughDiagnostics D;
394 D.diag_MaybeFallThrough_HasNoReturn =
395 diag::err_noreturn_lambda_has_return_expr;
396 D.diag_MaybeFallThrough_ReturnsNonVoid =
397 diag::warn_maybe_falloff_nonvoid_lambda;
398 D.diag_AlwaysFallThrough_HasNoReturn =
399 diag::err_noreturn_lambda_has_return_expr;
400 D.diag_AlwaysFallThrough_ReturnsNonVoid =
401 diag::warn_falloff_nonvoid_lambda;
402 D.diag_NeverFallThroughOrReturn = 0;
403 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000404 return D;
405 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000406
David Blaikie9c902b52011-09-25 23:23:43 +0000407 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000408 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000409 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000410 return (ReturnsVoid ||
411 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000412 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000413 && (!HasNoReturn ||
414 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000415 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000416 && (!ReturnsVoid ||
417 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000418 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000419 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000420
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000421 // For blocks / lambdas.
422 return ReturnsVoid && !HasNoReturn
423 && ((funMode == Lambda) ||
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000424 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000425 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000426 }
427};
428
Dan Gohman28ade552010-07-26 21:25:24 +0000429}
430
Ted Kremenek918fe842010-03-20 21:06:02 +0000431/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
432/// function that should return a value. Check that we don't fall off the end
433/// of a noreturn function. We assume that functions and blocks not marked
434/// noreturn will return.
435static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000436 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000437 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000438 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000439
440 bool ReturnsVoid = false;
441 bool HasNoReturn = false;
442
443 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000444 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000445 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000446 }
447 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000448 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000449 HasNoReturn = MD->hasAttr<NoReturnAttr>();
450 }
451 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000452 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000453 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000454 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000455 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000456 ReturnsVoid = true;
457 if (FT->getNoReturnAttr())
458 HasNoReturn = true;
459 }
460 }
461
David Blaikie9c902b52011-09-25 23:23:43 +0000462 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000463
464 // Short circuit for compilation speed.
465 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
466 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000467
Ted Kremenek918fe842010-03-20 21:06:02 +0000468 // FIXME: Function try block
469 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
470 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000471 case UnknownFallThrough:
472 break;
473
Ted Kremenek918fe842010-03-20 21:06:02 +0000474 case MaybeFallThrough:
475 if (HasNoReturn)
476 S.Diag(Compound->getRBracLoc(),
477 CD.diag_MaybeFallThrough_HasNoReturn);
478 else if (!ReturnsVoid)
479 S.Diag(Compound->getRBracLoc(),
480 CD.diag_MaybeFallThrough_ReturnsNonVoid);
481 break;
482 case AlwaysFallThrough:
483 if (HasNoReturn)
484 S.Diag(Compound->getRBracLoc(),
485 CD.diag_AlwaysFallThrough_HasNoReturn);
486 else if (!ReturnsVoid)
487 S.Diag(Compound->getRBracLoc(),
488 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
489 break;
490 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000491 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
492 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
493 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000494 << 0 << FD;
495 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
496 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
497 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000498 } else {
499 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
500 }
501 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000502 break;
503 case NeverFallThrough:
504 break;
505 }
506 }
507}
508
509//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000510// -Wuninitialized
511//===----------------------------------------------------------------------===//
512
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000513namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000514/// ContainsReference - A visitor class to search for references to
515/// a particular declaration (the needle) within any evaluated component of an
516/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000517class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000518 bool FoundReference;
519 const DeclRefExpr *Needle;
520
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000521public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000522 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
523 : EvaluatedExprVisitor<ContainsReference>(Context),
524 FoundReference(false), Needle(Needle) {}
525
526 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000527 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000528 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000529 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000530
531 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000532 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000533
534 void VisitDeclRefExpr(DeclRefExpr *E) {
535 if (E == Needle)
536 FoundReference = true;
537 else
538 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000539 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000540
541 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000542};
543}
544
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000545static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000546 QualType VariableTy = VD->getType().getCanonicalType();
547 if (VariableTy->isBlockPointerType() &&
548 !VD->hasAttr<BlocksAttr>()) {
549 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
550 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
551 return true;
552 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000553
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000554 // Don't issue a fixit if there is already an initializer.
555 if (VD->getInit())
556 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000557
558 // Don't suggest a fixit inside macros.
559 if (VD->getLocEnd().isMacroID())
560 return false;
561
Richard Smith8d06f422012-01-12 23:53:29 +0000562 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000563
564 // Suggest possible initialization (if any).
565 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
566 if (Init.empty())
567 return false;
568
Richard Smith8d06f422012-01-12 23:53:29 +0000569 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
570 << FixItHint::CreateInsertion(Loc, Init);
571 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000572}
573
Richard Smith1bb8edb82012-05-26 06:20:46 +0000574/// Create a fixit to remove an if-like statement, on the assumption that its
575/// condition is CondVal.
576static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
577 const Stmt *Else, bool CondVal,
578 FixItHint &Fixit1, FixItHint &Fixit2) {
579 if (CondVal) {
580 // If condition is always true, remove all but the 'then'.
581 Fixit1 = FixItHint::CreateRemoval(
582 CharSourceRange::getCharRange(If->getLocStart(),
583 Then->getLocStart()));
584 if (Else) {
585 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
586 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
587 Fixit2 = FixItHint::CreateRemoval(
588 SourceRange(ElseKwLoc, Else->getLocEnd()));
589 }
590 } else {
591 // If condition is always false, remove all but the 'else'.
592 if (Else)
593 Fixit1 = FixItHint::CreateRemoval(
594 CharSourceRange::getCharRange(If->getLocStart(),
595 Else->getLocStart()));
596 else
597 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
598 }
599}
600
601/// DiagUninitUse -- Helper function to produce a diagnostic for an
602/// uninitialized use of a variable.
603static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
604 bool IsCapturedByBlock) {
605 bool Diagnosed = false;
606
Richard Smithba8071e2013-09-12 18:49:10 +0000607 switch (Use.getKind()) {
608 case UninitUse::Always:
609 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
610 << VD->getDeclName() << IsCapturedByBlock
611 << Use.getUser()->getSourceRange();
612 return;
613
614 case UninitUse::AfterDecl:
615 case UninitUse::AfterCall:
616 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
617 << VD->getDeclName() << IsCapturedByBlock
618 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
619 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
620 << VD->getSourceRange();
621 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
622 << IsCapturedByBlock << Use.getUser()->getSourceRange();
623 return;
624
625 case UninitUse::Maybe:
626 case UninitUse::Sometimes:
627 // Carry on to report sometimes-uninitialized branches, if possible,
628 // or a 'may be used uninitialized' diagnostic otherwise.
629 break;
630 }
631
Richard Smith1bb8edb82012-05-26 06:20:46 +0000632 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000633 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
634 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000635 assert(Use.getKind() == UninitUse::Sometimes);
636
637 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000638 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000639
640 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000641 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000642 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000643 SourceRange Range;
644
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000645 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000646 // For all binary terminators, branch 0 is taken if the condition is true,
647 // and branch 1 is taken if the condition is false.
648 int RemoveDiagKind = -1;
649 const char *FixitStr =
650 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
651 : (I->Output ? "1" : "0");
652 FixItHint Fixit1, Fixit2;
653
Richard Smithba8071e2013-09-12 18:49:10 +0000654 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000655 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000656 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000657 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000658 continue;
659
660 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000661 case Stmt::IfStmtClass: {
662 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000663 DiagKind = 0;
664 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000665 Range = IS->getCond()->getSourceRange();
666 RemoveDiagKind = 0;
667 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
668 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000669 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000670 }
671 case Stmt::ConditionalOperatorClass: {
672 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000673 DiagKind = 0;
674 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000675 Range = CO->getCond()->getSourceRange();
676 RemoveDiagKind = 0;
677 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
678 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000679 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000680 }
Richard Smith4323bf82012-05-25 02:17:09 +0000681 case Stmt::BinaryOperatorClass: {
682 const BinaryOperator *BO = cast<BinaryOperator>(Term);
683 if (!BO->isLogicalOp())
684 continue;
685 DiagKind = 0;
686 Str = BO->getOpcodeStr();
687 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000688 RemoveDiagKind = 0;
689 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
690 (BO->getOpcode() == BO_LOr && !I->Output))
691 // true && y -> y, false || y -> y.
692 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
693 BO->getOperatorLoc()));
694 else
695 // false && y -> false, true || y -> true.
696 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000697 break;
698 }
699
700 // "loop is entered / loop is exited".
701 case Stmt::WhileStmtClass:
702 DiagKind = 1;
703 Str = "while";
704 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000705 RemoveDiagKind = 1;
706 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000707 break;
708 case Stmt::ForStmtClass:
709 DiagKind = 1;
710 Str = "for";
711 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000712 RemoveDiagKind = 1;
713 if (I->Output)
714 Fixit1 = FixItHint::CreateRemoval(Range);
715 else
716 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000717 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000718 case Stmt::CXXForRangeStmtClass:
719 if (I->Output == 1) {
720 // The use occurs if a range-based for loop's body never executes.
721 // That may be impossible, and there's no syntactic fix for this,
722 // so treat it as a 'may be uninitialized' case.
723 continue;
724 }
725 DiagKind = 1;
726 Str = "for";
727 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
728 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000729
730 // "condition is true / loop is exited".
731 case Stmt::DoStmtClass:
732 DiagKind = 2;
733 Str = "do";
734 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000735 RemoveDiagKind = 1;
736 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000737 break;
738
739 // "switch case is taken".
740 case Stmt::CaseStmtClass:
741 DiagKind = 3;
742 Str = "case";
743 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
744 break;
745 case Stmt::DefaultStmtClass:
746 DiagKind = 3;
747 Str = "default";
748 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
749 break;
750 }
751
Richard Smith1bb8edb82012-05-26 06:20:46 +0000752 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
753 << VD->getDeclName() << IsCapturedByBlock << DiagKind
754 << Str << I->Output << Range;
755 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
756 << IsCapturedByBlock << User->getSourceRange();
757 if (RemoveDiagKind != -1)
758 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
759 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
760
761 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000762 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000763
764 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000765 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000766 << VD->getDeclName() << IsCapturedByBlock
767 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000768}
769
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000770/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
771/// uninitialized variable. This manages the different forms of diagnostic
772/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000773/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000774/// false.
775static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000776 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000777 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000778
Richard Smith4323bf82012-05-25 02:17:09 +0000779 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000780 // Inspect the initializer of the variable declaration which is
781 // being referenced prior to its initialization. We emit
782 // specialized diagnostics for self-initialization, and we
783 // specifically avoid warning about self references which take the
784 // form of:
785 //
786 // int x = x;
787 //
788 // This is used to indicate to GCC that 'x' is intentionally left
789 // uninitialized. Proven code paths which access 'x' in
790 // an uninitialized state after this will still warn.
791 if (const Expr *Initializer = VD->getInit()) {
792 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
793 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000794
Richard Trieu43a2fc72012-05-09 21:08:22 +0000795 ContainsReference CR(S.Context, DRE);
796 CR.Visit(const_cast<Expr*>(Initializer));
797 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000798 S.Diag(DRE->getLocStart(),
799 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000800 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
801 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000802 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000803 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000804
Richard Smith1bb8edb82012-05-26 06:20:46 +0000805 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000806 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000807 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000808 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
809 S.Diag(BE->getLocStart(),
810 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000811 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000812 else
813 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000814 }
815
816 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000817 // the initializer of that declaration & we didn't already suggest
818 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000819 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000820 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
821 << VD->getDeclName();
822
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000823 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000824}
825
Richard Smith84837d52012-05-03 18:27:39 +0000826namespace {
827 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
828 public:
829 FallthroughMapper(Sema &S)
830 : FoundSwitchStatements(false),
831 S(S) {
832 }
833
834 bool foundSwitchStatements() const { return FoundSwitchStatements; }
835
836 void markFallthroughVisited(const AttributedStmt *Stmt) {
837 bool Found = FallthroughStmts.erase(Stmt);
838 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000839 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000840 }
841
842 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
843
844 const AttrStmts &getFallthroughStmts() const {
845 return FallthroughStmts;
846 }
847
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000848 void fillReachableBlocks(CFG *Cfg) {
849 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
850 std::deque<const CFGBlock *> BlockQueue;
851
852 ReachableBlocks.insert(&Cfg->getEntry());
853 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000854 // Mark all case blocks reachable to avoid problems with switching on
855 // constants, covered enums, etc.
856 // These blocks can contain fall-through annotations, and we don't want to
857 // issue a warn_fallthrough_attr_unreachable for them.
858 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
859 const CFGBlock *B = *I;
860 const Stmt *L = B->getLabel();
861 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
862 BlockQueue.push_back(B);
863 }
864
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000865 while (!BlockQueue.empty()) {
866 const CFGBlock *P = BlockQueue.front();
867 BlockQueue.pop_front();
868 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
869 E = P->succ_end();
870 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000871 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000872 BlockQueue.push_back(*I);
873 }
874 }
875 }
876
Richard Smith84837d52012-05-03 18:27:39 +0000877 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000878 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
879
Richard Smith84837d52012-05-03 18:27:39 +0000880 int UnannotatedCnt = 0;
881 AnnotatedCnt = 0;
882
883 std::deque<const CFGBlock*> BlockQueue;
884
885 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
886
887 while (!BlockQueue.empty()) {
888 const CFGBlock *P = BlockQueue.front();
889 BlockQueue.pop_front();
890
891 const Stmt *Term = P->getTerminator();
892 if (Term && isa<SwitchStmt>(Term))
893 continue; // Switch statement, good.
894
895 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
896 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
897 continue; // Previous case label has no statements, good.
898
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000899 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
900 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
901 continue; // Case label is preceded with a normal label, good.
902
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000903 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000904 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
905 ElemEnd = P->rend();
906 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000907 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
908 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000909 S.Diag(AS->getLocStart(),
910 diag::warn_fallthrough_attr_unreachable);
911 markFallthroughVisited(AS);
912 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000913 break;
Richard Smith84837d52012-05-03 18:27:39 +0000914 }
915 // Don't care about other unreachable statements.
916 }
917 }
918 // If there are no unreachable statements, this may be a special
919 // case in CFG:
920 // case X: {
921 // A a; // A has a destructor.
922 // break;
923 // }
924 // // <<<< This place is represented by a 'hanging' CFG block.
925 // case Y:
926 continue;
927 }
928
929 const Stmt *LastStmt = getLastStmt(*P);
930 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
931 markFallthroughVisited(AS);
932 ++AnnotatedCnt;
933 continue; // Fallthrough annotation, good.
934 }
935
936 if (!LastStmt) { // This block contains no executable statements.
937 // Traverse its predecessors.
938 std::copy(P->pred_begin(), P->pred_end(),
939 std::back_inserter(BlockQueue));
940 continue;
941 }
942
943 ++UnannotatedCnt;
944 }
945 return !!UnannotatedCnt;
946 }
947
948 // RecursiveASTVisitor setup.
949 bool shouldWalkTypesOfTypeLocs() const { return false; }
950
951 bool VisitAttributedStmt(AttributedStmt *S) {
952 if (asFallThroughAttr(S))
953 FallthroughStmts.insert(S);
954 return true;
955 }
956
957 bool VisitSwitchStmt(SwitchStmt *S) {
958 FoundSwitchStatements = true;
959 return true;
960 }
961
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000962 // We don't want to traverse local type declarations. We analyze their
963 // methods separately.
964 bool TraverseDecl(Decl *D) { return true; }
965
Richard Smith84837d52012-05-03 18:27:39 +0000966 private:
967
968 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
969 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
970 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
971 return AS;
972 }
973 return 0;
974 }
975
976 static const Stmt *getLastStmt(const CFGBlock &B) {
977 if (const Stmt *Term = B.getTerminator())
978 return Term;
979 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
980 ElemEnd = B.rend();
981 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000982 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
983 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +0000984 }
985 // Workaround to detect a statement thrown out by CFGBuilder:
986 // case X: {} case Y:
987 // case X: ; case Y:
988 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
989 if (!isa<SwitchCase>(SW->getSubStmt()))
990 return SW->getSubStmt();
991
992 return 0;
993 }
994
995 bool FoundSwitchStatements;
996 AttrStmts FallthroughStmts;
997 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000998 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +0000999 };
1000}
1001
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001002static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001003 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001004 // Only perform this analysis when using C++11. There is no good workflow
1005 // for this warning when not using C++11. There is no good way to silence
1006 // the warning (no attribute is available) unless we are using C++11's support
1007 // for generalized attributes. Once could use pragmas to silence the warning,
1008 // but as a general solution that is gross and not in the spirit of this
1009 // warning.
1010 //
1011 // NOTE: This an intermediate solution. There are on-going discussions on
1012 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001013 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001014 return;
1015
Richard Smith84837d52012-05-03 18:27:39 +00001016 FallthroughMapper FM(S);
1017 FM.TraverseStmt(AC.getBody());
1018
1019 if (!FM.foundSwitchStatements())
1020 return;
1021
Alexis Hunt2178f142012-06-15 21:22:05 +00001022 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001023 return;
1024
Richard Smith84837d52012-05-03 18:27:39 +00001025 CFG *Cfg = AC.getCFG();
1026
1027 if (!Cfg)
1028 return;
1029
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001030 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001031
1032 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001033 const CFGBlock *B = *I;
1034 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001035
1036 if (!Label || !isa<SwitchCase>(Label))
1037 continue;
1038
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001039 int AnnotatedCnt;
1040
Alexander Kornienko55488792013-01-25 15:49:34 +00001041 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001042 continue;
1043
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001044 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001045 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1046 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001047
1048 if (!AnnotatedCnt) {
1049 SourceLocation L = Label->getLocStart();
1050 if (L.isMacroID())
1051 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001052 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001053 const Stmt *Term = B->getTerminator();
1054 // Skip empty cases.
1055 while (B->empty() && !Term && B->succ_size() == 1) {
1056 B = *B->succ_begin();
1057 Term = B->getTerminator();
1058 }
1059 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001060 Preprocessor &PP = S.getPreprocessor();
1061 TokenValue Tokens[] = {
1062 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1063 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1064 tok::r_square, tok::r_square
1065 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001066 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1067 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1068 if (!MacroName.empty())
1069 AnnotationSpelling = MacroName;
1070 SmallString<64> TextToInsert(AnnotationSpelling);
1071 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001072 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001073 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001074 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001075 }
Richard Smith84837d52012-05-03 18:27:39 +00001076 }
1077 S.Diag(L, diag::note_insert_break_fixit) <<
1078 FixItHint::CreateInsertion(L, "break; ");
1079 }
1080 }
1081
1082 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1083 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1084 E = Fallthroughs.end();
1085 I != E; ++I) {
1086 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1087 }
1088
1089}
1090
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001091namespace {
Jordan Rosed61f3b42012-09-28 22:29:02 +00001092typedef std::pair<const Stmt *,
1093 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
1094 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001095
Jordan Rosed61f3b42012-09-28 22:29:02 +00001096class StmtUseSorter {
Jordan Rosed3934582012-09-28 22:21:30 +00001097 const SourceManager &SM;
1098
1099public:
Jordan Rosed61f3b42012-09-28 22:29:02 +00001100 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
Jordan Rosed3934582012-09-28 22:21:30 +00001101
1102 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1103 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1104 RHS.first->getLocStart());
1105 }
1106};
Jordan Rosed61f3b42012-09-28 22:29:02 +00001107}
Jordan Rosed3934582012-09-28 22:21:30 +00001108
Jordan Rose25c0ea82012-10-29 17:46:47 +00001109static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1110 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001111 assert(S);
1112
1113 do {
1114 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001115 case Stmt::ForStmtClass:
1116 case Stmt::WhileStmtClass:
1117 case Stmt::CXXForRangeStmtClass:
1118 case Stmt::ObjCForCollectionStmtClass:
1119 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001120 case Stmt::DoStmtClass: {
1121 const Expr *Cond = cast<DoStmt>(S)->getCond();
1122 llvm::APSInt Val;
1123 if (!Cond->EvaluateAsInt(Val, Ctx))
1124 return true;
1125 return Val.getBoolValue();
1126 }
Jordan Rose76831c62012-10-11 16:10:19 +00001127 default:
1128 break;
1129 }
1130 } while ((S = PM.getParent(S)));
1131
1132 return false;
1133}
1134
Jordan Rosed3934582012-09-28 22:21:30 +00001135
1136static void diagnoseRepeatedUseOfWeak(Sema &S,
1137 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001138 const Decl *D,
1139 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001140 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1141 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1142 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1143
Jordan Rose25c0ea82012-10-29 17:46:47 +00001144 ASTContext &Ctx = S.getASTContext();
1145
Jordan Rosed3934582012-09-28 22:21:30 +00001146 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1147
1148 // Extract all weak objects that are referenced more than once.
1149 SmallVector<StmtUsesPair, 8> UsesByStmt;
1150 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1151 I != E; ++I) {
1152 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001153
1154 // Find the first read of the weak object.
1155 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1156 for ( ; UI != UE; ++UI) {
1157 if (UI->isUnsafe())
1158 break;
1159 }
1160
1161 // If there were only writes to this object, don't warn.
1162 if (UI == UE)
1163 continue;
1164
Jordan Rose76831c62012-10-11 16:10:19 +00001165 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001166 // read is not within a loop, don't warn. Additionally, don't warn in a
1167 // loop if the base object is a local variable -- local variables are often
1168 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001169 if (UI == Uses.begin()) {
1170 WeakUseVector::const_iterator UI2 = UI;
1171 for (++UI2; UI2 != UE; ++UI2)
1172 if (UI2->isUnsafe())
1173 break;
1174
Jordan Rose25c0ea82012-10-29 17:46:47 +00001175 if (UI2 == UE) {
1176 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001177 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001178
1179 const WeakObjectProfileTy &Profile = I->first;
1180 if (!Profile.isExactProfile())
1181 continue;
1182
1183 const NamedDecl *Base = Profile.getBase();
1184 if (!Base)
1185 Base = Profile.getProperty();
1186 assert(Base && "A profile always has a base or property.");
1187
1188 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1189 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1190 continue;
1191 }
Jordan Rose76831c62012-10-11 16:10:19 +00001192 }
1193
Jordan Rosed3934582012-09-28 22:21:30 +00001194 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1195 }
1196
1197 if (UsesByStmt.empty())
1198 return;
1199
1200 // Sort by first use so that we emit the warnings in a deterministic order.
1201 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Jordan Rosed61f3b42012-09-28 22:29:02 +00001202 StmtUseSorter(S.getSourceManager()));
Jordan Rosed3934582012-09-28 22:21:30 +00001203
1204 // Classify the current code body for better warning text.
1205 // This enum should stay in sync with the cases in
1206 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1207 // FIXME: Should we use a common classification enum and the same set of
1208 // possibilities all throughout Sema?
1209 enum {
1210 Function,
1211 Method,
1212 Block,
1213 Lambda
1214 } FunctionKind;
1215
1216 if (isa<sema::BlockScopeInfo>(CurFn))
1217 FunctionKind = Block;
1218 else if (isa<sema::LambdaScopeInfo>(CurFn))
1219 FunctionKind = Lambda;
1220 else if (isa<ObjCMethodDecl>(D))
1221 FunctionKind = Method;
1222 else
1223 FunctionKind = Function;
1224
1225 // Iterate through the sorted problems and emit warnings for each.
1226 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1227 E = UsesByStmt.end();
1228 I != E; ++I) {
1229 const Stmt *FirstRead = I->first;
1230 const WeakObjectProfileTy &Key = I->second->first;
1231 const WeakUseVector &Uses = I->second->second;
1232
Jordan Rose657b5f42012-09-28 22:21:35 +00001233 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1234 // may not contain enough information to determine that these are different
1235 // properties. We can only be 100% sure of a repeated use in certain cases,
1236 // and we adjust the diagnostic kind accordingly so that the less certain
1237 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001238 unsigned DiagKind;
1239 if (Key.isExactProfile())
1240 DiagKind = diag::warn_arc_repeated_use_of_weak;
1241 else
1242 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1243
Jordan Rose657b5f42012-09-28 22:21:35 +00001244 // Classify the weak object being accessed for better warning text.
1245 // This enum should stay in sync with the cases in
1246 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1247 enum {
1248 Variable,
1249 Property,
1250 ImplicitProperty,
1251 Ivar
1252 } ObjectKind;
1253
1254 const NamedDecl *D = Key.getProperty();
1255 if (isa<VarDecl>(D))
1256 ObjectKind = Variable;
1257 else if (isa<ObjCPropertyDecl>(D))
1258 ObjectKind = Property;
1259 else if (isa<ObjCMethodDecl>(D))
1260 ObjectKind = ImplicitProperty;
1261 else if (isa<ObjCIvarDecl>(D))
1262 ObjectKind = Ivar;
1263 else
1264 llvm_unreachable("Unexpected weak object kind!");
1265
Jordan Rosed3934582012-09-28 22:21:30 +00001266 // Show the first time the object was read.
1267 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001268 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001269 << FirstRead->getSourceRange();
1270
1271 // Print all the other accesses as notes.
1272 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1273 UI != UE; ++UI) {
1274 if (UI->getUseExpr() == FirstRead)
1275 continue;
1276 S.Diag(UI->getUseExpr()->getLocStart(),
1277 diag::note_arc_weak_also_accessed_here)
1278 << UI->getUseExpr()->getSourceRange();
1279 }
1280 }
1281}
1282
1283
1284namespace {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001285struct SLocSort {
Ted Kremenekc8c4e5f2011-03-15 04:57:38 +00001286 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith4323bf82012-05-25 02:17:09 +00001287 // Prefer a more confident report over a less confident one.
1288 if (a.getKind() != b.getKind())
1289 return a.getKind() > b.getKind();
1290 SourceLocation aLoc = a.getUser()->getLocStart();
1291 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek39fa0562011-01-21 19:41:41 +00001292 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1293 }
1294};
1295
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001296class UninitValsDiagReporter : public UninitVariablesHandler {
1297 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001298 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001299 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001300 // Prefer using MapVector to DenseMap, so that iteration order will be
1301 // the same as insertion order. This is needed to obtain a deterministic
1302 // order of diagnostics when calling flushDiagnostics().
1303 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001304 UsesMap *uses;
1305
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001306public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001307 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1308 ~UninitValsDiagReporter() {
1309 flushDiagnostics();
1310 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001311
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001312 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001313 if (!uses)
1314 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001315
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001316 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001317 if (!V.getPointer())
1318 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001319
Ted Kremenek596fa162011-10-13 18:50:06 +00001320 return V;
1321 }
1322
Richard Smith4323bf82012-05-25 02:17:09 +00001323 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001324 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001325 }
1326
1327 void handleSelfInit(const VarDecl *vd) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001328 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001329 }
1330
1331 void flushDiagnostics() {
1332 if (!uses)
1333 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001334
Ted Kremenek39fa0562011-01-21 19:41:41 +00001335 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1336 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001337 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001338
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001339 UsesVec *vec = V.getPointer();
1340 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001341
1342 // Specially handle the case where we have uses of an uninitialized
1343 // variable, but the root cause is an idiomatic self-init. We want
1344 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001345 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001346 DiagnoseUninitializedUse(S, vd,
1347 UninitUse(vd->getInit()->IgnoreParenCasts(),
1348 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001349 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001350 else {
1351 // Sort the uses by their SourceLocations. While not strictly
1352 // guaranteed to produce them in line/column order, this will provide
1353 // a stable ordering.
1354 std::sort(vec->begin(), vec->end(), SLocSort());
1355
1356 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1357 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001358 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1359 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1360
1361 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001362 // Skip further diagnostics for this variable. We try to warn only
1363 // on the first point at which a variable is used uninitialized.
1364 break;
1365 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001366 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001367
1368 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001369 delete vec;
1370 }
1371 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001372 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001373
1374private:
1375 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1376 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001377 if (i->getKind() == UninitUse::Always ||
1378 i->getKind() == UninitUse::AfterCall ||
1379 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001380 return true;
1381 }
1382 }
1383 return false;
1384}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001385};
1386}
1387
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001388namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001389namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001390typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001391typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001392typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001393
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001394struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001395 SourceManager &SM;
1396 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001397
1398 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1399 // Although this call will be slow, this is only called when outputting
1400 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001401 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001402 }
1403};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001404}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001405
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001406//===----------------------------------------------------------------------===//
1407// -Wthread-safety
1408//===----------------------------------------------------------------------===//
1409namespace clang {
1410namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001411namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001412class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1413 Sema &S;
1414 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001415 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001416
1417 // Helper functions
1418 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001419 // Gracefully handle rare cases when the analysis can't get a more
1420 // precise source location.
1421 if (!Loc.isValid())
1422 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001423 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1424 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001425 }
1426
1427 public:
Richard Smith92286672012-02-03 04:45:26 +00001428 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1429 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001430
1431 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1432 /// We need to output diagnostics produced while iterating through
1433 /// the lockset in deterministic order, so this function orders diagnostics
1434 /// and outputs them.
1435 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001436 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001437 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001438 I != E; ++I) {
1439 S.Diag(I->first.first, I->first.second);
1440 const OptionalNotes &Notes = I->second;
1441 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1442 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1443 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001444 }
1445
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001446 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001447 PartialDiagnosticAt Warning(Loc,
1448 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1449 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001450 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001451 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1452 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1453 }
1454
1455 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1456 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1457 }
1458
Richard Smith92286672012-02-03 04:45:26 +00001459 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1460 SourceLocation LocEndOfScope,
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001461 LockErrorKind LEK){
1462 unsigned DiagID = 0;
1463 switch (LEK) {
1464 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001465 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001466 break;
1467 case LEK_LockedSomeLoopIterations:
1468 DiagID = diag::warn_expecting_lock_held_on_loop;
1469 break;
1470 case LEK_LockedAtEndOfFunction:
1471 DiagID = diag::warn_no_unlock;
1472 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001473 case LEK_NotLockedAtEndOfFunction:
1474 DiagID = diag::warn_expecting_locked;
1475 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001476 }
Richard Smith92286672012-02-03 04:45:26 +00001477 if (LocEndOfScope.isInvalid())
1478 LocEndOfScope = FunEndLocation;
1479
1480 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001481 if (LocLocked.isValid()) {
1482 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1483 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1484 return;
1485 }
1486 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001487 }
1488
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001489
1490 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1491 SourceLocation Loc2) {
Richard Smith92286672012-02-03 04:45:26 +00001492 PartialDiagnosticAt Warning(
1493 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1494 PartialDiagnosticAt Note(
1495 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1496 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001497 }
1498
1499 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1500 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001501 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1502 && "Only works for variables");
1503 unsigned DiagID = POK == POK_VarAccess?
1504 diag::warn_variable_requires_any_lock:
1505 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001506 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001507 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001508 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001509 }
1510
1511 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001512 Name LockName, LockKind LK, SourceLocation Loc,
1513 Name *PossibleMatch) {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001514 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001515 if (PossibleMatch) {
1516 switch (POK) {
1517 case POK_VarAccess:
1518 DiagID = diag::warn_variable_requires_lock_precise;
1519 break;
1520 case POK_VarDereference:
1521 DiagID = diag::warn_var_deref_requires_lock_precise;
1522 break;
1523 case POK_FunctionCall:
1524 DiagID = diag::warn_fun_requires_lock_precise;
1525 break;
1526 }
1527 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001528 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001529 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1530 << *PossibleMatch);
1531 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1532 } else {
1533 switch (POK) {
1534 case POK_VarAccess:
1535 DiagID = diag::warn_variable_requires_lock;
1536 break;
1537 case POK_VarDereference:
1538 DiagID = diag::warn_var_deref_requires_lock;
1539 break;
1540 case POK_FunctionCall:
1541 DiagID = diag::warn_fun_requires_lock;
1542 break;
1543 }
1544 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001545 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001546 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001547 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001548 }
1549
1550 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001551 PartialDiagnosticAt Warning(Loc,
1552 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1553 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001554 }
1555};
1556}
1557}
David Blaikie68e081d2011-12-20 02:48:34 +00001558}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001559
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001560//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001561// -Wconsumed
1562//===----------------------------------------------------------------------===//
1563
1564namespace clang {
1565namespace consumed {
1566namespace {
1567class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1568
1569 Sema &S;
1570 DiagList Warnings;
1571
1572public:
1573
1574 ConsumedWarningsHandler(Sema &S) : S(S) {}
1575
1576 void emitDiagnostics() {
1577 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1578
1579 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1580 I != E; ++I) {
1581
1582 const OptionalNotes &Notes = I->second;
1583 S.Diag(I->first.first, I->first.second);
1584
1585 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1586 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1587 }
1588 }
1589 }
1590
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001591 void warnLoopStateMismatch(SourceLocation Loc, StringRef VariableName) {
1592 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1593 VariableName);
1594
1595 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1596 }
1597
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001598 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1599 StringRef VariableName,
1600 StringRef ExpectedState,
1601 StringRef ObservedState) {
1602
1603 PartialDiagnosticAt Warning(Loc, S.PDiag(
1604 diag::warn_param_return_typestate_mismatch) << VariableName <<
1605 ExpectedState << ObservedState);
1606
1607 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1608 }
1609
DeLesley Hutchins69391772013-10-17 23:23:53 +00001610 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1611 StringRef ObservedState) {
1612
1613 PartialDiagnosticAt Warning(Loc, S.PDiag(
1614 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1615
1616 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1617 }
1618
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001619 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1620 StringRef TypeName) {
1621 PartialDiagnosticAt Warning(Loc, S.PDiag(
1622 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1623
1624 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1625 }
1626
1627 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1628 StringRef ObservedState) {
1629
1630 PartialDiagnosticAt Warning(Loc, S.PDiag(
1631 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1632
1633 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1634 }
1635
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001636 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1637 SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001638
1639 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001640 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001641
1642 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1643 }
1644
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001645 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1646 StringRef State, SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001647
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001648 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1649 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001650
1651 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1652 }
1653};
1654}}}
1655
1656//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001657// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1658// warnings on a function, method, or block.
1659//===----------------------------------------------------------------------===//
1660
Ted Kremenek0b405322010-03-23 00:13:23 +00001661clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1662 enableCheckFallThrough = 1;
1663 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001664 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001665 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001666}
1667
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001668clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1669 : S(s),
1670 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001671 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001672 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001673 MaxCFGBlocksPerFunction(0),
1674 NumUninitAnalysisFunctions(0),
1675 NumUninitAnalysisVariables(0),
1676 MaxUninitAnalysisVariablesPerFunction(0),
1677 NumUninitAnalysisBlockVisits(0),
1678 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikie9c902b52011-09-25 23:23:43 +00001679 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenek0b405322010-03-23 00:13:23 +00001680 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001681 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001682 DiagnosticsEngine::Ignored);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001683 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1684 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001685 DiagnosticsEngine::Ignored);
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001686 DefaultPolicy.enableConsumedAnalysis = (unsigned)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001687 (D.getDiagnosticLevel(diag::warn_use_in_invalid_state, SourceLocation()) !=
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001688 DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +00001689}
1690
Ted Kremenek3427fac2011-02-23 01:52:04 +00001691static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001692 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001693 i = fscope->PossiblyUnreachableDiags.begin(),
1694 e = fscope->PossiblyUnreachableDiags.end();
1695 i != e; ++i) {
1696 const sema::PossiblyUnreachableDiag &D = *i;
1697 S.Diag(D.Loc, D.PD);
1698 }
1699}
1700
Ted Kremenek0b405322010-03-23 00:13:23 +00001701void clang::sema::
1702AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001703 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001704 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001705
Ted Kremenek918fe842010-03-20 21:06:02 +00001706 // We avoid doing analysis-based warnings when there are errors for
1707 // two reasons:
1708 // (1) The CFGs often can't be constructed (if the body is invalid), so
1709 // don't bother trying.
1710 // (2) The code already has problems; running the analysis just takes more
1711 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001712 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001713
Ted Kremenek0b405322010-03-23 00:13:23 +00001714 // Do not do any analysis for declarations in system headers if we are
1715 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001716 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001717 S.SourceMgr.isInSystemHeader(D->getLocation()))
1718 return;
1719
John McCall1d570a72010-08-25 05:56:39 +00001720 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001721 if (cast<DeclContext>(D)->isDependentContext())
1722 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001723
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001724 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001725 // Flush out any possibly unreachable diagnostics.
1726 flushDiagnostics(S, fscope);
1727 return;
1728 }
1729
Ted Kremenek918fe842010-03-20 21:06:02 +00001730 const Stmt *Body = D->getBody();
1731 assert(Body);
1732
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001733 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001734 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001735
Ted Kremenek918fe842010-03-20 21:06:02 +00001736 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001737 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001738 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1739 AC.getCFGBuildOptions().AddEHEdges = false;
1740 AC.getCFGBuildOptions().AddInitializers = true;
1741 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001742 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001743 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001744
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001745 // Force that certain expressions appear as CFGElements in the CFG. This
1746 // is used to speed up various analyses.
1747 // FIXME: This isn't the right factoring. This is here for initial
1748 // prototyping, but we need a way for analyses to say what expressions they
1749 // expect to always be CFGElements and then fill in the BuildOptions
1750 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001751 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1752 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001753 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001754 AC.getCFGBuildOptions().setAllAlwaysAdd();
1755 }
1756 else {
1757 AC.getCFGBuildOptions()
1758 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001759 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001760 .setAlwaysAdd(Stmt::BlockExprClass)
1761 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1762 .setAlwaysAdd(Stmt::DeclRefExprClass)
1763 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001764 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1765 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001766 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001767
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001768
Ted Kremenek3427fac2011-02-23 01:52:04 +00001769 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001770 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001771 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001772
1773 // Register the expressions with the CFGBuilder.
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 if (const Stmt *stmt = i->stmt)
1779 AC.registerForcedBlockExpression(stmt);
1780 }
1781
1782 if (AC.getCFG()) {
1783 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001784 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001785 i = fscope->PossiblyUnreachableDiags.begin(),
1786 e = fscope->PossiblyUnreachableDiags.end();
1787 i != e; ++i)
1788 {
1789 const sema::PossiblyUnreachableDiag &D = *i;
1790 bool processed = false;
1791 if (const Stmt *stmt = i->stmt) {
1792 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001793 CFGReverseBlockReachabilityAnalysis *cra =
1794 AC.getCFGReachablityAnalysis();
1795 // FIXME: We should be able to assert that block is non-null, but
1796 // the CFG analysis can skip potentially-evaluated expressions in
1797 // edge cases; see test/Sema/vla-2.c.
1798 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001799 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001800 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001801 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001802 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001803 }
1804 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001805 if (!processed) {
1806 // Emit the warning anyway if we cannot map to a basic block.
1807 S.Diag(D.Loc, D.PD);
1808 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001809 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001810 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001811
1812 if (!analyzed)
1813 flushDiagnostics(S, fscope);
1814 }
1815
1816
Ted Kremenek918fe842010-03-20 21:06:02 +00001817 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001818 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001819 const CheckFallThroughDiagnostics &CD =
1820 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001821 : (isa<CXXMethodDecl>(D) &&
1822 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1823 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1824 ? CheckFallThroughDiagnostics::MakeForLambda()
1825 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001826 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001827 }
1828
1829 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001830 if (P.enableCheckUnreachable) {
1831 // Only check for unreachable code on non-template instantiations.
1832 // Different template instantiations can effectively change the control-flow
1833 // and it is very difficult to prove that a snippet of code in a template
1834 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001835 bool isTemplateInstantiation = false;
1836 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1837 isTemplateInstantiation = Function->isTemplateInstantiation();
1838 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001839 CheckUnreachable(S, AC);
1840 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001841
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001842 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001843 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001844 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001845 SourceLocation FEL = AC.getDecl()->getLocEnd();
1846 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001847 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1848 != DiagnosticsEngine::Ignored)
1849 Reporter.setIssueBetaWarnings(true);
1850
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001851 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1852 Reporter.emitDiagnostics();
1853 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001854
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001855 // Check for violations of consumed properties.
1856 if (P.enableConsumedAnalysis) {
1857 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001858 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001859 Analyzer.run(AC);
1860 }
1861
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001862 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001863 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001864 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1865 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001866 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001867 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001868 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001869 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001870 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001871 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001872 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001873 reporter, stats);
1874
1875 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1876 ++NumUninitAnalysisFunctions;
1877 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1878 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1879 MaxUninitAnalysisVariablesPerFunction =
1880 std::max(MaxUninitAnalysisVariablesPerFunction,
1881 stats.NumVariablesAnalyzed);
1882 MaxUninitAnalysisBlockVisitsPerFunction =
1883 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1884 stats.NumBlockVisits);
1885 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001886 }
1887 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001888
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001889 bool FallThroughDiagFull =
1890 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1891 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001892 bool FallThroughDiagPerFunction =
1893 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001894 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001895 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001896 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001897 }
1898
Jordan Rosed3934582012-09-28 22:21:30 +00001899 if (S.getLangOpts().ObjCARCWeak &&
1900 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1901 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001902 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001903
Richard Trieu2f024f42013-12-21 02:33:43 +00001904
1905 // Check for infinite self-recursion in functions
1906 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1907 D->getLocStart())
1908 != DiagnosticsEngine::Ignored) {
1909 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1910 checkRecursiveFunction(S, FD, Body, AC);
1911 }
1912 }
1913
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001914 // Collect statistics about the CFG if it was built.
1915 if (S.CollectStats && AC.isCFGBuilt()) {
1916 ++NumFunctionsAnalyzed;
1917 if (CFG *cfg = AC.getCFG()) {
1918 // If we successfully built a CFG for this context, record some more
1919 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001920 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001921 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001922 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001923 } else {
1924 ++NumFunctionsWithBadCFGs;
1925 }
1926 }
1927}
1928
1929void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1930 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1931
1932 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1933 unsigned AvgCFGBlocksPerFunction =
1934 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1935 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1936 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1937 << " " << NumCFGBlocks << " CFG blocks built.\n"
1938 << " " << AvgCFGBlocksPerFunction
1939 << " average CFG blocks per function.\n"
1940 << " " << MaxCFGBlocksPerFunction
1941 << " max CFG blocks per function.\n";
1942
1943 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1944 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1945 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1946 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1947 llvm::errs() << NumUninitAnalysisFunctions
1948 << " functions analyzed for uninitialiazed variables\n"
1949 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1950 << " " << AvgUninitVariablesPerFunction
1951 << " average variables per function.\n"
1952 << " " << MaxUninitAnalysisVariablesPerFunction
1953 << " max variables per function.\n"
1954 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1955 << " " << AvgUninitBlockVisitsPerFunction
1956 << " average block visits per function.\n"
1957 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1958 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001959}