blob: a489e8c911b1e7597e9bb550ba11ec9c77373ea8 [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()) {
92 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.PP.getLocForEndOfToken(Close);
94 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
120//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000121// Check for infinite self-recursion in functions
122//===----------------------------------------------------------------------===//
123
124// All blocks are in one of three states. States are ordered so that blocks
125// can only move to higher states.
126enum RecursiveState {
127 FoundNoPath,
128 FoundPath,
129 FoundPathWithNoRecursiveCall
130};
131
132static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
133 CFGBlock &Block, unsigned ExitID,
134 llvm::SmallVectorImpl<RecursiveState> &States,
135 RecursiveState State) {
136 unsigned ID = Block.getBlockID();
137
138 // A block's state can only move to a higher state.
139 if (States[ID] >= State)
140 return;
141
142 States[ID] = State;
143
144 // Found a path to the exit node without a recursive call.
145 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
146 return;
147
148 if (State == FoundPathWithNoRecursiveCall) {
149 // If the current state is FoundPathWithNoRecursiveCall, the successors
150 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
151 // which, process all the Stmt's in this block to find any recursive calls.
152 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
153 if (I->getKind() != CFGElement::Statement)
154 continue;
155
156 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
157 if (CE && CE->getCalleeDecl() &&
158 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000159
160 // Skip function calls which are qualified with a templated class.
161 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
162 CE->getCallee()->IgnoreParenImpCasts())) {
163 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
164 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
165 isa<TemplateSpecializationType>(NNS->getAsType())) {
166 continue;
167 }
168 }
169 }
170
Richard Trieu2f024f42013-12-21 02:33:43 +0000171 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
172 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
173 !MCE->getMethodDecl()->isVirtual()) {
174 State = FoundPath;
175 break;
176 }
177 } else {
178 State = FoundPath;
179 break;
180 }
181 }
182 }
183 }
184
185 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
186 I != E; ++I)
187 if (*I)
188 checkForFunctionCall(S, FD, **I, ExitID, States, State);
189}
190
191static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
192 const Stmt *Body,
193 AnalysisDeclContext &AC) {
194 FD = FD->getCanonicalDecl();
195
196 // Only run on non-templated functions and non-templated members of
197 // templated classes.
198 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
199 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
200 return;
201
202 CFG *cfg = AC.getCFG();
203 if (cfg == 0) return;
204
205 // If the exit block is unreachable, skip processing the function.
206 if (cfg->getExit().pred_empty())
207 return;
208
209 // Mark all nodes as FoundNoPath, then begin processing the entry block.
210 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
211 FoundNoPath);
212 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
213 states, FoundPathWithNoRecursiveCall);
214
215 // Check that the exit block is reachable. This prevents triggering the
216 // warning on functions that do not terminate.
217 if (states[cfg->getExit().getBlockID()] == FoundPath)
218 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
219}
220
221//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000222// Check for missing return value.
223//===----------------------------------------------------------------------===//
224
John McCall5c6ec8c2010-05-16 09:34:11 +0000225enum ControlFlowKind {
226 UnknownFallThrough,
227 NeverFallThrough,
228 MaybeFallThrough,
229 AlwaysFallThrough,
230 NeverFallThroughOrReturn
231};
Ted Kremenek918fe842010-03-20 21:06:02 +0000232
233/// CheckFallThrough - Check that we don't fall off the end of a
234/// Statement that should return a value.
235///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000236/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
237/// MaybeFallThrough iff we might or might not fall off the end,
238/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
239/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000240/// statement but we may return. We assume that functions not marked noreturn
241/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000242static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000243 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000244 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000245
246 // The CFG leaves in dead things, and we don't want the dead code paths to
247 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000248 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000249 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000250 live);
251
252 bool AddEHEdges = AC.getAddEHEdges();
253 if (!AddEHEdges && count != cfg->getNumBlockIDs())
254 // When there are things remaining dead, and we didn't add EH edges
255 // from CallExprs to the catch clauses, we have to go back and
256 // mark them as live.
257 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
258 CFGBlock &b = **I;
259 if (!live[b.getBlockID()]) {
260 if (b.pred_begin() == b.pred_end()) {
261 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
262 // When not adding EH edges from calls, catch clauses
263 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000264 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000265 continue;
266 }
267 }
268 }
269
270 // Now we know what is live, we check the live precessors of the exit block
271 // and look for fall through paths, being careful to ignore normal returns,
272 // and exceptional paths.
273 bool HasLiveReturn = false;
274 bool HasFakeEdge = false;
275 bool HasPlainEdge = false;
276 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000277
278 // Ignore default cases that aren't likely to be reachable because all
279 // enums in a switch(X) have explicit case statements.
280 CFGBlock::FilterOptions FO;
281 FO.IgnoreDefaultsWithCoveredEnums = 1;
282
283 for (CFGBlock::filtered_pred_iterator
284 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
285 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000286 if (!live[B.getBlockID()])
287 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000288
Chandler Carruth03faf782011-09-13 09:53:58 +0000289 // Skip blocks which contain an element marked as no-return. They don't
290 // represent actually viable edges into the exit block, so mark them as
291 // abnormal.
292 if (B.hasNoReturnElement()) {
293 HasAbnormalEdge = true;
294 continue;
295 }
296
Ted Kremenek5d068492011-01-26 04:49:52 +0000297 // Destructors can appear after the 'return' in the CFG. This is
298 // normal. We need to look pass the destructors for the return
299 // statement (if it exists).
300 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000301
Chandler Carruth03faf782011-09-13 09:53:58 +0000302 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000303 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000304 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000305
Ted Kremenek5d068492011-01-26 04:49:52 +0000306 // No more CFGElements in the block?
307 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000308 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
309 HasAbnormalEdge = true;
310 continue;
311 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000312 // A labeled empty statement, or the entry block...
313 HasPlainEdge = true;
314 continue;
315 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000316
David Blaikie2a01f5d2013-02-21 20:58:29 +0000317 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000318 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000319 if (isa<ReturnStmt>(S)) {
320 HasLiveReturn = true;
321 continue;
322 }
323 if (isa<ObjCAtThrowStmt>(S)) {
324 HasFakeEdge = true;
325 continue;
326 }
327 if (isa<CXXThrowExpr>(S)) {
328 HasFakeEdge = true;
329 continue;
330 }
Chad Rosier32503022012-06-11 20:47:18 +0000331 if (isa<MSAsmStmt>(S)) {
332 // TODO: Verify this is correct.
333 HasFakeEdge = true;
334 HasLiveReturn = true;
335 continue;
336 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000337 if (isa<CXXTryStmt>(S)) {
338 HasAbnormalEdge = true;
339 continue;
340 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000341 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
342 == B.succ_end()) {
343 HasAbnormalEdge = true;
344 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000345 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000346
347 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000348 }
349 if (!HasPlainEdge) {
350 if (HasLiveReturn)
351 return NeverFallThrough;
352 return NeverFallThroughOrReturn;
353 }
354 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
355 return MaybeFallThrough;
356 // This says AlwaysFallThrough for calls to functions that are not marked
357 // noreturn, that don't return. If people would like this warning to be more
358 // accurate, such functions should be marked as noreturn.
359 return AlwaysFallThrough;
360}
361
Dan Gohman28ade552010-07-26 21:25:24 +0000362namespace {
363
Ted Kremenek918fe842010-03-20 21:06:02 +0000364struct CheckFallThroughDiagnostics {
365 unsigned diag_MaybeFallThrough_HasNoReturn;
366 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
367 unsigned diag_AlwaysFallThrough_HasNoReturn;
368 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
369 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000370 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000371 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000372
Douglas Gregor24f27692010-04-16 23:28:44 +0000373 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000374 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000375 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000376 D.diag_MaybeFallThrough_HasNoReturn =
377 diag::warn_falloff_noreturn_function;
378 D.diag_MaybeFallThrough_ReturnsNonVoid =
379 diag::warn_maybe_falloff_nonvoid_function;
380 D.diag_AlwaysFallThrough_HasNoReturn =
381 diag::warn_falloff_noreturn_function;
382 D.diag_AlwaysFallThrough_ReturnsNonVoid =
383 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000384
385 // Don't suggest that virtual functions be marked "noreturn", since they
386 // might be overridden by non-noreturn functions.
387 bool isVirtualMethod = false;
388 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
389 isVirtualMethod = Method->isVirtual();
390
Douglas Gregor0de57202011-10-10 18:15:57 +0000391 // Don't suggest that template instantiations be marked "noreturn"
392 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000393 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
394 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000395
396 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000397 D.diag_NeverFallThroughOrReturn =
398 diag::warn_suggest_noreturn_function;
399 else
400 D.diag_NeverFallThroughOrReturn = 0;
401
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000402 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000403 return D;
404 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000405
Ted Kremenek918fe842010-03-20 21:06:02 +0000406 static CheckFallThroughDiagnostics MakeForBlock() {
407 CheckFallThroughDiagnostics D;
408 D.diag_MaybeFallThrough_HasNoReturn =
409 diag::err_noreturn_block_has_return_expr;
410 D.diag_MaybeFallThrough_ReturnsNonVoid =
411 diag::err_maybe_falloff_nonvoid_block;
412 D.diag_AlwaysFallThrough_HasNoReturn =
413 diag::err_noreturn_block_has_return_expr;
414 D.diag_AlwaysFallThrough_ReturnsNonVoid =
415 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000416 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000417 D.funMode = Block;
418 return D;
419 }
420
421 static CheckFallThroughDiagnostics MakeForLambda() {
422 CheckFallThroughDiagnostics D;
423 D.diag_MaybeFallThrough_HasNoReturn =
424 diag::err_noreturn_lambda_has_return_expr;
425 D.diag_MaybeFallThrough_ReturnsNonVoid =
426 diag::warn_maybe_falloff_nonvoid_lambda;
427 D.diag_AlwaysFallThrough_HasNoReturn =
428 diag::err_noreturn_lambda_has_return_expr;
429 D.diag_AlwaysFallThrough_ReturnsNonVoid =
430 diag::warn_falloff_nonvoid_lambda;
431 D.diag_NeverFallThroughOrReturn = 0;
432 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000433 return D;
434 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000435
David Blaikie9c902b52011-09-25 23:23:43 +0000436 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000437 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000438 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000439 return (ReturnsVoid ||
440 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000441 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000442 && (!HasNoReturn ||
443 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000444 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000445 && (!ReturnsVoid ||
446 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000447 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000448 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000449
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000450 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000451 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000452 }
453};
454
Dan Gohman28ade552010-07-26 21:25:24 +0000455}
456
Ted Kremenek918fe842010-03-20 21:06:02 +0000457/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
458/// function that should return a value. Check that we don't fall off the end
459/// of a noreturn function. We assume that functions and blocks not marked
460/// noreturn will return.
461static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000462 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000463 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000464 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000465
466 bool ReturnsVoid = false;
467 bool HasNoReturn = false;
468
469 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000470 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000471 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000472 }
473 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000474 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000475 HasNoReturn = MD->hasAttr<NoReturnAttr>();
476 }
477 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000478 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000479 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000480 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000481 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000482 ReturnsVoid = true;
483 if (FT->getNoReturnAttr())
484 HasNoReturn = true;
485 }
486 }
487
David Blaikie9c902b52011-09-25 23:23:43 +0000488 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000489
490 // Short circuit for compilation speed.
491 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
492 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000493
Ted Kremenek918fe842010-03-20 21:06:02 +0000494 // FIXME: Function try block
495 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
496 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000497 case UnknownFallThrough:
498 break;
499
Ted Kremenek918fe842010-03-20 21:06:02 +0000500 case MaybeFallThrough:
501 if (HasNoReturn)
502 S.Diag(Compound->getRBracLoc(),
503 CD.diag_MaybeFallThrough_HasNoReturn);
504 else if (!ReturnsVoid)
505 S.Diag(Compound->getRBracLoc(),
506 CD.diag_MaybeFallThrough_ReturnsNonVoid);
507 break;
508 case AlwaysFallThrough:
509 if (HasNoReturn)
510 S.Diag(Compound->getRBracLoc(),
511 CD.diag_AlwaysFallThrough_HasNoReturn);
512 else if (!ReturnsVoid)
513 S.Diag(Compound->getRBracLoc(),
514 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
515 break;
516 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000517 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
518 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
519 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000520 << 0 << FD;
521 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
522 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
523 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000524 } else {
525 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
526 }
527 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000528 break;
529 case NeverFallThrough:
530 break;
531 }
532 }
533}
534
535//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000536// -Wuninitialized
537//===----------------------------------------------------------------------===//
538
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000539namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000540/// ContainsReference - A visitor class to search for references to
541/// a particular declaration (the needle) within any evaluated component of an
542/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000543class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000544 bool FoundReference;
545 const DeclRefExpr *Needle;
546
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000547public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000548 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
549 : EvaluatedExprVisitor<ContainsReference>(Context),
550 FoundReference(false), Needle(Needle) {}
551
552 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000553 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000554 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000555 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000556
557 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000558 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000559
560 void VisitDeclRefExpr(DeclRefExpr *E) {
561 if (E == Needle)
562 FoundReference = true;
563 else
564 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000565 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000566
567 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000568};
569}
570
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000571static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000572 QualType VariableTy = VD->getType().getCanonicalType();
573 if (VariableTy->isBlockPointerType() &&
574 !VD->hasAttr<BlocksAttr>()) {
575 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
576 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
577 return true;
578 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000579
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000580 // Don't issue a fixit if there is already an initializer.
581 if (VD->getInit())
582 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000583
584 // Don't suggest a fixit inside macros.
585 if (VD->getLocEnd().isMacroID())
586 return false;
587
Richard Smith8d06f422012-01-12 23:53:29 +0000588 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000589
590 // Suggest possible initialization (if any).
591 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
592 if (Init.empty())
593 return false;
594
Richard Smith8d06f422012-01-12 23:53:29 +0000595 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
596 << FixItHint::CreateInsertion(Loc, Init);
597 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000598}
599
Richard Smith1bb8edb82012-05-26 06:20:46 +0000600/// Create a fixit to remove an if-like statement, on the assumption that its
601/// condition is CondVal.
602static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
603 const Stmt *Else, bool CondVal,
604 FixItHint &Fixit1, FixItHint &Fixit2) {
605 if (CondVal) {
606 // If condition is always true, remove all but the 'then'.
607 Fixit1 = FixItHint::CreateRemoval(
608 CharSourceRange::getCharRange(If->getLocStart(),
609 Then->getLocStart()));
610 if (Else) {
611 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
612 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
613 Fixit2 = FixItHint::CreateRemoval(
614 SourceRange(ElseKwLoc, Else->getLocEnd()));
615 }
616 } else {
617 // If condition is always false, remove all but the 'else'.
618 if (Else)
619 Fixit1 = FixItHint::CreateRemoval(
620 CharSourceRange::getCharRange(If->getLocStart(),
621 Else->getLocStart()));
622 else
623 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
624 }
625}
626
627/// DiagUninitUse -- Helper function to produce a diagnostic for an
628/// uninitialized use of a variable.
629static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
630 bool IsCapturedByBlock) {
631 bool Diagnosed = false;
632
Richard Smithba8071e2013-09-12 18:49:10 +0000633 switch (Use.getKind()) {
634 case UninitUse::Always:
635 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
636 << VD->getDeclName() << IsCapturedByBlock
637 << Use.getUser()->getSourceRange();
638 return;
639
640 case UninitUse::AfterDecl:
641 case UninitUse::AfterCall:
642 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
643 << VD->getDeclName() << IsCapturedByBlock
644 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
645 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
646 << VD->getSourceRange();
647 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
648 << IsCapturedByBlock << Use.getUser()->getSourceRange();
649 return;
650
651 case UninitUse::Maybe:
652 case UninitUse::Sometimes:
653 // Carry on to report sometimes-uninitialized branches, if possible,
654 // or a 'may be used uninitialized' diagnostic otherwise.
655 break;
656 }
657
Richard Smith1bb8edb82012-05-26 06:20:46 +0000658 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000659 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
660 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000661 assert(Use.getKind() == UninitUse::Sometimes);
662
663 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000664 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000665
666 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000667 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000668 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000669 SourceRange Range;
670
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000671 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000672 // For all binary terminators, branch 0 is taken if the condition is true,
673 // and branch 1 is taken if the condition is false.
674 int RemoveDiagKind = -1;
675 const char *FixitStr =
676 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
677 : (I->Output ? "1" : "0");
678 FixItHint Fixit1, Fixit2;
679
Richard Smithba8071e2013-09-12 18:49:10 +0000680 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000681 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000682 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000683 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000684 continue;
685
686 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000687 case Stmt::IfStmtClass: {
688 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000689 DiagKind = 0;
690 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000691 Range = IS->getCond()->getSourceRange();
692 RemoveDiagKind = 0;
693 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
694 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000695 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000696 }
697 case Stmt::ConditionalOperatorClass: {
698 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000699 DiagKind = 0;
700 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000701 Range = CO->getCond()->getSourceRange();
702 RemoveDiagKind = 0;
703 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
704 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000705 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000706 }
Richard Smith4323bf82012-05-25 02:17:09 +0000707 case Stmt::BinaryOperatorClass: {
708 const BinaryOperator *BO = cast<BinaryOperator>(Term);
709 if (!BO->isLogicalOp())
710 continue;
711 DiagKind = 0;
712 Str = BO->getOpcodeStr();
713 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000714 RemoveDiagKind = 0;
715 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
716 (BO->getOpcode() == BO_LOr && !I->Output))
717 // true && y -> y, false || y -> y.
718 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
719 BO->getOperatorLoc()));
720 else
721 // false && y -> false, true || y -> true.
722 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000723 break;
724 }
725
726 // "loop is entered / loop is exited".
727 case Stmt::WhileStmtClass:
728 DiagKind = 1;
729 Str = "while";
730 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000731 RemoveDiagKind = 1;
732 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000733 break;
734 case Stmt::ForStmtClass:
735 DiagKind = 1;
736 Str = "for";
737 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000738 RemoveDiagKind = 1;
739 if (I->Output)
740 Fixit1 = FixItHint::CreateRemoval(Range);
741 else
742 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000743 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000744 case Stmt::CXXForRangeStmtClass:
745 if (I->Output == 1) {
746 // The use occurs if a range-based for loop's body never executes.
747 // That may be impossible, and there's no syntactic fix for this,
748 // so treat it as a 'may be uninitialized' case.
749 continue;
750 }
751 DiagKind = 1;
752 Str = "for";
753 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
754 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000755
756 // "condition is true / loop is exited".
757 case Stmt::DoStmtClass:
758 DiagKind = 2;
759 Str = "do";
760 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000761 RemoveDiagKind = 1;
762 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000763 break;
764
765 // "switch case is taken".
766 case Stmt::CaseStmtClass:
767 DiagKind = 3;
768 Str = "case";
769 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
770 break;
771 case Stmt::DefaultStmtClass:
772 DiagKind = 3;
773 Str = "default";
774 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
775 break;
776 }
777
Richard Smith1bb8edb82012-05-26 06:20:46 +0000778 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
779 << VD->getDeclName() << IsCapturedByBlock << DiagKind
780 << Str << I->Output << Range;
781 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
782 << IsCapturedByBlock << User->getSourceRange();
783 if (RemoveDiagKind != -1)
784 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
785 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
786
787 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000788 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000789
790 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000791 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000792 << VD->getDeclName() << IsCapturedByBlock
793 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000794}
795
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000796/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
797/// uninitialized variable. This manages the different forms of diagnostic
798/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000799/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000800/// false.
801static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000802 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000803 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000804
Richard Smith4323bf82012-05-25 02:17:09 +0000805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000806 // Inspect the initializer of the variable declaration which is
807 // being referenced prior to its initialization. We emit
808 // specialized diagnostics for self-initialization, and we
809 // specifically avoid warning about self references which take the
810 // form of:
811 //
812 // int x = x;
813 //
814 // This is used to indicate to GCC that 'x' is intentionally left
815 // uninitialized. Proven code paths which access 'x' in
816 // an uninitialized state after this will still warn.
817 if (const Expr *Initializer = VD->getInit()) {
818 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
819 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000820
Richard Trieu43a2fc72012-05-09 21:08:22 +0000821 ContainsReference CR(S.Context, DRE);
822 CR.Visit(const_cast<Expr*>(Initializer));
823 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000824 S.Diag(DRE->getLocStart(),
825 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000826 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
827 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000828 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000829 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000830
Richard Smith1bb8edb82012-05-26 06:20:46 +0000831 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000832 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000833 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000834 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
835 S.Diag(BE->getLocStart(),
836 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000837 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000838 else
839 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000840 }
841
842 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000843 // the initializer of that declaration & we didn't already suggest
844 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000845 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000846 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
847 << VD->getDeclName();
848
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000849 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000850}
851
Richard Smith84837d52012-05-03 18:27:39 +0000852namespace {
853 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
854 public:
855 FallthroughMapper(Sema &S)
856 : FoundSwitchStatements(false),
857 S(S) {
858 }
859
860 bool foundSwitchStatements() const { return FoundSwitchStatements; }
861
862 void markFallthroughVisited(const AttributedStmt *Stmt) {
863 bool Found = FallthroughStmts.erase(Stmt);
864 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000865 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000866 }
867
868 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
869
870 const AttrStmts &getFallthroughStmts() const {
871 return FallthroughStmts;
872 }
873
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000874 void fillReachableBlocks(CFG *Cfg) {
875 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
876 std::deque<const CFGBlock *> BlockQueue;
877
878 ReachableBlocks.insert(&Cfg->getEntry());
879 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000880 // Mark all case blocks reachable to avoid problems with switching on
881 // constants, covered enums, etc.
882 // These blocks can contain fall-through annotations, and we don't want to
883 // issue a warn_fallthrough_attr_unreachable for them.
884 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
885 const CFGBlock *B = *I;
886 const Stmt *L = B->getLabel();
887 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
888 BlockQueue.push_back(B);
889 }
890
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000891 while (!BlockQueue.empty()) {
892 const CFGBlock *P = BlockQueue.front();
893 BlockQueue.pop_front();
894 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
895 E = P->succ_end();
896 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000897 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000898 BlockQueue.push_back(*I);
899 }
900 }
901 }
902
Richard Smith84837d52012-05-03 18:27:39 +0000903 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000904 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
905
Richard Smith84837d52012-05-03 18:27:39 +0000906 int UnannotatedCnt = 0;
907 AnnotatedCnt = 0;
908
909 std::deque<const CFGBlock*> BlockQueue;
910
911 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
912
913 while (!BlockQueue.empty()) {
914 const CFGBlock *P = BlockQueue.front();
915 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000916 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000917
918 const Stmt *Term = P->getTerminator();
919 if (Term && isa<SwitchStmt>(Term))
920 continue; // Switch statement, good.
921
922 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
923 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
924 continue; // Previous case label has no statements, good.
925
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000926 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
927 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
928 continue; // Case label is preceded with a normal label, good.
929
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000930 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000931 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
932 ElemEnd = P->rend();
933 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000934 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
935 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000936 S.Diag(AS->getLocStart(),
937 diag::warn_fallthrough_attr_unreachable);
938 markFallthroughVisited(AS);
939 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000940 break;
Richard Smith84837d52012-05-03 18:27:39 +0000941 }
942 // Don't care about other unreachable statements.
943 }
944 }
945 // If there are no unreachable statements, this may be a special
946 // case in CFG:
947 // case X: {
948 // A a; // A has a destructor.
949 // break;
950 // }
951 // // <<<< This place is represented by a 'hanging' CFG block.
952 // case Y:
953 continue;
954 }
955
956 const Stmt *LastStmt = getLastStmt(*P);
957 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
958 markFallthroughVisited(AS);
959 ++AnnotatedCnt;
960 continue; // Fallthrough annotation, good.
961 }
962
963 if (!LastStmt) { // This block contains no executable statements.
964 // Traverse its predecessors.
965 std::copy(P->pred_begin(), P->pred_end(),
966 std::back_inserter(BlockQueue));
967 continue;
968 }
969
970 ++UnannotatedCnt;
971 }
972 return !!UnannotatedCnt;
973 }
974
975 // RecursiveASTVisitor setup.
976 bool shouldWalkTypesOfTypeLocs() const { return false; }
977
978 bool VisitAttributedStmt(AttributedStmt *S) {
979 if (asFallThroughAttr(S))
980 FallthroughStmts.insert(S);
981 return true;
982 }
983
984 bool VisitSwitchStmt(SwitchStmt *S) {
985 FoundSwitchStatements = true;
986 return true;
987 }
988
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000989 // We don't want to traverse local type declarations. We analyze their
990 // methods separately.
991 bool TraverseDecl(Decl *D) { return true; }
992
Richard Smith84837d52012-05-03 18:27:39 +0000993 private:
994
995 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
996 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
997 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
998 return AS;
999 }
1000 return 0;
1001 }
1002
1003 static const Stmt *getLastStmt(const CFGBlock &B) {
1004 if (const Stmt *Term = B.getTerminator())
1005 return Term;
1006 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1007 ElemEnd = B.rend();
1008 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001009 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1010 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001011 }
1012 // Workaround to detect a statement thrown out by CFGBuilder:
1013 // case X: {} case Y:
1014 // case X: ; case Y:
1015 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1016 if (!isa<SwitchCase>(SW->getSubStmt()))
1017 return SW->getSubStmt();
1018
1019 return 0;
1020 }
1021
1022 bool FoundSwitchStatements;
1023 AttrStmts FallthroughStmts;
1024 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001025 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001026 };
1027}
1028
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001029static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001030 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001031 // Only perform this analysis when using C++11. There is no good workflow
1032 // for this warning when not using C++11. There is no good way to silence
1033 // the warning (no attribute is available) unless we are using C++11's support
1034 // for generalized attributes. Once could use pragmas to silence the warning,
1035 // but as a general solution that is gross and not in the spirit of this
1036 // warning.
1037 //
1038 // NOTE: This an intermediate solution. There are on-going discussions on
1039 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001040 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001041 return;
1042
Richard Smith84837d52012-05-03 18:27:39 +00001043 FallthroughMapper FM(S);
1044 FM.TraverseStmt(AC.getBody());
1045
1046 if (!FM.foundSwitchStatements())
1047 return;
1048
Alexis Hunt2178f142012-06-15 21:22:05 +00001049 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001050 return;
1051
Richard Smith84837d52012-05-03 18:27:39 +00001052 CFG *Cfg = AC.getCFG();
1053
1054 if (!Cfg)
1055 return;
1056
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001057 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001058
1059 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001060 const CFGBlock *B = *I;
1061 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001062
1063 if (!Label || !isa<SwitchCase>(Label))
1064 continue;
1065
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001066 int AnnotatedCnt;
1067
Alexander Kornienko55488792013-01-25 15:49:34 +00001068 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001069 continue;
1070
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001071 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001072 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1073 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001074
1075 if (!AnnotatedCnt) {
1076 SourceLocation L = Label->getLocStart();
1077 if (L.isMacroID())
1078 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001079 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001080 const Stmt *Term = B->getTerminator();
1081 // Skip empty cases.
1082 while (B->empty() && !Term && B->succ_size() == 1) {
1083 B = *B->succ_begin();
1084 Term = B->getTerminator();
1085 }
1086 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001087 Preprocessor &PP = S.getPreprocessor();
1088 TokenValue Tokens[] = {
1089 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1090 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1091 tok::r_square, tok::r_square
1092 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001093 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1094 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1095 if (!MacroName.empty())
1096 AnnotationSpelling = MacroName;
1097 SmallString<64> TextToInsert(AnnotationSpelling);
1098 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001099 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001100 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001101 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001102 }
Richard Smith84837d52012-05-03 18:27:39 +00001103 }
1104 S.Diag(L, diag::note_insert_break_fixit) <<
1105 FixItHint::CreateInsertion(L, "break; ");
1106 }
1107 }
1108
1109 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1110 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1111 E = Fallthroughs.end();
1112 I != E; ++I) {
1113 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1114 }
1115
1116}
1117
Jordan Rose25c0ea82012-10-29 17:46:47 +00001118static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1119 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001120 assert(S);
1121
1122 do {
1123 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001124 case Stmt::ForStmtClass:
1125 case Stmt::WhileStmtClass:
1126 case Stmt::CXXForRangeStmtClass:
1127 case Stmt::ObjCForCollectionStmtClass:
1128 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001129 case Stmt::DoStmtClass: {
1130 const Expr *Cond = cast<DoStmt>(S)->getCond();
1131 llvm::APSInt Val;
1132 if (!Cond->EvaluateAsInt(Val, Ctx))
1133 return true;
1134 return Val.getBoolValue();
1135 }
Jordan Rose76831c62012-10-11 16:10:19 +00001136 default:
1137 break;
1138 }
1139 } while ((S = PM.getParent(S)));
1140
1141 return false;
1142}
1143
Jordan Rosed3934582012-09-28 22:21:30 +00001144
1145static void diagnoseRepeatedUseOfWeak(Sema &S,
1146 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001147 const Decl *D,
1148 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001149 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1150 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1151 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001152 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1153 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001154
Jordan Rose25c0ea82012-10-29 17:46:47 +00001155 ASTContext &Ctx = S.getASTContext();
1156
Jordan Rosed3934582012-09-28 22:21:30 +00001157 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1158
1159 // Extract all weak objects that are referenced more than once.
1160 SmallVector<StmtUsesPair, 8> UsesByStmt;
1161 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1162 I != E; ++I) {
1163 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001164
1165 // Find the first read of the weak object.
1166 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1167 for ( ; UI != UE; ++UI) {
1168 if (UI->isUnsafe())
1169 break;
1170 }
1171
1172 // If there were only writes to this object, don't warn.
1173 if (UI == UE)
1174 continue;
1175
Jordan Rose76831c62012-10-11 16:10:19 +00001176 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001177 // read is not within a loop, don't warn. Additionally, don't warn in a
1178 // loop if the base object is a local variable -- local variables are often
1179 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001180 if (UI == Uses.begin()) {
1181 WeakUseVector::const_iterator UI2 = UI;
1182 for (++UI2; UI2 != UE; ++UI2)
1183 if (UI2->isUnsafe())
1184 break;
1185
Jordan Rose25c0ea82012-10-29 17:46:47 +00001186 if (UI2 == UE) {
1187 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001188 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001189
1190 const WeakObjectProfileTy &Profile = I->first;
1191 if (!Profile.isExactProfile())
1192 continue;
1193
1194 const NamedDecl *Base = Profile.getBase();
1195 if (!Base)
1196 Base = Profile.getProperty();
1197 assert(Base && "A profile always has a base or property.");
1198
1199 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1200 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1201 continue;
1202 }
Jordan Rose76831c62012-10-11 16:10:19 +00001203 }
1204
Jordan Rosed3934582012-09-28 22:21:30 +00001205 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1206 }
1207
1208 if (UsesByStmt.empty())
1209 return;
1210
1211 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001212 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001213 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001214 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1215 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1216 RHS.first->getLocStart());
1217 });
Jordan Rosed3934582012-09-28 22:21:30 +00001218
1219 // Classify the current code body for better warning text.
1220 // This enum should stay in sync with the cases in
1221 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1222 // FIXME: Should we use a common classification enum and the same set of
1223 // possibilities all throughout Sema?
1224 enum {
1225 Function,
1226 Method,
1227 Block,
1228 Lambda
1229 } FunctionKind;
1230
1231 if (isa<sema::BlockScopeInfo>(CurFn))
1232 FunctionKind = Block;
1233 else if (isa<sema::LambdaScopeInfo>(CurFn))
1234 FunctionKind = Lambda;
1235 else if (isa<ObjCMethodDecl>(D))
1236 FunctionKind = Method;
1237 else
1238 FunctionKind = Function;
1239
1240 // Iterate through the sorted problems and emit warnings for each.
1241 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1242 E = UsesByStmt.end();
1243 I != E; ++I) {
1244 const Stmt *FirstRead = I->first;
1245 const WeakObjectProfileTy &Key = I->second->first;
1246 const WeakUseVector &Uses = I->second->second;
1247
Jordan Rose657b5f42012-09-28 22:21:35 +00001248 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1249 // may not contain enough information to determine that these are different
1250 // properties. We can only be 100% sure of a repeated use in certain cases,
1251 // and we adjust the diagnostic kind accordingly so that the less certain
1252 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001253 unsigned DiagKind;
1254 if (Key.isExactProfile())
1255 DiagKind = diag::warn_arc_repeated_use_of_weak;
1256 else
1257 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1258
Jordan Rose657b5f42012-09-28 22:21:35 +00001259 // Classify the weak object being accessed for better warning text.
1260 // This enum should stay in sync with the cases in
1261 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1262 enum {
1263 Variable,
1264 Property,
1265 ImplicitProperty,
1266 Ivar
1267 } ObjectKind;
1268
1269 const NamedDecl *D = Key.getProperty();
1270 if (isa<VarDecl>(D))
1271 ObjectKind = Variable;
1272 else if (isa<ObjCPropertyDecl>(D))
1273 ObjectKind = Property;
1274 else if (isa<ObjCMethodDecl>(D))
1275 ObjectKind = ImplicitProperty;
1276 else if (isa<ObjCIvarDecl>(D))
1277 ObjectKind = Ivar;
1278 else
1279 llvm_unreachable("Unexpected weak object kind!");
1280
Jordan Rosed3934582012-09-28 22:21:30 +00001281 // Show the first time the object was read.
1282 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001283 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001284 << FirstRead->getSourceRange();
1285
1286 // Print all the other accesses as notes.
1287 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1288 UI != UE; ++UI) {
1289 if (UI->getUseExpr() == FirstRead)
1290 continue;
1291 S.Diag(UI->getUseExpr()->getLocStart(),
1292 diag::note_arc_weak_also_accessed_here)
1293 << UI->getUseExpr()->getSourceRange();
1294 }
1295 }
1296}
1297
Jordan Rosed3934582012-09-28 22:21:30 +00001298namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001299class UninitValsDiagReporter : public UninitVariablesHandler {
1300 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001301 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001302 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001303 // Prefer using MapVector to DenseMap, so that iteration order will be
1304 // the same as insertion order. This is needed to obtain a deterministic
1305 // order of diagnostics when calling flushDiagnostics().
1306 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001307 UsesMap *uses;
1308
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001309public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001310 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1311 ~UninitValsDiagReporter() {
1312 flushDiagnostics();
1313 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001314
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001315 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001316 if (!uses)
1317 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001318
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001319 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001320 if (!V.getPointer())
1321 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001322
Ted Kremenek596fa162011-10-13 18:50:06 +00001323 return V;
1324 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001325
1326 void handleUseOfUninitVariable(const VarDecl *vd,
1327 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001328 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001329 }
1330
Craig Toppere14c0f82014-03-12 04:55:44 +00001331 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001332 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001333 }
1334
1335 void flushDiagnostics() {
1336 if (!uses)
1337 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001338
Ted Kremenek39fa0562011-01-21 19:41:41 +00001339 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1340 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001341 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001342
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001343 UsesVec *vec = V.getPointer();
1344 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001345
1346 // Specially handle the case where we have uses of an uninitialized
1347 // variable, but the root cause is an idiomatic self-init. We want
1348 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001349 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001350 DiagnoseUninitializedUse(S, vd,
1351 UninitUse(vd->getInit()->IgnoreParenCasts(),
1352 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001353 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001354 else {
1355 // Sort the uses by their SourceLocations. While not strictly
1356 // guaranteed to produce them in line/column order, this will provide
1357 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001358 std::sort(vec->begin(), vec->end(),
1359 [](const UninitUse &a, const UninitUse &b) {
1360 // Prefer a more confident report over a less confident one.
1361 if (a.getKind() != b.getKind())
1362 return a.getKind() > b.getKind();
1363 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1364 });
1365
Ted Kremenek596fa162011-10-13 18:50:06 +00001366 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1367 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001368 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1369 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1370
1371 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001372 // Skip further diagnostics for this variable. We try to warn only
1373 // on the first point at which a variable is used uninitialized.
1374 break;
1375 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001376 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001377
1378 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001379 delete vec;
1380 }
1381 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001382 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001383
1384private:
1385 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1386 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001387 if (i->getKind() == UninitUse::Always ||
1388 i->getKind() == UninitUse::AfterCall ||
1389 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001390 return true;
1391 }
1392 }
1393 return false;
1394}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001395};
1396}
1397
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001398namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001399namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001400typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001401typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001402typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001403
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001404struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001405 SourceManager &SM;
1406 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001407
1408 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1409 // Although this call will be slow, this is only called when outputting
1410 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001411 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001412 }
1413};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001414}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001415
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001416//===----------------------------------------------------------------------===//
1417// -Wthread-safety
1418//===----------------------------------------------------------------------===//
1419namespace clang {
1420namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001421namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001422class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1423 Sema &S;
1424 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001425 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001426
1427 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001428 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1429 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001430 // Gracefully handle rare cases when the analysis can't get a more
1431 // precise source location.
1432 if (!Loc.isValid())
1433 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001434 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001435 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001436 }
1437
1438 public:
Richard Smith92286672012-02-03 04:45:26 +00001439 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1440 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001441
1442 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1443 /// We need to output diagnostics produced while iterating through
1444 /// the lockset in deterministic order, so this function orders diagnostics
1445 /// and outputs them.
1446 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001447 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001448 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001449 I != E; ++I) {
1450 S.Diag(I->first.first, I->first.second);
1451 const OptionalNotes &Notes = I->second;
1452 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1453 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1454 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001455 }
1456
Aaron Ballmane0449042014-04-01 21:43:23 +00001457 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1458 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1459 << Loc);
Richard Smith92286672012-02-03 04:45:26 +00001460 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001461 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001462 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1463 SourceLocation Loc) override {
1464 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001465 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001466 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1467 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001468 SourceLocation Loc) override {
1469 if (Loc.isInvalid())
1470 Loc = FunLocation;
1471 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001472 << Kind << LockName << Received
1473 << Expected);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001474 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1475 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001476 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1477 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001478 }
1479
Aaron Ballmane0449042014-04-01 21:43:23 +00001480 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1481 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001482 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001483 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001484 unsigned DiagID = 0;
1485 switch (LEK) {
1486 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001487 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001488 break;
1489 case LEK_LockedSomeLoopIterations:
1490 DiagID = diag::warn_expecting_lock_held_on_loop;
1491 break;
1492 case LEK_LockedAtEndOfFunction:
1493 DiagID = diag::warn_no_unlock;
1494 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001495 case LEK_NotLockedAtEndOfFunction:
1496 DiagID = diag::warn_expecting_locked;
1497 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001498 }
Richard Smith92286672012-02-03 04:45:26 +00001499 if (LocEndOfScope.isInvalid())
1500 LocEndOfScope = FunEndLocation;
1501
Aaron Ballmane0449042014-04-01 21:43:23 +00001502 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1503 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001504 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001505 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1506 << Kind);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001507 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1508 return;
1509 }
1510 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001511 }
1512
Aaron Ballmane0449042014-04-01 21:43:23 +00001513 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1514 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001515 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001516 PartialDiagnosticAt Warning(Loc1,
1517 S.PDiag(diag::warn_lock_exclusive_and_shared)
1518 << Kind << LockName);
1519 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1520 << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001521 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001522 }
1523
Aaron Ballmane0449042014-04-01 21:43:23 +00001524 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1525 ProtectedOperationKind POK, AccessKind AK,
1526 SourceLocation Loc) override {
1527 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1528 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001529 unsigned DiagID = POK == POK_VarAccess?
1530 diag::warn_variable_requires_any_lock:
1531 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001532 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001533 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001534 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001535 }
1536
Aaron Ballmane0449042014-04-01 21:43:23 +00001537 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1538 ProtectedOperationKind POK, Name LockName,
1539 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001540 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001541 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001542 if (PossibleMatch) {
1543 switch (POK) {
1544 case POK_VarAccess:
1545 DiagID = diag::warn_variable_requires_lock_precise;
1546 break;
1547 case POK_VarDereference:
1548 DiagID = diag::warn_var_deref_requires_lock_precise;
1549 break;
1550 case POK_FunctionCall:
1551 DiagID = diag::warn_fun_requires_lock_precise;
1552 break;
1553 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001554 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1555 << D->getNameAsString()
1556 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001557 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001558 << *PossibleMatch);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001559 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1560 } else {
1561 switch (POK) {
1562 case POK_VarAccess:
1563 DiagID = diag::warn_variable_requires_lock;
1564 break;
1565 case POK_VarDereference:
1566 DiagID = diag::warn_var_deref_requires_lock;
1567 break;
1568 case POK_FunctionCall:
1569 DiagID = diag::warn_fun_requires_lock;
1570 break;
1571 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001572 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1573 << D->getNameAsString()
1574 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001575 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001576 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001577 }
1578
Aaron Ballmane0449042014-04-01 21:43:23 +00001579 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001580 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001581 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1582 << Kind << FunName << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001583 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001584 }
1585};
1586}
1587}
David Blaikie68e081d2011-12-20 02:48:34 +00001588}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001589
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001590//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001591// -Wconsumed
1592//===----------------------------------------------------------------------===//
1593
1594namespace clang {
1595namespace consumed {
1596namespace {
1597class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1598
1599 Sema &S;
1600 DiagList Warnings;
1601
1602public:
1603
1604 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001605
1606 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001607 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1608
1609 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1610 I != E; ++I) {
1611
1612 const OptionalNotes &Notes = I->second;
1613 S.Diag(I->first.first, I->first.second);
1614
1615 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1616 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1617 }
1618 }
1619 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001620
1621 void warnLoopStateMismatch(SourceLocation Loc,
1622 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001623 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1624 VariableName);
1625
1626 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1627 }
1628
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001629 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1630 StringRef VariableName,
1631 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001632 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001633
1634 PartialDiagnosticAt Warning(Loc, S.PDiag(
1635 diag::warn_param_return_typestate_mismatch) << VariableName <<
1636 ExpectedState << ObservedState);
1637
1638 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1639 }
1640
DeLesley Hutchins69391772013-10-17 23:23:53 +00001641 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001642 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001643
1644 PartialDiagnosticAt Warning(Loc, S.PDiag(
1645 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1646
1647 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1648 }
1649
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001650 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001651 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001652 PartialDiagnosticAt Warning(Loc, S.PDiag(
1653 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1654
1655 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1656 }
1657
1658 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001659 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001660
1661 PartialDiagnosticAt Warning(Loc, S.PDiag(
1662 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1663
1664 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1665 }
1666
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001667 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001668 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001669
1670 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001671 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001672
1673 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1674 }
1675
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001676 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001677 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001678
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001679 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1680 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001681
1682 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1683 }
1684};
1685}}}
1686
1687//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001688// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1689// warnings on a function, method, or block.
1690//===----------------------------------------------------------------------===//
1691
Ted Kremenek0b405322010-03-23 00:13:23 +00001692clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1693 enableCheckFallThrough = 1;
1694 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001695 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001696 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001697}
1698
Ted Kremenekad8753c2014-03-15 05:47:06 +00001699static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1700 return (unsigned) D.getDiagnosticLevel(diag, SourceLocation()) !=
1701 DiagnosticsEngine::Ignored;
1702}
1703
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001704clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1705 : S(s),
1706 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001707 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001708 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001709 MaxCFGBlocksPerFunction(0),
1710 NumUninitAnalysisFunctions(0),
1711 NumUninitAnalysisVariables(0),
1712 MaxUninitAnalysisVariablesPerFunction(0),
1713 NumUninitAnalysisBlockVisits(0),
1714 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001715
1716 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001717 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001718
1719 DefaultPolicy.enableCheckUnreachable =
1720 isEnabled(D, warn_unreachable) ||
1721 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001722 isEnabled(D, warn_unreachable_return) ||
1723 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001724
1725 DefaultPolicy.enableThreadSafetyAnalysis =
1726 isEnabled(D, warn_double_lock);
1727
1728 DefaultPolicy.enableConsumedAnalysis =
1729 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001730}
1731
Ted Kremenek3427fac2011-02-23 01:52:04 +00001732static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001733 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001734 i = fscope->PossiblyUnreachableDiags.begin(),
1735 e = fscope->PossiblyUnreachableDiags.end();
1736 i != e; ++i) {
1737 const sema::PossiblyUnreachableDiag &D = *i;
1738 S.Diag(D.Loc, D.PD);
1739 }
1740}
1741
Ted Kremenek0b405322010-03-23 00:13:23 +00001742void clang::sema::
1743AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001744 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001745 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001746
Ted Kremenek918fe842010-03-20 21:06:02 +00001747 // We avoid doing analysis-based warnings when there are errors for
1748 // two reasons:
1749 // (1) The CFGs often can't be constructed (if the body is invalid), so
1750 // don't bother trying.
1751 // (2) The code already has problems; running the analysis just takes more
1752 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001753 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001754
Ted Kremenek0b405322010-03-23 00:13:23 +00001755 // Do not do any analysis for declarations in system headers if we are
1756 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001757 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001758 S.SourceMgr.isInSystemHeader(D->getLocation()))
1759 return;
1760
John McCall1d570a72010-08-25 05:56:39 +00001761 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001762 if (cast<DeclContext>(D)->isDependentContext())
1763 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001764
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001765 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001766 // Flush out any possibly unreachable diagnostics.
1767 flushDiagnostics(S, fscope);
1768 return;
1769 }
1770
Ted Kremenek918fe842010-03-20 21:06:02 +00001771 const Stmt *Body = D->getBody();
1772 assert(Body);
1773
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001774 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001775 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001776
Ted Kremenek918fe842010-03-20 21:06:02 +00001777 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001778 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001779 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1780 AC.getCFGBuildOptions().AddEHEdges = false;
1781 AC.getCFGBuildOptions().AddInitializers = true;
1782 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001783 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001784 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001785
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001786 // Force that certain expressions appear as CFGElements in the CFG. This
1787 // is used to speed up various analyses.
1788 // FIXME: This isn't the right factoring. This is here for initial
1789 // prototyping, but we need a way for analyses to say what expressions they
1790 // expect to always be CFGElements and then fill in the BuildOptions
1791 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001792 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1793 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001794 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001795 AC.getCFGBuildOptions().setAllAlwaysAdd();
1796 }
1797 else {
1798 AC.getCFGBuildOptions()
1799 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001800 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001801 .setAlwaysAdd(Stmt::BlockExprClass)
1802 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1803 .setAlwaysAdd(Stmt::DeclRefExprClass)
1804 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001805 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1806 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001807 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001808
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001809
Ted Kremenek3427fac2011-02-23 01:52:04 +00001810 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001811 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001812 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001813
1814 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001815 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001816 i = fscope->PossiblyUnreachableDiags.begin(),
1817 e = fscope->PossiblyUnreachableDiags.end();
1818 i != e; ++i) {
1819 if (const Stmt *stmt = i->stmt)
1820 AC.registerForcedBlockExpression(stmt);
1821 }
1822
1823 if (AC.getCFG()) {
1824 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001825 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001826 i = fscope->PossiblyUnreachableDiags.begin(),
1827 e = fscope->PossiblyUnreachableDiags.end();
1828 i != e; ++i)
1829 {
1830 const sema::PossiblyUnreachableDiag &D = *i;
1831 bool processed = false;
1832 if (const Stmt *stmt = i->stmt) {
1833 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001834 CFGReverseBlockReachabilityAnalysis *cra =
1835 AC.getCFGReachablityAnalysis();
1836 // FIXME: We should be able to assert that block is non-null, but
1837 // the CFG analysis can skip potentially-evaluated expressions in
1838 // edge cases; see test/Sema/vla-2.c.
1839 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001840 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001841 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001842 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001843 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001844 }
1845 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001846 if (!processed) {
1847 // Emit the warning anyway if we cannot map to a basic block.
1848 S.Diag(D.Loc, D.PD);
1849 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001850 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001851 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001852
1853 if (!analyzed)
1854 flushDiagnostics(S, fscope);
1855 }
1856
1857
Ted Kremenek918fe842010-03-20 21:06:02 +00001858 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001859 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001860 const CheckFallThroughDiagnostics &CD =
1861 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001862 : (isa<CXXMethodDecl>(D) &&
1863 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1864 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1865 ? CheckFallThroughDiagnostics::MakeForLambda()
1866 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001867 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001868 }
1869
1870 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001871 if (P.enableCheckUnreachable) {
1872 // Only check for unreachable code on non-template instantiations.
1873 // Different template instantiations can effectively change the control-flow
1874 // and it is very difficult to prove that a snippet of code in a template
1875 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001876 bool isTemplateInstantiation = false;
1877 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1878 isTemplateInstantiation = Function->isTemplateInstantiation();
1879 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001880 CheckUnreachable(S, AC);
1881 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001882
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001883 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001884 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001885 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001886 SourceLocation FEL = AC.getDecl()->getLocEnd();
1887 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001888 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1889 != DiagnosticsEngine::Ignored)
1890 Reporter.setIssueBetaWarnings(true);
1891
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001892 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1893 Reporter.emitDiagnostics();
1894 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001895
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001896 // Check for violations of consumed properties.
1897 if (P.enableConsumedAnalysis) {
1898 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001899 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001900 Analyzer.run(AC);
1901 }
1902
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001903 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001904 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001905 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1906 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001907 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001908 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001909 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001910 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001911 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001912 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001913 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001914 reporter, stats);
1915
1916 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1917 ++NumUninitAnalysisFunctions;
1918 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1919 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1920 MaxUninitAnalysisVariablesPerFunction =
1921 std::max(MaxUninitAnalysisVariablesPerFunction,
1922 stats.NumVariablesAnalyzed);
1923 MaxUninitAnalysisBlockVisitsPerFunction =
1924 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1925 stats.NumBlockVisits);
1926 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001927 }
1928 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001929
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001930 bool FallThroughDiagFull =
1931 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1932 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001933 bool FallThroughDiagPerFunction =
1934 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001935 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001936 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001937 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001938 }
1939
Jordan Rosed3934582012-09-28 22:21:30 +00001940 if (S.getLangOpts().ObjCARCWeak &&
1941 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1942 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001943 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001944
Richard Trieu2f024f42013-12-21 02:33:43 +00001945
1946 // Check for infinite self-recursion in functions
1947 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1948 D->getLocStart())
1949 != DiagnosticsEngine::Ignored) {
1950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1951 checkRecursiveFunction(S, FD, Body, AC);
1952 }
1953 }
1954
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001955 // Collect statistics about the CFG if it was built.
1956 if (S.CollectStats && AC.isCFGBuilt()) {
1957 ++NumFunctionsAnalyzed;
1958 if (CFG *cfg = AC.getCFG()) {
1959 // If we successfully built a CFG for this context, record some more
1960 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001961 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001962 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001963 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001964 } else {
1965 ++NumFunctionsWithBadCFGs;
1966 }
1967 }
1968}
1969
1970void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1971 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1972
1973 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1974 unsigned AvgCFGBlocksPerFunction =
1975 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1976 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1977 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1978 << " " << NumCFGBlocks << " CFG blocks built.\n"
1979 << " " << AvgCFGBlocksPerFunction
1980 << " average CFG blocks per function.\n"
1981 << " " << MaxCFGBlocksPerFunction
1982 << " max CFG blocks per function.\n";
1983
1984 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1985 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1986 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1987 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1988 llvm::errs() << NumUninitAnalysisFunctions
1989 << " functions analyzed for uninitialiazed variables\n"
1990 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1991 << " " << AvgUninitVariablesPerFunction
1992 << " average variables per function.\n"
1993 << " " << MaxUninitAnalysisVariablesPerFunction
1994 << " max variables per function.\n"
1995 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1996 << " " << AvgUninitBlockVisitsPerFunction
1997 << " average block visits per function.\n"
1998 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1999 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002000}