blob: 59d13de8309aefbc8e1eae2f44153c81cd387d08 [file] [log] [blame]
Ted Kremenek918fe842010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Rose76831c62012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smith84837d52012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
DeLesley Hutchins48a31762013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/ReachableCode.h"
30#include "clang/Analysis/Analyses/ThreadSafety.h"
31#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
Ted Kremenek3427fac2011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
Alexander Kornienkoe61e5622012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenek918fe842010-03-20 21:06:02 +000055
56using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Unreachable code analysis.
60//===----------------------------------------------------------------------===//
61
62namespace {
63 class UnreachableCodeHandler : public reachable_code::Callback {
64 Sema &S;
65 public:
66 UnreachableCodeHandler(Sema &s) : S(s) {}
67
Ted Kremenek1a8641c2014-03-15 01:26:32 +000068 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000069 SourceLocation L,
70 SourceRange SilenceableCondVal,
71 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000072 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000073 unsigned diag = diag::warn_unreachable;
74 switch (UK) {
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
77 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000078 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000079 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000080 break;
Ted Kremenek14210372014-03-21 06:02:36 +000081 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
83 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 case reachable_code::UK_Other:
85 break;
86 }
87
88 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000089
90 SourceLocation Open = SilenceableCondVal.getBegin();
91 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000092 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000094 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
98 }
99 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000100 }
101 };
102}
103
104/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000105static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000106 // As a heuristic prune all diagnostics not in the main file. Currently
107 // the majority of warnings in headers are false positives. These
108 // are largely caused by configuration state, e.g. preprocessor
109 // defined code, etc.
110 //
111 // Note that this is also a performance optimization. Analyzing
112 // headers many times can be expensive.
113 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
114 return;
115
Ted Kremenek918fe842010-03-20 21:06:02 +0000116 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000118}
119
Richard Trieuf935b562014-04-05 05:17:01 +0000120/// \brief Warn on logical operator errors in CFGBuilder
121class LogicalErrorHandler : public CFGCallback {
122 Sema &S;
123
124public:
125 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
126
127 static bool HasMacroID(const Expr *E) {
128 if (E->getExprLoc().isMacroID())
129 return true;
130
131 // Recurse to children.
132 for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
133 if (*SubStmts)
134 if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
135 if (HasMacroID(SubExpr))
136 return true;
137
138 return false;
139 }
140
141 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {
142 if (HasMacroID(B))
143 return;
144
145 SourceRange DiagRange = B->getSourceRange();
146 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
147 << DiagRange << isAlwaysTrue;
148 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000149
150 void compareBitwiseEquality(const BinaryOperator *B, bool isAlwaysTrue) {
151 if (HasMacroID(B))
152 return;
153
154 SourceRange DiagRange = B->getSourceRange();
155 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
156 << DiagRange << isAlwaysTrue;
157 }
Richard Trieuf935b562014-04-05 05:17:01 +0000158};
159
160
Ted Kremenek918fe842010-03-20 21:06:02 +0000161//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000162// Check for infinite self-recursion in functions
163//===----------------------------------------------------------------------===//
164
165// All blocks are in one of three states. States are ordered so that blocks
166// can only move to higher states.
167enum RecursiveState {
168 FoundNoPath,
169 FoundPath,
170 FoundPathWithNoRecursiveCall
171};
172
173static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
174 CFGBlock &Block, unsigned ExitID,
175 llvm::SmallVectorImpl<RecursiveState> &States,
176 RecursiveState State) {
177 unsigned ID = Block.getBlockID();
178
179 // A block's state can only move to a higher state.
180 if (States[ID] >= State)
181 return;
182
183 States[ID] = State;
184
185 // Found a path to the exit node without a recursive call.
186 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
187 return;
188
189 if (State == FoundPathWithNoRecursiveCall) {
190 // If the current state is FoundPathWithNoRecursiveCall, the successors
191 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
192 // which, process all the Stmt's in this block to find any recursive calls.
Aaron Ballmane5195222014-05-15 20:50:47 +0000193 for (const auto &B : Block) {
194 if (B.getKind() != CFGElement::Statement)
Richard Trieu2f024f42013-12-21 02:33:43 +0000195 continue;
196
Aaron Ballmane5195222014-05-15 20:50:47 +0000197 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
Richard Trieu2f024f42013-12-21 02:33:43 +0000198 if (CE && CE->getCalleeDecl() &&
199 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000200
201 // Skip function calls which are qualified with a templated class.
202 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
203 CE->getCallee()->IgnoreParenImpCasts())) {
204 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
205 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
206 isa<TemplateSpecializationType>(NNS->getAsType())) {
207 continue;
208 }
209 }
210 }
211
Richard Trieu2f024f42013-12-21 02:33:43 +0000212 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
213 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
214 !MCE->getMethodDecl()->isVirtual()) {
215 State = FoundPath;
216 break;
217 }
218 } else {
219 State = FoundPath;
220 break;
221 }
222 }
223 }
224 }
225
226 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
227 I != E; ++I)
228 if (*I)
229 checkForFunctionCall(S, FD, **I, ExitID, States, State);
230}
231
232static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
233 const Stmt *Body,
234 AnalysisDeclContext &AC) {
235 FD = FD->getCanonicalDecl();
236
237 // Only run on non-templated functions and non-templated members of
238 // templated classes.
239 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
240 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
241 return;
242
243 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000244 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000245
246 // If the exit block is unreachable, skip processing the function.
247 if (cfg->getExit().pred_empty())
248 return;
249
250 // Mark all nodes as FoundNoPath, then begin processing the entry block.
251 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
252 FoundNoPath);
253 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
254 states, FoundPathWithNoRecursiveCall);
255
256 // Check that the exit block is reachable. This prevents triggering the
257 // warning on functions that do not terminate.
258 if (states[cfg->getExit().getBlockID()] == FoundPath)
259 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
260}
261
262//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000263// Check for missing return value.
264//===----------------------------------------------------------------------===//
265
John McCall5c6ec8c2010-05-16 09:34:11 +0000266enum ControlFlowKind {
267 UnknownFallThrough,
268 NeverFallThrough,
269 MaybeFallThrough,
270 AlwaysFallThrough,
271 NeverFallThroughOrReturn
272};
Ted Kremenek918fe842010-03-20 21:06:02 +0000273
274/// CheckFallThrough - Check that we don't fall off the end of a
275/// Statement that should return a value.
276///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000277/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
278/// MaybeFallThrough iff we might or might not fall off the end,
279/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
280/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000281/// statement but we may return. We assume that functions not marked noreturn
282/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000283static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000284 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000285 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000286
287 // The CFG leaves in dead things, and we don't want the dead code paths to
288 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000289 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000290 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000291 live);
292
293 bool AddEHEdges = AC.getAddEHEdges();
294 if (!AddEHEdges && count != cfg->getNumBlockIDs())
295 // When there are things remaining dead, and we didn't add EH edges
296 // from CallExprs to the catch clauses, we have to go back and
297 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000298 for (const auto *B : *cfg) {
299 if (!live[B->getBlockID()]) {
300 if (B->pred_begin() == B->pred_end()) {
301 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000302 // When not adding EH edges from calls, catch clauses
303 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000304 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000305 continue;
306 }
307 }
308 }
309
310 // Now we know what is live, we check the live precessors of the exit block
311 // and look for fall through paths, being careful to ignore normal returns,
312 // and exceptional paths.
313 bool HasLiveReturn = false;
314 bool HasFakeEdge = false;
315 bool HasPlainEdge = false;
316 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000317
318 // Ignore default cases that aren't likely to be reachable because all
319 // enums in a switch(X) have explicit case statements.
320 CFGBlock::FilterOptions FO;
321 FO.IgnoreDefaultsWithCoveredEnums = 1;
322
323 for (CFGBlock::filtered_pred_iterator
324 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
325 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000326 if (!live[B.getBlockID()])
327 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000328
Chandler Carruth03faf782011-09-13 09:53:58 +0000329 // Skip blocks which contain an element marked as no-return. They don't
330 // represent actually viable edges into the exit block, so mark them as
331 // abnormal.
332 if (B.hasNoReturnElement()) {
333 HasAbnormalEdge = true;
334 continue;
335 }
336
Ted Kremenek5d068492011-01-26 04:49:52 +0000337 // Destructors can appear after the 'return' in the CFG. This is
338 // normal. We need to look pass the destructors for the return
339 // statement (if it exists).
340 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000341
Chandler Carruth03faf782011-09-13 09:53:58 +0000342 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000343 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000344 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000345
Ted Kremenek5d068492011-01-26 04:49:52 +0000346 // No more CFGElements in the block?
347 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000348 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
349 HasAbnormalEdge = true;
350 continue;
351 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000352 // A labeled empty statement, or the entry block...
353 HasPlainEdge = true;
354 continue;
355 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000356
David Blaikie2a01f5d2013-02-21 20:58:29 +0000357 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000358 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000359 if (isa<ReturnStmt>(S)) {
360 HasLiveReturn = true;
361 continue;
362 }
363 if (isa<ObjCAtThrowStmt>(S)) {
364 HasFakeEdge = true;
365 continue;
366 }
367 if (isa<CXXThrowExpr>(S)) {
368 HasFakeEdge = true;
369 continue;
370 }
Chad Rosier32503022012-06-11 20:47:18 +0000371 if (isa<MSAsmStmt>(S)) {
372 // TODO: Verify this is correct.
373 HasFakeEdge = true;
374 HasLiveReturn = true;
375 continue;
376 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000377 if (isa<CXXTryStmt>(S)) {
378 HasAbnormalEdge = true;
379 continue;
380 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000381 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
382 == B.succ_end()) {
383 HasAbnormalEdge = true;
384 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000385 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000386
387 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000388 }
389 if (!HasPlainEdge) {
390 if (HasLiveReturn)
391 return NeverFallThrough;
392 return NeverFallThroughOrReturn;
393 }
394 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
395 return MaybeFallThrough;
396 // This says AlwaysFallThrough for calls to functions that are not marked
397 // noreturn, that don't return. If people would like this warning to be more
398 // accurate, such functions should be marked as noreturn.
399 return AlwaysFallThrough;
400}
401
Dan Gohman28ade552010-07-26 21:25:24 +0000402namespace {
403
Ted Kremenek918fe842010-03-20 21:06:02 +0000404struct CheckFallThroughDiagnostics {
405 unsigned diag_MaybeFallThrough_HasNoReturn;
406 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
407 unsigned diag_AlwaysFallThrough_HasNoReturn;
408 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
409 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000410 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000411 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000412
Douglas Gregor24f27692010-04-16 23:28:44 +0000413 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000414 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000415 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000416 D.diag_MaybeFallThrough_HasNoReturn =
417 diag::warn_falloff_noreturn_function;
418 D.diag_MaybeFallThrough_ReturnsNonVoid =
419 diag::warn_maybe_falloff_nonvoid_function;
420 D.diag_AlwaysFallThrough_HasNoReturn =
421 diag::warn_falloff_noreturn_function;
422 D.diag_AlwaysFallThrough_ReturnsNonVoid =
423 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000424
425 // Don't suggest that virtual functions be marked "noreturn", since they
426 // might be overridden by non-noreturn functions.
427 bool isVirtualMethod = false;
428 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
429 isVirtualMethod = Method->isVirtual();
430
Douglas Gregor0de57202011-10-10 18:15:57 +0000431 // Don't suggest that template instantiations be marked "noreturn"
432 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000433 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
434 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000435
436 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000437 D.diag_NeverFallThroughOrReturn =
438 diag::warn_suggest_noreturn_function;
439 else
440 D.diag_NeverFallThroughOrReturn = 0;
441
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000442 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000443 return D;
444 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000445
Ted Kremenek918fe842010-03-20 21:06:02 +0000446 static CheckFallThroughDiagnostics MakeForBlock() {
447 CheckFallThroughDiagnostics D;
448 D.diag_MaybeFallThrough_HasNoReturn =
449 diag::err_noreturn_block_has_return_expr;
450 D.diag_MaybeFallThrough_ReturnsNonVoid =
451 diag::err_maybe_falloff_nonvoid_block;
452 D.diag_AlwaysFallThrough_HasNoReturn =
453 diag::err_noreturn_block_has_return_expr;
454 D.diag_AlwaysFallThrough_ReturnsNonVoid =
455 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000456 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000457 D.funMode = Block;
458 return D;
459 }
460
461 static CheckFallThroughDiagnostics MakeForLambda() {
462 CheckFallThroughDiagnostics D;
463 D.diag_MaybeFallThrough_HasNoReturn =
464 diag::err_noreturn_lambda_has_return_expr;
465 D.diag_MaybeFallThrough_ReturnsNonVoid =
466 diag::warn_maybe_falloff_nonvoid_lambda;
467 D.diag_AlwaysFallThrough_HasNoReturn =
468 diag::err_noreturn_lambda_has_return_expr;
469 D.diag_AlwaysFallThrough_ReturnsNonVoid =
470 diag::warn_falloff_nonvoid_lambda;
471 D.diag_NeverFallThroughOrReturn = 0;
472 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000473 return D;
474 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000475
David Blaikie9c902b52011-09-25 23:23:43 +0000476 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000477 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000478 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000479 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000480 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
481 FuncLoc)) &&
482 (!HasNoReturn ||
483 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
484 FuncLoc)) &&
485 (!ReturnsVoid ||
486 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000487 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000488
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000489 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000490 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000491 }
492};
493
Dan Gohman28ade552010-07-26 21:25:24 +0000494}
495
Ted Kremenek918fe842010-03-20 21:06:02 +0000496/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
497/// function that should return a value. Check that we don't fall off the end
498/// of a noreturn function. We assume that functions and blocks not marked
499/// noreturn will return.
500static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000501 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000502 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000503 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000504
505 bool ReturnsVoid = false;
506 bool HasNoReturn = false;
507
508 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000509 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000510 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000511 }
512 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000513 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000514 HasNoReturn = MD->hasAttr<NoReturnAttr>();
515 }
516 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000517 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000518 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000519 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000520 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000521 ReturnsVoid = true;
522 if (FT->getNoReturnAttr())
523 HasNoReturn = true;
524 }
525 }
526
David Blaikie9c902b52011-09-25 23:23:43 +0000527 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000528
529 // Short circuit for compilation speed.
530 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
531 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000532
Ted Kremenek918fe842010-03-20 21:06:02 +0000533 // FIXME: Function try block
534 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
535 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000536 case UnknownFallThrough:
537 break;
538
Ted Kremenek918fe842010-03-20 21:06:02 +0000539 case MaybeFallThrough:
540 if (HasNoReturn)
541 S.Diag(Compound->getRBracLoc(),
542 CD.diag_MaybeFallThrough_HasNoReturn);
543 else if (!ReturnsVoid)
544 S.Diag(Compound->getRBracLoc(),
545 CD.diag_MaybeFallThrough_ReturnsNonVoid);
546 break;
547 case AlwaysFallThrough:
548 if (HasNoReturn)
549 S.Diag(Compound->getRBracLoc(),
550 CD.diag_AlwaysFallThrough_HasNoReturn);
551 else if (!ReturnsVoid)
552 S.Diag(Compound->getRBracLoc(),
553 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
554 break;
555 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000556 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
557 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
558 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000559 << 0 << FD;
560 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
561 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
562 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000563 } else {
564 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
565 }
566 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000567 break;
568 case NeverFallThrough:
569 break;
570 }
571 }
572}
573
574//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000575// -Wuninitialized
576//===----------------------------------------------------------------------===//
577
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000578namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000579/// ContainsReference - A visitor class to search for references to
580/// a particular declaration (the needle) within any evaluated component of an
581/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000582class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000583 bool FoundReference;
584 const DeclRefExpr *Needle;
585
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000586public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000587 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
588 : EvaluatedExprVisitor<ContainsReference>(Context),
589 FoundReference(false), Needle(Needle) {}
590
591 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000592 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000593 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000594 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000595
596 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000597 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000598
599 void VisitDeclRefExpr(DeclRefExpr *E) {
600 if (E == Needle)
601 FoundReference = true;
602 else
603 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000604 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000605
606 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000607};
608}
609
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000610static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000611 QualType VariableTy = VD->getType().getCanonicalType();
612 if (VariableTy->isBlockPointerType() &&
613 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000614 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
615 << VD->getDeclName()
616 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000617 return true;
618 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000619
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000620 // Don't issue a fixit if there is already an initializer.
621 if (VD->getInit())
622 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000623
624 // Don't suggest a fixit inside macros.
625 if (VD->getLocEnd().isMacroID())
626 return false;
627
Alp Tokerb6cc5922014-05-03 03:45:55 +0000628 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000629
630 // Suggest possible initialization (if any).
631 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
632 if (Init.empty())
633 return false;
634
Richard Smith8d06f422012-01-12 23:53:29 +0000635 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
636 << FixItHint::CreateInsertion(Loc, Init);
637 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000638}
639
Richard Smith1bb8edb82012-05-26 06:20:46 +0000640/// Create a fixit to remove an if-like statement, on the assumption that its
641/// condition is CondVal.
642static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
643 const Stmt *Else, bool CondVal,
644 FixItHint &Fixit1, FixItHint &Fixit2) {
645 if (CondVal) {
646 // If condition is always true, remove all but the 'then'.
647 Fixit1 = FixItHint::CreateRemoval(
648 CharSourceRange::getCharRange(If->getLocStart(),
649 Then->getLocStart()));
650 if (Else) {
651 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
652 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
653 Fixit2 = FixItHint::CreateRemoval(
654 SourceRange(ElseKwLoc, Else->getLocEnd()));
655 }
656 } else {
657 // If condition is always false, remove all but the 'else'.
658 if (Else)
659 Fixit1 = FixItHint::CreateRemoval(
660 CharSourceRange::getCharRange(If->getLocStart(),
661 Else->getLocStart()));
662 else
663 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
664 }
665}
666
667/// DiagUninitUse -- Helper function to produce a diagnostic for an
668/// uninitialized use of a variable.
669static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
670 bool IsCapturedByBlock) {
671 bool Diagnosed = false;
672
Richard Smithba8071e2013-09-12 18:49:10 +0000673 switch (Use.getKind()) {
674 case UninitUse::Always:
675 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
676 << VD->getDeclName() << IsCapturedByBlock
677 << Use.getUser()->getSourceRange();
678 return;
679
680 case UninitUse::AfterDecl:
681 case UninitUse::AfterCall:
682 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
683 << VD->getDeclName() << IsCapturedByBlock
684 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
685 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
686 << VD->getSourceRange();
687 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
688 << IsCapturedByBlock << Use.getUser()->getSourceRange();
689 return;
690
691 case UninitUse::Maybe:
692 case UninitUse::Sometimes:
693 // Carry on to report sometimes-uninitialized branches, if possible,
694 // or a 'may be used uninitialized' diagnostic otherwise.
695 break;
696 }
697
Richard Smith1bb8edb82012-05-26 06:20:46 +0000698 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000699 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
700 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000701 assert(Use.getKind() == UninitUse::Sometimes);
702
703 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000704 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000705
706 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000707 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000708 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000709 SourceRange Range;
710
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000711 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000712 // For all binary terminators, branch 0 is taken if the condition is true,
713 // and branch 1 is taken if the condition is false.
714 int RemoveDiagKind = -1;
715 const char *FixitStr =
716 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
717 : (I->Output ? "1" : "0");
718 FixItHint Fixit1, Fixit2;
719
Richard Smithba8071e2013-09-12 18:49:10 +0000720 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000721 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000722 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000723 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000724 continue;
725
726 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000727 case Stmt::IfStmtClass: {
728 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000729 DiagKind = 0;
730 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000731 Range = IS->getCond()->getSourceRange();
732 RemoveDiagKind = 0;
733 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
734 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000735 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000736 }
737 case Stmt::ConditionalOperatorClass: {
738 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000739 DiagKind = 0;
740 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000741 Range = CO->getCond()->getSourceRange();
742 RemoveDiagKind = 0;
743 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
744 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000745 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000746 }
Richard Smith4323bf82012-05-25 02:17:09 +0000747 case Stmt::BinaryOperatorClass: {
748 const BinaryOperator *BO = cast<BinaryOperator>(Term);
749 if (!BO->isLogicalOp())
750 continue;
751 DiagKind = 0;
752 Str = BO->getOpcodeStr();
753 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000754 RemoveDiagKind = 0;
755 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
756 (BO->getOpcode() == BO_LOr && !I->Output))
757 // true && y -> y, false || y -> y.
758 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
759 BO->getOperatorLoc()));
760 else
761 // false && y -> false, true || y -> true.
762 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000763 break;
764 }
765
766 // "loop is entered / loop is exited".
767 case Stmt::WhileStmtClass:
768 DiagKind = 1;
769 Str = "while";
770 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000771 RemoveDiagKind = 1;
772 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000773 break;
774 case Stmt::ForStmtClass:
775 DiagKind = 1;
776 Str = "for";
777 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000778 RemoveDiagKind = 1;
779 if (I->Output)
780 Fixit1 = FixItHint::CreateRemoval(Range);
781 else
782 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000783 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000784 case Stmt::CXXForRangeStmtClass:
785 if (I->Output == 1) {
786 // The use occurs if a range-based for loop's body never executes.
787 // That may be impossible, and there's no syntactic fix for this,
788 // so treat it as a 'may be uninitialized' case.
789 continue;
790 }
791 DiagKind = 1;
792 Str = "for";
793 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
794 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000795
796 // "condition is true / loop is exited".
797 case Stmt::DoStmtClass:
798 DiagKind = 2;
799 Str = "do";
800 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000801 RemoveDiagKind = 1;
802 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000803 break;
804
805 // "switch case is taken".
806 case Stmt::CaseStmtClass:
807 DiagKind = 3;
808 Str = "case";
809 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
810 break;
811 case Stmt::DefaultStmtClass:
812 DiagKind = 3;
813 Str = "default";
814 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
815 break;
816 }
817
Richard Smith1bb8edb82012-05-26 06:20:46 +0000818 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
819 << VD->getDeclName() << IsCapturedByBlock << DiagKind
820 << Str << I->Output << Range;
821 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
822 << IsCapturedByBlock << User->getSourceRange();
823 if (RemoveDiagKind != -1)
824 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
825 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
826
827 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000828 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000829
830 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000831 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000832 << VD->getDeclName() << IsCapturedByBlock
833 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000834}
835
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000836/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
837/// uninitialized variable. This manages the different forms of diagnostic
838/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000839/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000840/// false.
841static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000842 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000843 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000844
Richard Smith4323bf82012-05-25 02:17:09 +0000845 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000846 // Inspect the initializer of the variable declaration which is
847 // being referenced prior to its initialization. We emit
848 // specialized diagnostics for self-initialization, and we
849 // specifically avoid warning about self references which take the
850 // form of:
851 //
852 // int x = x;
853 //
854 // This is used to indicate to GCC that 'x' is intentionally left
855 // uninitialized. Proven code paths which access 'x' in
856 // an uninitialized state after this will still warn.
857 if (const Expr *Initializer = VD->getInit()) {
858 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
859 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000860
Richard Trieu43a2fc72012-05-09 21:08:22 +0000861 ContainsReference CR(S.Context, DRE);
862 CR.Visit(const_cast<Expr*>(Initializer));
863 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000864 S.Diag(DRE->getLocStart(),
865 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000866 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
867 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000868 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000869 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000870
Richard Smith1bb8edb82012-05-26 06:20:46 +0000871 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000872 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000873 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000874 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
875 S.Diag(BE->getLocStart(),
876 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000877 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000878 else
879 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000880 }
881
882 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000883 // the initializer of that declaration & we didn't already suggest
884 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000885 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000886 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
887 << VD->getDeclName();
888
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000889 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000890}
891
Richard Smith84837d52012-05-03 18:27:39 +0000892namespace {
893 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
894 public:
895 FallthroughMapper(Sema &S)
896 : FoundSwitchStatements(false),
897 S(S) {
898 }
899
900 bool foundSwitchStatements() const { return FoundSwitchStatements; }
901
902 void markFallthroughVisited(const AttributedStmt *Stmt) {
903 bool Found = FallthroughStmts.erase(Stmt);
904 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000905 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000906 }
907
908 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
909
910 const AttrStmts &getFallthroughStmts() const {
911 return FallthroughStmts;
912 }
913
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000914 void fillReachableBlocks(CFG *Cfg) {
915 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
916 std::deque<const CFGBlock *> BlockQueue;
917
918 ReachableBlocks.insert(&Cfg->getEntry());
919 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000920 // Mark all case blocks reachable to avoid problems with switching on
921 // constants, covered enums, etc.
922 // These blocks can contain fall-through annotations, and we don't want to
923 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +0000924 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000925 const Stmt *L = B->getLabel();
926 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
927 BlockQueue.push_back(B);
928 }
929
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000930 while (!BlockQueue.empty()) {
931 const CFGBlock *P = BlockQueue.front();
932 BlockQueue.pop_front();
933 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
934 E = P->succ_end();
935 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000936 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000937 BlockQueue.push_back(*I);
938 }
939 }
940 }
941
Richard Smith84837d52012-05-03 18:27:39 +0000942 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000943 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
944
Richard Smith84837d52012-05-03 18:27:39 +0000945 int UnannotatedCnt = 0;
946 AnnotatedCnt = 0;
947
Aaron Ballmane5195222014-05-15 20:50:47 +0000948 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +0000949 while (!BlockQueue.empty()) {
950 const CFGBlock *P = BlockQueue.front();
951 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000952 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000953
954 const Stmt *Term = P->getTerminator();
955 if (Term && isa<SwitchStmt>(Term))
956 continue; // Switch statement, good.
957
958 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
959 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
960 continue; // Previous case label has no statements, good.
961
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000962 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
963 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
964 continue; // Case label is preceded with a normal label, good.
965
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000966 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000967 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
968 ElemEnd = P->rend();
969 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000970 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
971 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000972 S.Diag(AS->getLocStart(),
973 diag::warn_fallthrough_attr_unreachable);
974 markFallthroughVisited(AS);
975 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000976 break;
Richard Smith84837d52012-05-03 18:27:39 +0000977 }
978 // Don't care about other unreachable statements.
979 }
980 }
981 // If there are no unreachable statements, this may be a special
982 // case in CFG:
983 // case X: {
984 // A a; // A has a destructor.
985 // break;
986 // }
987 // // <<<< This place is represented by a 'hanging' CFG block.
988 // case Y:
989 continue;
990 }
991
992 const Stmt *LastStmt = getLastStmt(*P);
993 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
994 markFallthroughVisited(AS);
995 ++AnnotatedCnt;
996 continue; // Fallthrough annotation, good.
997 }
998
999 if (!LastStmt) { // This block contains no executable statements.
1000 // Traverse its predecessors.
1001 std::copy(P->pred_begin(), P->pred_end(),
1002 std::back_inserter(BlockQueue));
1003 continue;
1004 }
1005
1006 ++UnannotatedCnt;
1007 }
1008 return !!UnannotatedCnt;
1009 }
1010
1011 // RecursiveASTVisitor setup.
1012 bool shouldWalkTypesOfTypeLocs() const { return false; }
1013
1014 bool VisitAttributedStmt(AttributedStmt *S) {
1015 if (asFallThroughAttr(S))
1016 FallthroughStmts.insert(S);
1017 return true;
1018 }
1019
1020 bool VisitSwitchStmt(SwitchStmt *S) {
1021 FoundSwitchStatements = true;
1022 return true;
1023 }
1024
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001025 // We don't want to traverse local type declarations. We analyze their
1026 // methods separately.
1027 bool TraverseDecl(Decl *D) { return true; }
1028
Alexander Kornienkobf911642014-06-24 15:28:21 +00001029 // We analyze lambda bodies separately. Skip them here.
1030 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1031
Richard Smith84837d52012-05-03 18:27:39 +00001032 private:
1033
1034 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1035 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1036 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1037 return AS;
1038 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001039 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001040 }
1041
1042 static const Stmt *getLastStmt(const CFGBlock &B) {
1043 if (const Stmt *Term = B.getTerminator())
1044 return Term;
1045 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1046 ElemEnd = B.rend();
1047 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001048 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1049 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001050 }
1051 // Workaround to detect a statement thrown out by CFGBuilder:
1052 // case X: {} case Y:
1053 // case X: ; case Y:
1054 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1055 if (!isa<SwitchCase>(SW->getSubStmt()))
1056 return SW->getSubStmt();
1057
Craig Topperc3ec1492014-05-26 06:22:03 +00001058 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001059 }
1060
1061 bool FoundSwitchStatements;
1062 AttrStmts FallthroughStmts;
1063 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001064 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001065 };
1066}
1067
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001068static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001069 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001070 // Only perform this analysis when using C++11. There is no good workflow
1071 // for this warning when not using C++11. There is no good way to silence
1072 // the warning (no attribute is available) unless we are using C++11's support
1073 // for generalized attributes. Once could use pragmas to silence the warning,
1074 // but as a general solution that is gross and not in the spirit of this
1075 // warning.
1076 //
1077 // NOTE: This an intermediate solution. There are on-going discussions on
1078 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001079 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001080 return;
1081
Richard Smith84837d52012-05-03 18:27:39 +00001082 FallthroughMapper FM(S);
1083 FM.TraverseStmt(AC.getBody());
1084
1085 if (!FM.foundSwitchStatements())
1086 return;
1087
Alexis Hunt2178f142012-06-15 21:22:05 +00001088 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001089 return;
1090
Richard Smith84837d52012-05-03 18:27:39 +00001091 CFG *Cfg = AC.getCFG();
1092
1093 if (!Cfg)
1094 return;
1095
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001096 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001097
1098 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001099 const CFGBlock *B = *I;
1100 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001101
1102 if (!Label || !isa<SwitchCase>(Label))
1103 continue;
1104
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001105 int AnnotatedCnt;
1106
Alexander Kornienko55488792013-01-25 15:49:34 +00001107 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001108 continue;
1109
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001110 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001111 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1112 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001113
1114 if (!AnnotatedCnt) {
1115 SourceLocation L = Label->getLocStart();
1116 if (L.isMacroID())
1117 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001118 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001119 const Stmt *Term = B->getTerminator();
1120 // Skip empty cases.
1121 while (B->empty() && !Term && B->succ_size() == 1) {
1122 B = *B->succ_begin();
1123 Term = B->getTerminator();
1124 }
1125 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001126 Preprocessor &PP = S.getPreprocessor();
1127 TokenValue Tokens[] = {
1128 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1129 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1130 tok::r_square, tok::r_square
1131 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001132 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1133 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1134 if (!MacroName.empty())
1135 AnnotationSpelling = MacroName;
1136 SmallString<64> TextToInsert(AnnotationSpelling);
1137 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001138 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001139 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001140 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001141 }
Richard Smith84837d52012-05-03 18:27:39 +00001142 }
1143 S.Diag(L, diag::note_insert_break_fixit) <<
1144 FixItHint::CreateInsertion(L, "break; ");
1145 }
1146 }
1147
Aaron Ballmane5195222014-05-15 20:50:47 +00001148 for (const auto *F : FM.getFallthroughStmts())
1149 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001150}
1151
Jordan Rose25c0ea82012-10-29 17:46:47 +00001152static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1153 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001154 assert(S);
1155
1156 do {
1157 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001158 case Stmt::ForStmtClass:
1159 case Stmt::WhileStmtClass:
1160 case Stmt::CXXForRangeStmtClass:
1161 case Stmt::ObjCForCollectionStmtClass:
1162 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001163 case Stmt::DoStmtClass: {
1164 const Expr *Cond = cast<DoStmt>(S)->getCond();
1165 llvm::APSInt Val;
1166 if (!Cond->EvaluateAsInt(Val, Ctx))
1167 return true;
1168 return Val.getBoolValue();
1169 }
Jordan Rose76831c62012-10-11 16:10:19 +00001170 default:
1171 break;
1172 }
1173 } while ((S = PM.getParent(S)));
1174
1175 return false;
1176}
1177
Jordan Rosed3934582012-09-28 22:21:30 +00001178
1179static void diagnoseRepeatedUseOfWeak(Sema &S,
1180 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001181 const Decl *D,
1182 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001183 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1184 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1185 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001186 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1187 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001188
Jordan Rose25c0ea82012-10-29 17:46:47 +00001189 ASTContext &Ctx = S.getASTContext();
1190
Jordan Rosed3934582012-09-28 22:21:30 +00001191 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1192
1193 // Extract all weak objects that are referenced more than once.
1194 SmallVector<StmtUsesPair, 8> UsesByStmt;
1195 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1196 I != E; ++I) {
1197 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001198
1199 // Find the first read of the weak object.
1200 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1201 for ( ; UI != UE; ++UI) {
1202 if (UI->isUnsafe())
1203 break;
1204 }
1205
1206 // If there were only writes to this object, don't warn.
1207 if (UI == UE)
1208 continue;
1209
Jordan Rose76831c62012-10-11 16:10:19 +00001210 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001211 // read is not within a loop, don't warn. Additionally, don't warn in a
1212 // loop if the base object is a local variable -- local variables are often
1213 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001214 if (UI == Uses.begin()) {
1215 WeakUseVector::const_iterator UI2 = UI;
1216 for (++UI2; UI2 != UE; ++UI2)
1217 if (UI2->isUnsafe())
1218 break;
1219
Jordan Rose25c0ea82012-10-29 17:46:47 +00001220 if (UI2 == UE) {
1221 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001222 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001223
1224 const WeakObjectProfileTy &Profile = I->first;
1225 if (!Profile.isExactProfile())
1226 continue;
1227
1228 const NamedDecl *Base = Profile.getBase();
1229 if (!Base)
1230 Base = Profile.getProperty();
1231 assert(Base && "A profile always has a base or property.");
1232
1233 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1234 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1235 continue;
1236 }
Jordan Rose76831c62012-10-11 16:10:19 +00001237 }
1238
Jordan Rosed3934582012-09-28 22:21:30 +00001239 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1240 }
1241
1242 if (UsesByStmt.empty())
1243 return;
1244
1245 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001246 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001247 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001248 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1249 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1250 RHS.first->getLocStart());
1251 });
Jordan Rosed3934582012-09-28 22:21:30 +00001252
1253 // Classify the current code body for better warning text.
1254 // This enum should stay in sync with the cases in
1255 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1256 // FIXME: Should we use a common classification enum and the same set of
1257 // possibilities all throughout Sema?
1258 enum {
1259 Function,
1260 Method,
1261 Block,
1262 Lambda
1263 } FunctionKind;
1264
1265 if (isa<sema::BlockScopeInfo>(CurFn))
1266 FunctionKind = Block;
1267 else if (isa<sema::LambdaScopeInfo>(CurFn))
1268 FunctionKind = Lambda;
1269 else if (isa<ObjCMethodDecl>(D))
1270 FunctionKind = Method;
1271 else
1272 FunctionKind = Function;
1273
1274 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001275 for (const auto &P : UsesByStmt) {
1276 const Stmt *FirstRead = P.first;
1277 const WeakObjectProfileTy &Key = P.second->first;
1278 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001279
Jordan Rose657b5f42012-09-28 22:21:35 +00001280 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1281 // may not contain enough information to determine that these are different
1282 // properties. We can only be 100% sure of a repeated use in certain cases,
1283 // and we adjust the diagnostic kind accordingly so that the less certain
1284 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001285 unsigned DiagKind;
1286 if (Key.isExactProfile())
1287 DiagKind = diag::warn_arc_repeated_use_of_weak;
1288 else
1289 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1290
Jordan Rose657b5f42012-09-28 22:21:35 +00001291 // Classify the weak object being accessed for better warning text.
1292 // This enum should stay in sync with the cases in
1293 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1294 enum {
1295 Variable,
1296 Property,
1297 ImplicitProperty,
1298 Ivar
1299 } ObjectKind;
1300
1301 const NamedDecl *D = Key.getProperty();
1302 if (isa<VarDecl>(D))
1303 ObjectKind = Variable;
1304 else if (isa<ObjCPropertyDecl>(D))
1305 ObjectKind = Property;
1306 else if (isa<ObjCMethodDecl>(D))
1307 ObjectKind = ImplicitProperty;
1308 else if (isa<ObjCIvarDecl>(D))
1309 ObjectKind = Ivar;
1310 else
1311 llvm_unreachable("Unexpected weak object kind!");
1312
Jordan Rosed3934582012-09-28 22:21:30 +00001313 // Show the first time the object was read.
1314 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001315 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001316 << FirstRead->getSourceRange();
1317
1318 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001319 for (const auto &Use : Uses) {
1320 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001321 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001322 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001323 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001324 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001325 }
1326 }
1327}
1328
Jordan Rosed3934582012-09-28 22:21:30 +00001329namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001330class UninitValsDiagReporter : public UninitVariablesHandler {
1331 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001332 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001333 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001334 // Prefer using MapVector to DenseMap, so that iteration order will be
1335 // the same as insertion order. This is needed to obtain a deterministic
1336 // order of diagnostics when calling flushDiagnostics().
1337 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001338 UsesMap *uses;
1339
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001340public:
Craig Topperc3ec1492014-05-26 06:22:03 +00001341 UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
Ted Kremenek39fa0562011-01-21 19:41:41 +00001342 ~UninitValsDiagReporter() {
1343 flushDiagnostics();
1344 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001345
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001346 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001347 if (!uses)
1348 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001349
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001350 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001351 if (!V.getPointer())
1352 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001353
Ted Kremenek596fa162011-10-13 18:50:06 +00001354 return V;
1355 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001356
1357 void handleUseOfUninitVariable(const VarDecl *vd,
1358 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001359 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001360 }
1361
Craig Toppere14c0f82014-03-12 04:55:44 +00001362 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001363 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001364 }
1365
1366 void flushDiagnostics() {
1367 if (!uses)
1368 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001369
Aaron Ballmane5195222014-05-15 20:50:47 +00001370 for (const auto &P : *uses) {
1371 const VarDecl *vd = P.first;
1372 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001373
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001374 UsesVec *vec = V.getPointer();
1375 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001376
1377 // Specially handle the case where we have uses of an uninitialized
1378 // variable, but the root cause is an idiomatic self-init. We want
1379 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001380 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001381 DiagnoseUninitializedUse(S, vd,
1382 UninitUse(vd->getInit()->IgnoreParenCasts(),
1383 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001384 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001385 else {
1386 // Sort the uses by their SourceLocations. While not strictly
1387 // guaranteed to produce them in line/column order, this will provide
1388 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001389 std::sort(vec->begin(), vec->end(),
1390 [](const UninitUse &a, const UninitUse &b) {
1391 // Prefer a more confident report over a less confident one.
1392 if (a.getKind() != b.getKind())
1393 return a.getKind() > b.getKind();
1394 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1395 });
1396
Aaron Ballmane5195222014-05-15 20:50:47 +00001397 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001398 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001399 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001400
1401 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001402 // Skip further diagnostics for this variable. We try to warn only
1403 // on the first point at which a variable is used uninitialized.
1404 break;
1405 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001406 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001407
1408 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001409 delete vec;
1410 }
1411 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001412 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001413
1414private:
1415 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001416 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1417 return U.getKind() == UninitUse::Always ||
1418 U.getKind() == UninitUse::AfterCall ||
1419 U.getKind() == UninitUse::AfterDecl;
1420 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001421 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001422};
1423}
1424
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001425namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001426namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001427typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001428typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001429typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001430
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001431struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001432 SourceManager &SM;
1433 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001434
1435 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1436 // Although this call will be slow, this is only called when outputting
1437 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001438 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001439 }
1440};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001441}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001442
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001443//===----------------------------------------------------------------------===//
1444// -Wthread-safety
1445//===----------------------------------------------------------------------===//
1446namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001447namespace threadSafety {
1448
1449class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001450 Sema &S;
1451 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001452 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001453
1454 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001455 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1456 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001457 // Gracefully handle rare cases when the analysis can't get a more
1458 // precise source location.
1459 if (!Loc.isValid())
1460 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001461 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001462 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001463 }
1464
1465 public:
Richard Smith92286672012-02-03 04:45:26 +00001466 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1467 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001468
1469 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1470 /// We need to output diagnostics produced while iterating through
1471 /// the lockset in deterministic order, so this function orders diagnostics
1472 /// and outputs them.
1473 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001474 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001475 for (const auto &Diag : Warnings) {
1476 S.Diag(Diag.first.first, Diag.first.second);
1477 for (const auto &Note : Diag.second)
1478 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001479 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001480 }
1481
Aaron Ballmane0449042014-04-01 21:43:23 +00001482 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1483 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1484 << Loc);
Richard Smith92286672012-02-03 04:45:26 +00001485 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001486 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001487 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1488 SourceLocation Loc) override {
1489 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001490 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001491 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1492 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001493 SourceLocation Loc) override {
1494 if (Loc.isInvalid())
1495 Loc = FunLocation;
1496 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001497 << Kind << LockName << Received
1498 << Expected);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001499 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1500 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001501 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1502 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001503 }
1504
Aaron Ballmane0449042014-04-01 21:43:23 +00001505 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1506 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001507 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001508 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001509 unsigned DiagID = 0;
1510 switch (LEK) {
1511 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001512 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001513 break;
1514 case LEK_LockedSomeLoopIterations:
1515 DiagID = diag::warn_expecting_lock_held_on_loop;
1516 break;
1517 case LEK_LockedAtEndOfFunction:
1518 DiagID = diag::warn_no_unlock;
1519 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001520 case LEK_NotLockedAtEndOfFunction:
1521 DiagID = diag::warn_expecting_locked;
1522 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001523 }
Richard Smith92286672012-02-03 04:45:26 +00001524 if (LocEndOfScope.isInvalid())
1525 LocEndOfScope = FunEndLocation;
1526
Aaron Ballmane0449042014-04-01 21:43:23 +00001527 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1528 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001529 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001530 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1531 << Kind);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001532 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1533 return;
1534 }
1535 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001536 }
1537
Aaron Ballmane0449042014-04-01 21:43:23 +00001538 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1539 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001540 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001541 PartialDiagnosticAt Warning(Loc1,
1542 S.PDiag(diag::warn_lock_exclusive_and_shared)
1543 << Kind << LockName);
1544 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1545 << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001546 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001547 }
1548
Aaron Ballmane0449042014-04-01 21:43:23 +00001549 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1550 ProtectedOperationKind POK, AccessKind AK,
1551 SourceLocation Loc) override {
1552 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1553 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001554 unsigned DiagID = POK == POK_VarAccess?
1555 diag::warn_variable_requires_any_lock:
1556 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001557 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001558 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001559 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001560 }
1561
Aaron Ballmane0449042014-04-01 21:43:23 +00001562 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1563 ProtectedOperationKind POK, Name LockName,
1564 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001565 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001566 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001567 if (PossibleMatch) {
1568 switch (POK) {
1569 case POK_VarAccess:
1570 DiagID = diag::warn_variable_requires_lock_precise;
1571 break;
1572 case POK_VarDereference:
1573 DiagID = diag::warn_var_deref_requires_lock_precise;
1574 break;
1575 case POK_FunctionCall:
1576 DiagID = diag::warn_fun_requires_lock_precise;
1577 break;
1578 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001579 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1580 << D->getNameAsString()
1581 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001582 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001583 << *PossibleMatch);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001584 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1585 } else {
1586 switch (POK) {
1587 case POK_VarAccess:
1588 DiagID = diag::warn_variable_requires_lock;
1589 break;
1590 case POK_VarDereference:
1591 DiagID = diag::warn_var_deref_requires_lock;
1592 break;
1593 case POK_FunctionCall:
1594 DiagID = diag::warn_fun_requires_lock;
1595 break;
1596 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001597 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1598 << D->getNameAsString()
1599 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001600 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001601 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001602 }
1603
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001604 virtual void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1605 SourceLocation Loc) {
1606 PartialDiagnosticAt Warning(Loc,
1607 S.PDiag(diag::warn_acquire_requires_negative_cap)
1608 << Kind << LockName << Neg);
1609 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1610 }
1611
1612
Aaron Ballmane0449042014-04-01 21:43:23 +00001613 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001614 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001615 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1616 << Kind << FunName << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001617 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001618 }
1619};
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001620
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001621}
David Blaikie68e081d2011-12-20 02:48:34 +00001622}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001623
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001624//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001625// -Wconsumed
1626//===----------------------------------------------------------------------===//
1627
1628namespace clang {
1629namespace consumed {
1630namespace {
1631class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1632
1633 Sema &S;
1634 DiagList Warnings;
1635
1636public:
1637
1638 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001639
1640 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001641 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001642 for (const auto &Diag : Warnings) {
1643 S.Diag(Diag.first.first, Diag.first.second);
1644 for (const auto &Note : Diag.second)
1645 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001646 }
1647 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001648
1649 void warnLoopStateMismatch(SourceLocation Loc,
1650 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001651 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1652 VariableName);
1653
1654 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1655 }
1656
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001657 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1658 StringRef VariableName,
1659 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001660 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001661
1662 PartialDiagnosticAt Warning(Loc, S.PDiag(
1663 diag::warn_param_return_typestate_mismatch) << VariableName <<
1664 ExpectedState << ObservedState);
1665
1666 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1667 }
1668
DeLesley Hutchins69391772013-10-17 23:23:53 +00001669 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001670 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001671
1672 PartialDiagnosticAt Warning(Loc, S.PDiag(
1673 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1674
1675 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1676 }
1677
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001678 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001679 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001680 PartialDiagnosticAt Warning(Loc, S.PDiag(
1681 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1682
1683 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1684 }
1685
1686 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001687 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001688
1689 PartialDiagnosticAt Warning(Loc, S.PDiag(
1690 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1691
1692 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1693 }
1694
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001695 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001696 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001697
1698 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001699 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001700
1701 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1702 }
1703
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001704 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001705 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001706
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001707 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1708 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001709
1710 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1711 }
1712};
1713}}}
1714
1715//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001716// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1717// warnings on a function, method, or block.
1718//===----------------------------------------------------------------------===//
1719
Ted Kremenek0b405322010-03-23 00:13:23 +00001720clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1721 enableCheckFallThrough = 1;
1722 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001723 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001724 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001725}
1726
Ted Kremenekad8753c2014-03-15 05:47:06 +00001727static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001728 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001729}
1730
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001731clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1732 : S(s),
1733 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001734 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001735 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001736 MaxCFGBlocksPerFunction(0),
1737 NumUninitAnalysisFunctions(0),
1738 NumUninitAnalysisVariables(0),
1739 MaxUninitAnalysisVariablesPerFunction(0),
1740 NumUninitAnalysisBlockVisits(0),
1741 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001742
1743 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001744 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001745
1746 DefaultPolicy.enableCheckUnreachable =
1747 isEnabled(D, warn_unreachable) ||
1748 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001749 isEnabled(D, warn_unreachable_return) ||
1750 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001751
1752 DefaultPolicy.enableThreadSafetyAnalysis =
1753 isEnabled(D, warn_double_lock);
1754
1755 DefaultPolicy.enableConsumedAnalysis =
1756 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001757}
1758
Aaron Ballmane5195222014-05-15 20:50:47 +00001759static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1760 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001761 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001762}
1763
Ted Kremenek0b405322010-03-23 00:13:23 +00001764void clang::sema::
1765AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001766 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001767 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001768
Ted Kremenek918fe842010-03-20 21:06:02 +00001769 // We avoid doing analysis-based warnings when there are errors for
1770 // two reasons:
1771 // (1) The CFGs often can't be constructed (if the body is invalid), so
1772 // don't bother trying.
1773 // (2) The code already has problems; running the analysis just takes more
1774 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001775 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001776
Ted Kremenek0b405322010-03-23 00:13:23 +00001777 // Do not do any analysis for declarations in system headers if we are
1778 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001779 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001780 S.SourceMgr.isInSystemHeader(D->getLocation()))
1781 return;
1782
John McCall1d570a72010-08-25 05:56:39 +00001783 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001784 if (cast<DeclContext>(D)->isDependentContext())
1785 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001786
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001787 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001788 // Flush out any possibly unreachable diagnostics.
1789 flushDiagnostics(S, fscope);
1790 return;
1791 }
1792
Ted Kremenek918fe842010-03-20 21:06:02 +00001793 const Stmt *Body = D->getBody();
1794 assert(Body);
1795
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001796 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00001797 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001798
Ted Kremenek918fe842010-03-20 21:06:02 +00001799 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001800 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001801 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1802 AC.getCFGBuildOptions().AddEHEdges = false;
1803 AC.getCFGBuildOptions().AddInitializers = true;
1804 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001805 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001806 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001807
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001808 // Force that certain expressions appear as CFGElements in the CFG. This
1809 // is used to speed up various analyses.
1810 // FIXME: This isn't the right factoring. This is here for initial
1811 // prototyping, but we need a way for analyses to say what expressions they
1812 // expect to always be CFGElements and then fill in the BuildOptions
1813 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001814 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1815 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001816 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001817 AC.getCFGBuildOptions().setAllAlwaysAdd();
1818 }
1819 else {
1820 AC.getCFGBuildOptions()
1821 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001822 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001823 .setAlwaysAdd(Stmt::BlockExprClass)
1824 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1825 .setAlwaysAdd(Stmt::DeclRefExprClass)
1826 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001827 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1828 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001829 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001830
Richard Trieue9fa2662014-04-15 00:57:50 +00001831 // Install the logical handler for -Wtautological-overlap-compare
1832 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001833 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1834 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00001835 LEH.reset(new LogicalErrorHandler(S));
1836 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00001837 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001838
Ted Kremenek3427fac2011-02-23 01:52:04 +00001839 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001840 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001841 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001842
1843 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00001844 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1845 if (D.stmt)
1846 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00001847 }
1848
1849 if (AC.getCFG()) {
1850 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00001851 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00001852 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00001853 if (D.stmt) {
1854 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001855 CFGReverseBlockReachabilityAnalysis *cra =
1856 AC.getCFGReachablityAnalysis();
1857 // FIXME: We should be able to assert that block is non-null, but
1858 // the CFG analysis can skip potentially-evaluated expressions in
1859 // edge cases; see test/Sema/vla-2.c.
1860 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001861 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001862 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001863 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001864 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001865 }
1866 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001867 if (!processed) {
1868 // Emit the warning anyway if we cannot map to a basic block.
1869 S.Diag(D.Loc, D.PD);
1870 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001871 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001872 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001873
1874 if (!analyzed)
1875 flushDiagnostics(S, fscope);
1876 }
1877
1878
Ted Kremenek918fe842010-03-20 21:06:02 +00001879 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001880 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001881 const CheckFallThroughDiagnostics &CD =
1882 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001883 : (isa<CXXMethodDecl>(D) &&
1884 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1885 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1886 ? CheckFallThroughDiagnostics::MakeForLambda()
1887 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001888 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001889 }
1890
1891 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001892 if (P.enableCheckUnreachable) {
1893 // Only check for unreachable code on non-template instantiations.
1894 // Different template instantiations can effectively change the control-flow
1895 // and it is very difficult to prove that a snippet of code in a template
1896 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001897 bool isTemplateInstantiation = false;
1898 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1899 isTemplateInstantiation = Function->isTemplateInstantiation();
1900 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001901 CheckUnreachable(S, AC);
1902 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001903
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001904 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001905 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001906 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001907 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001908 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001909 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001910 Reporter.setIssueBetaWarnings(true);
1911
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001912 threadSafety::runThreadSafetyAnalysis(AC, Reporter);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001913 Reporter.emitDiagnostics();
1914 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001915
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001916 // Check for violations of consumed properties.
1917 if (P.enableConsumedAnalysis) {
1918 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001919 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001920 Analyzer.run(AC);
1921 }
1922
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001923 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
1924 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
1925 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001926 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001927 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001928 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001929 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001930 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001931 reporter, stats);
1932
1933 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1934 ++NumUninitAnalysisFunctions;
1935 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1936 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1937 MaxUninitAnalysisVariablesPerFunction =
1938 std::max(MaxUninitAnalysisVariablesPerFunction,
1939 stats.NumVariablesAnalyzed);
1940 MaxUninitAnalysisBlockVisitsPerFunction =
1941 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1942 stats.NumBlockVisits);
1943 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001944 }
1945 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001946
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001947 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001948 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
1949 bool FallThroughDiagPerFunction = !Diags.isIgnored(
1950 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Alexis Hunt2178f142012-06-15 21:22:05 +00001951 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001952 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001953 }
1954
Jordan Rosed3934582012-09-28 22:21:30 +00001955 if (S.getLangOpts().ObjCARCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001956 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00001957 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001958
Richard Trieu2f024f42013-12-21 02:33:43 +00001959
1960 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001961 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
1962 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00001963 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1964 checkRecursiveFunction(S, FD, Body, AC);
1965 }
1966 }
1967
Richard Trieue9fa2662014-04-15 00:57:50 +00001968 // If none of the previous checks caused a CFG build, trigger one here
1969 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001970 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00001971 D->getLocStart())) {
1972 AC.getCFG();
1973 }
1974
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001975 // Collect statistics about the CFG if it was built.
1976 if (S.CollectStats && AC.isCFGBuilt()) {
1977 ++NumFunctionsAnalyzed;
1978 if (CFG *cfg = AC.getCFG()) {
1979 // If we successfully built a CFG for this context, record some more
1980 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001981 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001982 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001983 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001984 } else {
1985 ++NumFunctionsWithBadCFGs;
1986 }
1987 }
1988}
1989
1990void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1991 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1992
1993 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1994 unsigned AvgCFGBlocksPerFunction =
1995 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1996 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1997 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1998 << " " << NumCFGBlocks << " CFG blocks built.\n"
1999 << " " << AvgCFGBlocksPerFunction
2000 << " average CFG blocks per function.\n"
2001 << " " << MaxCFGBlocksPerFunction
2002 << " max CFG blocks per function.\n";
2003
2004 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2005 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2006 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2007 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2008 llvm::errs() << NumUninitAnalysisFunctions
2009 << " functions analyzed for uninitialiazed variables\n"
2010 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2011 << " " << AvgUninitVariablesPerFunction
2012 << " average variables per function.\n"
2013 << " " << MaxUninitAnalysisVariablesPerFunction
2014 << " max variables per function.\n"
2015 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2016 << " " << AvgUninitBlockVisitsPerFunction
2017 << " average block visits per function.\n"
2018 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2019 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002020}