blob: efaf966562cf1ce3bf81a200c880ced40b3594f0 [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;
Ted Kremenek14210372014-03-21 06:02:36 +000079 case reachable_code::UK_Loop_Increment:
80 diag = diag::warn_unreachable_loop_increment;
81 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000082 case reachable_code::UK_Other:
83 break;
84 }
85
86 S.Diag(L, diag) << R1 << R2;
Ted Kremenek918fe842010-03-20 21:06:02 +000087 }
88 };
89}
90
91/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +000092static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +000093 // As a heuristic prune all diagnostics not in the main file. Currently
94 // the majority of warnings in headers are false positives. These
95 // are largely caused by configuration state, e.g. preprocessor
96 // defined code, etc.
97 //
98 // Note that this is also a performance optimization. Analyzing
99 // headers many times can be expensive.
100 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
101 return;
102
Ted Kremenek918fe842010-03-20 21:06:02 +0000103 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000104 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000105}
106
107//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000108// Check for infinite self-recursion in functions
109//===----------------------------------------------------------------------===//
110
111// All blocks are in one of three states. States are ordered so that blocks
112// can only move to higher states.
113enum RecursiveState {
114 FoundNoPath,
115 FoundPath,
116 FoundPathWithNoRecursiveCall
117};
118
119static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
120 CFGBlock &Block, unsigned ExitID,
121 llvm::SmallVectorImpl<RecursiveState> &States,
122 RecursiveState State) {
123 unsigned ID = Block.getBlockID();
124
125 // A block's state can only move to a higher state.
126 if (States[ID] >= State)
127 return;
128
129 States[ID] = State;
130
131 // Found a path to the exit node without a recursive call.
132 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
133 return;
134
135 if (State == FoundPathWithNoRecursiveCall) {
136 // If the current state is FoundPathWithNoRecursiveCall, the successors
137 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
138 // which, process all the Stmt's in this block to find any recursive calls.
139 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
140 if (I->getKind() != CFGElement::Statement)
141 continue;
142
143 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
144 if (CE && CE->getCalleeDecl() &&
145 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000146
147 // Skip function calls which are qualified with a templated class.
148 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
149 CE->getCallee()->IgnoreParenImpCasts())) {
150 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
151 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
152 isa<TemplateSpecializationType>(NNS->getAsType())) {
153 continue;
154 }
155 }
156 }
157
Richard Trieu2f024f42013-12-21 02:33:43 +0000158 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
159 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
160 !MCE->getMethodDecl()->isVirtual()) {
161 State = FoundPath;
162 break;
163 }
164 } else {
165 State = FoundPath;
166 break;
167 }
168 }
169 }
170 }
171
172 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
173 I != E; ++I)
174 if (*I)
175 checkForFunctionCall(S, FD, **I, ExitID, States, State);
176}
177
178static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
179 const Stmt *Body,
180 AnalysisDeclContext &AC) {
181 FD = FD->getCanonicalDecl();
182
183 // Only run on non-templated functions and non-templated members of
184 // templated classes.
185 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
186 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
187 return;
188
189 CFG *cfg = AC.getCFG();
190 if (cfg == 0) return;
191
192 // If the exit block is unreachable, skip processing the function.
193 if (cfg->getExit().pred_empty())
194 return;
195
196 // Mark all nodes as FoundNoPath, then begin processing the entry block.
197 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
198 FoundNoPath);
199 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
200 states, FoundPathWithNoRecursiveCall);
201
202 // Check that the exit block is reachable. This prevents triggering the
203 // warning on functions that do not terminate.
204 if (states[cfg->getExit().getBlockID()] == FoundPath)
205 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
206}
207
208//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000209// Check for missing return value.
210//===----------------------------------------------------------------------===//
211
John McCall5c6ec8c2010-05-16 09:34:11 +0000212enum ControlFlowKind {
213 UnknownFallThrough,
214 NeverFallThrough,
215 MaybeFallThrough,
216 AlwaysFallThrough,
217 NeverFallThroughOrReturn
218};
Ted Kremenek918fe842010-03-20 21:06:02 +0000219
220/// CheckFallThrough - Check that we don't fall off the end of a
221/// Statement that should return a value.
222///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000223/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
224/// MaybeFallThrough iff we might or might not fall off the end,
225/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
226/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000227/// statement but we may return. We assume that functions not marked noreturn
228/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000229static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000230 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000231 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000232
233 // The CFG leaves in dead things, and we don't want the dead code paths to
234 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000235 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000236 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000237 live);
238
239 bool AddEHEdges = AC.getAddEHEdges();
240 if (!AddEHEdges && count != cfg->getNumBlockIDs())
241 // When there are things remaining dead, and we didn't add EH edges
242 // from CallExprs to the catch clauses, we have to go back and
243 // mark them as live.
244 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
245 CFGBlock &b = **I;
246 if (!live[b.getBlockID()]) {
247 if (b.pred_begin() == b.pred_end()) {
248 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
249 // When not adding EH edges from calls, catch clauses
250 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000251 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000252 continue;
253 }
254 }
255 }
256
257 // Now we know what is live, we check the live precessors of the exit block
258 // and look for fall through paths, being careful to ignore normal returns,
259 // and exceptional paths.
260 bool HasLiveReturn = false;
261 bool HasFakeEdge = false;
262 bool HasPlainEdge = false;
263 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000264
265 // Ignore default cases that aren't likely to be reachable because all
266 // enums in a switch(X) have explicit case statements.
267 CFGBlock::FilterOptions FO;
268 FO.IgnoreDefaultsWithCoveredEnums = 1;
269
270 for (CFGBlock::filtered_pred_iterator
271 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
272 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000273 if (!live[B.getBlockID()])
274 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000275
Chandler Carruth03faf782011-09-13 09:53:58 +0000276 // Skip blocks which contain an element marked as no-return. They don't
277 // represent actually viable edges into the exit block, so mark them as
278 // abnormal.
279 if (B.hasNoReturnElement()) {
280 HasAbnormalEdge = true;
281 continue;
282 }
283
Ted Kremenek5d068492011-01-26 04:49:52 +0000284 // Destructors can appear after the 'return' in the CFG. This is
285 // normal. We need to look pass the destructors for the return
286 // statement (if it exists).
287 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000288
Chandler Carruth03faf782011-09-13 09:53:58 +0000289 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000290 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000291 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000292
Ted Kremenek5d068492011-01-26 04:49:52 +0000293 // No more CFGElements in the block?
294 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000295 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
296 HasAbnormalEdge = true;
297 continue;
298 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000299 // A labeled empty statement, or the entry block...
300 HasPlainEdge = true;
301 continue;
302 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000303
David Blaikie2a01f5d2013-02-21 20:58:29 +0000304 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000305 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000306 if (isa<ReturnStmt>(S)) {
307 HasLiveReturn = true;
308 continue;
309 }
310 if (isa<ObjCAtThrowStmt>(S)) {
311 HasFakeEdge = true;
312 continue;
313 }
314 if (isa<CXXThrowExpr>(S)) {
315 HasFakeEdge = true;
316 continue;
317 }
Chad Rosier32503022012-06-11 20:47:18 +0000318 if (isa<MSAsmStmt>(S)) {
319 // TODO: Verify this is correct.
320 HasFakeEdge = true;
321 HasLiveReturn = true;
322 continue;
323 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000324 if (isa<CXXTryStmt>(S)) {
325 HasAbnormalEdge = true;
326 continue;
327 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000328 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
329 == B.succ_end()) {
330 HasAbnormalEdge = true;
331 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000332 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000333
334 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000335 }
336 if (!HasPlainEdge) {
337 if (HasLiveReturn)
338 return NeverFallThrough;
339 return NeverFallThroughOrReturn;
340 }
341 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
342 return MaybeFallThrough;
343 // This says AlwaysFallThrough for calls to functions that are not marked
344 // noreturn, that don't return. If people would like this warning to be more
345 // accurate, such functions should be marked as noreturn.
346 return AlwaysFallThrough;
347}
348
Dan Gohman28ade552010-07-26 21:25:24 +0000349namespace {
350
Ted Kremenek918fe842010-03-20 21:06:02 +0000351struct CheckFallThroughDiagnostics {
352 unsigned diag_MaybeFallThrough_HasNoReturn;
353 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
354 unsigned diag_AlwaysFallThrough_HasNoReturn;
355 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
356 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000357 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000358 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000359
Douglas Gregor24f27692010-04-16 23:28:44 +0000360 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000361 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000362 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000363 D.diag_MaybeFallThrough_HasNoReturn =
364 diag::warn_falloff_noreturn_function;
365 D.diag_MaybeFallThrough_ReturnsNonVoid =
366 diag::warn_maybe_falloff_nonvoid_function;
367 D.diag_AlwaysFallThrough_HasNoReturn =
368 diag::warn_falloff_noreturn_function;
369 D.diag_AlwaysFallThrough_ReturnsNonVoid =
370 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000371
372 // Don't suggest that virtual functions be marked "noreturn", since they
373 // might be overridden by non-noreturn functions.
374 bool isVirtualMethod = false;
375 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
376 isVirtualMethod = Method->isVirtual();
377
Douglas Gregor0de57202011-10-10 18:15:57 +0000378 // Don't suggest that template instantiations be marked "noreturn"
379 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000380 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
381 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000382
383 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000384 D.diag_NeverFallThroughOrReturn =
385 diag::warn_suggest_noreturn_function;
386 else
387 D.diag_NeverFallThroughOrReturn = 0;
388
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000389 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000390 return D;
391 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000392
Ted Kremenek918fe842010-03-20 21:06:02 +0000393 static CheckFallThroughDiagnostics MakeForBlock() {
394 CheckFallThroughDiagnostics D;
395 D.diag_MaybeFallThrough_HasNoReturn =
396 diag::err_noreturn_block_has_return_expr;
397 D.diag_MaybeFallThrough_ReturnsNonVoid =
398 diag::err_maybe_falloff_nonvoid_block;
399 D.diag_AlwaysFallThrough_HasNoReturn =
400 diag::err_noreturn_block_has_return_expr;
401 D.diag_AlwaysFallThrough_ReturnsNonVoid =
402 diag::err_falloff_nonvoid_block;
403 D.diag_NeverFallThroughOrReturn =
404 diag::warn_suggest_noreturn_block;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000405 D.funMode = Block;
406 return D;
407 }
408
409 static CheckFallThroughDiagnostics MakeForLambda() {
410 CheckFallThroughDiagnostics D;
411 D.diag_MaybeFallThrough_HasNoReturn =
412 diag::err_noreturn_lambda_has_return_expr;
413 D.diag_MaybeFallThrough_ReturnsNonVoid =
414 diag::warn_maybe_falloff_nonvoid_lambda;
415 D.diag_AlwaysFallThrough_HasNoReturn =
416 diag::err_noreturn_lambda_has_return_expr;
417 D.diag_AlwaysFallThrough_ReturnsNonVoid =
418 diag::warn_falloff_nonvoid_lambda;
419 D.diag_NeverFallThroughOrReturn = 0;
420 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000421 return D;
422 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000423
David Blaikie9c902b52011-09-25 23:23:43 +0000424 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000425 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000426 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000427 return (ReturnsVoid ||
428 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000429 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000430 && (!HasNoReturn ||
431 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000432 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000433 && (!ReturnsVoid ||
434 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000435 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000436 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000437
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000438 // For blocks / lambdas.
439 return ReturnsVoid && !HasNoReturn
440 && ((funMode == Lambda) ||
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000441 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000442 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000443 }
444};
445
Dan Gohman28ade552010-07-26 21:25:24 +0000446}
447
Ted Kremenek918fe842010-03-20 21:06:02 +0000448/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
449/// function that should return a value. Check that we don't fall off the end
450/// of a noreturn function. We assume that functions and blocks not marked
451/// noreturn will return.
452static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000453 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000454 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000455 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000456
457 bool ReturnsVoid = false;
458 bool HasNoReturn = false;
459
460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000461 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000462 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000463 }
464 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000465 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000466 HasNoReturn = MD->hasAttr<NoReturnAttr>();
467 }
468 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000469 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000470 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000471 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000472 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000473 ReturnsVoid = true;
474 if (FT->getNoReturnAttr())
475 HasNoReturn = true;
476 }
477 }
478
David Blaikie9c902b52011-09-25 23:23:43 +0000479 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000480
481 // Short circuit for compilation speed.
482 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
483 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000484
Ted Kremenek918fe842010-03-20 21:06:02 +0000485 // FIXME: Function try block
486 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
487 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000488 case UnknownFallThrough:
489 break;
490
Ted Kremenek918fe842010-03-20 21:06:02 +0000491 case MaybeFallThrough:
492 if (HasNoReturn)
493 S.Diag(Compound->getRBracLoc(),
494 CD.diag_MaybeFallThrough_HasNoReturn);
495 else if (!ReturnsVoid)
496 S.Diag(Compound->getRBracLoc(),
497 CD.diag_MaybeFallThrough_ReturnsNonVoid);
498 break;
499 case AlwaysFallThrough:
500 if (HasNoReturn)
501 S.Diag(Compound->getRBracLoc(),
502 CD.diag_AlwaysFallThrough_HasNoReturn);
503 else if (!ReturnsVoid)
504 S.Diag(Compound->getRBracLoc(),
505 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
506 break;
507 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000508 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
509 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
510 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000511 << 0 << FD;
512 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
513 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
514 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000515 } else {
516 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
517 }
518 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000519 break;
520 case NeverFallThrough:
521 break;
522 }
523 }
524}
525
526//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000527// -Wuninitialized
528//===----------------------------------------------------------------------===//
529
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000530namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000531/// ContainsReference - A visitor class to search for references to
532/// a particular declaration (the needle) within any evaluated component of an
533/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000534class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000535 bool FoundReference;
536 const DeclRefExpr *Needle;
537
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000538public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000539 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
540 : EvaluatedExprVisitor<ContainsReference>(Context),
541 FoundReference(false), Needle(Needle) {}
542
543 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000544 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000545 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000546 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000547
548 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000549 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000550
551 void VisitDeclRefExpr(DeclRefExpr *E) {
552 if (E == Needle)
553 FoundReference = true;
554 else
555 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000556 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000557
558 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000559};
560}
561
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000562static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000563 QualType VariableTy = VD->getType().getCanonicalType();
564 if (VariableTy->isBlockPointerType() &&
565 !VD->hasAttr<BlocksAttr>()) {
566 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
567 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
568 return true;
569 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000570
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000571 // Don't issue a fixit if there is already an initializer.
572 if (VD->getInit())
573 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000574
575 // Don't suggest a fixit inside macros.
576 if (VD->getLocEnd().isMacroID())
577 return false;
578
Richard Smith8d06f422012-01-12 23:53:29 +0000579 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000580
581 // Suggest possible initialization (if any).
582 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
583 if (Init.empty())
584 return false;
585
Richard Smith8d06f422012-01-12 23:53:29 +0000586 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
587 << FixItHint::CreateInsertion(Loc, Init);
588 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000589}
590
Richard Smith1bb8edb82012-05-26 06:20:46 +0000591/// Create a fixit to remove an if-like statement, on the assumption that its
592/// condition is CondVal.
593static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
594 const Stmt *Else, bool CondVal,
595 FixItHint &Fixit1, FixItHint &Fixit2) {
596 if (CondVal) {
597 // If condition is always true, remove all but the 'then'.
598 Fixit1 = FixItHint::CreateRemoval(
599 CharSourceRange::getCharRange(If->getLocStart(),
600 Then->getLocStart()));
601 if (Else) {
602 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
603 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
604 Fixit2 = FixItHint::CreateRemoval(
605 SourceRange(ElseKwLoc, Else->getLocEnd()));
606 }
607 } else {
608 // If condition is always false, remove all but the 'else'.
609 if (Else)
610 Fixit1 = FixItHint::CreateRemoval(
611 CharSourceRange::getCharRange(If->getLocStart(),
612 Else->getLocStart()));
613 else
614 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
615 }
616}
617
618/// DiagUninitUse -- Helper function to produce a diagnostic for an
619/// uninitialized use of a variable.
620static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
621 bool IsCapturedByBlock) {
622 bool Diagnosed = false;
623
Richard Smithba8071e2013-09-12 18:49:10 +0000624 switch (Use.getKind()) {
625 case UninitUse::Always:
626 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
627 << VD->getDeclName() << IsCapturedByBlock
628 << Use.getUser()->getSourceRange();
629 return;
630
631 case UninitUse::AfterDecl:
632 case UninitUse::AfterCall:
633 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
634 << VD->getDeclName() << IsCapturedByBlock
635 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
636 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
637 << VD->getSourceRange();
638 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
639 << IsCapturedByBlock << Use.getUser()->getSourceRange();
640 return;
641
642 case UninitUse::Maybe:
643 case UninitUse::Sometimes:
644 // Carry on to report sometimes-uninitialized branches, if possible,
645 // or a 'may be used uninitialized' diagnostic otherwise.
646 break;
647 }
648
Richard Smith1bb8edb82012-05-26 06:20:46 +0000649 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000650 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
651 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000652 assert(Use.getKind() == UninitUse::Sometimes);
653
654 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000655 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000656
657 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000658 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000659 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000660 SourceRange Range;
661
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000662 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000663 // For all binary terminators, branch 0 is taken if the condition is true,
664 // and branch 1 is taken if the condition is false.
665 int RemoveDiagKind = -1;
666 const char *FixitStr =
667 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
668 : (I->Output ? "1" : "0");
669 FixItHint Fixit1, Fixit2;
670
Richard Smithba8071e2013-09-12 18:49:10 +0000671 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000672 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000673 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000674 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000675 continue;
676
677 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000678 case Stmt::IfStmtClass: {
679 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000680 DiagKind = 0;
681 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000682 Range = IS->getCond()->getSourceRange();
683 RemoveDiagKind = 0;
684 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
685 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000686 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000687 }
688 case Stmt::ConditionalOperatorClass: {
689 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000690 DiagKind = 0;
691 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000692 Range = CO->getCond()->getSourceRange();
693 RemoveDiagKind = 0;
694 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
695 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000696 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000697 }
Richard Smith4323bf82012-05-25 02:17:09 +0000698 case Stmt::BinaryOperatorClass: {
699 const BinaryOperator *BO = cast<BinaryOperator>(Term);
700 if (!BO->isLogicalOp())
701 continue;
702 DiagKind = 0;
703 Str = BO->getOpcodeStr();
704 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000705 RemoveDiagKind = 0;
706 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
707 (BO->getOpcode() == BO_LOr && !I->Output))
708 // true && y -> y, false || y -> y.
709 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
710 BO->getOperatorLoc()));
711 else
712 // false && y -> false, true || y -> true.
713 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000714 break;
715 }
716
717 // "loop is entered / loop is exited".
718 case Stmt::WhileStmtClass:
719 DiagKind = 1;
720 Str = "while";
721 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000722 RemoveDiagKind = 1;
723 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000724 break;
725 case Stmt::ForStmtClass:
726 DiagKind = 1;
727 Str = "for";
728 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000729 RemoveDiagKind = 1;
730 if (I->Output)
731 Fixit1 = FixItHint::CreateRemoval(Range);
732 else
733 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000734 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000735 case Stmt::CXXForRangeStmtClass:
736 if (I->Output == 1) {
737 // The use occurs if a range-based for loop's body never executes.
738 // That may be impossible, and there's no syntactic fix for this,
739 // so treat it as a 'may be uninitialized' case.
740 continue;
741 }
742 DiagKind = 1;
743 Str = "for";
744 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
745 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000746
747 // "condition is true / loop is exited".
748 case Stmt::DoStmtClass:
749 DiagKind = 2;
750 Str = "do";
751 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000752 RemoveDiagKind = 1;
753 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000754 break;
755
756 // "switch case is taken".
757 case Stmt::CaseStmtClass:
758 DiagKind = 3;
759 Str = "case";
760 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
761 break;
762 case Stmt::DefaultStmtClass:
763 DiagKind = 3;
764 Str = "default";
765 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
766 break;
767 }
768
Richard Smith1bb8edb82012-05-26 06:20:46 +0000769 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
770 << VD->getDeclName() << IsCapturedByBlock << DiagKind
771 << Str << I->Output << Range;
772 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
773 << IsCapturedByBlock << User->getSourceRange();
774 if (RemoveDiagKind != -1)
775 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
776 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
777
778 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000779 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000780
781 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000782 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000783 << VD->getDeclName() << IsCapturedByBlock
784 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000785}
786
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000787/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
788/// uninitialized variable. This manages the different forms of diagnostic
789/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000790/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000791/// false.
792static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000793 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000794 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000795
Richard Smith4323bf82012-05-25 02:17:09 +0000796 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000797 // Inspect the initializer of the variable declaration which is
798 // being referenced prior to its initialization. We emit
799 // specialized diagnostics for self-initialization, and we
800 // specifically avoid warning about self references which take the
801 // form of:
802 //
803 // int x = x;
804 //
805 // This is used to indicate to GCC that 'x' is intentionally left
806 // uninitialized. Proven code paths which access 'x' in
807 // an uninitialized state after this will still warn.
808 if (const Expr *Initializer = VD->getInit()) {
809 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
810 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000811
Richard Trieu43a2fc72012-05-09 21:08:22 +0000812 ContainsReference CR(S.Context, DRE);
813 CR.Visit(const_cast<Expr*>(Initializer));
814 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000815 S.Diag(DRE->getLocStart(),
816 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000817 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
818 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000819 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000820 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000821
Richard Smith1bb8edb82012-05-26 06:20:46 +0000822 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000823 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000824 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000825 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
826 S.Diag(BE->getLocStart(),
827 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000828 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000829 else
830 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000831 }
832
833 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000834 // the initializer of that declaration & we didn't already suggest
835 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000836 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000837 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
838 << VD->getDeclName();
839
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000840 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000841}
842
Richard Smith84837d52012-05-03 18:27:39 +0000843namespace {
844 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
845 public:
846 FallthroughMapper(Sema &S)
847 : FoundSwitchStatements(false),
848 S(S) {
849 }
850
851 bool foundSwitchStatements() const { return FoundSwitchStatements; }
852
853 void markFallthroughVisited(const AttributedStmt *Stmt) {
854 bool Found = FallthroughStmts.erase(Stmt);
855 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000856 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000857 }
858
859 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
860
861 const AttrStmts &getFallthroughStmts() const {
862 return FallthroughStmts;
863 }
864
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000865 void fillReachableBlocks(CFG *Cfg) {
866 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
867 std::deque<const CFGBlock *> BlockQueue;
868
869 ReachableBlocks.insert(&Cfg->getEntry());
870 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000871 // Mark all case blocks reachable to avoid problems with switching on
872 // constants, covered enums, etc.
873 // These blocks can contain fall-through annotations, and we don't want to
874 // issue a warn_fallthrough_attr_unreachable for them.
875 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
876 const CFGBlock *B = *I;
877 const Stmt *L = B->getLabel();
878 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
879 BlockQueue.push_back(B);
880 }
881
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000882 while (!BlockQueue.empty()) {
883 const CFGBlock *P = BlockQueue.front();
884 BlockQueue.pop_front();
885 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
886 E = P->succ_end();
887 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000888 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000889 BlockQueue.push_back(*I);
890 }
891 }
892 }
893
Richard Smith84837d52012-05-03 18:27:39 +0000894 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000895 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
896
Richard Smith84837d52012-05-03 18:27:39 +0000897 int UnannotatedCnt = 0;
898 AnnotatedCnt = 0;
899
900 std::deque<const CFGBlock*> BlockQueue;
901
902 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
903
904 while (!BlockQueue.empty()) {
905 const CFGBlock *P = BlockQueue.front();
906 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000907 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000908
909 const Stmt *Term = P->getTerminator();
910 if (Term && isa<SwitchStmt>(Term))
911 continue; // Switch statement, good.
912
913 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
914 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
915 continue; // Previous case label has no statements, good.
916
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000917 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
918 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
919 continue; // Case label is preceded with a normal label, good.
920
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000921 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000922 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
923 ElemEnd = P->rend();
924 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000925 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
926 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000927 S.Diag(AS->getLocStart(),
928 diag::warn_fallthrough_attr_unreachable);
929 markFallthroughVisited(AS);
930 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000931 break;
Richard Smith84837d52012-05-03 18:27:39 +0000932 }
933 // Don't care about other unreachable statements.
934 }
935 }
936 // If there are no unreachable statements, this may be a special
937 // case in CFG:
938 // case X: {
939 // A a; // A has a destructor.
940 // break;
941 // }
942 // // <<<< This place is represented by a 'hanging' CFG block.
943 // case Y:
944 continue;
945 }
946
947 const Stmt *LastStmt = getLastStmt(*P);
948 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
949 markFallthroughVisited(AS);
950 ++AnnotatedCnt;
951 continue; // Fallthrough annotation, good.
952 }
953
954 if (!LastStmt) { // This block contains no executable statements.
955 // Traverse its predecessors.
956 std::copy(P->pred_begin(), P->pred_end(),
957 std::back_inserter(BlockQueue));
958 continue;
959 }
960
961 ++UnannotatedCnt;
962 }
963 return !!UnannotatedCnt;
964 }
965
966 // RecursiveASTVisitor setup.
967 bool shouldWalkTypesOfTypeLocs() const { return false; }
968
969 bool VisitAttributedStmt(AttributedStmt *S) {
970 if (asFallThroughAttr(S))
971 FallthroughStmts.insert(S);
972 return true;
973 }
974
975 bool VisitSwitchStmt(SwitchStmt *S) {
976 FoundSwitchStatements = true;
977 return true;
978 }
979
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000980 // We don't want to traverse local type declarations. We analyze their
981 // methods separately.
982 bool TraverseDecl(Decl *D) { return true; }
983
Richard Smith84837d52012-05-03 18:27:39 +0000984 private:
985
986 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
987 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
988 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
989 return AS;
990 }
991 return 0;
992 }
993
994 static const Stmt *getLastStmt(const CFGBlock &B) {
995 if (const Stmt *Term = B.getTerminator())
996 return Term;
997 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
998 ElemEnd = B.rend();
999 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001000 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1001 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001002 }
1003 // Workaround to detect a statement thrown out by CFGBuilder:
1004 // case X: {} case Y:
1005 // case X: ; case Y:
1006 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1007 if (!isa<SwitchCase>(SW->getSubStmt()))
1008 return SW->getSubStmt();
1009
1010 return 0;
1011 }
1012
1013 bool FoundSwitchStatements;
1014 AttrStmts FallthroughStmts;
1015 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001016 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001017 };
1018}
1019
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001020static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001021 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001022 // Only perform this analysis when using C++11. There is no good workflow
1023 // for this warning when not using C++11. There is no good way to silence
1024 // the warning (no attribute is available) unless we are using C++11's support
1025 // for generalized attributes. Once could use pragmas to silence the warning,
1026 // but as a general solution that is gross and not in the spirit of this
1027 // warning.
1028 //
1029 // NOTE: This an intermediate solution. There are on-going discussions on
1030 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001031 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001032 return;
1033
Richard Smith84837d52012-05-03 18:27:39 +00001034 FallthroughMapper FM(S);
1035 FM.TraverseStmt(AC.getBody());
1036
1037 if (!FM.foundSwitchStatements())
1038 return;
1039
Alexis Hunt2178f142012-06-15 21:22:05 +00001040 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001041 return;
1042
Richard Smith84837d52012-05-03 18:27:39 +00001043 CFG *Cfg = AC.getCFG();
1044
1045 if (!Cfg)
1046 return;
1047
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001048 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001049
1050 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001051 const CFGBlock *B = *I;
1052 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001053
1054 if (!Label || !isa<SwitchCase>(Label))
1055 continue;
1056
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001057 int AnnotatedCnt;
1058
Alexander Kornienko55488792013-01-25 15:49:34 +00001059 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001060 continue;
1061
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001062 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001063 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1064 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001065
1066 if (!AnnotatedCnt) {
1067 SourceLocation L = Label->getLocStart();
1068 if (L.isMacroID())
1069 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001070 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001071 const Stmt *Term = B->getTerminator();
1072 // Skip empty cases.
1073 while (B->empty() && !Term && B->succ_size() == 1) {
1074 B = *B->succ_begin();
1075 Term = B->getTerminator();
1076 }
1077 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001078 Preprocessor &PP = S.getPreprocessor();
1079 TokenValue Tokens[] = {
1080 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1081 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1082 tok::r_square, tok::r_square
1083 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001084 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1085 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1086 if (!MacroName.empty())
1087 AnnotationSpelling = MacroName;
1088 SmallString<64> TextToInsert(AnnotationSpelling);
1089 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001090 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001091 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001092 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001093 }
Richard Smith84837d52012-05-03 18:27:39 +00001094 }
1095 S.Diag(L, diag::note_insert_break_fixit) <<
1096 FixItHint::CreateInsertion(L, "break; ");
1097 }
1098 }
1099
1100 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1101 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1102 E = Fallthroughs.end();
1103 I != E; ++I) {
1104 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1105 }
1106
1107}
1108
Jordan Rose25c0ea82012-10-29 17:46:47 +00001109static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1110 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001111 assert(S);
1112
1113 do {
1114 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001115 case Stmt::ForStmtClass:
1116 case Stmt::WhileStmtClass:
1117 case Stmt::CXXForRangeStmtClass:
1118 case Stmt::ObjCForCollectionStmtClass:
1119 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001120 case Stmt::DoStmtClass: {
1121 const Expr *Cond = cast<DoStmt>(S)->getCond();
1122 llvm::APSInt Val;
1123 if (!Cond->EvaluateAsInt(Val, Ctx))
1124 return true;
1125 return Val.getBoolValue();
1126 }
Jordan Rose76831c62012-10-11 16:10:19 +00001127 default:
1128 break;
1129 }
1130 } while ((S = PM.getParent(S)));
1131
1132 return false;
1133}
1134
Jordan Rosed3934582012-09-28 22:21:30 +00001135
1136static void diagnoseRepeatedUseOfWeak(Sema &S,
1137 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001138 const Decl *D,
1139 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001140 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1141 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1142 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001143 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1144 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001145
Jordan Rose25c0ea82012-10-29 17:46:47 +00001146 ASTContext &Ctx = S.getASTContext();
1147
Jordan Rosed3934582012-09-28 22:21:30 +00001148 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1149
1150 // Extract all weak objects that are referenced more than once.
1151 SmallVector<StmtUsesPair, 8> UsesByStmt;
1152 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1153 I != E; ++I) {
1154 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001155
1156 // Find the first read of the weak object.
1157 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1158 for ( ; UI != UE; ++UI) {
1159 if (UI->isUnsafe())
1160 break;
1161 }
1162
1163 // If there were only writes to this object, don't warn.
1164 if (UI == UE)
1165 continue;
1166
Jordan Rose76831c62012-10-11 16:10:19 +00001167 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001168 // read is not within a loop, don't warn. Additionally, don't warn in a
1169 // loop if the base object is a local variable -- local variables are often
1170 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001171 if (UI == Uses.begin()) {
1172 WeakUseVector::const_iterator UI2 = UI;
1173 for (++UI2; UI2 != UE; ++UI2)
1174 if (UI2->isUnsafe())
1175 break;
1176
Jordan Rose25c0ea82012-10-29 17:46:47 +00001177 if (UI2 == UE) {
1178 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001179 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001180
1181 const WeakObjectProfileTy &Profile = I->first;
1182 if (!Profile.isExactProfile())
1183 continue;
1184
1185 const NamedDecl *Base = Profile.getBase();
1186 if (!Base)
1187 Base = Profile.getProperty();
1188 assert(Base && "A profile always has a base or property.");
1189
1190 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1191 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1192 continue;
1193 }
Jordan Rose76831c62012-10-11 16:10:19 +00001194 }
1195
Jordan Rosed3934582012-09-28 22:21:30 +00001196 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1197 }
1198
1199 if (UsesByStmt.empty())
1200 return;
1201
1202 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001203 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001204 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001205 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1206 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1207 RHS.first->getLocStart());
1208 });
Jordan Rosed3934582012-09-28 22:21:30 +00001209
1210 // Classify the current code body for better warning text.
1211 // This enum should stay in sync with the cases in
1212 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1213 // FIXME: Should we use a common classification enum and the same set of
1214 // possibilities all throughout Sema?
1215 enum {
1216 Function,
1217 Method,
1218 Block,
1219 Lambda
1220 } FunctionKind;
1221
1222 if (isa<sema::BlockScopeInfo>(CurFn))
1223 FunctionKind = Block;
1224 else if (isa<sema::LambdaScopeInfo>(CurFn))
1225 FunctionKind = Lambda;
1226 else if (isa<ObjCMethodDecl>(D))
1227 FunctionKind = Method;
1228 else
1229 FunctionKind = Function;
1230
1231 // Iterate through the sorted problems and emit warnings for each.
1232 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1233 E = UsesByStmt.end();
1234 I != E; ++I) {
1235 const Stmt *FirstRead = I->first;
1236 const WeakObjectProfileTy &Key = I->second->first;
1237 const WeakUseVector &Uses = I->second->second;
1238
Jordan Rose657b5f42012-09-28 22:21:35 +00001239 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1240 // may not contain enough information to determine that these are different
1241 // properties. We can only be 100% sure of a repeated use in certain cases,
1242 // and we adjust the diagnostic kind accordingly so that the less certain
1243 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001244 unsigned DiagKind;
1245 if (Key.isExactProfile())
1246 DiagKind = diag::warn_arc_repeated_use_of_weak;
1247 else
1248 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1249
Jordan Rose657b5f42012-09-28 22:21:35 +00001250 // Classify the weak object being accessed for better warning text.
1251 // This enum should stay in sync with the cases in
1252 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1253 enum {
1254 Variable,
1255 Property,
1256 ImplicitProperty,
1257 Ivar
1258 } ObjectKind;
1259
1260 const NamedDecl *D = Key.getProperty();
1261 if (isa<VarDecl>(D))
1262 ObjectKind = Variable;
1263 else if (isa<ObjCPropertyDecl>(D))
1264 ObjectKind = Property;
1265 else if (isa<ObjCMethodDecl>(D))
1266 ObjectKind = ImplicitProperty;
1267 else if (isa<ObjCIvarDecl>(D))
1268 ObjectKind = Ivar;
1269 else
1270 llvm_unreachable("Unexpected weak object kind!");
1271
Jordan Rosed3934582012-09-28 22:21:30 +00001272 // Show the first time the object was read.
1273 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001274 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001275 << FirstRead->getSourceRange();
1276
1277 // Print all the other accesses as notes.
1278 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1279 UI != UE; ++UI) {
1280 if (UI->getUseExpr() == FirstRead)
1281 continue;
1282 S.Diag(UI->getUseExpr()->getLocStart(),
1283 diag::note_arc_weak_also_accessed_here)
1284 << UI->getUseExpr()->getSourceRange();
1285 }
1286 }
1287}
1288
Jordan Rosed3934582012-09-28 22:21:30 +00001289namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001290class UninitValsDiagReporter : public UninitVariablesHandler {
1291 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001292 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001293 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001294 // Prefer using MapVector to DenseMap, so that iteration order will be
1295 // the same as insertion order. This is needed to obtain a deterministic
1296 // order of diagnostics when calling flushDiagnostics().
1297 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001298 UsesMap *uses;
1299
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001300public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001301 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1302 ~UninitValsDiagReporter() {
1303 flushDiagnostics();
1304 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001305
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001306 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001307 if (!uses)
1308 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001309
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001310 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001311 if (!V.getPointer())
1312 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001313
Ted Kremenek596fa162011-10-13 18:50:06 +00001314 return V;
1315 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001316
1317 void handleUseOfUninitVariable(const VarDecl *vd,
1318 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001319 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001320 }
1321
Craig Toppere14c0f82014-03-12 04:55:44 +00001322 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001323 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001324 }
1325
1326 void flushDiagnostics() {
1327 if (!uses)
1328 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001329
Ted Kremenek39fa0562011-01-21 19:41:41 +00001330 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1331 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001332 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001333
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001334 UsesVec *vec = V.getPointer();
1335 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001336
1337 // Specially handle the case where we have uses of an uninitialized
1338 // variable, but the root cause is an idiomatic self-init. We want
1339 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001340 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001341 DiagnoseUninitializedUse(S, vd,
1342 UninitUse(vd->getInit()->IgnoreParenCasts(),
1343 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001344 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001345 else {
1346 // Sort the uses by their SourceLocations. While not strictly
1347 // guaranteed to produce them in line/column order, this will provide
1348 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001349 std::sort(vec->begin(), vec->end(),
1350 [](const UninitUse &a, const UninitUse &b) {
1351 // Prefer a more confident report over a less confident one.
1352 if (a.getKind() != b.getKind())
1353 return a.getKind() > b.getKind();
1354 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1355 });
1356
Ted Kremenek596fa162011-10-13 18:50:06 +00001357 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1358 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001359 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1360 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1361
1362 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001363 // Skip further diagnostics for this variable. We try to warn only
1364 // on the first point at which a variable is used uninitialized.
1365 break;
1366 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001367 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001368
1369 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001370 delete vec;
1371 }
1372 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001373 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001374
1375private:
1376 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1377 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001378 if (i->getKind() == UninitUse::Always ||
1379 i->getKind() == UninitUse::AfterCall ||
1380 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001381 return true;
1382 }
1383 }
1384 return false;
1385}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001386};
1387}
1388
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001389namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001390namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001391typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001392typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001393typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001394
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001395struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001396 SourceManager &SM;
1397 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001398
1399 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1400 // Although this call will be slow, this is only called when outputting
1401 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001402 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001403 }
1404};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001405}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001406
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001407//===----------------------------------------------------------------------===//
1408// -Wthread-safety
1409//===----------------------------------------------------------------------===//
1410namespace clang {
1411namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001412namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001413class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1414 Sema &S;
1415 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001416 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001417
1418 // Helper functions
1419 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001420 // Gracefully handle rare cases when the analysis can't get a more
1421 // precise source location.
1422 if (!Loc.isValid())
1423 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001424 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1425 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001426 }
1427
1428 public:
Richard Smith92286672012-02-03 04:45:26 +00001429 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1430 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001431
1432 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1433 /// We need to output diagnostics produced while iterating through
1434 /// the lockset in deterministic order, so this function orders diagnostics
1435 /// and outputs them.
1436 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001437 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001438 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001439 I != E; ++I) {
1440 S.Diag(I->first.first, I->first.second);
1441 const OptionalNotes &Notes = I->second;
1442 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1443 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1444 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001445 }
1446
Craig Toppere14c0f82014-03-12 04:55:44 +00001447 void handleInvalidLockExp(SourceLocation Loc) override {
Richard Smith92286672012-02-03 04:45:26 +00001448 PartialDiagnosticAt Warning(Loc,
1449 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1450 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001451 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001452 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) override {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001453 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1454 }
Aaron Ballmandf115d92014-03-21 14:48:48 +00001455 void handleIncorrectUnlockKind(Name LockName, LockKind Expected,
1456 LockKind Received,
1457 SourceLocation Loc) override {
1458 if (Loc.isInvalid())
1459 Loc = FunLocation;
1460 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1461 << LockName << Received << Expected);
1462 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1463 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001464 void handleDoubleLock(Name LockName, SourceLocation Loc) override {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001465 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1466 }
1467
Richard Smith92286672012-02-03 04:45:26 +00001468 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1469 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001470 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001471 unsigned DiagID = 0;
1472 switch (LEK) {
1473 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001474 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001475 break;
1476 case LEK_LockedSomeLoopIterations:
1477 DiagID = diag::warn_expecting_lock_held_on_loop;
1478 break;
1479 case LEK_LockedAtEndOfFunction:
1480 DiagID = diag::warn_no_unlock;
1481 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001482 case LEK_NotLockedAtEndOfFunction:
1483 DiagID = diag::warn_expecting_locked;
1484 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001485 }
Richard Smith92286672012-02-03 04:45:26 +00001486 if (LocEndOfScope.isInvalid())
1487 LocEndOfScope = FunEndLocation;
1488
1489 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001490 if (LocLocked.isValid()) {
1491 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1492 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1493 return;
1494 }
1495 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001496 }
1497
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001498
1499 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001500 SourceLocation Loc2) override {
Richard Smith92286672012-02-03 04:45:26 +00001501 PartialDiagnosticAt Warning(
1502 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1503 PartialDiagnosticAt Note(
1504 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1505 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001506 }
1507
1508 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
Craig Toppere14c0f82014-03-12 04:55:44 +00001509 AccessKind AK, SourceLocation Loc) override {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001510 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1511 && "Only works for variables");
1512 unsigned DiagID = POK == POK_VarAccess?
1513 diag::warn_variable_requires_any_lock:
1514 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001515 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001516 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001517 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001518 }
1519
1520 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001521 Name LockName, LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001522 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001523 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001524 if (PossibleMatch) {
1525 switch (POK) {
1526 case POK_VarAccess:
1527 DiagID = diag::warn_variable_requires_lock_precise;
1528 break;
1529 case POK_VarDereference:
1530 DiagID = diag::warn_var_deref_requires_lock_precise;
1531 break;
1532 case POK_FunctionCall:
1533 DiagID = diag::warn_fun_requires_lock_precise;
1534 break;
1535 }
1536 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001537 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001538 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1539 << *PossibleMatch);
1540 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1541 } else {
1542 switch (POK) {
1543 case POK_VarAccess:
1544 DiagID = diag::warn_variable_requires_lock;
1545 break;
1546 case POK_VarDereference:
1547 DiagID = diag::warn_var_deref_requires_lock;
1548 break;
1549 case POK_FunctionCall:
1550 DiagID = diag::warn_fun_requires_lock;
1551 break;
1552 }
1553 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001554 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001555 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001556 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001557 }
1558
Craig Toppere14c0f82014-03-12 04:55:44 +00001559 void handleFunExcludesLock(Name FunName, Name LockName,
1560 SourceLocation Loc) override {
Richard Smith92286672012-02-03 04:45:26 +00001561 PartialDiagnosticAt Warning(Loc,
1562 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1563 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001564 }
1565};
1566}
1567}
David Blaikie68e081d2011-12-20 02:48:34 +00001568}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001569
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001570//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001571// -Wconsumed
1572//===----------------------------------------------------------------------===//
1573
1574namespace clang {
1575namespace consumed {
1576namespace {
1577class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1578
1579 Sema &S;
1580 DiagList Warnings;
1581
1582public:
1583
1584 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001585
1586 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001587 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1588
1589 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1590 I != E; ++I) {
1591
1592 const OptionalNotes &Notes = I->second;
1593 S.Diag(I->first.first, I->first.second);
1594
1595 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1596 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1597 }
1598 }
1599 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001600
1601 void warnLoopStateMismatch(SourceLocation Loc,
1602 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001603 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1604 VariableName);
1605
1606 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1607 }
1608
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001609 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1610 StringRef VariableName,
1611 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001612 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001613
1614 PartialDiagnosticAt Warning(Loc, S.PDiag(
1615 diag::warn_param_return_typestate_mismatch) << VariableName <<
1616 ExpectedState << ObservedState);
1617
1618 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1619 }
1620
DeLesley Hutchins69391772013-10-17 23:23:53 +00001621 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001622 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001623
1624 PartialDiagnosticAt Warning(Loc, S.PDiag(
1625 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1626
1627 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1628 }
1629
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001630 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001631 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001632 PartialDiagnosticAt Warning(Loc, S.PDiag(
1633 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1634
1635 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1636 }
1637
1638 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001639 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001640
1641 PartialDiagnosticAt Warning(Loc, S.PDiag(
1642 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1643
1644 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1645 }
1646
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001647 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001648 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001649
1650 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001651 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001652
1653 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1654 }
1655
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001656 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001657 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001658
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001659 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1660 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001661
1662 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1663 }
1664};
1665}}}
1666
1667//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001668// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1669// warnings on a function, method, or block.
1670//===----------------------------------------------------------------------===//
1671
Ted Kremenek0b405322010-03-23 00:13:23 +00001672clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1673 enableCheckFallThrough = 1;
1674 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001675 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001676 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001677}
1678
Ted Kremenekad8753c2014-03-15 05:47:06 +00001679static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1680 return (unsigned) D.getDiagnosticLevel(diag, SourceLocation()) !=
1681 DiagnosticsEngine::Ignored;
1682}
1683
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001684clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1685 : S(s),
1686 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001687 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001688 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001689 MaxCFGBlocksPerFunction(0),
1690 NumUninitAnalysisFunctions(0),
1691 NumUninitAnalysisVariables(0),
1692 MaxUninitAnalysisVariablesPerFunction(0),
1693 NumUninitAnalysisBlockVisits(0),
1694 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001695
1696 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001697 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001698
1699 DefaultPolicy.enableCheckUnreachable =
1700 isEnabled(D, warn_unreachable) ||
1701 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001702 isEnabled(D, warn_unreachable_return) ||
1703 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001704
1705 DefaultPolicy.enableThreadSafetyAnalysis =
1706 isEnabled(D, warn_double_lock);
1707
1708 DefaultPolicy.enableConsumedAnalysis =
1709 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001710}
1711
Ted Kremenek3427fac2011-02-23 01:52:04 +00001712static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001713 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001714 i = fscope->PossiblyUnreachableDiags.begin(),
1715 e = fscope->PossiblyUnreachableDiags.end();
1716 i != e; ++i) {
1717 const sema::PossiblyUnreachableDiag &D = *i;
1718 S.Diag(D.Loc, D.PD);
1719 }
1720}
1721
Ted Kremenek0b405322010-03-23 00:13:23 +00001722void clang::sema::
1723AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001724 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001725 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001726
Ted Kremenek918fe842010-03-20 21:06:02 +00001727 // We avoid doing analysis-based warnings when there are errors for
1728 // two reasons:
1729 // (1) The CFGs often can't be constructed (if the body is invalid), so
1730 // don't bother trying.
1731 // (2) The code already has problems; running the analysis just takes more
1732 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001733 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001734
Ted Kremenek0b405322010-03-23 00:13:23 +00001735 // Do not do any analysis for declarations in system headers if we are
1736 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001737 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001738 S.SourceMgr.isInSystemHeader(D->getLocation()))
1739 return;
1740
John McCall1d570a72010-08-25 05:56:39 +00001741 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001742 if (cast<DeclContext>(D)->isDependentContext())
1743 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001744
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001745 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001746 // Flush out any possibly unreachable diagnostics.
1747 flushDiagnostics(S, fscope);
1748 return;
1749 }
1750
Ted Kremenek918fe842010-03-20 21:06:02 +00001751 const Stmt *Body = D->getBody();
1752 assert(Body);
1753
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001754 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001755 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001756
Ted Kremenek918fe842010-03-20 21:06:02 +00001757 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001758 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001759 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1760 AC.getCFGBuildOptions().AddEHEdges = false;
1761 AC.getCFGBuildOptions().AddInitializers = true;
1762 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001763 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001764 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001765
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001766 // Force that certain expressions appear as CFGElements in the CFG. This
1767 // is used to speed up various analyses.
1768 // FIXME: This isn't the right factoring. This is here for initial
1769 // prototyping, but we need a way for analyses to say what expressions they
1770 // expect to always be CFGElements and then fill in the BuildOptions
1771 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001772 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1773 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001774 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001775 AC.getCFGBuildOptions().setAllAlwaysAdd();
1776 }
1777 else {
1778 AC.getCFGBuildOptions()
1779 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001780 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001781 .setAlwaysAdd(Stmt::BlockExprClass)
1782 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1783 .setAlwaysAdd(Stmt::DeclRefExprClass)
1784 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001785 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1786 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001787 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001788
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001789
Ted Kremenek3427fac2011-02-23 01:52:04 +00001790 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001791 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001792 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001793
1794 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001795 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001796 i = fscope->PossiblyUnreachableDiags.begin(),
1797 e = fscope->PossiblyUnreachableDiags.end();
1798 i != e; ++i) {
1799 if (const Stmt *stmt = i->stmt)
1800 AC.registerForcedBlockExpression(stmt);
1801 }
1802
1803 if (AC.getCFG()) {
1804 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001805 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001806 i = fscope->PossiblyUnreachableDiags.begin(),
1807 e = fscope->PossiblyUnreachableDiags.end();
1808 i != e; ++i)
1809 {
1810 const sema::PossiblyUnreachableDiag &D = *i;
1811 bool processed = false;
1812 if (const Stmt *stmt = i->stmt) {
1813 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001814 CFGReverseBlockReachabilityAnalysis *cra =
1815 AC.getCFGReachablityAnalysis();
1816 // FIXME: We should be able to assert that block is non-null, but
1817 // the CFG analysis can skip potentially-evaluated expressions in
1818 // edge cases; see test/Sema/vla-2.c.
1819 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001820 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001821 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001822 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001823 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001824 }
1825 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001826 if (!processed) {
1827 // Emit the warning anyway if we cannot map to a basic block.
1828 S.Diag(D.Loc, D.PD);
1829 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001830 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001831 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001832
1833 if (!analyzed)
1834 flushDiagnostics(S, fscope);
1835 }
1836
1837
Ted Kremenek918fe842010-03-20 21:06:02 +00001838 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001839 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001840 const CheckFallThroughDiagnostics &CD =
1841 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001842 : (isa<CXXMethodDecl>(D) &&
1843 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1844 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1845 ? CheckFallThroughDiagnostics::MakeForLambda()
1846 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001847 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001848 }
1849
1850 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001851 if (P.enableCheckUnreachable) {
1852 // Only check for unreachable code on non-template instantiations.
1853 // Different template instantiations can effectively change the control-flow
1854 // and it is very difficult to prove that a snippet of code in a template
1855 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001856 bool isTemplateInstantiation = false;
1857 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1858 isTemplateInstantiation = Function->isTemplateInstantiation();
1859 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001860 CheckUnreachable(S, AC);
1861 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001862
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001863 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001864 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001865 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001866 SourceLocation FEL = AC.getDecl()->getLocEnd();
1867 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001868 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1869 != DiagnosticsEngine::Ignored)
1870 Reporter.setIssueBetaWarnings(true);
1871
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001872 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1873 Reporter.emitDiagnostics();
1874 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001875
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001876 // Check for violations of consumed properties.
1877 if (P.enableConsumedAnalysis) {
1878 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001879 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001880 Analyzer.run(AC);
1881 }
1882
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001883 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001884 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001885 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1886 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001887 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001888 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001889 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001890 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001891 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001892 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001893 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001894 reporter, stats);
1895
1896 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1897 ++NumUninitAnalysisFunctions;
1898 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1899 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1900 MaxUninitAnalysisVariablesPerFunction =
1901 std::max(MaxUninitAnalysisVariablesPerFunction,
1902 stats.NumVariablesAnalyzed);
1903 MaxUninitAnalysisBlockVisitsPerFunction =
1904 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1905 stats.NumBlockVisits);
1906 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001907 }
1908 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001909
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001910 bool FallThroughDiagFull =
1911 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1912 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001913 bool FallThroughDiagPerFunction =
1914 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001915 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001916 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001917 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001918 }
1919
Jordan Rosed3934582012-09-28 22:21:30 +00001920 if (S.getLangOpts().ObjCARCWeak &&
1921 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1922 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001923 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001924
Richard Trieu2f024f42013-12-21 02:33:43 +00001925
1926 // Check for infinite self-recursion in functions
1927 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1928 D->getLocStart())
1929 != DiagnosticsEngine::Ignored) {
1930 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1931 checkRecursiveFunction(S, FD, Body, AC);
1932 }
1933 }
1934
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001935 // Collect statistics about the CFG if it was built.
1936 if (S.CollectStats && AC.isCFGBuilt()) {
1937 ++NumFunctionsAnalyzed;
1938 if (CFG *cfg = AC.getCFG()) {
1939 // If we successfully built a CFG for this context, record some more
1940 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001941 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001942 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001943 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001944 } else {
1945 ++NumFunctionsWithBadCFGs;
1946 }
1947 }
1948}
1949
1950void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1951 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1952
1953 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1954 unsigned AvgCFGBlocksPerFunction =
1955 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1956 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1957 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1958 << " " << NumCFGBlocks << " CFG blocks built.\n"
1959 << " " << AvgCFGBlocksPerFunction
1960 << " average CFG blocks per function.\n"
1961 << " " << MaxCFGBlocksPerFunction
1962 << " max CFG blocks per function.\n";
1963
1964 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1965 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1966 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1967 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1968 llvm::errs() << NumUninitAnalysisFunctions
1969 << " functions analyzed for uninitialiazed variables\n"
1970 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1971 << " " << AvgUninitVariablesPerFunction
1972 << " average variables per function.\n"
1973 << " " << MaxUninitAnalysisVariablesPerFunction
1974 << " max variables per function.\n"
1975 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1976 << " " << AvgUninitBlockVisitsPerFunction
1977 << " average block visits per function.\n"
1978 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1979 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001980}