blob: d10b5a84960314482dbb8288075d361330b164a5 [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,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000069 SourceLocation L,
70 SourceRange SilenceableCondVal,
71 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000072 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000073 unsigned diag = diag::warn_unreachable;
74 switch (UK) {
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
77 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000078 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000079 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000080 break;
Ted Kremenek14210372014-03-21 06:02:36 +000081 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
83 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 case reachable_code::UK_Other:
85 break;
86 }
87
88 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000089
90 SourceLocation Open = SilenceableCondVal.getBegin();
91 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000092 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000094 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
98 }
99 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000100 }
101 };
102}
103
104/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000105static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000106 // As a heuristic prune all diagnostics not in the main file. Currently
107 // the majority of warnings in headers are false positives. These
108 // are largely caused by configuration state, e.g. preprocessor
109 // defined code, etc.
110 //
111 // Note that this is also a performance optimization. Analyzing
112 // headers many times can be expensive.
113 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
114 return;
115
Ted Kremenek918fe842010-03-20 21:06:02 +0000116 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000118}
119
Richard Trieuf935b562014-04-05 05:17:01 +0000120/// \brief Warn on logical operator errors in CFGBuilder
121class LogicalErrorHandler : public CFGCallback {
122 Sema &S;
123
124public:
125 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
126
127 static bool HasMacroID(const Expr *E) {
128 if (E->getExprLoc().isMacroID())
129 return true;
130
131 // Recurse to children.
132 for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
133 if (*SubStmts)
134 if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
135 if (HasMacroID(SubExpr))
136 return true;
137
138 return false;
139 }
140
141 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {
142 if (HasMacroID(B))
143 return;
144
145 SourceRange DiagRange = B->getSourceRange();
146 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
147 << DiagRange << isAlwaysTrue;
148 }
149};
150
151
Ted Kremenek918fe842010-03-20 21:06:02 +0000152//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000153// Check for infinite self-recursion in functions
154//===----------------------------------------------------------------------===//
155
156// All blocks are in one of three states. States are ordered so that blocks
157// can only move to higher states.
158enum RecursiveState {
159 FoundNoPath,
160 FoundPath,
161 FoundPathWithNoRecursiveCall
162};
163
164static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
165 CFGBlock &Block, unsigned ExitID,
166 llvm::SmallVectorImpl<RecursiveState> &States,
167 RecursiveState State) {
168 unsigned ID = Block.getBlockID();
169
170 // A block's state can only move to a higher state.
171 if (States[ID] >= State)
172 return;
173
174 States[ID] = State;
175
176 // Found a path to the exit node without a recursive call.
177 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
178 return;
179
180 if (State == FoundPathWithNoRecursiveCall) {
181 // If the current state is FoundPathWithNoRecursiveCall, the successors
182 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
183 // which, process all the Stmt's in this block to find any recursive calls.
Aaron Ballmane5195222014-05-15 20:50:47 +0000184 for (const auto &B : Block) {
185 if (B.getKind() != CFGElement::Statement)
Richard Trieu2f024f42013-12-21 02:33:43 +0000186 continue;
187
Aaron Ballmane5195222014-05-15 20:50:47 +0000188 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
Richard Trieu2f024f42013-12-21 02:33:43 +0000189 if (CE && CE->getCalleeDecl() &&
190 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000191
192 // Skip function calls which are qualified with a templated class.
193 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
194 CE->getCallee()->IgnoreParenImpCasts())) {
195 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
196 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
197 isa<TemplateSpecializationType>(NNS->getAsType())) {
198 continue;
199 }
200 }
201 }
202
Richard Trieu2f024f42013-12-21 02:33:43 +0000203 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
204 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
205 !MCE->getMethodDecl()->isVirtual()) {
206 State = FoundPath;
207 break;
208 }
209 } else {
210 State = FoundPath;
211 break;
212 }
213 }
214 }
215 }
216
217 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
218 I != E; ++I)
219 if (*I)
220 checkForFunctionCall(S, FD, **I, ExitID, States, State);
221}
222
223static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
224 const Stmt *Body,
225 AnalysisDeclContext &AC) {
226 FD = FD->getCanonicalDecl();
227
228 // Only run on non-templated functions and non-templated members of
229 // templated classes.
230 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
231 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
232 return;
233
234 CFG *cfg = AC.getCFG();
235 if (cfg == 0) return;
236
237 // If the exit block is unreachable, skip processing the function.
238 if (cfg->getExit().pred_empty())
239 return;
240
241 // Mark all nodes as FoundNoPath, then begin processing the entry block.
242 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
243 FoundNoPath);
244 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
245 states, FoundPathWithNoRecursiveCall);
246
247 // Check that the exit block is reachable. This prevents triggering the
248 // warning on functions that do not terminate.
249 if (states[cfg->getExit().getBlockID()] == FoundPath)
250 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
251}
252
253//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000254// Check for missing return value.
255//===----------------------------------------------------------------------===//
256
John McCall5c6ec8c2010-05-16 09:34:11 +0000257enum ControlFlowKind {
258 UnknownFallThrough,
259 NeverFallThrough,
260 MaybeFallThrough,
261 AlwaysFallThrough,
262 NeverFallThroughOrReturn
263};
Ted Kremenek918fe842010-03-20 21:06:02 +0000264
265/// CheckFallThrough - Check that we don't fall off the end of a
266/// Statement that should return a value.
267///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000268/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
269/// MaybeFallThrough iff we might or might not fall off the end,
270/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
271/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000272/// statement but we may return. We assume that functions not marked noreturn
273/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000274static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000275 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000276 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000277
278 // The CFG leaves in dead things, and we don't want the dead code paths to
279 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000280 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000281 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000282 live);
283
284 bool AddEHEdges = AC.getAddEHEdges();
285 if (!AddEHEdges && count != cfg->getNumBlockIDs())
286 // When there are things remaining dead, and we didn't add EH edges
287 // from CallExprs to the catch clauses, we have to go back and
288 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000289 for (const auto *B : *cfg) {
290 if (!live[B->getBlockID()]) {
291 if (B->pred_begin() == B->pred_end()) {
292 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000293 // When not adding EH edges from calls, catch clauses
294 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000295 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000296 continue;
297 }
298 }
299 }
300
301 // Now we know what is live, we check the live precessors of the exit block
302 // and look for fall through paths, being careful to ignore normal returns,
303 // and exceptional paths.
304 bool HasLiveReturn = false;
305 bool HasFakeEdge = false;
306 bool HasPlainEdge = false;
307 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000308
309 // Ignore default cases that aren't likely to be reachable because all
310 // enums in a switch(X) have explicit case statements.
311 CFGBlock::FilterOptions FO;
312 FO.IgnoreDefaultsWithCoveredEnums = 1;
313
314 for (CFGBlock::filtered_pred_iterator
315 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
316 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000317 if (!live[B.getBlockID()])
318 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000319
Chandler Carruth03faf782011-09-13 09:53:58 +0000320 // Skip blocks which contain an element marked as no-return. They don't
321 // represent actually viable edges into the exit block, so mark them as
322 // abnormal.
323 if (B.hasNoReturnElement()) {
324 HasAbnormalEdge = true;
325 continue;
326 }
327
Ted Kremenek5d068492011-01-26 04:49:52 +0000328 // Destructors can appear after the 'return' in the CFG. This is
329 // normal. We need to look pass the destructors for the return
330 // statement (if it exists).
331 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000332
Chandler Carruth03faf782011-09-13 09:53:58 +0000333 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000334 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000335 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000336
Ted Kremenek5d068492011-01-26 04:49:52 +0000337 // No more CFGElements in the block?
338 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000339 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
340 HasAbnormalEdge = true;
341 continue;
342 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000343 // A labeled empty statement, or the entry block...
344 HasPlainEdge = true;
345 continue;
346 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000347
David Blaikie2a01f5d2013-02-21 20:58:29 +0000348 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000349 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000350 if (isa<ReturnStmt>(S)) {
351 HasLiveReturn = true;
352 continue;
353 }
354 if (isa<ObjCAtThrowStmt>(S)) {
355 HasFakeEdge = true;
356 continue;
357 }
358 if (isa<CXXThrowExpr>(S)) {
359 HasFakeEdge = true;
360 continue;
361 }
Chad Rosier32503022012-06-11 20:47:18 +0000362 if (isa<MSAsmStmt>(S)) {
363 // TODO: Verify this is correct.
364 HasFakeEdge = true;
365 HasLiveReturn = true;
366 continue;
367 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000368 if (isa<CXXTryStmt>(S)) {
369 HasAbnormalEdge = true;
370 continue;
371 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000372 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
373 == B.succ_end()) {
374 HasAbnormalEdge = true;
375 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000376 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000377
378 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000379 }
380 if (!HasPlainEdge) {
381 if (HasLiveReturn)
382 return NeverFallThrough;
383 return NeverFallThroughOrReturn;
384 }
385 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
386 return MaybeFallThrough;
387 // This says AlwaysFallThrough for calls to functions that are not marked
388 // noreturn, that don't return. If people would like this warning to be more
389 // accurate, such functions should be marked as noreturn.
390 return AlwaysFallThrough;
391}
392
Dan Gohman28ade552010-07-26 21:25:24 +0000393namespace {
394
Ted Kremenek918fe842010-03-20 21:06:02 +0000395struct CheckFallThroughDiagnostics {
396 unsigned diag_MaybeFallThrough_HasNoReturn;
397 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
398 unsigned diag_AlwaysFallThrough_HasNoReturn;
399 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
400 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000401 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000402 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000403
Douglas Gregor24f27692010-04-16 23:28:44 +0000404 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000405 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000406 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000407 D.diag_MaybeFallThrough_HasNoReturn =
408 diag::warn_falloff_noreturn_function;
409 D.diag_MaybeFallThrough_ReturnsNonVoid =
410 diag::warn_maybe_falloff_nonvoid_function;
411 D.diag_AlwaysFallThrough_HasNoReturn =
412 diag::warn_falloff_noreturn_function;
413 D.diag_AlwaysFallThrough_ReturnsNonVoid =
414 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000415
416 // Don't suggest that virtual functions be marked "noreturn", since they
417 // might be overridden by non-noreturn functions.
418 bool isVirtualMethod = false;
419 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
420 isVirtualMethod = Method->isVirtual();
421
Douglas Gregor0de57202011-10-10 18:15:57 +0000422 // Don't suggest that template instantiations be marked "noreturn"
423 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000424 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
425 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000426
427 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000428 D.diag_NeverFallThroughOrReturn =
429 diag::warn_suggest_noreturn_function;
430 else
431 D.diag_NeverFallThroughOrReturn = 0;
432
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000433 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000434 return D;
435 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000436
Ted Kremenek918fe842010-03-20 21:06:02 +0000437 static CheckFallThroughDiagnostics MakeForBlock() {
438 CheckFallThroughDiagnostics D;
439 D.diag_MaybeFallThrough_HasNoReturn =
440 diag::err_noreturn_block_has_return_expr;
441 D.diag_MaybeFallThrough_ReturnsNonVoid =
442 diag::err_maybe_falloff_nonvoid_block;
443 D.diag_AlwaysFallThrough_HasNoReturn =
444 diag::err_noreturn_block_has_return_expr;
445 D.diag_AlwaysFallThrough_ReturnsNonVoid =
446 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000447 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000448 D.funMode = Block;
449 return D;
450 }
451
452 static CheckFallThroughDiagnostics MakeForLambda() {
453 CheckFallThroughDiagnostics D;
454 D.diag_MaybeFallThrough_HasNoReturn =
455 diag::err_noreturn_lambda_has_return_expr;
456 D.diag_MaybeFallThrough_ReturnsNonVoid =
457 diag::warn_maybe_falloff_nonvoid_lambda;
458 D.diag_AlwaysFallThrough_HasNoReturn =
459 diag::err_noreturn_lambda_has_return_expr;
460 D.diag_AlwaysFallThrough_ReturnsNonVoid =
461 diag::warn_falloff_nonvoid_lambda;
462 D.diag_NeverFallThroughOrReturn = 0;
463 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000464 return D;
465 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000466
David Blaikie9c902b52011-09-25 23:23:43 +0000467 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000468 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000469 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000470 return (ReturnsVoid ||
471 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000472 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000473 && (!HasNoReturn ||
474 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000475 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000476 && (!ReturnsVoid ||
477 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000478 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000479 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000480
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000481 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000482 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000483 }
484};
485
Dan Gohman28ade552010-07-26 21:25:24 +0000486}
487
Ted Kremenek918fe842010-03-20 21:06:02 +0000488/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
489/// function that should return a value. Check that we don't fall off the end
490/// of a noreturn function. We assume that functions and blocks not marked
491/// noreturn will return.
492static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000493 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000494 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000495 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000496
497 bool ReturnsVoid = false;
498 bool HasNoReturn = false;
499
500 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000501 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000502 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000503 }
504 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000505 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000506 HasNoReturn = MD->hasAttr<NoReturnAttr>();
507 }
508 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000509 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000510 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000511 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000512 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000513 ReturnsVoid = true;
514 if (FT->getNoReturnAttr())
515 HasNoReturn = true;
516 }
517 }
518
David Blaikie9c902b52011-09-25 23:23:43 +0000519 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000520
521 // Short circuit for compilation speed.
522 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
523 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000524
Ted Kremenek918fe842010-03-20 21:06:02 +0000525 // FIXME: Function try block
526 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
527 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000528 case UnknownFallThrough:
529 break;
530
Ted Kremenek918fe842010-03-20 21:06:02 +0000531 case MaybeFallThrough:
532 if (HasNoReturn)
533 S.Diag(Compound->getRBracLoc(),
534 CD.diag_MaybeFallThrough_HasNoReturn);
535 else if (!ReturnsVoid)
536 S.Diag(Compound->getRBracLoc(),
537 CD.diag_MaybeFallThrough_ReturnsNonVoid);
538 break;
539 case AlwaysFallThrough:
540 if (HasNoReturn)
541 S.Diag(Compound->getRBracLoc(),
542 CD.diag_AlwaysFallThrough_HasNoReturn);
543 else if (!ReturnsVoid)
544 S.Diag(Compound->getRBracLoc(),
545 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
546 break;
547 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000548 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
549 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
550 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000551 << 0 << FD;
552 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
553 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
554 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000555 } else {
556 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
557 }
558 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000559 break;
560 case NeverFallThrough:
561 break;
562 }
563 }
564}
565
566//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000567// -Wuninitialized
568//===----------------------------------------------------------------------===//
569
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000570namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000571/// ContainsReference - A visitor class to search for references to
572/// a particular declaration (the needle) within any evaluated component of an
573/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000574class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000575 bool FoundReference;
576 const DeclRefExpr *Needle;
577
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000578public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000579 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
580 : EvaluatedExprVisitor<ContainsReference>(Context),
581 FoundReference(false), Needle(Needle) {}
582
583 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000584 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000585 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000586 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000587
588 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000589 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000590
591 void VisitDeclRefExpr(DeclRefExpr *E) {
592 if (E == Needle)
593 FoundReference = true;
594 else
595 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000596 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000597
598 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000599};
600}
601
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000602static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000603 QualType VariableTy = VD->getType().getCanonicalType();
604 if (VariableTy->isBlockPointerType() &&
605 !VD->hasAttr<BlocksAttr>()) {
606 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
607 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
608 return true;
609 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000610
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000611 // Don't issue a fixit if there is already an initializer.
612 if (VD->getInit())
613 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000614
615 // Don't suggest a fixit inside macros.
616 if (VD->getLocEnd().isMacroID())
617 return false;
618
Alp Tokerb6cc5922014-05-03 03:45:55 +0000619 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000620
621 // Suggest possible initialization (if any).
622 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
623 if (Init.empty())
624 return false;
625
Richard Smith8d06f422012-01-12 23:53:29 +0000626 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
627 << FixItHint::CreateInsertion(Loc, Init);
628 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000629}
630
Richard Smith1bb8edb82012-05-26 06:20:46 +0000631/// Create a fixit to remove an if-like statement, on the assumption that its
632/// condition is CondVal.
633static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
634 const Stmt *Else, bool CondVal,
635 FixItHint &Fixit1, FixItHint &Fixit2) {
636 if (CondVal) {
637 // If condition is always true, remove all but the 'then'.
638 Fixit1 = FixItHint::CreateRemoval(
639 CharSourceRange::getCharRange(If->getLocStart(),
640 Then->getLocStart()));
641 if (Else) {
642 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
643 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
644 Fixit2 = FixItHint::CreateRemoval(
645 SourceRange(ElseKwLoc, Else->getLocEnd()));
646 }
647 } else {
648 // If condition is always false, remove all but the 'else'.
649 if (Else)
650 Fixit1 = FixItHint::CreateRemoval(
651 CharSourceRange::getCharRange(If->getLocStart(),
652 Else->getLocStart()));
653 else
654 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
655 }
656}
657
658/// DiagUninitUse -- Helper function to produce a diagnostic for an
659/// uninitialized use of a variable.
660static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
661 bool IsCapturedByBlock) {
662 bool Diagnosed = false;
663
Richard Smithba8071e2013-09-12 18:49:10 +0000664 switch (Use.getKind()) {
665 case UninitUse::Always:
666 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
667 << VD->getDeclName() << IsCapturedByBlock
668 << Use.getUser()->getSourceRange();
669 return;
670
671 case UninitUse::AfterDecl:
672 case UninitUse::AfterCall:
673 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
674 << VD->getDeclName() << IsCapturedByBlock
675 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
676 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
677 << VD->getSourceRange();
678 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
679 << IsCapturedByBlock << Use.getUser()->getSourceRange();
680 return;
681
682 case UninitUse::Maybe:
683 case UninitUse::Sometimes:
684 // Carry on to report sometimes-uninitialized branches, if possible,
685 // or a 'may be used uninitialized' diagnostic otherwise.
686 break;
687 }
688
Richard Smith1bb8edb82012-05-26 06:20:46 +0000689 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000690 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
691 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000692 assert(Use.getKind() == UninitUse::Sometimes);
693
694 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000695 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000696
697 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000698 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000699 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000700 SourceRange Range;
701
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000702 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000703 // For all binary terminators, branch 0 is taken if the condition is true,
704 // and branch 1 is taken if the condition is false.
705 int RemoveDiagKind = -1;
706 const char *FixitStr =
707 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
708 : (I->Output ? "1" : "0");
709 FixItHint Fixit1, Fixit2;
710
Richard Smithba8071e2013-09-12 18:49:10 +0000711 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000712 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000713 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000714 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000715 continue;
716
717 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000718 case Stmt::IfStmtClass: {
719 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000720 DiagKind = 0;
721 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000722 Range = IS->getCond()->getSourceRange();
723 RemoveDiagKind = 0;
724 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
725 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000726 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000727 }
728 case Stmt::ConditionalOperatorClass: {
729 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000730 DiagKind = 0;
731 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000732 Range = CO->getCond()->getSourceRange();
733 RemoveDiagKind = 0;
734 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
735 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000736 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000737 }
Richard Smith4323bf82012-05-25 02:17:09 +0000738 case Stmt::BinaryOperatorClass: {
739 const BinaryOperator *BO = cast<BinaryOperator>(Term);
740 if (!BO->isLogicalOp())
741 continue;
742 DiagKind = 0;
743 Str = BO->getOpcodeStr();
744 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000745 RemoveDiagKind = 0;
746 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
747 (BO->getOpcode() == BO_LOr && !I->Output))
748 // true && y -> y, false || y -> y.
749 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
750 BO->getOperatorLoc()));
751 else
752 // false && y -> false, true || y -> true.
753 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000754 break;
755 }
756
757 // "loop is entered / loop is exited".
758 case Stmt::WhileStmtClass:
759 DiagKind = 1;
760 Str = "while";
761 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000762 RemoveDiagKind = 1;
763 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000764 break;
765 case Stmt::ForStmtClass:
766 DiagKind = 1;
767 Str = "for";
768 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000769 RemoveDiagKind = 1;
770 if (I->Output)
771 Fixit1 = FixItHint::CreateRemoval(Range);
772 else
773 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000774 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000775 case Stmt::CXXForRangeStmtClass:
776 if (I->Output == 1) {
777 // The use occurs if a range-based for loop's body never executes.
778 // That may be impossible, and there's no syntactic fix for this,
779 // so treat it as a 'may be uninitialized' case.
780 continue;
781 }
782 DiagKind = 1;
783 Str = "for";
784 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
785 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000786
787 // "condition is true / loop is exited".
788 case Stmt::DoStmtClass:
789 DiagKind = 2;
790 Str = "do";
791 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000792 RemoveDiagKind = 1;
793 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000794 break;
795
796 // "switch case is taken".
797 case Stmt::CaseStmtClass:
798 DiagKind = 3;
799 Str = "case";
800 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
801 break;
802 case Stmt::DefaultStmtClass:
803 DiagKind = 3;
804 Str = "default";
805 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
806 break;
807 }
808
Richard Smith1bb8edb82012-05-26 06:20:46 +0000809 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
810 << VD->getDeclName() << IsCapturedByBlock << DiagKind
811 << Str << I->Output << Range;
812 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
813 << IsCapturedByBlock << User->getSourceRange();
814 if (RemoveDiagKind != -1)
815 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
816 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
817
818 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000819 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000820
821 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000822 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000823 << VD->getDeclName() << IsCapturedByBlock
824 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000825}
826
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000827/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
828/// uninitialized variable. This manages the different forms of diagnostic
829/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000830/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000831/// false.
832static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000833 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000834 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000835
Richard Smith4323bf82012-05-25 02:17:09 +0000836 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000837 // Inspect the initializer of the variable declaration which is
838 // being referenced prior to its initialization. We emit
839 // specialized diagnostics for self-initialization, and we
840 // specifically avoid warning about self references which take the
841 // form of:
842 //
843 // int x = x;
844 //
845 // This is used to indicate to GCC that 'x' is intentionally left
846 // uninitialized. Proven code paths which access 'x' in
847 // an uninitialized state after this will still warn.
848 if (const Expr *Initializer = VD->getInit()) {
849 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
850 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000851
Richard Trieu43a2fc72012-05-09 21:08:22 +0000852 ContainsReference CR(S.Context, DRE);
853 CR.Visit(const_cast<Expr*>(Initializer));
854 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000855 S.Diag(DRE->getLocStart(),
856 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000857 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
858 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000859 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000860 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000861
Richard Smith1bb8edb82012-05-26 06:20:46 +0000862 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000863 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000864 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000865 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
866 S.Diag(BE->getLocStart(),
867 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000868 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000869 else
870 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000871 }
872
873 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000874 // the initializer of that declaration & we didn't already suggest
875 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000876 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000877 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
878 << VD->getDeclName();
879
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000880 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000881}
882
Richard Smith84837d52012-05-03 18:27:39 +0000883namespace {
884 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
885 public:
886 FallthroughMapper(Sema &S)
887 : FoundSwitchStatements(false),
888 S(S) {
889 }
890
891 bool foundSwitchStatements() const { return FoundSwitchStatements; }
892
893 void markFallthroughVisited(const AttributedStmt *Stmt) {
894 bool Found = FallthroughStmts.erase(Stmt);
895 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000896 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000897 }
898
899 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
900
901 const AttrStmts &getFallthroughStmts() const {
902 return FallthroughStmts;
903 }
904
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000905 void fillReachableBlocks(CFG *Cfg) {
906 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
907 std::deque<const CFGBlock *> BlockQueue;
908
909 ReachableBlocks.insert(&Cfg->getEntry());
910 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000911 // Mark all case blocks reachable to avoid problems with switching on
912 // constants, covered enums, etc.
913 // These blocks can contain fall-through annotations, and we don't want to
914 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +0000915 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000916 const Stmt *L = B->getLabel();
917 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
918 BlockQueue.push_back(B);
919 }
920
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000921 while (!BlockQueue.empty()) {
922 const CFGBlock *P = BlockQueue.front();
923 BlockQueue.pop_front();
924 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
925 E = P->succ_end();
926 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000927 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000928 BlockQueue.push_back(*I);
929 }
930 }
931 }
932
Richard Smith84837d52012-05-03 18:27:39 +0000933 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000934 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
935
Richard Smith84837d52012-05-03 18:27:39 +0000936 int UnannotatedCnt = 0;
937 AnnotatedCnt = 0;
938
Aaron Ballmane5195222014-05-15 20:50:47 +0000939 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +0000940 while (!BlockQueue.empty()) {
941 const CFGBlock *P = BlockQueue.front();
942 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000943 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000944
945 const Stmt *Term = P->getTerminator();
946 if (Term && isa<SwitchStmt>(Term))
947 continue; // Switch statement, good.
948
949 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
950 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
951 continue; // Previous case label has no statements, good.
952
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000953 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
954 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
955 continue; // Case label is preceded with a normal label, good.
956
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000957 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000958 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
959 ElemEnd = P->rend();
960 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000961 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
962 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000963 S.Diag(AS->getLocStart(),
964 diag::warn_fallthrough_attr_unreachable);
965 markFallthroughVisited(AS);
966 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000967 break;
Richard Smith84837d52012-05-03 18:27:39 +0000968 }
969 // Don't care about other unreachable statements.
970 }
971 }
972 // If there are no unreachable statements, this may be a special
973 // case in CFG:
974 // case X: {
975 // A a; // A has a destructor.
976 // break;
977 // }
978 // // <<<< This place is represented by a 'hanging' CFG block.
979 // case Y:
980 continue;
981 }
982
983 const Stmt *LastStmt = getLastStmt(*P);
984 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
985 markFallthroughVisited(AS);
986 ++AnnotatedCnt;
987 continue; // Fallthrough annotation, good.
988 }
989
990 if (!LastStmt) { // This block contains no executable statements.
991 // Traverse its predecessors.
992 std::copy(P->pred_begin(), P->pred_end(),
993 std::back_inserter(BlockQueue));
994 continue;
995 }
996
997 ++UnannotatedCnt;
998 }
999 return !!UnannotatedCnt;
1000 }
1001
1002 // RecursiveASTVisitor setup.
1003 bool shouldWalkTypesOfTypeLocs() const { return false; }
1004
1005 bool VisitAttributedStmt(AttributedStmt *S) {
1006 if (asFallThroughAttr(S))
1007 FallthroughStmts.insert(S);
1008 return true;
1009 }
1010
1011 bool VisitSwitchStmt(SwitchStmt *S) {
1012 FoundSwitchStatements = true;
1013 return true;
1014 }
1015
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001016 // We don't want to traverse local type declarations. We analyze their
1017 // methods separately.
1018 bool TraverseDecl(Decl *D) { return true; }
1019
Richard Smith84837d52012-05-03 18:27:39 +00001020 private:
1021
1022 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1023 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1024 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1025 return AS;
1026 }
1027 return 0;
1028 }
1029
1030 static const Stmt *getLastStmt(const CFGBlock &B) {
1031 if (const Stmt *Term = B.getTerminator())
1032 return Term;
1033 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1034 ElemEnd = B.rend();
1035 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001036 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1037 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001038 }
1039 // Workaround to detect a statement thrown out by CFGBuilder:
1040 // case X: {} case Y:
1041 // case X: ; case Y:
1042 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1043 if (!isa<SwitchCase>(SW->getSubStmt()))
1044 return SW->getSubStmt();
1045
1046 return 0;
1047 }
1048
1049 bool FoundSwitchStatements;
1050 AttrStmts FallthroughStmts;
1051 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001052 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001053 };
1054}
1055
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001056static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001057 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001058 // Only perform this analysis when using C++11. There is no good workflow
1059 // for this warning when not using C++11. There is no good way to silence
1060 // the warning (no attribute is available) unless we are using C++11's support
1061 // for generalized attributes. Once could use pragmas to silence the warning,
1062 // but as a general solution that is gross and not in the spirit of this
1063 // warning.
1064 //
1065 // NOTE: This an intermediate solution. There are on-going discussions on
1066 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001067 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001068 return;
1069
Richard Smith84837d52012-05-03 18:27:39 +00001070 FallthroughMapper FM(S);
1071 FM.TraverseStmt(AC.getBody());
1072
1073 if (!FM.foundSwitchStatements())
1074 return;
1075
Alexis Hunt2178f142012-06-15 21:22:05 +00001076 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001077 return;
1078
Richard Smith84837d52012-05-03 18:27:39 +00001079 CFG *Cfg = AC.getCFG();
1080
1081 if (!Cfg)
1082 return;
1083
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001084 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001085
1086 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001087 const CFGBlock *B = *I;
1088 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001089
1090 if (!Label || !isa<SwitchCase>(Label))
1091 continue;
1092
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001093 int AnnotatedCnt;
1094
Alexander Kornienko55488792013-01-25 15:49:34 +00001095 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001096 continue;
1097
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001098 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001099 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1100 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001101
1102 if (!AnnotatedCnt) {
1103 SourceLocation L = Label->getLocStart();
1104 if (L.isMacroID())
1105 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001106 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001107 const Stmt *Term = B->getTerminator();
1108 // Skip empty cases.
1109 while (B->empty() && !Term && B->succ_size() == 1) {
1110 B = *B->succ_begin();
1111 Term = B->getTerminator();
1112 }
1113 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001114 Preprocessor &PP = S.getPreprocessor();
1115 TokenValue Tokens[] = {
1116 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1117 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1118 tok::r_square, tok::r_square
1119 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001120 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1121 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1122 if (!MacroName.empty())
1123 AnnotationSpelling = MacroName;
1124 SmallString<64> TextToInsert(AnnotationSpelling);
1125 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001126 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001127 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001128 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001129 }
Richard Smith84837d52012-05-03 18:27:39 +00001130 }
1131 S.Diag(L, diag::note_insert_break_fixit) <<
1132 FixItHint::CreateInsertion(L, "break; ");
1133 }
1134 }
1135
Aaron Ballmane5195222014-05-15 20:50:47 +00001136 for (const auto *F : FM.getFallthroughStmts())
1137 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001138}
1139
Jordan Rose25c0ea82012-10-29 17:46:47 +00001140static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1141 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001142 assert(S);
1143
1144 do {
1145 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001146 case Stmt::ForStmtClass:
1147 case Stmt::WhileStmtClass:
1148 case Stmt::CXXForRangeStmtClass:
1149 case Stmt::ObjCForCollectionStmtClass:
1150 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001151 case Stmt::DoStmtClass: {
1152 const Expr *Cond = cast<DoStmt>(S)->getCond();
1153 llvm::APSInt Val;
1154 if (!Cond->EvaluateAsInt(Val, Ctx))
1155 return true;
1156 return Val.getBoolValue();
1157 }
Jordan Rose76831c62012-10-11 16:10:19 +00001158 default:
1159 break;
1160 }
1161 } while ((S = PM.getParent(S)));
1162
1163 return false;
1164}
1165
Jordan Rosed3934582012-09-28 22:21:30 +00001166
1167static void diagnoseRepeatedUseOfWeak(Sema &S,
1168 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001169 const Decl *D,
1170 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001171 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1172 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1173 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001174 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1175 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001176
Jordan Rose25c0ea82012-10-29 17:46:47 +00001177 ASTContext &Ctx = S.getASTContext();
1178
Jordan Rosed3934582012-09-28 22:21:30 +00001179 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1180
1181 // Extract all weak objects that are referenced more than once.
1182 SmallVector<StmtUsesPair, 8> UsesByStmt;
1183 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1184 I != E; ++I) {
1185 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001186
1187 // Find the first read of the weak object.
1188 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1189 for ( ; UI != UE; ++UI) {
1190 if (UI->isUnsafe())
1191 break;
1192 }
1193
1194 // If there were only writes to this object, don't warn.
1195 if (UI == UE)
1196 continue;
1197
Jordan Rose76831c62012-10-11 16:10:19 +00001198 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001199 // read is not within a loop, don't warn. Additionally, don't warn in a
1200 // loop if the base object is a local variable -- local variables are often
1201 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001202 if (UI == Uses.begin()) {
1203 WeakUseVector::const_iterator UI2 = UI;
1204 for (++UI2; UI2 != UE; ++UI2)
1205 if (UI2->isUnsafe())
1206 break;
1207
Jordan Rose25c0ea82012-10-29 17:46:47 +00001208 if (UI2 == UE) {
1209 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001210 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001211
1212 const WeakObjectProfileTy &Profile = I->first;
1213 if (!Profile.isExactProfile())
1214 continue;
1215
1216 const NamedDecl *Base = Profile.getBase();
1217 if (!Base)
1218 Base = Profile.getProperty();
1219 assert(Base && "A profile always has a base or property.");
1220
1221 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1222 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1223 continue;
1224 }
Jordan Rose76831c62012-10-11 16:10:19 +00001225 }
1226
Jordan Rosed3934582012-09-28 22:21:30 +00001227 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1228 }
1229
1230 if (UsesByStmt.empty())
1231 return;
1232
1233 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001234 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001235 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001236 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1237 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1238 RHS.first->getLocStart());
1239 });
Jordan Rosed3934582012-09-28 22:21:30 +00001240
1241 // Classify the current code body for better warning text.
1242 // This enum should stay in sync with the cases in
1243 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1244 // FIXME: Should we use a common classification enum and the same set of
1245 // possibilities all throughout Sema?
1246 enum {
1247 Function,
1248 Method,
1249 Block,
1250 Lambda
1251 } FunctionKind;
1252
1253 if (isa<sema::BlockScopeInfo>(CurFn))
1254 FunctionKind = Block;
1255 else if (isa<sema::LambdaScopeInfo>(CurFn))
1256 FunctionKind = Lambda;
1257 else if (isa<ObjCMethodDecl>(D))
1258 FunctionKind = Method;
1259 else
1260 FunctionKind = Function;
1261
1262 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001263 for (const auto &P : UsesByStmt) {
1264 const Stmt *FirstRead = P.first;
1265 const WeakObjectProfileTy &Key = P.second->first;
1266 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001267
Jordan Rose657b5f42012-09-28 22:21:35 +00001268 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1269 // may not contain enough information to determine that these are different
1270 // properties. We can only be 100% sure of a repeated use in certain cases,
1271 // and we adjust the diagnostic kind accordingly so that the less certain
1272 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001273 unsigned DiagKind;
1274 if (Key.isExactProfile())
1275 DiagKind = diag::warn_arc_repeated_use_of_weak;
1276 else
1277 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1278
Jordan Rose657b5f42012-09-28 22:21:35 +00001279 // Classify the weak object being accessed for better warning text.
1280 // This enum should stay in sync with the cases in
1281 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1282 enum {
1283 Variable,
1284 Property,
1285 ImplicitProperty,
1286 Ivar
1287 } ObjectKind;
1288
1289 const NamedDecl *D = Key.getProperty();
1290 if (isa<VarDecl>(D))
1291 ObjectKind = Variable;
1292 else if (isa<ObjCPropertyDecl>(D))
1293 ObjectKind = Property;
1294 else if (isa<ObjCMethodDecl>(D))
1295 ObjectKind = ImplicitProperty;
1296 else if (isa<ObjCIvarDecl>(D))
1297 ObjectKind = Ivar;
1298 else
1299 llvm_unreachable("Unexpected weak object kind!");
1300
Jordan Rosed3934582012-09-28 22:21:30 +00001301 // Show the first time the object was read.
1302 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001303 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001304 << FirstRead->getSourceRange();
1305
1306 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001307 for (const auto &Use : Uses) {
1308 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001309 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001310 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001311 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001312 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001313 }
1314 }
1315}
1316
Jordan Rosed3934582012-09-28 22:21:30 +00001317namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001318class UninitValsDiagReporter : public UninitVariablesHandler {
1319 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001320 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001321 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001322 // Prefer using MapVector to DenseMap, so that iteration order will be
1323 // the same as insertion order. This is needed to obtain a deterministic
1324 // order of diagnostics when calling flushDiagnostics().
1325 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001326 UsesMap *uses;
1327
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001328public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001329 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1330 ~UninitValsDiagReporter() {
1331 flushDiagnostics();
1332 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001333
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001334 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001335 if (!uses)
1336 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001337
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001338 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001339 if (!V.getPointer())
1340 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001341
Ted Kremenek596fa162011-10-13 18:50:06 +00001342 return V;
1343 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001344
1345 void handleUseOfUninitVariable(const VarDecl *vd,
1346 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001347 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001348 }
1349
Craig Toppere14c0f82014-03-12 04:55:44 +00001350 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001351 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001352 }
1353
1354 void flushDiagnostics() {
1355 if (!uses)
1356 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001357
Aaron Ballmane5195222014-05-15 20:50:47 +00001358 for (const auto &P : *uses) {
1359 const VarDecl *vd = P.first;
1360 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001361
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001362 UsesVec *vec = V.getPointer();
1363 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001364
1365 // Specially handle the case where we have uses of an uninitialized
1366 // variable, but the root cause is an idiomatic self-init. We want
1367 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001368 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001369 DiagnoseUninitializedUse(S, vd,
1370 UninitUse(vd->getInit()->IgnoreParenCasts(),
1371 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001372 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001373 else {
1374 // Sort the uses by their SourceLocations. While not strictly
1375 // guaranteed to produce them in line/column order, this will provide
1376 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001377 std::sort(vec->begin(), vec->end(),
1378 [](const UninitUse &a, const UninitUse &b) {
1379 // Prefer a more confident report over a less confident one.
1380 if (a.getKind() != b.getKind())
1381 return a.getKind() > b.getKind();
1382 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1383 });
1384
Aaron Ballmane5195222014-05-15 20:50:47 +00001385 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001386 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001387 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001388
1389 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001390 // Skip further diagnostics for this variable. We try to warn only
1391 // on the first point at which a variable is used uninitialized.
1392 break;
1393 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001394 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001395
1396 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001397 delete vec;
1398 }
1399 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001400 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001401
1402private:
1403 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001404 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1405 return U.getKind() == UninitUse::Always ||
1406 U.getKind() == UninitUse::AfterCall ||
1407 U.getKind() == UninitUse::AfterDecl;
1408 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001409 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001410};
1411}
1412
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001413namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001414namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001415typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001416typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001417typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001418
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001419struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001420 SourceManager &SM;
1421 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001422
1423 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1424 // Although this call will be slow, this is only called when outputting
1425 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001426 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001427 }
1428};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001429}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001430
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001431//===----------------------------------------------------------------------===//
1432// -Wthread-safety
1433//===----------------------------------------------------------------------===//
1434namespace clang {
1435namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001436namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001437class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1438 Sema &S;
1439 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001440 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001441
1442 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001443 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1444 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001445 // Gracefully handle rare cases when the analysis can't get a more
1446 // precise source location.
1447 if (!Loc.isValid())
1448 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001449 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001450 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001451 }
1452
1453 public:
Richard Smith92286672012-02-03 04:45:26 +00001454 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1455 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001456
1457 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1458 /// We need to output diagnostics produced while iterating through
1459 /// the lockset in deterministic order, so this function orders diagnostics
1460 /// and outputs them.
1461 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001462 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001463 for (const auto &Diag : Warnings) {
1464 S.Diag(Diag.first.first, Diag.first.second);
1465 for (const auto &Note : Diag.second)
1466 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001467 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001468 }
1469
Aaron Ballmane0449042014-04-01 21:43:23 +00001470 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1471 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1472 << Loc);
Richard Smith92286672012-02-03 04:45:26 +00001473 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001474 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001475 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1476 SourceLocation Loc) override {
1477 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001478 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001479 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1480 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001481 SourceLocation Loc) override {
1482 if (Loc.isInvalid())
1483 Loc = FunLocation;
1484 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001485 << Kind << LockName << Received
1486 << Expected);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001487 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1488 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001489 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1490 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001491 }
1492
Aaron Ballmane0449042014-04-01 21:43:23 +00001493 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1494 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001495 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001496 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001497 unsigned DiagID = 0;
1498 switch (LEK) {
1499 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001500 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001501 break;
1502 case LEK_LockedSomeLoopIterations:
1503 DiagID = diag::warn_expecting_lock_held_on_loop;
1504 break;
1505 case LEK_LockedAtEndOfFunction:
1506 DiagID = diag::warn_no_unlock;
1507 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001508 case LEK_NotLockedAtEndOfFunction:
1509 DiagID = diag::warn_expecting_locked;
1510 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001511 }
Richard Smith92286672012-02-03 04:45:26 +00001512 if (LocEndOfScope.isInvalid())
1513 LocEndOfScope = FunEndLocation;
1514
Aaron Ballmane0449042014-04-01 21:43:23 +00001515 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1516 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001517 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001518 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1519 << Kind);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001520 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1521 return;
1522 }
1523 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001524 }
1525
Aaron Ballmane0449042014-04-01 21:43:23 +00001526 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1527 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001528 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001529 PartialDiagnosticAt Warning(Loc1,
1530 S.PDiag(diag::warn_lock_exclusive_and_shared)
1531 << Kind << LockName);
1532 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1533 << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001534 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001535 }
1536
Aaron Ballmane0449042014-04-01 21:43:23 +00001537 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1538 ProtectedOperationKind POK, AccessKind AK,
1539 SourceLocation Loc) override {
1540 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1541 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001542 unsigned DiagID = POK == POK_VarAccess?
1543 diag::warn_variable_requires_any_lock:
1544 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001545 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001546 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001547 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001548 }
1549
Aaron Ballmane0449042014-04-01 21:43:23 +00001550 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1551 ProtectedOperationKind POK, Name LockName,
1552 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001553 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001554 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001555 if (PossibleMatch) {
1556 switch (POK) {
1557 case POK_VarAccess:
1558 DiagID = diag::warn_variable_requires_lock_precise;
1559 break;
1560 case POK_VarDereference:
1561 DiagID = diag::warn_var_deref_requires_lock_precise;
1562 break;
1563 case POK_FunctionCall:
1564 DiagID = diag::warn_fun_requires_lock_precise;
1565 break;
1566 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001567 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1568 << D->getNameAsString()
1569 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001570 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001571 << *PossibleMatch);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001572 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1573 } else {
1574 switch (POK) {
1575 case POK_VarAccess:
1576 DiagID = diag::warn_variable_requires_lock;
1577 break;
1578 case POK_VarDereference:
1579 DiagID = diag::warn_var_deref_requires_lock;
1580 break;
1581 case POK_FunctionCall:
1582 DiagID = diag::warn_fun_requires_lock;
1583 break;
1584 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001585 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1586 << D->getNameAsString()
1587 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001588 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001589 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001590 }
1591
Aaron Ballmane0449042014-04-01 21:43:23 +00001592 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001593 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001594 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1595 << Kind << FunName << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001596 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001597 }
1598};
1599}
1600}
David Blaikie68e081d2011-12-20 02:48:34 +00001601}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001602
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001603//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001604// -Wconsumed
1605//===----------------------------------------------------------------------===//
1606
1607namespace clang {
1608namespace consumed {
1609namespace {
1610class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1611
1612 Sema &S;
1613 DiagList Warnings;
1614
1615public:
1616
1617 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001618
1619 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001620 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001621 for (const auto &Diag : Warnings) {
1622 S.Diag(Diag.first.first, Diag.first.second);
1623 for (const auto &Note : Diag.second)
1624 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001625 }
1626 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001627
1628 void warnLoopStateMismatch(SourceLocation Loc,
1629 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001630 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1631 VariableName);
1632
1633 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1634 }
1635
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001636 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1637 StringRef VariableName,
1638 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001639 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001640
1641 PartialDiagnosticAt Warning(Loc, S.PDiag(
1642 diag::warn_param_return_typestate_mismatch) << VariableName <<
1643 ExpectedState << ObservedState);
1644
1645 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1646 }
1647
DeLesley Hutchins69391772013-10-17 23:23:53 +00001648 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001649 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001650
1651 PartialDiagnosticAt Warning(Loc, S.PDiag(
1652 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1653
1654 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1655 }
1656
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001657 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001658 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001659 PartialDiagnosticAt Warning(Loc, S.PDiag(
1660 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1661
1662 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1663 }
1664
1665 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001666 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001667
1668 PartialDiagnosticAt Warning(Loc, S.PDiag(
1669 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1670
1671 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1672 }
1673
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001674 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001675 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001676
1677 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001678 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001679
1680 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1681 }
1682
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001683 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001684 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001685
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001686 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1687 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001688
1689 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1690 }
1691};
1692}}}
1693
1694//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001695// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1696// warnings on a function, method, or block.
1697//===----------------------------------------------------------------------===//
1698
Ted Kremenek0b405322010-03-23 00:13:23 +00001699clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1700 enableCheckFallThrough = 1;
1701 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001702 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001703 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001704}
1705
Ted Kremenekad8753c2014-03-15 05:47:06 +00001706static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1707 return (unsigned) D.getDiagnosticLevel(diag, SourceLocation()) !=
1708 DiagnosticsEngine::Ignored;
1709}
1710
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001711clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1712 : S(s),
1713 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001714 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001715 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001716 MaxCFGBlocksPerFunction(0),
1717 NumUninitAnalysisFunctions(0),
1718 NumUninitAnalysisVariables(0),
1719 MaxUninitAnalysisVariablesPerFunction(0),
1720 NumUninitAnalysisBlockVisits(0),
1721 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001722
1723 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001724 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001725
1726 DefaultPolicy.enableCheckUnreachable =
1727 isEnabled(D, warn_unreachable) ||
1728 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001729 isEnabled(D, warn_unreachable_return) ||
1730 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001731
1732 DefaultPolicy.enableThreadSafetyAnalysis =
1733 isEnabled(D, warn_double_lock);
1734
1735 DefaultPolicy.enableConsumedAnalysis =
1736 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001737}
1738
Aaron Ballmane5195222014-05-15 20:50:47 +00001739static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1740 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001741 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001742}
1743
Ted Kremenek0b405322010-03-23 00:13:23 +00001744void clang::sema::
1745AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001746 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001747 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001748
Ted Kremenek918fe842010-03-20 21:06:02 +00001749 // We avoid doing analysis-based warnings when there are errors for
1750 // two reasons:
1751 // (1) The CFGs often can't be constructed (if the body is invalid), so
1752 // don't bother trying.
1753 // (2) The code already has problems; running the analysis just takes more
1754 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001755 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001756
Ted Kremenek0b405322010-03-23 00:13:23 +00001757 // Do not do any analysis for declarations in system headers if we are
1758 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001759 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001760 S.SourceMgr.isInSystemHeader(D->getLocation()))
1761 return;
1762
John McCall1d570a72010-08-25 05:56:39 +00001763 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001764 if (cast<DeclContext>(D)->isDependentContext())
1765 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001766
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001767 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001768 // Flush out any possibly unreachable diagnostics.
1769 flushDiagnostics(S, fscope);
1770 return;
1771 }
1772
Ted Kremenek918fe842010-03-20 21:06:02 +00001773 const Stmt *Body = D->getBody();
1774 assert(Body);
1775
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001776 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001777 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001778
Ted Kremenek918fe842010-03-20 21:06:02 +00001779 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001780 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001781 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1782 AC.getCFGBuildOptions().AddEHEdges = false;
1783 AC.getCFGBuildOptions().AddInitializers = true;
1784 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001785 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001786 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001787
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001788 // Force that certain expressions appear as CFGElements in the CFG. This
1789 // is used to speed up various analyses.
1790 // FIXME: This isn't the right factoring. This is here for initial
1791 // prototyping, but we need a way for analyses to say what expressions they
1792 // expect to always be CFGElements and then fill in the BuildOptions
1793 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001794 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1795 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001796 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001797 AC.getCFGBuildOptions().setAllAlwaysAdd();
1798 }
1799 else {
1800 AC.getCFGBuildOptions()
1801 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001802 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001803 .setAlwaysAdd(Stmt::BlockExprClass)
1804 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1805 .setAlwaysAdd(Stmt::DeclRefExprClass)
1806 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001807 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1808 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001809 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001810
Richard Trieue9fa2662014-04-15 00:57:50 +00001811 // Install the logical handler for -Wtautological-overlap-compare
1812 std::unique_ptr<LogicalErrorHandler> LEH;
Richard Trieuf935b562014-04-05 05:17:01 +00001813 if (Diags.getDiagnosticLevel(diag::warn_tautological_overlap_comparison,
1814 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00001815 LEH.reset(new LogicalErrorHandler(S));
1816 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00001817 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001818
Ted Kremenek3427fac2011-02-23 01:52:04 +00001819 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001820 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001821 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001822
1823 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00001824 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1825 if (D.stmt)
1826 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00001827 }
1828
1829 if (AC.getCFG()) {
1830 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00001831 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00001832 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00001833 if (D.stmt) {
1834 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001835 CFGReverseBlockReachabilityAnalysis *cra =
1836 AC.getCFGReachablityAnalysis();
1837 // FIXME: We should be able to assert that block is non-null, but
1838 // the CFG analysis can skip potentially-evaluated expressions in
1839 // edge cases; see test/Sema/vla-2.c.
1840 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001841 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001842 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001843 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001844 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001845 }
1846 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001847 if (!processed) {
1848 // Emit the warning anyway if we cannot map to a basic block.
1849 S.Diag(D.Loc, D.PD);
1850 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001851 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001852 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001853
1854 if (!analyzed)
1855 flushDiagnostics(S, fscope);
1856 }
1857
1858
Ted Kremenek918fe842010-03-20 21:06:02 +00001859 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001860 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001861 const CheckFallThroughDiagnostics &CD =
1862 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001863 : (isa<CXXMethodDecl>(D) &&
1864 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1865 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1866 ? CheckFallThroughDiagnostics::MakeForLambda()
1867 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001868 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001869 }
1870
1871 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001872 if (P.enableCheckUnreachable) {
1873 // Only check for unreachable code on non-template instantiations.
1874 // Different template instantiations can effectively change the control-flow
1875 // and it is very difficult to prove that a snippet of code in a template
1876 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001877 bool isTemplateInstantiation = false;
1878 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1879 isTemplateInstantiation = Function->isTemplateInstantiation();
1880 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001881 CheckUnreachable(S, AC);
1882 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001883
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001884 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001885 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001886 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001887 SourceLocation FEL = AC.getDecl()->getLocEnd();
1888 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001889 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1890 != DiagnosticsEngine::Ignored)
1891 Reporter.setIssueBetaWarnings(true);
1892
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001893 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1894 Reporter.emitDiagnostics();
1895 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001896
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001897 // Check for violations of consumed properties.
1898 if (P.enableConsumedAnalysis) {
1899 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001900 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001901 Analyzer.run(AC);
1902 }
1903
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001904 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001905 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001906 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1907 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001908 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001909 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001910 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001911 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001912 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001913 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001914 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001915 reporter, stats);
1916
1917 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1918 ++NumUninitAnalysisFunctions;
1919 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1920 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1921 MaxUninitAnalysisVariablesPerFunction =
1922 std::max(MaxUninitAnalysisVariablesPerFunction,
1923 stats.NumVariablesAnalyzed);
1924 MaxUninitAnalysisBlockVisitsPerFunction =
1925 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1926 stats.NumBlockVisits);
1927 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001928 }
1929 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001930
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001931 bool FallThroughDiagFull =
1932 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1933 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001934 bool FallThroughDiagPerFunction =
1935 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001936 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001937 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001938 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001939 }
1940
Jordan Rosed3934582012-09-28 22:21:30 +00001941 if (S.getLangOpts().ObjCARCWeak &&
1942 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1943 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001944 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001945
Richard Trieu2f024f42013-12-21 02:33:43 +00001946
1947 // Check for infinite self-recursion in functions
1948 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1949 D->getLocStart())
1950 != DiagnosticsEngine::Ignored) {
1951 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1952 checkRecursiveFunction(S, FD, Body, AC);
1953 }
1954 }
1955
Richard Trieue9fa2662014-04-15 00:57:50 +00001956 // If none of the previous checks caused a CFG build, trigger one here
1957 // for -Wtautological-overlap-compare
1958 if (Diags.getDiagnosticLevel(diag::warn_tautological_overlap_comparison,
1959 D->getLocStart())) {
1960 AC.getCFG();
1961 }
1962
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001963 // Collect statistics about the CFG if it was built.
1964 if (S.CollectStats && AC.isCFGBuilt()) {
1965 ++NumFunctionsAnalyzed;
1966 if (CFG *cfg = AC.getCFG()) {
1967 // If we successfully built a CFG for this context, record some more
1968 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001969 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001970 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001971 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001972 } else {
1973 ++NumFunctionsWithBadCFGs;
1974 }
1975 }
1976}
1977
1978void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1979 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1980
1981 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1982 unsigned AvgCFGBlocksPerFunction =
1983 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1984 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1985 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1986 << " " << NumCFGBlocks << " CFG blocks built.\n"
1987 << " " << AvgCFGBlocksPerFunction
1988 << " average CFG blocks per function.\n"
1989 << " " << MaxCFGBlocksPerFunction
1990 << " max CFG blocks per function.\n";
1991
1992 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1993 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1994 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1995 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1996 llvm::errs() << NumUninitAnalysisFunctions
1997 << " functions analyzed for uninitialiazed variables\n"
1998 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1999 << " " << AvgUninitVariablesPerFunction
2000 << " average variables per function.\n"
2001 << " " << MaxUninitAnalysisVariablesPerFunction
2002 << " max variables per function.\n"
2003 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2004 << " " << AvgUninitBlockVisitsPerFunction
2005 << " average block visits per function.\n"
2006 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2007 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002008}