blob: 389109a11bc3a9dd1777ba27af44ed888d576b6f [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
Ted Kremenek1a8641c2014-03-15 01:26:32 +000068 void HandleUnreachable(reachable_code::UnreachableKind UK,
69 SourceLocation L, SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000070 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000071 unsigned diag = diag::warn_unreachable;
72 switch (UK) {
73 case reachable_code::UK_Break:
74 diag = diag::warn_unreachable_break;
75 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000076 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000077 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000078 break;
79 case reachable_code::UK_Other:
80 break;
81 }
82
83 S.Diag(L, diag) << R1 << R2;
Ted Kremenek918fe842010-03-20 21:06:02 +000084 }
85 };
86}
87
88/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +000089static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +000090 // As a heuristic prune all diagnostics not in the main file. Currently
91 // the majority of warnings in headers are false positives. These
92 // are largely caused by configuration state, e.g. preprocessor
93 // defined code, etc.
94 //
95 // Note that this is also a performance optimization. Analyzing
96 // headers many times can be expensive.
97 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
98 return;
99
Ted Kremenek918fe842010-03-20 21:06:02 +0000100 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000101 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000102}
103
104//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000105// Check for infinite self-recursion in functions
106//===----------------------------------------------------------------------===//
107
108// All blocks are in one of three states. States are ordered so that blocks
109// can only move to higher states.
110enum RecursiveState {
111 FoundNoPath,
112 FoundPath,
113 FoundPathWithNoRecursiveCall
114};
115
116static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
117 CFGBlock &Block, unsigned ExitID,
118 llvm::SmallVectorImpl<RecursiveState> &States,
119 RecursiveState State) {
120 unsigned ID = Block.getBlockID();
121
122 // A block's state can only move to a higher state.
123 if (States[ID] >= State)
124 return;
125
126 States[ID] = State;
127
128 // Found a path to the exit node without a recursive call.
129 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
130 return;
131
132 if (State == FoundPathWithNoRecursiveCall) {
133 // If the current state is FoundPathWithNoRecursiveCall, the successors
134 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
135 // which, process all the Stmt's in this block to find any recursive calls.
136 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
137 if (I->getKind() != CFGElement::Statement)
138 continue;
139
140 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
141 if (CE && CE->getCalleeDecl() &&
142 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000143
144 // Skip function calls which are qualified with a templated class.
145 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
146 CE->getCallee()->IgnoreParenImpCasts())) {
147 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
148 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
149 isa<TemplateSpecializationType>(NNS->getAsType())) {
150 continue;
151 }
152 }
153 }
154
Richard Trieu2f024f42013-12-21 02:33:43 +0000155 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
156 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
157 !MCE->getMethodDecl()->isVirtual()) {
158 State = FoundPath;
159 break;
160 }
161 } else {
162 State = FoundPath;
163 break;
164 }
165 }
166 }
167 }
168
169 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
170 I != E; ++I)
171 if (*I)
172 checkForFunctionCall(S, FD, **I, ExitID, States, State);
173}
174
175static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
176 const Stmt *Body,
177 AnalysisDeclContext &AC) {
178 FD = FD->getCanonicalDecl();
179
180 // Only run on non-templated functions and non-templated members of
181 // templated classes.
182 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
183 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
184 return;
185
186 CFG *cfg = AC.getCFG();
187 if (cfg == 0) return;
188
189 // If the exit block is unreachable, skip processing the function.
190 if (cfg->getExit().pred_empty())
191 return;
192
193 // Mark all nodes as FoundNoPath, then begin processing the entry block.
194 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
195 FoundNoPath);
196 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
197 states, FoundPathWithNoRecursiveCall);
198
199 // Check that the exit block is reachable. This prevents triggering the
200 // warning on functions that do not terminate.
201 if (states[cfg->getExit().getBlockID()] == FoundPath)
202 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
203}
204
205//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000206// Check for missing return value.
207//===----------------------------------------------------------------------===//
208
John McCall5c6ec8c2010-05-16 09:34:11 +0000209enum ControlFlowKind {
210 UnknownFallThrough,
211 NeverFallThrough,
212 MaybeFallThrough,
213 AlwaysFallThrough,
214 NeverFallThroughOrReturn
215};
Ted Kremenek918fe842010-03-20 21:06:02 +0000216
217/// CheckFallThrough - Check that we don't fall off the end of a
218/// Statement that should return a value.
219///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000220/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
221/// MaybeFallThrough iff we might or might not fall off the end,
222/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
223/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000224/// statement but we may return. We assume that functions not marked noreturn
225/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000226static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000227 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000228 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000229
230 // The CFG leaves in dead things, and we don't want the dead code paths to
231 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000232 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000233 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000234 live);
235
236 bool AddEHEdges = AC.getAddEHEdges();
237 if (!AddEHEdges && count != cfg->getNumBlockIDs())
238 // When there are things remaining dead, and we didn't add EH edges
239 // from CallExprs to the catch clauses, we have to go back and
240 // mark them as live.
241 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
242 CFGBlock &b = **I;
243 if (!live[b.getBlockID()]) {
244 if (b.pred_begin() == b.pred_end()) {
245 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
246 // When not adding EH edges from calls, catch clauses
247 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000248 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000249 continue;
250 }
251 }
252 }
253
254 // Now we know what is live, we check the live precessors of the exit block
255 // and look for fall through paths, being careful to ignore normal returns,
256 // and exceptional paths.
257 bool HasLiveReturn = false;
258 bool HasFakeEdge = false;
259 bool HasPlainEdge = false;
260 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000261
262 // Ignore default cases that aren't likely to be reachable because all
263 // enums in a switch(X) have explicit case statements.
264 CFGBlock::FilterOptions FO;
265 FO.IgnoreDefaultsWithCoveredEnums = 1;
266
267 for (CFGBlock::filtered_pred_iterator
268 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
269 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000270 if (!live[B.getBlockID()])
271 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000272
Chandler Carruth03faf782011-09-13 09:53:58 +0000273 // Skip blocks which contain an element marked as no-return. They don't
274 // represent actually viable edges into the exit block, so mark them as
275 // abnormal.
276 if (B.hasNoReturnElement()) {
277 HasAbnormalEdge = true;
278 continue;
279 }
280
Ted Kremenek5d068492011-01-26 04:49:52 +0000281 // Destructors can appear after the 'return' in the CFG. This is
282 // normal. We need to look pass the destructors for the return
283 // statement (if it exists).
284 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000285
Chandler Carruth03faf782011-09-13 09:53:58 +0000286 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000287 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000288 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000289
Ted Kremenek5d068492011-01-26 04:49:52 +0000290 // No more CFGElements in the block?
291 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000292 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
293 HasAbnormalEdge = true;
294 continue;
295 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000296 // A labeled empty statement, or the entry block...
297 HasPlainEdge = true;
298 continue;
299 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000300
David Blaikie2a01f5d2013-02-21 20:58:29 +0000301 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000302 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000303 if (isa<ReturnStmt>(S)) {
304 HasLiveReturn = true;
305 continue;
306 }
307 if (isa<ObjCAtThrowStmt>(S)) {
308 HasFakeEdge = true;
309 continue;
310 }
311 if (isa<CXXThrowExpr>(S)) {
312 HasFakeEdge = true;
313 continue;
314 }
Chad Rosier32503022012-06-11 20:47:18 +0000315 if (isa<MSAsmStmt>(S)) {
316 // TODO: Verify this is correct.
317 HasFakeEdge = true;
318 HasLiveReturn = true;
319 continue;
320 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000321 if (isa<CXXTryStmt>(S)) {
322 HasAbnormalEdge = true;
323 continue;
324 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000325 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
326 == B.succ_end()) {
327 HasAbnormalEdge = true;
328 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000329 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000330
331 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000332 }
333 if (!HasPlainEdge) {
334 if (HasLiveReturn)
335 return NeverFallThrough;
336 return NeverFallThroughOrReturn;
337 }
338 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
339 return MaybeFallThrough;
340 // This says AlwaysFallThrough for calls to functions that are not marked
341 // noreturn, that don't return. If people would like this warning to be more
342 // accurate, such functions should be marked as noreturn.
343 return AlwaysFallThrough;
344}
345
Dan Gohman28ade552010-07-26 21:25:24 +0000346namespace {
347
Ted Kremenek918fe842010-03-20 21:06:02 +0000348struct CheckFallThroughDiagnostics {
349 unsigned diag_MaybeFallThrough_HasNoReturn;
350 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
351 unsigned diag_AlwaysFallThrough_HasNoReturn;
352 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
353 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000354 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000355 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000356
Douglas Gregor24f27692010-04-16 23:28:44 +0000357 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000358 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000359 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000360 D.diag_MaybeFallThrough_HasNoReturn =
361 diag::warn_falloff_noreturn_function;
362 D.diag_MaybeFallThrough_ReturnsNonVoid =
363 diag::warn_maybe_falloff_nonvoid_function;
364 D.diag_AlwaysFallThrough_HasNoReturn =
365 diag::warn_falloff_noreturn_function;
366 D.diag_AlwaysFallThrough_ReturnsNonVoid =
367 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000368
369 // Don't suggest that virtual functions be marked "noreturn", since they
370 // might be overridden by non-noreturn functions.
371 bool isVirtualMethod = false;
372 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
373 isVirtualMethod = Method->isVirtual();
374
Douglas Gregor0de57202011-10-10 18:15:57 +0000375 // Don't suggest that template instantiations be marked "noreturn"
376 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000377 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
378 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000379
380 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000381 D.diag_NeverFallThroughOrReturn =
382 diag::warn_suggest_noreturn_function;
383 else
384 D.diag_NeverFallThroughOrReturn = 0;
385
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000386 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000387 return D;
388 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000389
Ted Kremenek918fe842010-03-20 21:06:02 +0000390 static CheckFallThroughDiagnostics MakeForBlock() {
391 CheckFallThroughDiagnostics D;
392 D.diag_MaybeFallThrough_HasNoReturn =
393 diag::err_noreturn_block_has_return_expr;
394 D.diag_MaybeFallThrough_ReturnsNonVoid =
395 diag::err_maybe_falloff_nonvoid_block;
396 D.diag_AlwaysFallThrough_HasNoReturn =
397 diag::err_noreturn_block_has_return_expr;
398 D.diag_AlwaysFallThrough_ReturnsNonVoid =
399 diag::err_falloff_nonvoid_block;
400 D.diag_NeverFallThroughOrReturn =
401 diag::warn_suggest_noreturn_block;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000402 D.funMode = Block;
403 return D;
404 }
405
406 static CheckFallThroughDiagnostics MakeForLambda() {
407 CheckFallThroughDiagnostics D;
408 D.diag_MaybeFallThrough_HasNoReturn =
409 diag::err_noreturn_lambda_has_return_expr;
410 D.diag_MaybeFallThrough_ReturnsNonVoid =
411 diag::warn_maybe_falloff_nonvoid_lambda;
412 D.diag_AlwaysFallThrough_HasNoReturn =
413 diag::err_noreturn_lambda_has_return_expr;
414 D.diag_AlwaysFallThrough_ReturnsNonVoid =
415 diag::warn_falloff_nonvoid_lambda;
416 D.diag_NeverFallThroughOrReturn = 0;
417 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000418 return D;
419 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000420
David Blaikie9c902b52011-09-25 23:23:43 +0000421 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000422 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000423 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000424 return (ReturnsVoid ||
425 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000426 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000427 && (!HasNoReturn ||
428 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000429 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000430 && (!ReturnsVoid ||
431 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000432 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000433 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000434
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000435 // For blocks / lambdas.
436 return ReturnsVoid && !HasNoReturn
437 && ((funMode == Lambda) ||
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000438 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000439 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000440 }
441};
442
Dan Gohman28ade552010-07-26 21:25:24 +0000443}
444
Ted Kremenek918fe842010-03-20 21:06:02 +0000445/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
446/// function that should return a value. Check that we don't fall off the end
447/// of a noreturn function. We assume that functions and blocks not marked
448/// noreturn will return.
449static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000450 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000451 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000452 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000453
454 bool ReturnsVoid = false;
455 bool HasNoReturn = false;
456
457 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000458 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000459 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000460 }
461 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000462 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000463 HasNoReturn = MD->hasAttr<NoReturnAttr>();
464 }
465 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000466 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000467 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000468 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000469 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000470 ReturnsVoid = true;
471 if (FT->getNoReturnAttr())
472 HasNoReturn = true;
473 }
474 }
475
David Blaikie9c902b52011-09-25 23:23:43 +0000476 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000477
478 // Short circuit for compilation speed.
479 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
480 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000481
Ted Kremenek918fe842010-03-20 21:06:02 +0000482 // FIXME: Function try block
483 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
484 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000485 case UnknownFallThrough:
486 break;
487
Ted Kremenek918fe842010-03-20 21:06:02 +0000488 case MaybeFallThrough:
489 if (HasNoReturn)
490 S.Diag(Compound->getRBracLoc(),
491 CD.diag_MaybeFallThrough_HasNoReturn);
492 else if (!ReturnsVoid)
493 S.Diag(Compound->getRBracLoc(),
494 CD.diag_MaybeFallThrough_ReturnsNonVoid);
495 break;
496 case AlwaysFallThrough:
497 if (HasNoReturn)
498 S.Diag(Compound->getRBracLoc(),
499 CD.diag_AlwaysFallThrough_HasNoReturn);
500 else if (!ReturnsVoid)
501 S.Diag(Compound->getRBracLoc(),
502 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
503 break;
504 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000505 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
506 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
507 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000508 << 0 << FD;
509 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
510 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
511 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000512 } else {
513 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
514 }
515 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000516 break;
517 case NeverFallThrough:
518 break;
519 }
520 }
521}
522
523//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000524// -Wuninitialized
525//===----------------------------------------------------------------------===//
526
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000527namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000528/// ContainsReference - A visitor class to search for references to
529/// a particular declaration (the needle) within any evaluated component of an
530/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000531class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000532 bool FoundReference;
533 const DeclRefExpr *Needle;
534
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000535public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000536 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
537 : EvaluatedExprVisitor<ContainsReference>(Context),
538 FoundReference(false), Needle(Needle) {}
539
540 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000541 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000542 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000543 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000544
545 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000546 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000547
548 void VisitDeclRefExpr(DeclRefExpr *E) {
549 if (E == Needle)
550 FoundReference = true;
551 else
552 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000553 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000554
555 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000556};
557}
558
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000559static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000560 QualType VariableTy = VD->getType().getCanonicalType();
561 if (VariableTy->isBlockPointerType() &&
562 !VD->hasAttr<BlocksAttr>()) {
563 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
564 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
565 return true;
566 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000567
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000568 // Don't issue a fixit if there is already an initializer.
569 if (VD->getInit())
570 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000571
572 // Don't suggest a fixit inside macros.
573 if (VD->getLocEnd().isMacroID())
574 return false;
575
Richard Smith8d06f422012-01-12 23:53:29 +0000576 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000577
578 // Suggest possible initialization (if any).
579 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
580 if (Init.empty())
581 return false;
582
Richard Smith8d06f422012-01-12 23:53:29 +0000583 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
584 << FixItHint::CreateInsertion(Loc, Init);
585 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000586}
587
Richard Smith1bb8edb82012-05-26 06:20:46 +0000588/// Create a fixit to remove an if-like statement, on the assumption that its
589/// condition is CondVal.
590static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
591 const Stmt *Else, bool CondVal,
592 FixItHint &Fixit1, FixItHint &Fixit2) {
593 if (CondVal) {
594 // If condition is always true, remove all but the 'then'.
595 Fixit1 = FixItHint::CreateRemoval(
596 CharSourceRange::getCharRange(If->getLocStart(),
597 Then->getLocStart()));
598 if (Else) {
599 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
600 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
601 Fixit2 = FixItHint::CreateRemoval(
602 SourceRange(ElseKwLoc, Else->getLocEnd()));
603 }
604 } else {
605 // If condition is always false, remove all but the 'else'.
606 if (Else)
607 Fixit1 = FixItHint::CreateRemoval(
608 CharSourceRange::getCharRange(If->getLocStart(),
609 Else->getLocStart()));
610 else
611 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
612 }
613}
614
615/// DiagUninitUse -- Helper function to produce a diagnostic for an
616/// uninitialized use of a variable.
617static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
618 bool IsCapturedByBlock) {
619 bool Diagnosed = false;
620
Richard Smithba8071e2013-09-12 18:49:10 +0000621 switch (Use.getKind()) {
622 case UninitUse::Always:
623 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
624 << VD->getDeclName() << IsCapturedByBlock
625 << Use.getUser()->getSourceRange();
626 return;
627
628 case UninitUse::AfterDecl:
629 case UninitUse::AfterCall:
630 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
631 << VD->getDeclName() << IsCapturedByBlock
632 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
633 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
634 << VD->getSourceRange();
635 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
636 << IsCapturedByBlock << Use.getUser()->getSourceRange();
637 return;
638
639 case UninitUse::Maybe:
640 case UninitUse::Sometimes:
641 // Carry on to report sometimes-uninitialized branches, if possible,
642 // or a 'may be used uninitialized' diagnostic otherwise.
643 break;
644 }
645
Richard Smith1bb8edb82012-05-26 06:20:46 +0000646 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000647 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
648 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000649 assert(Use.getKind() == UninitUse::Sometimes);
650
651 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000652 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000653
654 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000655 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000656 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000657 SourceRange Range;
658
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000659 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000660 // For all binary terminators, branch 0 is taken if the condition is true,
661 // and branch 1 is taken if the condition is false.
662 int RemoveDiagKind = -1;
663 const char *FixitStr =
664 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
665 : (I->Output ? "1" : "0");
666 FixItHint Fixit1, Fixit2;
667
Richard Smithba8071e2013-09-12 18:49:10 +0000668 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000669 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000670 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000671 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000672 continue;
673
674 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000675 case Stmt::IfStmtClass: {
676 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000677 DiagKind = 0;
678 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000679 Range = IS->getCond()->getSourceRange();
680 RemoveDiagKind = 0;
681 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
682 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000683 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000684 }
685 case Stmt::ConditionalOperatorClass: {
686 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000687 DiagKind = 0;
688 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000689 Range = CO->getCond()->getSourceRange();
690 RemoveDiagKind = 0;
691 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
692 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000693 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000694 }
Richard Smith4323bf82012-05-25 02:17:09 +0000695 case Stmt::BinaryOperatorClass: {
696 const BinaryOperator *BO = cast<BinaryOperator>(Term);
697 if (!BO->isLogicalOp())
698 continue;
699 DiagKind = 0;
700 Str = BO->getOpcodeStr();
701 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000702 RemoveDiagKind = 0;
703 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
704 (BO->getOpcode() == BO_LOr && !I->Output))
705 // true && y -> y, false || y -> y.
706 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
707 BO->getOperatorLoc()));
708 else
709 // false && y -> false, true || y -> true.
710 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000711 break;
712 }
713
714 // "loop is entered / loop is exited".
715 case Stmt::WhileStmtClass:
716 DiagKind = 1;
717 Str = "while";
718 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000719 RemoveDiagKind = 1;
720 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000721 break;
722 case Stmt::ForStmtClass:
723 DiagKind = 1;
724 Str = "for";
725 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000726 RemoveDiagKind = 1;
727 if (I->Output)
728 Fixit1 = FixItHint::CreateRemoval(Range);
729 else
730 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000731 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000732 case Stmt::CXXForRangeStmtClass:
733 if (I->Output == 1) {
734 // The use occurs if a range-based for loop's body never executes.
735 // That may be impossible, and there's no syntactic fix for this,
736 // so treat it as a 'may be uninitialized' case.
737 continue;
738 }
739 DiagKind = 1;
740 Str = "for";
741 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
742 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000743
744 // "condition is true / loop is exited".
745 case Stmt::DoStmtClass:
746 DiagKind = 2;
747 Str = "do";
748 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000749 RemoveDiagKind = 1;
750 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000751 break;
752
753 // "switch case is taken".
754 case Stmt::CaseStmtClass:
755 DiagKind = 3;
756 Str = "case";
757 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
758 break;
759 case Stmt::DefaultStmtClass:
760 DiagKind = 3;
761 Str = "default";
762 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
763 break;
764 }
765
Richard Smith1bb8edb82012-05-26 06:20:46 +0000766 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
767 << VD->getDeclName() << IsCapturedByBlock << DiagKind
768 << Str << I->Output << Range;
769 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
770 << IsCapturedByBlock << User->getSourceRange();
771 if (RemoveDiagKind != -1)
772 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
773 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
774
775 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000776 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000777
778 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000779 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000780 << VD->getDeclName() << IsCapturedByBlock
781 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000782}
783
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000784/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
785/// uninitialized variable. This manages the different forms of diagnostic
786/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000787/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000788/// false.
789static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000790 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000791 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000792
Richard Smith4323bf82012-05-25 02:17:09 +0000793 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000794 // Inspect the initializer of the variable declaration which is
795 // being referenced prior to its initialization. We emit
796 // specialized diagnostics for self-initialization, and we
797 // specifically avoid warning about self references which take the
798 // form of:
799 //
800 // int x = x;
801 //
802 // This is used to indicate to GCC that 'x' is intentionally left
803 // uninitialized. Proven code paths which access 'x' in
804 // an uninitialized state after this will still warn.
805 if (const Expr *Initializer = VD->getInit()) {
806 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
807 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000808
Richard Trieu43a2fc72012-05-09 21:08:22 +0000809 ContainsReference CR(S.Context, DRE);
810 CR.Visit(const_cast<Expr*>(Initializer));
811 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000812 S.Diag(DRE->getLocStart(),
813 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000814 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
815 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000816 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000817 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000818
Richard Smith1bb8edb82012-05-26 06:20:46 +0000819 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000820 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000821 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000822 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
823 S.Diag(BE->getLocStart(),
824 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000825 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000826 else
827 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000828 }
829
830 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000831 // the initializer of that declaration & we didn't already suggest
832 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000833 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000834 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
835 << VD->getDeclName();
836
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000837 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000838}
839
Richard Smith84837d52012-05-03 18:27:39 +0000840namespace {
841 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
842 public:
843 FallthroughMapper(Sema &S)
844 : FoundSwitchStatements(false),
845 S(S) {
846 }
847
848 bool foundSwitchStatements() const { return FoundSwitchStatements; }
849
850 void markFallthroughVisited(const AttributedStmt *Stmt) {
851 bool Found = FallthroughStmts.erase(Stmt);
852 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000853 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000854 }
855
856 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
857
858 const AttrStmts &getFallthroughStmts() const {
859 return FallthroughStmts;
860 }
861
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000862 void fillReachableBlocks(CFG *Cfg) {
863 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
864 std::deque<const CFGBlock *> BlockQueue;
865
866 ReachableBlocks.insert(&Cfg->getEntry());
867 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000868 // Mark all case blocks reachable to avoid problems with switching on
869 // constants, covered enums, etc.
870 // These blocks can contain fall-through annotations, and we don't want to
871 // issue a warn_fallthrough_attr_unreachable for them.
872 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
873 const CFGBlock *B = *I;
874 const Stmt *L = B->getLabel();
875 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
876 BlockQueue.push_back(B);
877 }
878
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000879 while (!BlockQueue.empty()) {
880 const CFGBlock *P = BlockQueue.front();
881 BlockQueue.pop_front();
882 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
883 E = P->succ_end();
884 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000885 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000886 BlockQueue.push_back(*I);
887 }
888 }
889 }
890
Richard Smith84837d52012-05-03 18:27:39 +0000891 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000892 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
893
Richard Smith84837d52012-05-03 18:27:39 +0000894 int UnannotatedCnt = 0;
895 AnnotatedCnt = 0;
896
897 std::deque<const CFGBlock*> BlockQueue;
898
899 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
900
901 while (!BlockQueue.empty()) {
902 const CFGBlock *P = BlockQueue.front();
903 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000904 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000905
906 const Stmt *Term = P->getTerminator();
907 if (Term && isa<SwitchStmt>(Term))
908 continue; // Switch statement, good.
909
910 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
911 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
912 continue; // Previous case label has no statements, good.
913
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000914 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
915 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
916 continue; // Case label is preceded with a normal label, good.
917
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000918 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000919 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
920 ElemEnd = P->rend();
921 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000922 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
923 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000924 S.Diag(AS->getLocStart(),
925 diag::warn_fallthrough_attr_unreachable);
926 markFallthroughVisited(AS);
927 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000928 break;
Richard Smith84837d52012-05-03 18:27:39 +0000929 }
930 // Don't care about other unreachable statements.
931 }
932 }
933 // If there are no unreachable statements, this may be a special
934 // case in CFG:
935 // case X: {
936 // A a; // A has a destructor.
937 // break;
938 // }
939 // // <<<< This place is represented by a 'hanging' CFG block.
940 // case Y:
941 continue;
942 }
943
944 const Stmt *LastStmt = getLastStmt(*P);
945 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
946 markFallthroughVisited(AS);
947 ++AnnotatedCnt;
948 continue; // Fallthrough annotation, good.
949 }
950
951 if (!LastStmt) { // This block contains no executable statements.
952 // Traverse its predecessors.
953 std::copy(P->pred_begin(), P->pred_end(),
954 std::back_inserter(BlockQueue));
955 continue;
956 }
957
958 ++UnannotatedCnt;
959 }
960 return !!UnannotatedCnt;
961 }
962
963 // RecursiveASTVisitor setup.
964 bool shouldWalkTypesOfTypeLocs() const { return false; }
965
966 bool VisitAttributedStmt(AttributedStmt *S) {
967 if (asFallThroughAttr(S))
968 FallthroughStmts.insert(S);
969 return true;
970 }
971
972 bool VisitSwitchStmt(SwitchStmt *S) {
973 FoundSwitchStatements = true;
974 return true;
975 }
976
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000977 // We don't want to traverse local type declarations. We analyze their
978 // methods separately.
979 bool TraverseDecl(Decl *D) { return true; }
980
Richard Smith84837d52012-05-03 18:27:39 +0000981 private:
982
983 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
984 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
985 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
986 return AS;
987 }
988 return 0;
989 }
990
991 static const Stmt *getLastStmt(const CFGBlock &B) {
992 if (const Stmt *Term = B.getTerminator())
993 return Term;
994 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
995 ElemEnd = B.rend();
996 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000997 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
998 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +0000999 }
1000 // Workaround to detect a statement thrown out by CFGBuilder:
1001 // case X: {} case Y:
1002 // case X: ; case Y:
1003 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1004 if (!isa<SwitchCase>(SW->getSubStmt()))
1005 return SW->getSubStmt();
1006
1007 return 0;
1008 }
1009
1010 bool FoundSwitchStatements;
1011 AttrStmts FallthroughStmts;
1012 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001013 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001014 };
1015}
1016
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001017static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001018 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001019 // Only perform this analysis when using C++11. There is no good workflow
1020 // for this warning when not using C++11. There is no good way to silence
1021 // the warning (no attribute is available) unless we are using C++11's support
1022 // for generalized attributes. Once could use pragmas to silence the warning,
1023 // but as a general solution that is gross and not in the spirit of this
1024 // warning.
1025 //
1026 // NOTE: This an intermediate solution. There are on-going discussions on
1027 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001028 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001029 return;
1030
Richard Smith84837d52012-05-03 18:27:39 +00001031 FallthroughMapper FM(S);
1032 FM.TraverseStmt(AC.getBody());
1033
1034 if (!FM.foundSwitchStatements())
1035 return;
1036
Alexis Hunt2178f142012-06-15 21:22:05 +00001037 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001038 return;
1039
Richard Smith84837d52012-05-03 18:27:39 +00001040 CFG *Cfg = AC.getCFG();
1041
1042 if (!Cfg)
1043 return;
1044
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001045 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001046
1047 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001048 const CFGBlock *B = *I;
1049 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001050
1051 if (!Label || !isa<SwitchCase>(Label))
1052 continue;
1053
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001054 int AnnotatedCnt;
1055
Alexander Kornienko55488792013-01-25 15:49:34 +00001056 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001057 continue;
1058
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001059 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001060 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1061 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001062
1063 if (!AnnotatedCnt) {
1064 SourceLocation L = Label->getLocStart();
1065 if (L.isMacroID())
1066 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001067 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001068 const Stmt *Term = B->getTerminator();
1069 // Skip empty cases.
1070 while (B->empty() && !Term && B->succ_size() == 1) {
1071 B = *B->succ_begin();
1072 Term = B->getTerminator();
1073 }
1074 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001075 Preprocessor &PP = S.getPreprocessor();
1076 TokenValue Tokens[] = {
1077 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1078 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1079 tok::r_square, tok::r_square
1080 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001081 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1082 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1083 if (!MacroName.empty())
1084 AnnotationSpelling = MacroName;
1085 SmallString<64> TextToInsert(AnnotationSpelling);
1086 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001087 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001088 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001089 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001090 }
Richard Smith84837d52012-05-03 18:27:39 +00001091 }
1092 S.Diag(L, diag::note_insert_break_fixit) <<
1093 FixItHint::CreateInsertion(L, "break; ");
1094 }
1095 }
1096
1097 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1098 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1099 E = Fallthroughs.end();
1100 I != E; ++I) {
1101 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1102 }
1103
1104}
1105
Jordan Rose25c0ea82012-10-29 17:46:47 +00001106static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1107 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001108 assert(S);
1109
1110 do {
1111 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001112 case Stmt::ForStmtClass:
1113 case Stmt::WhileStmtClass:
1114 case Stmt::CXXForRangeStmtClass:
1115 case Stmt::ObjCForCollectionStmtClass:
1116 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001117 case Stmt::DoStmtClass: {
1118 const Expr *Cond = cast<DoStmt>(S)->getCond();
1119 llvm::APSInt Val;
1120 if (!Cond->EvaluateAsInt(Val, Ctx))
1121 return true;
1122 return Val.getBoolValue();
1123 }
Jordan Rose76831c62012-10-11 16:10:19 +00001124 default:
1125 break;
1126 }
1127 } while ((S = PM.getParent(S)));
1128
1129 return false;
1130}
1131
Jordan Rosed3934582012-09-28 22:21:30 +00001132
1133static void diagnoseRepeatedUseOfWeak(Sema &S,
1134 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001135 const Decl *D,
1136 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001137 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1138 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1139 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001140 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1141 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001142
Jordan Rose25c0ea82012-10-29 17:46:47 +00001143 ASTContext &Ctx = S.getASTContext();
1144
Jordan Rosed3934582012-09-28 22:21:30 +00001145 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1146
1147 // Extract all weak objects that are referenced more than once.
1148 SmallVector<StmtUsesPair, 8> UsesByStmt;
1149 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1150 I != E; ++I) {
1151 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001152
1153 // Find the first read of the weak object.
1154 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1155 for ( ; UI != UE; ++UI) {
1156 if (UI->isUnsafe())
1157 break;
1158 }
1159
1160 // If there were only writes to this object, don't warn.
1161 if (UI == UE)
1162 continue;
1163
Jordan Rose76831c62012-10-11 16:10:19 +00001164 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001165 // read is not within a loop, don't warn. Additionally, don't warn in a
1166 // loop if the base object is a local variable -- local variables are often
1167 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001168 if (UI == Uses.begin()) {
1169 WeakUseVector::const_iterator UI2 = UI;
1170 for (++UI2; UI2 != UE; ++UI2)
1171 if (UI2->isUnsafe())
1172 break;
1173
Jordan Rose25c0ea82012-10-29 17:46:47 +00001174 if (UI2 == UE) {
1175 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001176 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001177
1178 const WeakObjectProfileTy &Profile = I->first;
1179 if (!Profile.isExactProfile())
1180 continue;
1181
1182 const NamedDecl *Base = Profile.getBase();
1183 if (!Base)
1184 Base = Profile.getProperty();
1185 assert(Base && "A profile always has a base or property.");
1186
1187 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1188 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1189 continue;
1190 }
Jordan Rose76831c62012-10-11 16:10:19 +00001191 }
1192
Jordan Rosed3934582012-09-28 22:21:30 +00001193 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1194 }
1195
1196 if (UsesByStmt.empty())
1197 return;
1198
1199 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001200 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001201 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001202 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1203 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1204 RHS.first->getLocStart());
1205 });
Jordan Rosed3934582012-09-28 22:21:30 +00001206
1207 // Classify the current code body for better warning text.
1208 // This enum should stay in sync with the cases in
1209 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1210 // FIXME: Should we use a common classification enum and the same set of
1211 // possibilities all throughout Sema?
1212 enum {
1213 Function,
1214 Method,
1215 Block,
1216 Lambda
1217 } FunctionKind;
1218
1219 if (isa<sema::BlockScopeInfo>(CurFn))
1220 FunctionKind = Block;
1221 else if (isa<sema::LambdaScopeInfo>(CurFn))
1222 FunctionKind = Lambda;
1223 else if (isa<ObjCMethodDecl>(D))
1224 FunctionKind = Method;
1225 else
1226 FunctionKind = Function;
1227
1228 // Iterate through the sorted problems and emit warnings for each.
1229 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1230 E = UsesByStmt.end();
1231 I != E; ++I) {
1232 const Stmt *FirstRead = I->first;
1233 const WeakObjectProfileTy &Key = I->second->first;
1234 const WeakUseVector &Uses = I->second->second;
1235
Jordan Rose657b5f42012-09-28 22:21:35 +00001236 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1237 // may not contain enough information to determine that these are different
1238 // properties. We can only be 100% sure of a repeated use in certain cases,
1239 // and we adjust the diagnostic kind accordingly so that the less certain
1240 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001241 unsigned DiagKind;
1242 if (Key.isExactProfile())
1243 DiagKind = diag::warn_arc_repeated_use_of_weak;
1244 else
1245 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1246
Jordan Rose657b5f42012-09-28 22:21:35 +00001247 // Classify the weak object being accessed for better warning text.
1248 // This enum should stay in sync with the cases in
1249 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1250 enum {
1251 Variable,
1252 Property,
1253 ImplicitProperty,
1254 Ivar
1255 } ObjectKind;
1256
1257 const NamedDecl *D = Key.getProperty();
1258 if (isa<VarDecl>(D))
1259 ObjectKind = Variable;
1260 else if (isa<ObjCPropertyDecl>(D))
1261 ObjectKind = Property;
1262 else if (isa<ObjCMethodDecl>(D))
1263 ObjectKind = ImplicitProperty;
1264 else if (isa<ObjCIvarDecl>(D))
1265 ObjectKind = Ivar;
1266 else
1267 llvm_unreachable("Unexpected weak object kind!");
1268
Jordan Rosed3934582012-09-28 22:21:30 +00001269 // Show the first time the object was read.
1270 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001271 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001272 << FirstRead->getSourceRange();
1273
1274 // Print all the other accesses as notes.
1275 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1276 UI != UE; ++UI) {
1277 if (UI->getUseExpr() == FirstRead)
1278 continue;
1279 S.Diag(UI->getUseExpr()->getLocStart(),
1280 diag::note_arc_weak_also_accessed_here)
1281 << UI->getUseExpr()->getSourceRange();
1282 }
1283 }
1284}
1285
Jordan Rosed3934582012-09-28 22:21:30 +00001286namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001287class UninitValsDiagReporter : public UninitVariablesHandler {
1288 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001289 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001290 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001291 // Prefer using MapVector to DenseMap, so that iteration order will be
1292 // the same as insertion order. This is needed to obtain a deterministic
1293 // order of diagnostics when calling flushDiagnostics().
1294 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001295 UsesMap *uses;
1296
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001297public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001298 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1299 ~UninitValsDiagReporter() {
1300 flushDiagnostics();
1301 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001302
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001303 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001304 if (!uses)
1305 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001306
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001307 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001308 if (!V.getPointer())
1309 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001310
Ted Kremenek596fa162011-10-13 18:50:06 +00001311 return V;
1312 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001313
1314 void handleUseOfUninitVariable(const VarDecl *vd,
1315 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001316 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001317 }
1318
Craig Toppere14c0f82014-03-12 04:55:44 +00001319 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001320 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001321 }
1322
1323 void flushDiagnostics() {
1324 if (!uses)
1325 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001326
Ted Kremenek39fa0562011-01-21 19:41:41 +00001327 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1328 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001329 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001330
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001331 UsesVec *vec = V.getPointer();
1332 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001333
1334 // Specially handle the case where we have uses of an uninitialized
1335 // variable, but the root cause is an idiomatic self-init. We want
1336 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001337 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001338 DiagnoseUninitializedUse(S, vd,
1339 UninitUse(vd->getInit()->IgnoreParenCasts(),
1340 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001341 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001342 else {
1343 // Sort the uses by their SourceLocations. While not strictly
1344 // guaranteed to produce them in line/column order, this will provide
1345 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001346 std::sort(vec->begin(), vec->end(),
1347 [](const UninitUse &a, const UninitUse &b) {
1348 // Prefer a more confident report over a less confident one.
1349 if (a.getKind() != b.getKind())
1350 return a.getKind() > b.getKind();
1351 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1352 });
1353
Ted Kremenek596fa162011-10-13 18:50:06 +00001354 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1355 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001356 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1357 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1358
1359 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001360 // Skip further diagnostics for this variable. We try to warn only
1361 // on the first point at which a variable is used uninitialized.
1362 break;
1363 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001364 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001365
1366 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001367 delete vec;
1368 }
1369 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001370 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001371
1372private:
1373 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1374 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001375 if (i->getKind() == UninitUse::Always ||
1376 i->getKind() == UninitUse::AfterCall ||
1377 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001378 return true;
1379 }
1380 }
1381 return false;
1382}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001383};
1384}
1385
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001386namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001387namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001388typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001389typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001390typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001391
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001392struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001393 SourceManager &SM;
1394 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001395
1396 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1397 // Although this call will be slow, this is only called when outputting
1398 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001399 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001400 }
1401};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001402}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001403
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001404//===----------------------------------------------------------------------===//
1405// -Wthread-safety
1406//===----------------------------------------------------------------------===//
1407namespace clang {
1408namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001409namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001410class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1411 Sema &S;
1412 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001413 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001414
1415 // Helper functions
1416 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001417 // Gracefully handle rare cases when the analysis can't get a more
1418 // precise source location.
1419 if (!Loc.isValid())
1420 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001421 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1422 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001423 }
1424
1425 public:
Richard Smith92286672012-02-03 04:45:26 +00001426 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1427 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001428
1429 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1430 /// We need to output diagnostics produced while iterating through
1431 /// the lockset in deterministic order, so this function orders diagnostics
1432 /// and outputs them.
1433 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001434 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001435 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001436 I != E; ++I) {
1437 S.Diag(I->first.first, I->first.second);
1438 const OptionalNotes &Notes = I->second;
1439 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1440 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1441 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001442 }
1443
Craig Toppere14c0f82014-03-12 04:55:44 +00001444 void handleInvalidLockExp(SourceLocation Loc) override {
Richard Smith92286672012-02-03 04:45:26 +00001445 PartialDiagnosticAt Warning(Loc,
1446 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1447 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001448 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001449 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) override {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001450 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1451 }
1452
Craig Toppere14c0f82014-03-12 04:55:44 +00001453 void handleDoubleLock(Name LockName, SourceLocation Loc) override {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001454 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1455 }
1456
Richard Smith92286672012-02-03 04:45:26 +00001457 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1458 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001459 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001460 unsigned DiagID = 0;
1461 switch (LEK) {
1462 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001463 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001464 break;
1465 case LEK_LockedSomeLoopIterations:
1466 DiagID = diag::warn_expecting_lock_held_on_loop;
1467 break;
1468 case LEK_LockedAtEndOfFunction:
1469 DiagID = diag::warn_no_unlock;
1470 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001471 case LEK_NotLockedAtEndOfFunction:
1472 DiagID = diag::warn_expecting_locked;
1473 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001474 }
Richard Smith92286672012-02-03 04:45:26 +00001475 if (LocEndOfScope.isInvalid())
1476 LocEndOfScope = FunEndLocation;
1477
1478 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001479 if (LocLocked.isValid()) {
1480 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1481 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1482 return;
1483 }
1484 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001485 }
1486
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001487
1488 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001489 SourceLocation Loc2) override {
Richard Smith92286672012-02-03 04:45:26 +00001490 PartialDiagnosticAt Warning(
1491 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1492 PartialDiagnosticAt Note(
1493 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1494 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001495 }
1496
1497 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
Craig Toppere14c0f82014-03-12 04:55:44 +00001498 AccessKind AK, SourceLocation Loc) override {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001499 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1500 && "Only works for variables");
1501 unsigned DiagID = POK == POK_VarAccess?
1502 diag::warn_variable_requires_any_lock:
1503 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001504 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001505 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001506 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001507 }
1508
1509 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001510 Name LockName, LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001511 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001512 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001513 if (PossibleMatch) {
1514 switch (POK) {
1515 case POK_VarAccess:
1516 DiagID = diag::warn_variable_requires_lock_precise;
1517 break;
1518 case POK_VarDereference:
1519 DiagID = diag::warn_var_deref_requires_lock_precise;
1520 break;
1521 case POK_FunctionCall:
1522 DiagID = diag::warn_fun_requires_lock_precise;
1523 break;
1524 }
1525 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001526 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001527 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1528 << *PossibleMatch);
1529 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1530 } else {
1531 switch (POK) {
1532 case POK_VarAccess:
1533 DiagID = diag::warn_variable_requires_lock;
1534 break;
1535 case POK_VarDereference:
1536 DiagID = diag::warn_var_deref_requires_lock;
1537 break;
1538 case POK_FunctionCall:
1539 DiagID = diag::warn_fun_requires_lock;
1540 break;
1541 }
1542 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001543 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001544 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001545 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001546 }
1547
Craig Toppere14c0f82014-03-12 04:55:44 +00001548 void handleFunExcludesLock(Name FunName, Name LockName,
1549 SourceLocation Loc) override {
Richard Smith92286672012-02-03 04:45:26 +00001550 PartialDiagnosticAt Warning(Loc,
1551 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1552 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001553 }
1554};
1555}
1556}
David Blaikie68e081d2011-12-20 02:48:34 +00001557}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001558
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001559//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001560// -Wconsumed
1561//===----------------------------------------------------------------------===//
1562
1563namespace clang {
1564namespace consumed {
1565namespace {
1566class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1567
1568 Sema &S;
1569 DiagList Warnings;
1570
1571public:
1572
1573 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001574
1575 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001576 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1577
1578 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1579 I != E; ++I) {
1580
1581 const OptionalNotes &Notes = I->second;
1582 S.Diag(I->first.first, I->first.second);
1583
1584 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1585 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1586 }
1587 }
1588 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001589
1590 void warnLoopStateMismatch(SourceLocation Loc,
1591 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001592 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1593 VariableName);
1594
1595 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1596 }
1597
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001598 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1599 StringRef VariableName,
1600 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001601 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001602
1603 PartialDiagnosticAt Warning(Loc, S.PDiag(
1604 diag::warn_param_return_typestate_mismatch) << VariableName <<
1605 ExpectedState << ObservedState);
1606
1607 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1608 }
1609
DeLesley Hutchins69391772013-10-17 23:23:53 +00001610 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001611 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001612
1613 PartialDiagnosticAt Warning(Loc, S.PDiag(
1614 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1615
1616 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1617 }
1618
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001619 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001620 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001621 PartialDiagnosticAt Warning(Loc, S.PDiag(
1622 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1623
1624 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1625 }
1626
1627 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001628 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001629
1630 PartialDiagnosticAt Warning(Loc, S.PDiag(
1631 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1632
1633 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1634 }
1635
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001636 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001637 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001638
1639 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001640 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001641
1642 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1643 }
1644
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001645 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001646 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001647
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001648 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1649 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001650
1651 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1652 }
1653};
1654}}}
1655
1656//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001657// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1658// warnings on a function, method, or block.
1659//===----------------------------------------------------------------------===//
1660
Ted Kremenek0b405322010-03-23 00:13:23 +00001661clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1662 enableCheckFallThrough = 1;
1663 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001664 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001665 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001666}
1667
Ted Kremenekad8753c2014-03-15 05:47:06 +00001668static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1669 return (unsigned) D.getDiagnosticLevel(diag, SourceLocation()) !=
1670 DiagnosticsEngine::Ignored;
1671}
1672
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001673clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1674 : S(s),
1675 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001676 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001677 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001678 MaxCFGBlocksPerFunction(0),
1679 NumUninitAnalysisFunctions(0),
1680 NumUninitAnalysisVariables(0),
1681 MaxUninitAnalysisVariablesPerFunction(0),
1682 NumUninitAnalysisBlockVisits(0),
1683 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001684
1685 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001686 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001687
1688 DefaultPolicy.enableCheckUnreachable =
1689 isEnabled(D, warn_unreachable) ||
1690 isEnabled(D, warn_unreachable_break) ||
1691 isEnabled(D, warn_unreachable_return);
1692
1693 DefaultPolicy.enableThreadSafetyAnalysis =
1694 isEnabled(D, warn_double_lock);
1695
1696 DefaultPolicy.enableConsumedAnalysis =
1697 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001698}
1699
Ted Kremenek3427fac2011-02-23 01:52:04 +00001700static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001701 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001702 i = fscope->PossiblyUnreachableDiags.begin(),
1703 e = fscope->PossiblyUnreachableDiags.end();
1704 i != e; ++i) {
1705 const sema::PossiblyUnreachableDiag &D = *i;
1706 S.Diag(D.Loc, D.PD);
1707 }
1708}
1709
Ted Kremenek0b405322010-03-23 00:13:23 +00001710void clang::sema::
1711AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001712 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001713 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001714
Ted Kremenek918fe842010-03-20 21:06:02 +00001715 // We avoid doing analysis-based warnings when there are errors for
1716 // two reasons:
1717 // (1) The CFGs often can't be constructed (if the body is invalid), so
1718 // don't bother trying.
1719 // (2) The code already has problems; running the analysis just takes more
1720 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001721 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001722
Ted Kremenek0b405322010-03-23 00:13:23 +00001723 // Do not do any analysis for declarations in system headers if we are
1724 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001725 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001726 S.SourceMgr.isInSystemHeader(D->getLocation()))
1727 return;
1728
John McCall1d570a72010-08-25 05:56:39 +00001729 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001730 if (cast<DeclContext>(D)->isDependentContext())
1731 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001732
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001733 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001734 // Flush out any possibly unreachable diagnostics.
1735 flushDiagnostics(S, fscope);
1736 return;
1737 }
1738
Ted Kremenek918fe842010-03-20 21:06:02 +00001739 const Stmt *Body = D->getBody();
1740 assert(Body);
1741
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001742 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001743 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001744
Ted Kremenek918fe842010-03-20 21:06:02 +00001745 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001746 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001747 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1748 AC.getCFGBuildOptions().AddEHEdges = false;
1749 AC.getCFGBuildOptions().AddInitializers = true;
1750 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001751 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001752 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001753
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001754 // Force that certain expressions appear as CFGElements in the CFG. This
1755 // is used to speed up various analyses.
1756 // FIXME: This isn't the right factoring. This is here for initial
1757 // prototyping, but we need a way for analyses to say what expressions they
1758 // expect to always be CFGElements and then fill in the BuildOptions
1759 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001760 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1761 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001762 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001763 AC.getCFGBuildOptions().setAllAlwaysAdd();
1764 }
1765 else {
1766 AC.getCFGBuildOptions()
1767 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001768 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001769 .setAlwaysAdd(Stmt::BlockExprClass)
1770 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1771 .setAlwaysAdd(Stmt::DeclRefExprClass)
1772 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001773 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1774 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001775 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001776
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001777
Ted Kremenek3427fac2011-02-23 01:52:04 +00001778 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001779 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001780 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001781
1782 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001783 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001784 i = fscope->PossiblyUnreachableDiags.begin(),
1785 e = fscope->PossiblyUnreachableDiags.end();
1786 i != e; ++i) {
1787 if (const Stmt *stmt = i->stmt)
1788 AC.registerForcedBlockExpression(stmt);
1789 }
1790
1791 if (AC.getCFG()) {
1792 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001793 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001794 i = fscope->PossiblyUnreachableDiags.begin(),
1795 e = fscope->PossiblyUnreachableDiags.end();
1796 i != e; ++i)
1797 {
1798 const sema::PossiblyUnreachableDiag &D = *i;
1799 bool processed = false;
1800 if (const Stmt *stmt = i->stmt) {
1801 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001802 CFGReverseBlockReachabilityAnalysis *cra =
1803 AC.getCFGReachablityAnalysis();
1804 // FIXME: We should be able to assert that block is non-null, but
1805 // the CFG analysis can skip potentially-evaluated expressions in
1806 // edge cases; see test/Sema/vla-2.c.
1807 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001808 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001809 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001810 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001811 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001812 }
1813 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001814 if (!processed) {
1815 // Emit the warning anyway if we cannot map to a basic block.
1816 S.Diag(D.Loc, D.PD);
1817 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001818 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001819 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001820
1821 if (!analyzed)
1822 flushDiagnostics(S, fscope);
1823 }
1824
1825
Ted Kremenek918fe842010-03-20 21:06:02 +00001826 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001827 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001828 const CheckFallThroughDiagnostics &CD =
1829 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001830 : (isa<CXXMethodDecl>(D) &&
1831 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1832 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1833 ? CheckFallThroughDiagnostics::MakeForLambda()
1834 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001835 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001836 }
1837
1838 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001839 if (P.enableCheckUnreachable) {
1840 // Only check for unreachable code on non-template instantiations.
1841 // Different template instantiations can effectively change the control-flow
1842 // and it is very difficult to prove that a snippet of code in a template
1843 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001844 bool isTemplateInstantiation = false;
1845 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1846 isTemplateInstantiation = Function->isTemplateInstantiation();
1847 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001848 CheckUnreachable(S, AC);
1849 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001850
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001851 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001852 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001853 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001854 SourceLocation FEL = AC.getDecl()->getLocEnd();
1855 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001856 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1857 != DiagnosticsEngine::Ignored)
1858 Reporter.setIssueBetaWarnings(true);
1859
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001860 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1861 Reporter.emitDiagnostics();
1862 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001863
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001864 // Check for violations of consumed properties.
1865 if (P.enableConsumedAnalysis) {
1866 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001867 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001868 Analyzer.run(AC);
1869 }
1870
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001871 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001872 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001873 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1874 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001875 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001876 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001877 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001878 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001879 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001880 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001881 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001882 reporter, stats);
1883
1884 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1885 ++NumUninitAnalysisFunctions;
1886 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1887 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1888 MaxUninitAnalysisVariablesPerFunction =
1889 std::max(MaxUninitAnalysisVariablesPerFunction,
1890 stats.NumVariablesAnalyzed);
1891 MaxUninitAnalysisBlockVisitsPerFunction =
1892 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1893 stats.NumBlockVisits);
1894 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001895 }
1896 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001897
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001898 bool FallThroughDiagFull =
1899 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1900 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001901 bool FallThroughDiagPerFunction =
1902 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001903 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001904 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001905 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001906 }
1907
Jordan Rosed3934582012-09-28 22:21:30 +00001908 if (S.getLangOpts().ObjCARCWeak &&
1909 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1910 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001911 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001912
Richard Trieu2f024f42013-12-21 02:33:43 +00001913
1914 // Check for infinite self-recursion in functions
1915 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1916 D->getLocStart())
1917 != DiagnosticsEngine::Ignored) {
1918 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1919 checkRecursiveFunction(S, FD, Body, AC);
1920 }
1921 }
1922
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001923 // Collect statistics about the CFG if it was built.
1924 if (S.CollectStats && AC.isCFGBuilt()) {
1925 ++NumFunctionsAnalyzed;
1926 if (CFG *cfg = AC.getCFG()) {
1927 // If we successfully built a CFG for this context, record some more
1928 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001929 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001930 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001931 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001932 } else {
1933 ++NumFunctionsWithBadCFGs;
1934 }
1935 }
1936}
1937
1938void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1939 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1940
1941 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1942 unsigned AvgCFGBlocksPerFunction =
1943 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1944 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1945 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1946 << " " << NumCFGBlocks << " CFG blocks built.\n"
1947 << " " << AvgCFGBlocksPerFunction
1948 << " average CFG blocks per function.\n"
1949 << " " << MaxCFGBlocksPerFunction
1950 << " max CFG blocks per function.\n";
1951
1952 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1953 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1954 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1955 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1956 llvm::errs() << NumUninitAnalysisFunctions
1957 << " functions analyzed for uninitialiazed variables\n"
1958 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1959 << " " << AvgUninitVariablesPerFunction
1960 << " average variables per function.\n"
1961 << " " << MaxUninitAnalysisVariablesPerFunction
1962 << " max variables per function.\n"
1963 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1964 << " " << AvgUninitBlockVisitsPerFunction
1965 << " average block visits per function.\n"
1966 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1967 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001968}