blob: 46243f402d0f4926dd3e8702a32662ec071848a6 [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);
Ted Kremenek2dd810a2014-03-09 08:13:49 +000087 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +000088}
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();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000890 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000891
892 const Stmt *Term = P->getTerminator();
893 if (Term && isa<SwitchStmt>(Term))
894 continue; // Switch statement, good.
895
896 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
897 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
898 continue; // Previous case label has no statements, good.
899
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000900 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
901 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
902 continue; // Case label is preceded with a normal label, good.
903
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000904 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000905 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
906 ElemEnd = P->rend();
907 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000908 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
909 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000910 S.Diag(AS->getLocStart(),
911 diag::warn_fallthrough_attr_unreachable);
912 markFallthroughVisited(AS);
913 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000914 break;
Richard Smith84837d52012-05-03 18:27:39 +0000915 }
916 // Don't care about other unreachable statements.
917 }
918 }
919 // If there are no unreachable statements, this may be a special
920 // case in CFG:
921 // case X: {
922 // A a; // A has a destructor.
923 // break;
924 // }
925 // // <<<< This place is represented by a 'hanging' CFG block.
926 // case Y:
927 continue;
928 }
929
930 const Stmt *LastStmt = getLastStmt(*P);
931 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
932 markFallthroughVisited(AS);
933 ++AnnotatedCnt;
934 continue; // Fallthrough annotation, good.
935 }
936
937 if (!LastStmt) { // This block contains no executable statements.
938 // Traverse its predecessors.
939 std::copy(P->pred_begin(), P->pred_end(),
940 std::back_inserter(BlockQueue));
941 continue;
942 }
943
944 ++UnannotatedCnt;
945 }
946 return !!UnannotatedCnt;
947 }
948
949 // RecursiveASTVisitor setup.
950 bool shouldWalkTypesOfTypeLocs() const { return false; }
951
952 bool VisitAttributedStmt(AttributedStmt *S) {
953 if (asFallThroughAttr(S))
954 FallthroughStmts.insert(S);
955 return true;
956 }
957
958 bool VisitSwitchStmt(SwitchStmt *S) {
959 FoundSwitchStatements = true;
960 return true;
961 }
962
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000963 // We don't want to traverse local type declarations. We analyze their
964 // methods separately.
965 bool TraverseDecl(Decl *D) { return true; }
966
Richard Smith84837d52012-05-03 18:27:39 +0000967 private:
968
969 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
970 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
971 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
972 return AS;
973 }
974 return 0;
975 }
976
977 static const Stmt *getLastStmt(const CFGBlock &B) {
978 if (const Stmt *Term = B.getTerminator())
979 return Term;
980 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
981 ElemEnd = B.rend();
982 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000983 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
984 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +0000985 }
986 // Workaround to detect a statement thrown out by CFGBuilder:
987 // case X: {} case Y:
988 // case X: ; case Y:
989 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
990 if (!isa<SwitchCase>(SW->getSubStmt()))
991 return SW->getSubStmt();
992
993 return 0;
994 }
995
996 bool FoundSwitchStatements;
997 AttrStmts FallthroughStmts;
998 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000999 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001000 };
1001}
1002
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001003static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001004 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001005 // Only perform this analysis when using C++11. There is no good workflow
1006 // for this warning when not using C++11. There is no good way to silence
1007 // the warning (no attribute is available) unless we are using C++11's support
1008 // for generalized attributes. Once could use pragmas to silence the warning,
1009 // but as a general solution that is gross and not in the spirit of this
1010 // warning.
1011 //
1012 // NOTE: This an intermediate solution. There are on-going discussions on
1013 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001014 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001015 return;
1016
Richard Smith84837d52012-05-03 18:27:39 +00001017 FallthroughMapper FM(S);
1018 FM.TraverseStmt(AC.getBody());
1019
1020 if (!FM.foundSwitchStatements())
1021 return;
1022
Alexis Hunt2178f142012-06-15 21:22:05 +00001023 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001024 return;
1025
Richard Smith84837d52012-05-03 18:27:39 +00001026 CFG *Cfg = AC.getCFG();
1027
1028 if (!Cfg)
1029 return;
1030
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001031 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001032
1033 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001034 const CFGBlock *B = *I;
1035 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001036
1037 if (!Label || !isa<SwitchCase>(Label))
1038 continue;
1039
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001040 int AnnotatedCnt;
1041
Alexander Kornienko55488792013-01-25 15:49:34 +00001042 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001043 continue;
1044
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001045 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001046 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1047 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001048
1049 if (!AnnotatedCnt) {
1050 SourceLocation L = Label->getLocStart();
1051 if (L.isMacroID())
1052 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001053 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001054 const Stmt *Term = B->getTerminator();
1055 // Skip empty cases.
1056 while (B->empty() && !Term && B->succ_size() == 1) {
1057 B = *B->succ_begin();
1058 Term = B->getTerminator();
1059 }
1060 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001061 Preprocessor &PP = S.getPreprocessor();
1062 TokenValue Tokens[] = {
1063 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1064 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1065 tok::r_square, tok::r_square
1066 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001067 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1068 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1069 if (!MacroName.empty())
1070 AnnotationSpelling = MacroName;
1071 SmallString<64> TextToInsert(AnnotationSpelling);
1072 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001073 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001074 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001075 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001076 }
Richard Smith84837d52012-05-03 18:27:39 +00001077 }
1078 S.Diag(L, diag::note_insert_break_fixit) <<
1079 FixItHint::CreateInsertion(L, "break; ");
1080 }
1081 }
1082
1083 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1084 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1085 E = Fallthroughs.end();
1086 I != E; ++I) {
1087 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1088 }
1089
1090}
1091
Jordan Rose25c0ea82012-10-29 17:46:47 +00001092static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1093 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001094 assert(S);
1095
1096 do {
1097 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001098 case Stmt::ForStmtClass:
1099 case Stmt::WhileStmtClass:
1100 case Stmt::CXXForRangeStmtClass:
1101 case Stmt::ObjCForCollectionStmtClass:
1102 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001103 case Stmt::DoStmtClass: {
1104 const Expr *Cond = cast<DoStmt>(S)->getCond();
1105 llvm::APSInt Val;
1106 if (!Cond->EvaluateAsInt(Val, Ctx))
1107 return true;
1108 return Val.getBoolValue();
1109 }
Jordan Rose76831c62012-10-11 16:10:19 +00001110 default:
1111 break;
1112 }
1113 } while ((S = PM.getParent(S)));
1114
1115 return false;
1116}
1117
Jordan Rosed3934582012-09-28 22:21:30 +00001118
1119static void diagnoseRepeatedUseOfWeak(Sema &S,
1120 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001121 const Decl *D,
1122 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001123 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1124 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1125 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001126 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1127 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001128
Jordan Rose25c0ea82012-10-29 17:46:47 +00001129 ASTContext &Ctx = S.getASTContext();
1130
Jordan Rosed3934582012-09-28 22:21:30 +00001131 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1132
1133 // Extract all weak objects that are referenced more than once.
1134 SmallVector<StmtUsesPair, 8> UsesByStmt;
1135 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1136 I != E; ++I) {
1137 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001138
1139 // Find the first read of the weak object.
1140 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1141 for ( ; UI != UE; ++UI) {
1142 if (UI->isUnsafe())
1143 break;
1144 }
1145
1146 // If there were only writes to this object, don't warn.
1147 if (UI == UE)
1148 continue;
1149
Jordan Rose76831c62012-10-11 16:10:19 +00001150 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001151 // read is not within a loop, don't warn. Additionally, don't warn in a
1152 // loop if the base object is a local variable -- local variables are often
1153 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001154 if (UI == Uses.begin()) {
1155 WeakUseVector::const_iterator UI2 = UI;
1156 for (++UI2; UI2 != UE; ++UI2)
1157 if (UI2->isUnsafe())
1158 break;
1159
Jordan Rose25c0ea82012-10-29 17:46:47 +00001160 if (UI2 == UE) {
1161 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001162 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001163
1164 const WeakObjectProfileTy &Profile = I->first;
1165 if (!Profile.isExactProfile())
1166 continue;
1167
1168 const NamedDecl *Base = Profile.getBase();
1169 if (!Base)
1170 Base = Profile.getProperty();
1171 assert(Base && "A profile always has a base or property.");
1172
1173 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1174 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1175 continue;
1176 }
Jordan Rose76831c62012-10-11 16:10:19 +00001177 }
1178
Jordan Rosed3934582012-09-28 22:21:30 +00001179 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1180 }
1181
1182 if (UsesByStmt.empty())
1183 return;
1184
1185 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001186 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001187 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001188 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1189 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1190 RHS.first->getLocStart());
1191 });
Jordan Rosed3934582012-09-28 22:21:30 +00001192
1193 // Classify the current code body for better warning text.
1194 // This enum should stay in sync with the cases in
1195 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1196 // FIXME: Should we use a common classification enum and the same set of
1197 // possibilities all throughout Sema?
1198 enum {
1199 Function,
1200 Method,
1201 Block,
1202 Lambda
1203 } FunctionKind;
1204
1205 if (isa<sema::BlockScopeInfo>(CurFn))
1206 FunctionKind = Block;
1207 else if (isa<sema::LambdaScopeInfo>(CurFn))
1208 FunctionKind = Lambda;
1209 else if (isa<ObjCMethodDecl>(D))
1210 FunctionKind = Method;
1211 else
1212 FunctionKind = Function;
1213
1214 // Iterate through the sorted problems and emit warnings for each.
1215 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1216 E = UsesByStmt.end();
1217 I != E; ++I) {
1218 const Stmt *FirstRead = I->first;
1219 const WeakObjectProfileTy &Key = I->second->first;
1220 const WeakUseVector &Uses = I->second->second;
1221
Jordan Rose657b5f42012-09-28 22:21:35 +00001222 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1223 // may not contain enough information to determine that these are different
1224 // properties. We can only be 100% sure of a repeated use in certain cases,
1225 // and we adjust the diagnostic kind accordingly so that the less certain
1226 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001227 unsigned DiagKind;
1228 if (Key.isExactProfile())
1229 DiagKind = diag::warn_arc_repeated_use_of_weak;
1230 else
1231 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1232
Jordan Rose657b5f42012-09-28 22:21:35 +00001233 // Classify the weak object being accessed for better warning text.
1234 // This enum should stay in sync with the cases in
1235 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1236 enum {
1237 Variable,
1238 Property,
1239 ImplicitProperty,
1240 Ivar
1241 } ObjectKind;
1242
1243 const NamedDecl *D = Key.getProperty();
1244 if (isa<VarDecl>(D))
1245 ObjectKind = Variable;
1246 else if (isa<ObjCPropertyDecl>(D))
1247 ObjectKind = Property;
1248 else if (isa<ObjCMethodDecl>(D))
1249 ObjectKind = ImplicitProperty;
1250 else if (isa<ObjCIvarDecl>(D))
1251 ObjectKind = Ivar;
1252 else
1253 llvm_unreachable("Unexpected weak object kind!");
1254
Jordan Rosed3934582012-09-28 22:21:30 +00001255 // Show the first time the object was read.
1256 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001257 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001258 << FirstRead->getSourceRange();
1259
1260 // Print all the other accesses as notes.
1261 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1262 UI != UE; ++UI) {
1263 if (UI->getUseExpr() == FirstRead)
1264 continue;
1265 S.Diag(UI->getUseExpr()->getLocStart(),
1266 diag::note_arc_weak_also_accessed_here)
1267 << UI->getUseExpr()->getSourceRange();
1268 }
1269 }
1270}
1271
Jordan Rosed3934582012-09-28 22:21:30 +00001272namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001273class UninitValsDiagReporter : public UninitVariablesHandler {
1274 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001275 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001276 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001277 // Prefer using MapVector to DenseMap, so that iteration order will be
1278 // the same as insertion order. This is needed to obtain a deterministic
1279 // order of diagnostics when calling flushDiagnostics().
1280 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001281 UsesMap *uses;
1282
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001283public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001284 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1285 ~UninitValsDiagReporter() {
1286 flushDiagnostics();
1287 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001288
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001289 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001290 if (!uses)
1291 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001292
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001293 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001294 if (!V.getPointer())
1295 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001296
Ted Kremenek596fa162011-10-13 18:50:06 +00001297 return V;
1298 }
1299
Richard Smith4323bf82012-05-25 02:17:09 +00001300 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001301 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001302 }
1303
1304 void handleSelfInit(const VarDecl *vd) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001305 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001306 }
1307
1308 void flushDiagnostics() {
1309 if (!uses)
1310 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001311
Ted Kremenek39fa0562011-01-21 19:41:41 +00001312 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1313 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001314 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001315
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001316 UsesVec *vec = V.getPointer();
1317 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001318
1319 // Specially handle the case where we have uses of an uninitialized
1320 // variable, but the root cause is an idiomatic self-init. We want
1321 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001322 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001323 DiagnoseUninitializedUse(S, vd,
1324 UninitUse(vd->getInit()->IgnoreParenCasts(),
1325 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001326 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001327 else {
1328 // Sort the uses by their SourceLocations. While not strictly
1329 // guaranteed to produce them in line/column order, this will provide
1330 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001331 std::sort(vec->begin(), vec->end(),
1332 [](const UninitUse &a, const UninitUse &b) {
1333 // Prefer a more confident report over a less confident one.
1334 if (a.getKind() != b.getKind())
1335 return a.getKind() > b.getKind();
1336 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1337 });
1338
Ted Kremenek596fa162011-10-13 18:50:06 +00001339 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1340 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001341 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1342 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1343
1344 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001345 // Skip further diagnostics for this variable. We try to warn only
1346 // on the first point at which a variable is used uninitialized.
1347 break;
1348 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001349 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001350
1351 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001352 delete vec;
1353 }
1354 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001355 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001356
1357private:
1358 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1359 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001360 if (i->getKind() == UninitUse::Always ||
1361 i->getKind() == UninitUse::AfterCall ||
1362 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001363 return true;
1364 }
1365 }
1366 return false;
1367}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001368};
1369}
1370
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001371namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001372namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001373typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001374typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001375typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001376
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001377struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001378 SourceManager &SM;
1379 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001380
1381 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1382 // Although this call will be slow, this is only called when outputting
1383 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001384 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001385 }
1386};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001387}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001388
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001389//===----------------------------------------------------------------------===//
1390// -Wthread-safety
1391//===----------------------------------------------------------------------===//
1392namespace clang {
1393namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001394namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001395class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1396 Sema &S;
1397 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001398 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001399
1400 // Helper functions
1401 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001402 // Gracefully handle rare cases when the analysis can't get a more
1403 // precise source location.
1404 if (!Loc.isValid())
1405 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001406 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1407 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001408 }
1409
1410 public:
Richard Smith92286672012-02-03 04:45:26 +00001411 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1412 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001413
1414 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1415 /// We need to output diagnostics produced while iterating through
1416 /// the lockset in deterministic order, so this function orders diagnostics
1417 /// and outputs them.
1418 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001419 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001420 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001421 I != E; ++I) {
1422 S.Diag(I->first.first, I->first.second);
1423 const OptionalNotes &Notes = I->second;
1424 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1425 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1426 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001427 }
1428
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001429 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001430 PartialDiagnosticAt Warning(Loc,
1431 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1432 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001433 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001434 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1435 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1436 }
1437
1438 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1439 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1440 }
1441
Richard Smith92286672012-02-03 04:45:26 +00001442 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1443 SourceLocation LocEndOfScope,
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001444 LockErrorKind LEK){
1445 unsigned DiagID = 0;
1446 switch (LEK) {
1447 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001448 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001449 break;
1450 case LEK_LockedSomeLoopIterations:
1451 DiagID = diag::warn_expecting_lock_held_on_loop;
1452 break;
1453 case LEK_LockedAtEndOfFunction:
1454 DiagID = diag::warn_no_unlock;
1455 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001456 case LEK_NotLockedAtEndOfFunction:
1457 DiagID = diag::warn_expecting_locked;
1458 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001459 }
Richard Smith92286672012-02-03 04:45:26 +00001460 if (LocEndOfScope.isInvalid())
1461 LocEndOfScope = FunEndLocation;
1462
1463 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001464 if (LocLocked.isValid()) {
1465 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1466 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1467 return;
1468 }
1469 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001470 }
1471
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001472
1473 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1474 SourceLocation Loc2) {
Richard Smith92286672012-02-03 04:45:26 +00001475 PartialDiagnosticAt Warning(
1476 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1477 PartialDiagnosticAt Note(
1478 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1479 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001480 }
1481
1482 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1483 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001484 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1485 && "Only works for variables");
1486 unsigned DiagID = POK == POK_VarAccess?
1487 diag::warn_variable_requires_any_lock:
1488 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001489 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001490 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001491 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001492 }
1493
1494 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001495 Name LockName, LockKind LK, SourceLocation Loc,
1496 Name *PossibleMatch) {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001497 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001498 if (PossibleMatch) {
1499 switch (POK) {
1500 case POK_VarAccess:
1501 DiagID = diag::warn_variable_requires_lock_precise;
1502 break;
1503 case POK_VarDereference:
1504 DiagID = diag::warn_var_deref_requires_lock_precise;
1505 break;
1506 case POK_FunctionCall:
1507 DiagID = diag::warn_fun_requires_lock_precise;
1508 break;
1509 }
1510 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001511 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001512 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1513 << *PossibleMatch);
1514 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1515 } else {
1516 switch (POK) {
1517 case POK_VarAccess:
1518 DiagID = diag::warn_variable_requires_lock;
1519 break;
1520 case POK_VarDereference:
1521 DiagID = diag::warn_var_deref_requires_lock;
1522 break;
1523 case POK_FunctionCall:
1524 DiagID = diag::warn_fun_requires_lock;
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 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001530 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001531 }
1532
1533 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001534 PartialDiagnosticAt Warning(Loc,
1535 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1536 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001537 }
1538};
1539}
1540}
David Blaikie68e081d2011-12-20 02:48:34 +00001541}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001542
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001543//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001544// -Wconsumed
1545//===----------------------------------------------------------------------===//
1546
1547namespace clang {
1548namespace consumed {
1549namespace {
1550class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1551
1552 Sema &S;
1553 DiagList Warnings;
1554
1555public:
1556
1557 ConsumedWarningsHandler(Sema &S) : S(S) {}
1558
1559 void emitDiagnostics() {
1560 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1561
1562 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1563 I != E; ++I) {
1564
1565 const OptionalNotes &Notes = I->second;
1566 S.Diag(I->first.first, I->first.second);
1567
1568 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1569 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1570 }
1571 }
1572 }
1573
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001574 void warnLoopStateMismatch(SourceLocation Loc, StringRef VariableName) {
1575 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1576 VariableName);
1577
1578 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1579 }
1580
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001581 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1582 StringRef VariableName,
1583 StringRef ExpectedState,
1584 StringRef ObservedState) {
1585
1586 PartialDiagnosticAt Warning(Loc, S.PDiag(
1587 diag::warn_param_return_typestate_mismatch) << VariableName <<
1588 ExpectedState << ObservedState);
1589
1590 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1591 }
1592
DeLesley Hutchins69391772013-10-17 23:23:53 +00001593 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1594 StringRef ObservedState) {
1595
1596 PartialDiagnosticAt Warning(Loc, S.PDiag(
1597 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1598
1599 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1600 }
1601
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001602 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1603 StringRef TypeName) {
1604 PartialDiagnosticAt Warning(Loc, S.PDiag(
1605 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1606
1607 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1608 }
1609
1610 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1611 StringRef ObservedState) {
1612
1613 PartialDiagnosticAt Warning(Loc, S.PDiag(
1614 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1615
1616 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1617 }
1618
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001619 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1620 SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001621
1622 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001623 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001624
1625 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1626 }
1627
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001628 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1629 StringRef State, SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001630
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001631 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1632 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001633
1634 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1635 }
1636};
1637}}}
1638
1639//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001640// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1641// warnings on a function, method, or block.
1642//===----------------------------------------------------------------------===//
1643
Ted Kremenek0b405322010-03-23 00:13:23 +00001644clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1645 enableCheckFallThrough = 1;
1646 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001647 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001648 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001649}
1650
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001651clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1652 : S(s),
1653 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001654 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001655 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001656 MaxCFGBlocksPerFunction(0),
1657 NumUninitAnalysisFunctions(0),
1658 NumUninitAnalysisVariables(0),
1659 MaxUninitAnalysisVariablesPerFunction(0),
1660 NumUninitAnalysisBlockVisits(0),
1661 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikie9c902b52011-09-25 23:23:43 +00001662 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenek0b405322010-03-23 00:13:23 +00001663 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001664 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001665 DiagnosticsEngine::Ignored);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001666 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1667 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001668 DiagnosticsEngine::Ignored);
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001669 DefaultPolicy.enableConsumedAnalysis = (unsigned)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001670 (D.getDiagnosticLevel(diag::warn_use_in_invalid_state, SourceLocation()) !=
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001671 DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +00001672}
1673
Ted Kremenek3427fac2011-02-23 01:52:04 +00001674static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001675 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001676 i = fscope->PossiblyUnreachableDiags.begin(),
1677 e = fscope->PossiblyUnreachableDiags.end();
1678 i != e; ++i) {
1679 const sema::PossiblyUnreachableDiag &D = *i;
1680 S.Diag(D.Loc, D.PD);
1681 }
1682}
1683
Ted Kremenek0b405322010-03-23 00:13:23 +00001684void clang::sema::
1685AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001686 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001687 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001688
Ted Kremenek918fe842010-03-20 21:06:02 +00001689 // We avoid doing analysis-based warnings when there are errors for
1690 // two reasons:
1691 // (1) The CFGs often can't be constructed (if the body is invalid), so
1692 // don't bother trying.
1693 // (2) The code already has problems; running the analysis just takes more
1694 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001695 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001696
Ted Kremenek0b405322010-03-23 00:13:23 +00001697 // Do not do any analysis for declarations in system headers if we are
1698 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001699 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001700 S.SourceMgr.isInSystemHeader(D->getLocation()))
1701 return;
1702
John McCall1d570a72010-08-25 05:56:39 +00001703 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001704 if (cast<DeclContext>(D)->isDependentContext())
1705 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001706
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001707 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001708 // Flush out any possibly unreachable diagnostics.
1709 flushDiagnostics(S, fscope);
1710 return;
1711 }
1712
Ted Kremenek918fe842010-03-20 21:06:02 +00001713 const Stmt *Body = D->getBody();
1714 assert(Body);
1715
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001716 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001717 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001718
Ted Kremenek918fe842010-03-20 21:06:02 +00001719 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001720 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001721 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1722 AC.getCFGBuildOptions().AddEHEdges = false;
1723 AC.getCFGBuildOptions().AddInitializers = true;
1724 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001725 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001726 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001727
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001728 // Force that certain expressions appear as CFGElements in the CFG. This
1729 // is used to speed up various analyses.
1730 // FIXME: This isn't the right factoring. This is here for initial
1731 // prototyping, but we need a way for analyses to say what expressions they
1732 // expect to always be CFGElements and then fill in the BuildOptions
1733 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001734 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1735 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001736 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001737 AC.getCFGBuildOptions().setAllAlwaysAdd();
1738 }
1739 else {
1740 AC.getCFGBuildOptions()
1741 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001742 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001743 .setAlwaysAdd(Stmt::BlockExprClass)
1744 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1745 .setAlwaysAdd(Stmt::DeclRefExprClass)
1746 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001747 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1748 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001749 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001750
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001751
Ted Kremenek3427fac2011-02-23 01:52:04 +00001752 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001753 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001754 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001755
1756 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001757 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001758 i = fscope->PossiblyUnreachableDiags.begin(),
1759 e = fscope->PossiblyUnreachableDiags.end();
1760 i != e; ++i) {
1761 if (const Stmt *stmt = i->stmt)
1762 AC.registerForcedBlockExpression(stmt);
1763 }
1764
1765 if (AC.getCFG()) {
1766 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001767 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001768 i = fscope->PossiblyUnreachableDiags.begin(),
1769 e = fscope->PossiblyUnreachableDiags.end();
1770 i != e; ++i)
1771 {
1772 const sema::PossiblyUnreachableDiag &D = *i;
1773 bool processed = false;
1774 if (const Stmt *stmt = i->stmt) {
1775 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001776 CFGReverseBlockReachabilityAnalysis *cra =
1777 AC.getCFGReachablityAnalysis();
1778 // FIXME: We should be able to assert that block is non-null, but
1779 // the CFG analysis can skip potentially-evaluated expressions in
1780 // edge cases; see test/Sema/vla-2.c.
1781 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001782 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001783 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001784 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001785 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001786 }
1787 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001788 if (!processed) {
1789 // Emit the warning anyway if we cannot map to a basic block.
1790 S.Diag(D.Loc, D.PD);
1791 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001792 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001793 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001794
1795 if (!analyzed)
1796 flushDiagnostics(S, fscope);
1797 }
1798
1799
Ted Kremenek918fe842010-03-20 21:06:02 +00001800 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001801 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001802 const CheckFallThroughDiagnostics &CD =
1803 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001804 : (isa<CXXMethodDecl>(D) &&
1805 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1806 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1807 ? CheckFallThroughDiagnostics::MakeForLambda()
1808 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001809 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001810 }
1811
1812 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001813 if (P.enableCheckUnreachable) {
1814 // Only check for unreachable code on non-template instantiations.
1815 // Different template instantiations can effectively change the control-flow
1816 // and it is very difficult to prove that a snippet of code in a template
1817 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001818 bool isTemplateInstantiation = false;
1819 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1820 isTemplateInstantiation = Function->isTemplateInstantiation();
1821 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001822 CheckUnreachable(S, AC);
1823 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001824
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001825 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001826 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001827 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001828 SourceLocation FEL = AC.getDecl()->getLocEnd();
1829 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001830 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1831 != DiagnosticsEngine::Ignored)
1832 Reporter.setIssueBetaWarnings(true);
1833
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001834 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1835 Reporter.emitDiagnostics();
1836 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001837
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001838 // Check for violations of consumed properties.
1839 if (P.enableConsumedAnalysis) {
1840 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001841 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001842 Analyzer.run(AC);
1843 }
1844
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001845 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001846 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001847 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1848 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001849 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001850 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001851 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001852 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001853 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001854 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001855 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001856 reporter, stats);
1857
1858 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1859 ++NumUninitAnalysisFunctions;
1860 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1861 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1862 MaxUninitAnalysisVariablesPerFunction =
1863 std::max(MaxUninitAnalysisVariablesPerFunction,
1864 stats.NumVariablesAnalyzed);
1865 MaxUninitAnalysisBlockVisitsPerFunction =
1866 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1867 stats.NumBlockVisits);
1868 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001869 }
1870 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001871
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001872 bool FallThroughDiagFull =
1873 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1874 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001875 bool FallThroughDiagPerFunction =
1876 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001877 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001878 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001879 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001880 }
1881
Jordan Rosed3934582012-09-28 22:21:30 +00001882 if (S.getLangOpts().ObjCARCWeak &&
1883 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1884 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001885 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001886
Richard Trieu2f024f42013-12-21 02:33:43 +00001887
1888 // Check for infinite self-recursion in functions
1889 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1890 D->getLocStart())
1891 != DiagnosticsEngine::Ignored) {
1892 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1893 checkRecursiveFunction(S, FD, Body, AC);
1894 }
1895 }
1896
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001897 // Collect statistics about the CFG if it was built.
1898 if (S.CollectStats && AC.isCFGBuilt()) {
1899 ++NumFunctionsAnalyzed;
1900 if (CFG *cfg = AC.getCFG()) {
1901 // If we successfully built a CFG for this context, record some more
1902 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001903 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001904 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001905 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001906 } else {
1907 ++NumFunctionsWithBadCFGs;
1908 }
1909 }
1910}
1911
1912void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1913 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1914
1915 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1916 unsigned AvgCFGBlocksPerFunction =
1917 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1918 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1919 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1920 << " " << NumCFGBlocks << " CFG blocks built.\n"
1921 << " " << AvgCFGBlocksPerFunction
1922 << " average CFG blocks per function.\n"
1923 << " " << MaxCFGBlocksPerFunction
1924 << " max CFG blocks per function.\n";
1925
1926 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1927 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1928 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1929 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1930 llvm::errs() << NumUninitAnalysisFunctions
1931 << " functions analyzed for uninitialiazed variables\n"
1932 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1933 << " " << AvgUninitVariablesPerFunction
1934 << " average variables per function.\n"
1935 << " " << MaxUninitAnalysisVariablesPerFunction
1936 << " max variables per function.\n"
1937 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1938 << " " << AvgUninitBlockVisitsPerFunction
1939 << " average block visits per function.\n"
1940 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1941 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001942}