blob: 8ee241084547381244e4047a4fdf753b65031fb6 [file] [log] [blame]
Ted Kremenekdbdbaaf2010-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 Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall384aff82010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Roseb5cd1222012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smithe0d3b4c2012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth55fc8732012-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 Hutchinsdf7bef02013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth55fc8732012-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 Kremenekdbdbaaf2010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth55fc8732012-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 Kornienko66da0ab2012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella3285c782013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko19523542012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth55fc8732012-12-04 09:13:33 +000052#include <deque>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenekdbdbaaf2010-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
Stephen Hines651f13c2014-04-23 16:59:28 -070068 void HandleUnreachable(reachable_code::UnreachableKind UK,
69 SourceLocation L,
70 SourceRange SilenceableCondVal,
71 SourceRange R1,
72 SourceRange R2) override {
73 unsigned diag = diag::warn_unreachable;
74 switch (UK) {
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
77 break;
78 case reachable_code::UK_Return:
79 diag = diag::warn_unreachable_return;
80 break;
81 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
83 break;
84 case reachable_code::UK_Other:
85 break;
86 }
87
88 S.Diag(L, diag) << R1 << R2;
89
90 SourceLocation Open = SilenceableCondVal.getBegin();
91 if (Open.isValid()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070092 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
Stephen Hines651f13c2014-04-23 16:59:28 -070094 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
98 }
99 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000100 }
101 };
102}
103
104/// CheckUnreachable - Check for unreachable code.
Ted Kremenek1d26f482011-10-24 01:32:45 +0000105static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700106 // 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 Kremenekdbdbaaf2010-03-20 21:06:02 +0000116 UnreachableCodeHandler UC(S);
Stephen Hines651f13c2014-04-23 16:59:28 -0700117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
118}
119
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700120namespace {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700121/// \brief Warn on logical operator errors in CFGBuilder
122class LogicalErrorHandler : public CFGCallback {
123 Sema &S;
124
125public:
126 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
127
128 static bool HasMacroID(const Expr *E) {
129 if (E->getExprLoc().isMacroID())
130 return true;
131
132 // Recurse to children.
133 for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
134 if (*SubStmts)
135 if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
136 if (HasMacroID(SubExpr))
137 return true;
138
139 return false;
140 }
141
142 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {
143 if (HasMacroID(B))
144 return;
145
146 SourceRange DiagRange = B->getSourceRange();
147 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
148 << DiagRange << isAlwaysTrue;
149 }
150
151 void compareBitwiseEquality(const BinaryOperator *B, bool isAlwaysTrue) {
152 if (HasMacroID(B))
153 return;
154
155 SourceRange DiagRange = B->getSourceRange();
156 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
157 << DiagRange << isAlwaysTrue;
158 }
159};
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700160} // namespace
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700161
Stephen Hines651f13c2014-04-23 16:59:28 -0700162//===----------------------------------------------------------------------===//
163// Check for infinite self-recursion in functions
164//===----------------------------------------------------------------------===//
165
166// All blocks are in one of three states. States are ordered so that blocks
167// can only move to higher states.
168enum RecursiveState {
169 FoundNoPath,
170 FoundPath,
171 FoundPathWithNoRecursiveCall
172};
173
174static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
175 CFGBlock &Block, unsigned ExitID,
176 llvm::SmallVectorImpl<RecursiveState> &States,
177 RecursiveState State) {
178 unsigned ID = Block.getBlockID();
179
180 // A block's state can only move to a higher state.
181 if (States[ID] >= State)
182 return;
183
184 States[ID] = State;
185
186 // Found a path to the exit node without a recursive call.
187 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
188 return;
189
190 if (State == FoundPathWithNoRecursiveCall) {
191 // If the current state is FoundPathWithNoRecursiveCall, the successors
192 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
193 // which, process all the Stmt's in this block to find any recursive calls.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700194 for (const auto &B : Block) {
195 if (B.getKind() != CFGElement::Statement)
Stephen Hines651f13c2014-04-23 16:59:28 -0700196 continue;
197
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700198 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
Stephen Hines651f13c2014-04-23 16:59:28 -0700199 if (CE && CE->getCalleeDecl() &&
200 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
201
202 // Skip function calls which are qualified with a templated class.
203 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
204 CE->getCallee()->IgnoreParenImpCasts())) {
205 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
206 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
207 isa<TemplateSpecializationType>(NNS->getAsType())) {
208 continue;
209 }
210 }
211 }
212
213 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
214 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
215 !MCE->getMethodDecl()->isVirtual()) {
216 State = FoundPath;
217 break;
218 }
219 } else {
220 State = FoundPath;
221 break;
222 }
223 }
224 }
225 }
226
227 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
228 I != E; ++I)
229 if (*I)
230 checkForFunctionCall(S, FD, **I, ExitID, States, State);
231}
232
233static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
234 const Stmt *Body,
235 AnalysisDeclContext &AC) {
236 FD = FD->getCanonicalDecl();
237
238 // Only run on non-templated functions and non-templated members of
239 // templated classes.
240 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
241 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
242 return;
243
244 CFG *cfg = AC.getCFG();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700245 if (!cfg) return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700246
247 // If the exit block is unreachable, skip processing the function.
248 if (cfg->getExit().pred_empty())
249 return;
250
251 // Mark all nodes as FoundNoPath, then begin processing the entry block.
252 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
253 FoundNoPath);
254 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
255 states, FoundPathWithNoRecursiveCall);
256
257 // Check that the exit block is reachable. This prevents triggering the
258 // warning on functions that do not terminate.
259 if (states[cfg->getExit().getBlockID()] == FoundPath)
260 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000261}
262
263//===----------------------------------------------------------------------===//
264// Check for missing return value.
265//===----------------------------------------------------------------------===//
266
John McCall16565aa2010-05-16 09:34:11 +0000267enum ControlFlowKind {
268 UnknownFallThrough,
269 NeverFallThrough,
270 MaybeFallThrough,
271 AlwaysFallThrough,
272 NeverFallThroughOrReturn
273};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000274
275/// CheckFallThrough - Check that we don't fall off the end of a
276/// Statement that should return a value.
277///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000278/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
279/// MaybeFallThrough iff we might or might not fall off the end,
280/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
281/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000282/// statement but we may return. We assume that functions not marked noreturn
283/// will return.
Ted Kremenek1d26f482011-10-24 01:32:45 +0000284static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000285 CFG *cfg = AC.getCFG();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700286 if (!cfg) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000287
288 // The CFG leaves in dead things, and we don't want the dead code paths to
289 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000290 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000291 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000292 live);
293
294 bool AddEHEdges = AC.getAddEHEdges();
295 if (!AddEHEdges && count != cfg->getNumBlockIDs())
296 // When there are things remaining dead, and we didn't add EH edges
297 // from CallExprs to the catch clauses, we have to go back and
298 // mark them as live.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700299 for (const auto *B : *cfg) {
300 if (!live[B->getBlockID()]) {
301 if (B->pred_begin() == B->pred_end()) {
302 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000303 // When not adding EH edges from calls, catch clauses
304 // can otherwise seem dead. Avoid noting them as dead.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700305 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000306 continue;
307 }
308 }
309 }
310
311 // Now we know what is live, we check the live precessors of the exit block
312 // and look for fall through paths, being careful to ignore normal returns,
313 // and exceptional paths.
314 bool HasLiveReturn = false;
315 bool HasFakeEdge = false;
316 bool HasPlainEdge = false;
317 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000318
319 // Ignore default cases that aren't likely to be reachable because all
320 // enums in a switch(X) have explicit case statements.
321 CFGBlock::FilterOptions FO;
322 FO.IgnoreDefaultsWithCoveredEnums = 1;
323
324 for (CFGBlock::filtered_pred_iterator
325 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
326 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000327 if (!live[B.getBlockID()])
328 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000329
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000330 // Skip blocks which contain an element marked as no-return. They don't
331 // represent actually viable edges into the exit block, so mark them as
332 // abnormal.
333 if (B.hasNoReturnElement()) {
334 HasAbnormalEdge = true;
335 continue;
336 }
337
Ted Kremenek5811f592011-01-26 04:49:52 +0000338 // Destructors can appear after the 'return' in the CFG. This is
339 // normal. We need to look pass the destructors for the return
340 // statement (if it exists).
341 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000342
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000343 for ( ; ri != re ; ++ri)
David Blaikiefdf6a272013-02-21 20:58:29 +0000344 if (ri->getAs<CFGStmt>())
Ted Kremenek5811f592011-01-26 04:49:52 +0000345 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000346
Ted Kremenek5811f592011-01-26 04:49:52 +0000347 // No more CFGElements in the block?
348 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000349 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
350 HasAbnormalEdge = true;
351 continue;
352 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000353 // A labeled empty statement, or the entry block...
354 HasPlainEdge = true;
355 continue;
356 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000357
David Blaikiefdf6a272013-02-21 20:58:29 +0000358 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000359 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000360 if (isa<ReturnStmt>(S)) {
361 HasLiveReturn = true;
362 continue;
363 }
364 if (isa<ObjCAtThrowStmt>(S)) {
365 HasFakeEdge = true;
366 continue;
367 }
368 if (isa<CXXThrowExpr>(S)) {
369 HasFakeEdge = true;
370 continue;
371 }
Chad Rosier8cd64b42012-06-11 20:47:18 +0000372 if (isa<MSAsmStmt>(S)) {
373 // TODO: Verify this is correct.
374 HasFakeEdge = true;
375 HasLiveReturn = true;
376 continue;
377 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000378 if (isa<CXXTryStmt>(S)) {
379 HasAbnormalEdge = true;
380 continue;
381 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000382 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
383 == B.succ_end()) {
384 HasAbnormalEdge = true;
385 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000386 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000387
388 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000389 }
390 if (!HasPlainEdge) {
391 if (HasLiveReturn)
392 return NeverFallThrough;
393 return NeverFallThroughOrReturn;
394 }
395 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
396 return MaybeFallThrough;
397 // This says AlwaysFallThrough for calls to functions that are not marked
398 // noreturn, that don't return. If people would like this warning to be more
399 // accurate, such functions should be marked as noreturn.
400 return AlwaysFallThrough;
401}
402
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000403namespace {
404
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000405struct CheckFallThroughDiagnostics {
406 unsigned diag_MaybeFallThrough_HasNoReturn;
407 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
408 unsigned diag_AlwaysFallThrough_HasNoReturn;
409 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
410 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000411 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000412 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000413
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000414 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000415 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000416 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000417 D.diag_MaybeFallThrough_HasNoReturn =
418 diag::warn_falloff_noreturn_function;
419 D.diag_MaybeFallThrough_ReturnsNonVoid =
420 diag::warn_maybe_falloff_nonvoid_function;
421 D.diag_AlwaysFallThrough_HasNoReturn =
422 diag::warn_falloff_noreturn_function;
423 D.diag_AlwaysFallThrough_ReturnsNonVoid =
424 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000425
426 // Don't suggest that virtual functions be marked "noreturn", since they
427 // might be overridden by non-noreturn functions.
428 bool isVirtualMethod = false;
429 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
430 isVirtualMethod = Method->isVirtual();
431
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000432 // Don't suggest that template instantiations be marked "noreturn"
433 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000434 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
435 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000436
437 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000438 D.diag_NeverFallThroughOrReturn =
439 diag::warn_suggest_noreturn_function;
440 else
441 D.diag_NeverFallThroughOrReturn = 0;
442
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000443 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000444 return D;
445 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000446
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000447 static CheckFallThroughDiagnostics MakeForBlock() {
448 CheckFallThroughDiagnostics D;
449 D.diag_MaybeFallThrough_HasNoReturn =
450 diag::err_noreturn_block_has_return_expr;
451 D.diag_MaybeFallThrough_ReturnsNonVoid =
452 diag::err_maybe_falloff_nonvoid_block;
453 D.diag_AlwaysFallThrough_HasNoReturn =
454 diag::err_noreturn_block_has_return_expr;
455 D.diag_AlwaysFallThrough_ReturnsNonVoid =
456 diag::err_falloff_nonvoid_block;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700457 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000458 D.funMode = Block;
459 return D;
460 }
461
462 static CheckFallThroughDiagnostics MakeForLambda() {
463 CheckFallThroughDiagnostics D;
464 D.diag_MaybeFallThrough_HasNoReturn =
465 diag::err_noreturn_lambda_has_return_expr;
466 D.diag_MaybeFallThrough_ReturnsNonVoid =
467 diag::warn_maybe_falloff_nonvoid_lambda;
468 D.diag_AlwaysFallThrough_HasNoReturn =
469 diag::err_noreturn_lambda_has_return_expr;
470 D.diag_AlwaysFallThrough_ReturnsNonVoid =
471 diag::warn_falloff_nonvoid_lambda;
472 D.diag_NeverFallThroughOrReturn = 0;
473 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000474 return D;
475 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000476
David Blaikied6471f72011-09-25 23:23:43 +0000477 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000478 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000479 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000480 return (ReturnsVoid ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700481 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
482 FuncLoc)) &&
483 (!HasNoReturn ||
484 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
485 FuncLoc)) &&
486 (!ReturnsVoid ||
487 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000488 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000489
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000490 // For blocks / lambdas.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700491 return ReturnsVoid && !HasNoReturn;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000492 }
493};
494
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000495}
496
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000497/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
498/// function that should return a value. Check that we don't fall off the end
499/// of a noreturn function. We assume that functions and blocks not marked
500/// noreturn will return.
501static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000502 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000503 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000504 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000505
506 bool ReturnsVoid = false;
507 bool HasNoReturn = false;
508
509 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700510 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smithcd8ab512013-01-17 01:30:42 +0000511 HasNoReturn = FD->isNoReturn();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000512 }
513 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700514 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000515 HasNoReturn = MD->hasAttr<NoReturnAttr>();
516 }
517 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000518 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000519 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000520 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700521 if (FT->getReturnType()->isVoidType())
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000522 ReturnsVoid = true;
523 if (FT->getNoReturnAttr())
524 HasNoReturn = true;
525 }
526 }
527
David Blaikied6471f72011-09-25 23:23:43 +0000528 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000529
530 // Short circuit for compilation speed.
531 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
532 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000533
Stephen Hines176edba2014-12-01 14:53:08 -0800534 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
535 // Either in a function body compound statement, or a function-try-block.
536 switch (CheckFallThrough(AC)) {
537 case UnknownFallThrough:
538 break;
John McCall16565aa2010-05-16 09:34:11 +0000539
Stephen Hines176edba2014-12-01 14:53:08 -0800540 case MaybeFallThrough:
541 if (HasNoReturn)
542 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
543 else if (!ReturnsVoid)
544 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
545 break;
546 case AlwaysFallThrough:
547 if (HasNoReturn)
548 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
549 else if (!ReturnsVoid)
550 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
551 break;
552 case NeverFallThroughOrReturn:
553 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
554 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
555 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
556 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
557 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
558 } else {
559 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000560 }
Stephen Hines176edba2014-12-01 14:53:08 -0800561 }
562 break;
563 case NeverFallThrough:
564 break;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000565 }
566}
567
568//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000569// -Wuninitialized
570//===----------------------------------------------------------------------===//
571
Ted Kremenek6f417152011-04-04 20:56:00 +0000572namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000573/// ContainsReference - A visitor class to search for references to
574/// a particular declaration (the needle) within any evaluated component of an
575/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000576class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000577 bool FoundReference;
578 const DeclRefExpr *Needle;
579
Ted Kremenek6f417152011-04-04 20:56:00 +0000580public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000581 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
582 : EvaluatedExprVisitor<ContainsReference>(Context),
583 FoundReference(false), Needle(Needle) {}
584
585 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000586 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000587 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000588 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000589
590 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000591 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000592
593 void VisitDeclRefExpr(DeclRefExpr *E) {
594 if (E == Needle)
595 FoundReference = true;
596 else
597 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000598 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000599
600 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000601};
602}
603
David Blaikie4f4f3492011-09-10 05:35:08 +0000604static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000605 QualType VariableTy = VD->getType().getCanonicalType();
606 if (VariableTy->isBlockPointerType() &&
607 !VD->hasAttr<BlocksAttr>()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700608 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
609 << VD->getDeclName()
610 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000611 return true;
612 }
Richard Smith8adf8372013-09-20 00:27:40 +0000613
David Blaikie4f4f3492011-09-10 05:35:08 +0000614 // Don't issue a fixit if there is already an initializer.
615 if (VD->getInit())
616 return false;
Richard Trieu7b0a3e32012-05-03 01:09:59 +0000617
618 // Don't suggest a fixit inside macros.
619 if (VD->getLocEnd().isMacroID())
620 return false;
621
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700622 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smith8adf8372013-09-20 00:27:40 +0000623
624 // Suggest possible initialization (if any).
625 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
626 if (Init.empty())
627 return false;
628
Richard Smith7984de32012-01-12 23:53:29 +0000629 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
630 << FixItHint::CreateInsertion(Loc, Init);
631 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000632}
633
Richard Smithbdb97ff2012-05-26 06:20:46 +0000634/// Create a fixit to remove an if-like statement, on the assumption that its
635/// condition is CondVal.
636static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
637 const Stmt *Else, bool CondVal,
638 FixItHint &Fixit1, FixItHint &Fixit2) {
639 if (CondVal) {
640 // If condition is always true, remove all but the 'then'.
641 Fixit1 = FixItHint::CreateRemoval(
642 CharSourceRange::getCharRange(If->getLocStart(),
643 Then->getLocStart()));
644 if (Else) {
645 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
646 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
647 Fixit2 = FixItHint::CreateRemoval(
648 SourceRange(ElseKwLoc, Else->getLocEnd()));
649 }
650 } else {
651 // If condition is always false, remove all but the 'else'.
652 if (Else)
653 Fixit1 = FixItHint::CreateRemoval(
654 CharSourceRange::getCharRange(If->getLocStart(),
655 Else->getLocStart()));
656 else
657 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
658 }
659}
660
661/// DiagUninitUse -- Helper function to produce a diagnostic for an
662/// uninitialized use of a variable.
663static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
664 bool IsCapturedByBlock) {
665 bool Diagnosed = false;
666
Richard Smith8a1fdfc2013-09-12 18:49:10 +0000667 switch (Use.getKind()) {
668 case UninitUse::Always:
669 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
670 << VD->getDeclName() << IsCapturedByBlock
671 << Use.getUser()->getSourceRange();
672 return;
673
674 case UninitUse::AfterDecl:
675 case UninitUse::AfterCall:
676 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
677 << VD->getDeclName() << IsCapturedByBlock
678 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
679 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
680 << VD->getSourceRange();
681 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
682 << IsCapturedByBlock << Use.getUser()->getSourceRange();
683 return;
684
685 case UninitUse::Maybe:
686 case UninitUse::Sometimes:
687 // Carry on to report sometimes-uninitialized branches, if possible,
688 // or a 'may be used uninitialized' diagnostic otherwise.
689 break;
690 }
691
Richard Smithbdb97ff2012-05-26 06:20:46 +0000692 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith2815e1a2012-05-25 02:17:09 +0000693 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
694 I != E; ++I) {
Richard Smithbdb97ff2012-05-26 06:20:46 +0000695 assert(Use.getKind() == UninitUse::Sometimes);
696
697 const Expr *User = Use.getUser();
Richard Smith2815e1a2012-05-25 02:17:09 +0000698 const Stmt *Term = I->Terminator;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000699
700 // Information used when building the diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000701 unsigned DiagKind;
David Blaikie0bea8632012-10-08 01:11:04 +0000702 StringRef Str;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000703 SourceRange Range;
704
Stefanus Du Toitfc093362013-03-01 21:41:22 +0000705 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smithbdb97ff2012-05-26 06:20:46 +0000706 // For all binary terminators, branch 0 is taken if the condition is true,
707 // and branch 1 is taken if the condition is false.
708 int RemoveDiagKind = -1;
709 const char *FixitStr =
710 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
711 : (I->Output ? "1" : "0");
712 FixItHint Fixit1, Fixit2;
713
Richard Smith8a1fdfc2013-09-12 18:49:10 +0000714 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith2815e1a2012-05-25 02:17:09 +0000715 default:
Richard Smithbdb97ff2012-05-26 06:20:46 +0000716 // Don't know how to report this. Just fall back to 'may be used
Richard Smith8a1fdfc2013-09-12 18:49:10 +0000717 // uninitialized'. FIXME: Can this happen?
Richard Smith2815e1a2012-05-25 02:17:09 +0000718 continue;
719
720 // "condition is true / condition is false".
Richard Smithbdb97ff2012-05-26 06:20:46 +0000721 case Stmt::IfStmtClass: {
722 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000723 DiagKind = 0;
724 Str = "if";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000725 Range = IS->getCond()->getSourceRange();
726 RemoveDiagKind = 0;
727 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
728 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000729 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000730 }
731 case Stmt::ConditionalOperatorClass: {
732 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000733 DiagKind = 0;
734 Str = "?:";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000735 Range = CO->getCond()->getSourceRange();
736 RemoveDiagKind = 0;
737 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
738 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000739 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000740 }
Richard Smith2815e1a2012-05-25 02:17:09 +0000741 case Stmt::BinaryOperatorClass: {
742 const BinaryOperator *BO = cast<BinaryOperator>(Term);
743 if (!BO->isLogicalOp())
744 continue;
745 DiagKind = 0;
746 Str = BO->getOpcodeStr();
747 Range = BO->getLHS()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000748 RemoveDiagKind = 0;
749 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
750 (BO->getOpcode() == BO_LOr && !I->Output))
751 // true && y -> y, false || y -> y.
752 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
753 BO->getOperatorLoc()));
754 else
755 // false && y -> false, true || y -> true.
756 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000757 break;
758 }
759
760 // "loop is entered / loop is exited".
761 case Stmt::WhileStmtClass:
762 DiagKind = 1;
763 Str = "while";
764 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000765 RemoveDiagKind = 1;
766 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000767 break;
768 case Stmt::ForStmtClass:
769 DiagKind = 1;
770 Str = "for";
771 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000772 RemoveDiagKind = 1;
773 if (I->Output)
774 Fixit1 = FixItHint::CreateRemoval(Range);
775 else
776 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000777 break;
Richard Smith8a1fdfc2013-09-12 18:49:10 +0000778 case Stmt::CXXForRangeStmtClass:
779 if (I->Output == 1) {
780 // The use occurs if a range-based for loop's body never executes.
781 // That may be impossible, and there's no syntactic fix for this,
782 // so treat it as a 'may be uninitialized' case.
783 continue;
784 }
785 DiagKind = 1;
786 Str = "for";
787 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
788 break;
Richard Smith2815e1a2012-05-25 02:17:09 +0000789
790 // "condition is true / loop is exited".
791 case Stmt::DoStmtClass:
792 DiagKind = 2;
793 Str = "do";
794 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000795 RemoveDiagKind = 1;
796 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000797 break;
798
799 // "switch case is taken".
800 case Stmt::CaseStmtClass:
801 DiagKind = 3;
802 Str = "case";
803 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
804 break;
805 case Stmt::DefaultStmtClass:
806 DiagKind = 3;
807 Str = "default";
808 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
809 break;
810 }
811
Richard Smithbdb97ff2012-05-26 06:20:46 +0000812 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
813 << VD->getDeclName() << IsCapturedByBlock << DiagKind
814 << Str << I->Output << Range;
815 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
816 << IsCapturedByBlock << User->getSourceRange();
817 if (RemoveDiagKind != -1)
818 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
819 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
820
821 Diagnosed = true;
Richard Smith2815e1a2012-05-25 02:17:09 +0000822 }
Richard Smithbdb97ff2012-05-26 06:20:46 +0000823
824 if (!Diagnosed)
Richard Smith8a1fdfc2013-09-12 18:49:10 +0000825 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smithbdb97ff2012-05-26 06:20:46 +0000826 << VD->getDeclName() << IsCapturedByBlock
827 << Use.getUser()->getSourceRange();
Richard Smith2815e1a2012-05-25 02:17:09 +0000828}
829
Chandler Carruth262d50e2011-04-05 18:27:05 +0000830/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
831/// uninitialized variable. This manages the different forms of diagnostic
832/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith2815e1a2012-05-25 02:17:09 +0000833/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruth262d50e2011-04-05 18:27:05 +0000834/// false.
835static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith2815e1a2012-05-25 02:17:09 +0000836 const UninitUse &Use,
Ted Kremenek9e761722011-10-13 18:50:06 +0000837 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000838
Richard Smith2815e1a2012-05-25 02:17:09 +0000839 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieuf6278e52012-05-09 21:08:22 +0000840 // Inspect the initializer of the variable declaration which is
841 // being referenced prior to its initialization. We emit
842 // specialized diagnostics for self-initialization, and we
843 // specifically avoid warning about self references which take the
844 // form of:
845 //
846 // int x = x;
847 //
848 // This is used to indicate to GCC that 'x' is intentionally left
849 // uninitialized. Proven code paths which access 'x' in
850 // an uninitialized state after this will still warn.
851 if (const Expr *Initializer = VD->getInit()) {
852 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
853 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000854
Richard Trieuf6278e52012-05-09 21:08:22 +0000855 ContainsReference CR(S.Context, DRE);
856 CR.Visit(const_cast<Expr*>(Initializer));
857 if (CR.doesContainReference()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000858 S.Diag(DRE->getLocStart(),
859 diag::warn_uninit_self_reference_in_init)
Richard Trieuf6278e52012-05-09 21:08:22 +0000860 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
861 return true;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000862 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000863 }
Richard Trieuf6278e52012-05-09 21:08:22 +0000864
Richard Smithbdb97ff2012-05-26 06:20:46 +0000865 DiagUninitUse(S, VD, Use, false);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000866 } else {
Richard Smith2815e1a2012-05-25 02:17:09 +0000867 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smithbdb97ff2012-05-26 06:20:46 +0000868 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
869 S.Diag(BE->getLocStart(),
870 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000871 << VD->getDeclName();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000872 else
873 DiagUninitUse(S, VD, Use, true);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000874 }
875
876 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000877 // the initializer of that declaration & we didn't already suggest
878 // an initialization fixit.
Richard Trieuf6278e52012-05-09 21:08:22 +0000879 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000880 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
881 << VD->getDeclName();
882
Chandler Carruth262d50e2011-04-05 18:27:05 +0000883 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000884}
885
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000886namespace {
887 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
888 public:
889 FallthroughMapper(Sema &S)
890 : FoundSwitchStatements(false),
891 S(S) {
892 }
893
894 bool foundSwitchStatements() const { return FoundSwitchStatements; }
895
896 void markFallthroughVisited(const AttributedStmt *Stmt) {
897 bool Found = FallthroughStmts.erase(Stmt);
898 assert(Found);
Kaelyn Uhrain3bb29942012-05-03 19:46:38 +0000899 (void)Found;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000900 }
901
902 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
903
904 const AttrStmts &getFallthroughStmts() const {
905 return FallthroughStmts;
906 }
907
Alexander Kornienko4874a812013-01-30 03:49:44 +0000908 void fillReachableBlocks(CFG *Cfg) {
909 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
910 std::deque<const CFGBlock *> BlockQueue;
911
912 ReachableBlocks.insert(&Cfg->getEntry());
913 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000914 // Mark all case blocks reachable to avoid problems with switching on
915 // constants, covered enums, etc.
916 // These blocks can contain fall-through annotations, and we don't want to
917 // issue a warn_fallthrough_attr_unreachable for them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700918 for (const auto *B : *Cfg) {
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000919 const Stmt *L = B->getLabel();
Stephen Hines176edba2014-12-01 14:53:08 -0800920 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000921 BlockQueue.push_back(B);
922 }
923
Alexander Kornienko4874a812013-01-30 03:49:44 +0000924 while (!BlockQueue.empty()) {
925 const CFGBlock *P = BlockQueue.front();
926 BlockQueue.pop_front();
927 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
928 E = P->succ_end();
929 I != E; ++I) {
Stephen Hines176edba2014-12-01 14:53:08 -0800930 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienko4874a812013-01-30 03:49:44 +0000931 BlockQueue.push_back(*I);
932 }
933 }
934 }
935
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000936 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienko4874a812013-01-30 03:49:44 +0000937 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
938
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000939 int UnannotatedCnt = 0;
940 AnnotatedCnt = 0;
941
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700942 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000943 while (!BlockQueue.empty()) {
944 const CFGBlock *P = BlockQueue.front();
945 BlockQueue.pop_front();
Stephen Hines651f13c2014-04-23 16:59:28 -0700946 if (!P) continue;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000947
948 const Stmt *Term = P->getTerminator();
949 if (Term && isa<SwitchStmt>(Term))
950 continue; // Switch statement, good.
951
952 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
953 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
954 continue; // Previous case label has no statements, good.
955
Alexander Kornienkoc6dcea92013-01-25 20:44:56 +0000956 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
957 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
958 continue; // Case label is preceded with a normal label, good.
959
Alexander Kornienko4874a812013-01-30 03:49:44 +0000960 if (!ReachableBlocks.count(P)) {
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000961 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
962 ElemEnd = P->rend();
963 ElemIt != ElemEnd; ++ElemIt) {
David Blaikieb0780542013-02-23 00:29:34 +0000964 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
965 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000966 S.Diag(AS->getLocStart(),
967 diag::warn_fallthrough_attr_unreachable);
968 markFallthroughVisited(AS);
969 ++AnnotatedCnt;
Alexander Kornienko878d0ad2013-02-07 02:17:19 +0000970 break;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000971 }
972 // Don't care about other unreachable statements.
973 }
974 }
975 // If there are no unreachable statements, this may be a special
976 // case in CFG:
977 // case X: {
978 // A a; // A has a destructor.
979 // break;
980 // }
981 // // <<<< This place is represented by a 'hanging' CFG block.
982 // case Y:
983 continue;
984 }
985
986 const Stmt *LastStmt = getLastStmt(*P);
987 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
988 markFallthroughVisited(AS);
989 ++AnnotatedCnt;
990 continue; // Fallthrough annotation, good.
991 }
992
993 if (!LastStmt) { // This block contains no executable statements.
994 // Traverse its predecessors.
995 std::copy(P->pred_begin(), P->pred_end(),
996 std::back_inserter(BlockQueue));
997 continue;
998 }
999
1000 ++UnannotatedCnt;
1001 }
1002 return !!UnannotatedCnt;
1003 }
1004
1005 // RecursiveASTVisitor setup.
1006 bool shouldWalkTypesOfTypeLocs() const { return false; }
1007
1008 bool VisitAttributedStmt(AttributedStmt *S) {
1009 if (asFallThroughAttr(S))
1010 FallthroughStmts.insert(S);
1011 return true;
1012 }
1013
1014 bool VisitSwitchStmt(SwitchStmt *S) {
1015 FoundSwitchStatements = true;
1016 return true;
1017 }
1018
Alexander Kornienkob0707c92013-04-02 15:20:32 +00001019 // We don't want to traverse local type declarations. We analyze their
1020 // methods separately.
1021 bool TraverseDecl(Decl *D) { return true; }
1022
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001023 // We analyze lambda bodies separately. Skip them here.
1024 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1025
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001026 private:
1027
1028 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1029 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1030 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1031 return AS;
1032 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001033 return nullptr;
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001034 }
1035
1036 static const Stmt *getLastStmt(const CFGBlock &B) {
1037 if (const Stmt *Term = B.getTerminator())
1038 return Term;
1039 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1040 ElemEnd = B.rend();
1041 ElemIt != ElemEnd; ++ElemIt) {
David Blaikieb0780542013-02-23 00:29:34 +00001042 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1043 return CS->getStmt();
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001044 }
1045 // Workaround to detect a statement thrown out by CFGBuilder:
1046 // case X: {} case Y:
1047 // case X: ; case Y:
1048 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1049 if (!isa<SwitchCase>(SW->getSubStmt()))
1050 return SW->getSubStmt();
1051
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001052 return nullptr;
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001053 }
1054
1055 bool FoundSwitchStatements;
1056 AttrStmts FallthroughStmts;
1057 Sema &S;
Alexander Kornienko4874a812013-01-30 03:49:44 +00001058 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001059 };
1060}
1061
Alexander Kornienko19736342012-06-02 01:01:07 +00001062static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Sean Huntc2f51cf2012-06-15 21:22:05 +00001063 bool PerFunction) {
Ted Kremenek30783532012-11-12 21:20:48 +00001064 // Only perform this analysis when using C++11. There is no good workflow
1065 // for this warning when not using C++11. There is no good way to silence
1066 // the warning (no attribute is available) unless we are using C++11's support
1067 // for generalized attributes. Once could use pragmas to silence the warning,
1068 // but as a general solution that is gross and not in the spirit of this
1069 // warning.
1070 //
1071 // NOTE: This an intermediate solution. There are on-going discussions on
1072 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith80ad52f2013-01-02 11:42:31 +00001073 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenek30783532012-11-12 21:20:48 +00001074 return;
1075
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001076 FallthroughMapper FM(S);
1077 FM.TraverseStmt(AC.getBody());
1078
1079 if (!FM.foundSwitchStatements())
1080 return;
1081
Sean Huntc2f51cf2012-06-15 21:22:05 +00001082 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko19736342012-06-02 01:01:07 +00001083 return;
1084
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001085 CFG *Cfg = AC.getCFG();
1086
1087 if (!Cfg)
1088 return;
1089
Alexander Kornienko4874a812013-01-30 03:49:44 +00001090 FM.fillReachableBlocks(Cfg);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001091
1092 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienkoe992ed12013-01-25 15:49:34 +00001093 const CFGBlock *B = *I;
1094 const Stmt *Label = B->getLabel();
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001095
1096 if (!Label || !isa<SwitchCase>(Label))
1097 continue;
1098
Alexander Kornienko4874a812013-01-30 03:49:44 +00001099 int AnnotatedCnt;
1100
Alexander Kornienkoe992ed12013-01-25 15:49:34 +00001101 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001102 continue;
1103
Alexander Kornienko19736342012-06-02 01:01:07 +00001104 S.Diag(Label->getLocStart(),
Sean Huntc2f51cf2012-06-15 21:22:05 +00001105 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1106 : diag::warn_unannotated_fallthrough);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001107
1108 if (!AnnotatedCnt) {
1109 SourceLocation L = Label->getLocStart();
1110 if (L.isMacroID())
1111 continue;
Richard Smith80ad52f2013-01-02 11:42:31 +00001112 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienkoe992ed12013-01-25 15:49:34 +00001113 const Stmt *Term = B->getTerminator();
1114 // Skip empty cases.
1115 while (B->empty() && !Term && B->succ_size() == 1) {
1116 B = *B->succ_begin();
1117 Term = B->getTerminator();
1118 }
1119 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienko66da0ab2012-09-28 22:24:03 +00001120 Preprocessor &PP = S.getPreprocessor();
1121 TokenValue Tokens[] = {
1122 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1123 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1124 tok::r_square, tok::r_square
1125 };
Dmitri Gribenko19523542012-09-29 11:40:46 +00001126 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1127 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1128 if (!MacroName.empty())
1129 AnnotationSpelling = MacroName;
1130 SmallString<64> TextToInsert(AnnotationSpelling);
1131 TextToInsert += "; ";
Alexander Kornienkoa189d892012-05-26 00:49:15 +00001132 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienko66da0ab2012-09-28 22:24:03 +00001133 AnnotationSpelling <<
Dmitri Gribenko19523542012-09-29 11:40:46 +00001134 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienkoa189d892012-05-26 00:49:15 +00001135 }
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001136 }
1137 S.Diag(L, diag::note_insert_break_fixit) <<
1138 FixItHint::CreateInsertion(L, "break; ");
1139 }
1140 }
1141
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001142 for (const auto *F : FM.getFallthroughStmts())
1143 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001144}
1145
Jordan Rosec0e44452012-10-29 17:46:47 +00001146static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1147 const Stmt *S) {
Jordan Roseb5cd1222012-10-11 16:10:19 +00001148 assert(S);
1149
1150 do {
1151 switch (S->getStmtClass()) {
Jordan Roseb5cd1222012-10-11 16:10:19 +00001152 case Stmt::ForStmtClass:
1153 case Stmt::WhileStmtClass:
1154 case Stmt::CXXForRangeStmtClass:
1155 case Stmt::ObjCForCollectionStmtClass:
1156 return true;
Jordan Rosec0e44452012-10-29 17:46:47 +00001157 case Stmt::DoStmtClass: {
1158 const Expr *Cond = cast<DoStmt>(S)->getCond();
1159 llvm::APSInt Val;
1160 if (!Cond->EvaluateAsInt(Val, Ctx))
1161 return true;
1162 return Val.getBoolValue();
1163 }
Jordan Roseb5cd1222012-10-11 16:10:19 +00001164 default:
1165 break;
1166 }
1167 } while ((S = PM.getParent(S)));
1168
1169 return false;
1170}
1171
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001172
1173static void diagnoseRepeatedUseOfWeak(Sema &S,
1174 const sema::FunctionScopeInfo *CurFn,
Jordan Roseb5cd1222012-10-11 16:10:19 +00001175 const Decl *D,
1176 const ParentMap &PM) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001177 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1178 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1179 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Stephen Hines651f13c2014-04-23 16:59:28 -07001180 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1181 StmtUsesPair;
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001182
Jordan Rosec0e44452012-10-29 17:46:47 +00001183 ASTContext &Ctx = S.getASTContext();
1184
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001185 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1186
1187 // Extract all weak objects that are referenced more than once.
1188 SmallVector<StmtUsesPair, 8> UsesByStmt;
1189 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1190 I != E; ++I) {
1191 const WeakUseVector &Uses = I->second;
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001192
1193 // Find the first read of the weak object.
1194 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1195 for ( ; UI != UE; ++UI) {
1196 if (UI->isUnsafe())
1197 break;
1198 }
1199
1200 // If there were only writes to this object, don't warn.
1201 if (UI == UE)
1202 continue;
1203
Jordan Roseb5cd1222012-10-11 16:10:19 +00001204 // If there was only one read, followed by any number of writes, and the
Jordan Rosec0e44452012-10-29 17:46:47 +00001205 // read is not within a loop, don't warn. Additionally, don't warn in a
1206 // loop if the base object is a local variable -- local variables are often
1207 // changed in loops.
Jordan Roseb5cd1222012-10-11 16:10:19 +00001208 if (UI == Uses.begin()) {
1209 WeakUseVector::const_iterator UI2 = UI;
1210 for (++UI2; UI2 != UE; ++UI2)
1211 if (UI2->isUnsafe())
1212 break;
1213
Jordan Rosec0e44452012-10-29 17:46:47 +00001214 if (UI2 == UE) {
1215 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Roseb5cd1222012-10-11 16:10:19 +00001216 continue;
Jordan Rosec0e44452012-10-29 17:46:47 +00001217
1218 const WeakObjectProfileTy &Profile = I->first;
1219 if (!Profile.isExactProfile())
1220 continue;
1221
1222 const NamedDecl *Base = Profile.getBase();
1223 if (!Base)
1224 Base = Profile.getProperty();
1225 assert(Base && "A profile always has a base or property.");
1226
1227 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1228 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1229 continue;
1230 }
Jordan Roseb5cd1222012-10-11 16:10:19 +00001231 }
1232
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001233 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1234 }
1235
1236 if (UsesByStmt.empty())
1237 return;
1238
1239 // Sort by first use so that we emit the warnings in a deterministic order.
Stephen Hines651f13c2014-04-23 16:59:28 -07001240 SourceManager &SM = S.getSourceManager();
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001241 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001242 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1243 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1244 RHS.first->getLocStart());
1245 });
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001246
1247 // Classify the current code body for better warning text.
1248 // This enum should stay in sync with the cases in
1249 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1250 // FIXME: Should we use a common classification enum and the same set of
1251 // possibilities all throughout Sema?
1252 enum {
1253 Function,
1254 Method,
1255 Block,
1256 Lambda
1257 } FunctionKind;
1258
1259 if (isa<sema::BlockScopeInfo>(CurFn))
1260 FunctionKind = Block;
1261 else if (isa<sema::LambdaScopeInfo>(CurFn))
1262 FunctionKind = Lambda;
1263 else if (isa<ObjCMethodDecl>(D))
1264 FunctionKind = Method;
1265 else
1266 FunctionKind = Function;
1267
1268 // Iterate through the sorted problems and emit warnings for each.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001269 for (const auto &P : UsesByStmt) {
1270 const Stmt *FirstRead = P.first;
1271 const WeakObjectProfileTy &Key = P.second->first;
1272 const WeakUseVector &Uses = P.second->second;
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001273
Jordan Rose7a270482012-09-28 22:21:35 +00001274 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1275 // may not contain enough information to determine that these are different
1276 // properties. We can only be 100% sure of a repeated use in certain cases,
1277 // and we adjust the diagnostic kind accordingly so that the less certain
1278 // case can be turned off if it is too noisy.
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001279 unsigned DiagKind;
1280 if (Key.isExactProfile())
1281 DiagKind = diag::warn_arc_repeated_use_of_weak;
1282 else
1283 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1284
Jordan Rose7a270482012-09-28 22:21:35 +00001285 // Classify the weak object being accessed for better warning text.
1286 // This enum should stay in sync with the cases in
1287 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1288 enum {
1289 Variable,
1290 Property,
1291 ImplicitProperty,
1292 Ivar
1293 } ObjectKind;
1294
1295 const NamedDecl *D = Key.getProperty();
1296 if (isa<VarDecl>(D))
1297 ObjectKind = Variable;
1298 else if (isa<ObjCPropertyDecl>(D))
1299 ObjectKind = Property;
1300 else if (isa<ObjCMethodDecl>(D))
1301 ObjectKind = ImplicitProperty;
1302 else if (isa<ObjCIvarDecl>(D))
1303 ObjectKind = Ivar;
1304 else
1305 llvm_unreachable("Unexpected weak object kind!");
1306
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001307 // Show the first time the object was read.
1308 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenberger73484542013-06-26 21:31:47 +00001309 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001310 << FirstRead->getSourceRange();
1311
1312 // Print all the other accesses as notes.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001313 for (const auto &Use : Uses) {
1314 if (Use.getUseExpr() == FirstRead)
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001315 continue;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001316 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001317 diag::note_arc_weak_also_accessed_here)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001318 << Use.getUseExpr()->getSourceRange();
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001319 }
1320 }
1321}
1322
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001323namespace {
Ted Kremenek610068c2011-01-15 02:58:47 +00001324class UninitValsDiagReporter : public UninitVariablesHandler {
1325 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001326 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramere1039792013-06-29 17:52:13 +00001327 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella3285c782013-02-15 20:09:55 +00001328 // Prefer using MapVector to DenseMap, so that iteration order will be
1329 // the same as insertion order. This is needed to obtain a deterministic
1330 // order of diagnostics when calling flushDiagnostics().
1331 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001332 UsesMap *uses;
1333
Ted Kremenek610068c2011-01-15 02:58:47 +00001334public:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001335 UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001336 ~UninitValsDiagReporter() {
1337 flushDiagnostics();
1338 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001339
Enea Zaffanella3285c782013-02-15 20:09:55 +00001340 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001341 if (!uses)
1342 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +00001343
Enea Zaffanella3285c782013-02-15 20:09:55 +00001344 MappedType &V = (*uses)[vd];
Benjamin Kramere1039792013-06-29 17:52:13 +00001345 if (!V.getPointer())
1346 V.setPointer(new UsesVec());
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001347
Ted Kremenek9e761722011-10-13 18:50:06 +00001348 return V;
1349 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001350
1351 void handleUseOfUninitVariable(const VarDecl *vd,
1352 const UninitUse &use) override {
Benjamin Kramere1039792013-06-29 17:52:13 +00001353 getUses(vd).getPointer()->push_back(use);
Ted Kremenek9e761722011-10-13 18:50:06 +00001354 }
1355
Stephen Hines651f13c2014-04-23 16:59:28 -07001356 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramere1039792013-06-29 17:52:13 +00001357 getUses(vd).setInt(true);
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001358 }
1359
1360 void flushDiagnostics() {
1361 if (!uses)
1362 return;
Enea Zaffanella3285c782013-02-15 20:09:55 +00001363
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001364 for (const auto &P : *uses) {
1365 const VarDecl *vd = P.first;
1366 const MappedType &V = P.second;
Ted Kremenek609e3172011-02-02 23:35:53 +00001367
Benjamin Kramere1039792013-06-29 17:52:13 +00001368 UsesVec *vec = V.getPointer();
1369 bool hasSelfInit = V.getInt();
Ted Kremenek9e761722011-10-13 18:50:06 +00001370
1371 // Specially handle the case where we have uses of an uninitialized
1372 // variable, but the root cause is an idiomatic self-init. We want
1373 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001374 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith2815e1a2012-05-25 02:17:09 +00001375 DiagnoseUninitializedUse(S, vd,
1376 UninitUse(vd->getInit()->IgnoreParenCasts(),
1377 /* isAlwaysUninit */ true),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001378 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +00001379 else {
1380 // Sort the uses by their SourceLocations. While not strictly
1381 // guaranteed to produce them in line/column order, this will provide
1382 // a stable ordering.
Stephen Hines651f13c2014-04-23 16:59:28 -07001383 std::sort(vec->begin(), vec->end(),
1384 [](const UninitUse &a, const UninitUse &b) {
1385 // Prefer a more confident report over a less confident one.
1386 if (a.getKind() != b.getKind())
1387 return a.getKind() > b.getKind();
1388 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1389 });
1390
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001391 for (const auto &U : *vec) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001392 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001393 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith2815e1a2012-05-25 02:17:09 +00001394
1395 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek9e761722011-10-13 18:50:06 +00001396 // Skip further diagnostics for this variable. We try to warn only
1397 // on the first point at which a variable is used uninitialized.
1398 break;
1399 }
Chandler Carruth64fb9592011-04-05 18:18:08 +00001400 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001401
1402 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001403 delete vec;
1404 }
1405 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +00001406 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001407
1408private:
1409 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001410 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1411 return U.getKind() == UninitUse::Always ||
1412 U.getKind() == UninitUse::AfterCall ||
1413 U.getKind() == UninitUse::AfterDecl;
1414 });
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001415 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001416};
1417}
1418
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001419namespace clang {
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001420namespace {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001421typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith2e515622012-02-03 04:45:26 +00001422typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramerecafd302012-03-26 14:05:40 +00001423typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001424
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001425struct SortDiagBySourceLocation {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001426 SourceManager &SM;
1427 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001428
1429 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1430 // Although this call will be slow, this is only called when outputting
1431 // multiple warnings.
Benjamin Kramerecafd302012-03-26 14:05:40 +00001432 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001433 }
1434};
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001435}}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001436
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001437//===----------------------------------------------------------------------===//
1438// -Wthread-safety
1439//===----------------------------------------------------------------------===//
1440namespace clang {
Stephen Hines176edba2014-12-01 14:53:08 -08001441namespace threadSafety {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001442namespace {
Stephen Hines176edba2014-12-01 14:53:08 -08001443class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001444 Sema &S;
1445 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +00001446 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001447
Stephen Hines176edba2014-12-01 14:53:08 -08001448 const FunctionDecl *CurrentFunction;
1449 bool Verbose;
1450
1451 OptionalNotes getNotes() const {
1452 if (Verbose && CurrentFunction) {
1453 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1454 S.PDiag(diag::note_thread_warning_in_fun)
1455 << CurrentFunction->getNameAsString());
1456 return OptionalNotes(1, FNote);
1457 }
1458 return OptionalNotes();
1459 }
1460
1461 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1462 OptionalNotes ONS(1, Note);
1463 if (Verbose && CurrentFunction) {
1464 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1465 S.PDiag(diag::note_thread_warning_in_fun)
1466 << CurrentFunction->getNameAsString());
1467 ONS.push_back(FNote);
1468 }
1469 return ONS;
1470 }
1471
1472 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1473 const PartialDiagnosticAt &Note2) const {
1474 OptionalNotes ONS;
1475 ONS.push_back(Note1);
1476 ONS.push_back(Note2);
1477 if (Verbose && CurrentFunction) {
1478 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1479 S.PDiag(diag::note_thread_warning_in_fun)
1480 << CurrentFunction->getNameAsString());
1481 ONS.push_back(FNote);
1482 }
1483 return ONS;
1484 }
1485
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001486 // Helper functions
Stephen Hines651f13c2014-04-23 16:59:28 -07001487 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1488 SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001489 // Gracefully handle rare cases when the analysis can't get a more
1490 // precise source location.
1491 if (!Loc.isValid())
1492 Loc = FunLocation;
Stephen Hines651f13c2014-04-23 16:59:28 -07001493 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Stephen Hines176edba2014-12-01 14:53:08 -08001494 Warnings.push_back(DelayedDiag(Warning, getNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001495 }
1496
1497 public:
Richard Smith2e515622012-02-03 04:45:26 +00001498 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
Stephen Hines176edba2014-12-01 14:53:08 -08001499 : S(S), FunLocation(FL), FunEndLocation(FEL),
1500 CurrentFunction(nullptr), Verbose(false) {}
1501
1502 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001503
1504 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1505 /// We need to output diagnostics produced while iterating through
1506 /// the lockset in deterministic order, so this function orders diagnostics
1507 /// and outputs them.
1508 void emitDiagnostics() {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001509 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001510 for (const auto &Diag : Warnings) {
1511 S.Diag(Diag.first.first, Diag.first.second);
1512 for (const auto &Note : Diag.second)
1513 S.Diag(Note.first, Note.second);
Richard Smith2e515622012-02-03 04:45:26 +00001514 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001515 }
1516
Stephen Hines651f13c2014-04-23 16:59:28 -07001517 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1518 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1519 << Loc);
Stephen Hines176edba2014-12-01 14:53:08 -08001520 Warnings.push_back(DelayedDiag(Warning, getNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001521 }
Stephen Hines176edba2014-12-01 14:53:08 -08001522
Stephen Hines651f13c2014-04-23 16:59:28 -07001523 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1524 SourceLocation Loc) override {
1525 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1526 }
Stephen Hines176edba2014-12-01 14:53:08 -08001527
Stephen Hines651f13c2014-04-23 16:59:28 -07001528 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1529 LockKind Expected, LockKind Received,
1530 SourceLocation Loc) override {
1531 if (Loc.isInvalid())
1532 Loc = FunLocation;
1533 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1534 << Kind << LockName << Received
1535 << Expected);
Stephen Hines176edba2014-12-01 14:53:08 -08001536 Warnings.push_back(DelayedDiag(Warning, getNotes()));
Stephen Hines651f13c2014-04-23 16:59:28 -07001537 }
Stephen Hines176edba2014-12-01 14:53:08 -08001538
Stephen Hines651f13c2014-04-23 16:59:28 -07001539 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1540 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001541 }
1542
Stephen Hines651f13c2014-04-23 16:59:28 -07001543 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1544 SourceLocation LocLocked,
Richard Smith2e515622012-02-03 04:45:26 +00001545 SourceLocation LocEndOfScope,
Stephen Hines651f13c2014-04-23 16:59:28 -07001546 LockErrorKind LEK) override {
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001547 unsigned DiagID = 0;
1548 switch (LEK) {
1549 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +00001550 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001551 break;
1552 case LEK_LockedSomeLoopIterations:
1553 DiagID = diag::warn_expecting_lock_held_on_loop;
1554 break;
1555 case LEK_LockedAtEndOfFunction:
1556 DiagID = diag::warn_no_unlock;
1557 break;
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001558 case LEK_NotLockedAtEndOfFunction:
1559 DiagID = diag::warn_expecting_locked;
1560 break;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001561 }
Richard Smith2e515622012-02-03 04:45:26 +00001562 if (LocEndOfScope.isInvalid())
1563 LocEndOfScope = FunEndLocation;
1564
Stephen Hines651f13c2014-04-23 16:59:28 -07001565 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1566 << LockName);
DeLesley Hutchins56968842013-04-08 20:11:11 +00001567 if (LocLocked.isValid()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001568 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1569 << Kind);
Stephen Hines176edba2014-12-01 14:53:08 -08001570 Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
DeLesley Hutchins56968842013-04-08 20:11:11 +00001571 return;
1572 }
Stephen Hines176edba2014-12-01 14:53:08 -08001573 Warnings.push_back(DelayedDiag(Warning, getNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001574 }
1575
Stephen Hines651f13c2014-04-23 16:59:28 -07001576 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1577 SourceLocation Loc1,
1578 SourceLocation Loc2) override {
1579 PartialDiagnosticAt Warning(Loc1,
1580 S.PDiag(diag::warn_lock_exclusive_and_shared)
1581 << Kind << LockName);
1582 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1583 << Kind << LockName);
Stephen Hines176edba2014-12-01 14:53:08 -08001584 Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001585 }
1586
Stephen Hines651f13c2014-04-23 16:59:28 -07001587 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1588 ProtectedOperationKind POK, AccessKind AK,
1589 SourceLocation Loc) override {
1590 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1591 "Only works for variables");
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +00001592 unsigned DiagID = POK == POK_VarAccess?
1593 diag::warn_variable_requires_any_lock:
1594 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +00001595 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001596 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Stephen Hines176edba2014-12-01 14:53:08 -08001597 Warnings.push_back(DelayedDiag(Warning, getNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001598 }
1599
Stephen Hines651f13c2014-04-23 16:59:28 -07001600 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1601 ProtectedOperationKind POK, Name LockName,
1602 LockKind LK, SourceLocation Loc,
1603 Name *PossibleMatch) override {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +00001604 unsigned DiagID = 0;
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001605 if (PossibleMatch) {
1606 switch (POK) {
1607 case POK_VarAccess:
1608 DiagID = diag::warn_variable_requires_lock_precise;
1609 break;
1610 case POK_VarDereference:
1611 DiagID = diag::warn_var_deref_requires_lock_precise;
1612 break;
1613 case POK_FunctionCall:
1614 DiagID = diag::warn_fun_requires_lock_precise;
1615 break;
Stephen Hines176edba2014-12-01 14:53:08 -08001616 case POK_PassByRef:
1617 DiagID = diag::warn_guarded_pass_by_reference;
1618 break;
1619 case POK_PtPassByRef:
1620 DiagID = diag::warn_pt_guarded_pass_by_reference;
1621 break;
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001622 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001623 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1624 << D->getNameAsString()
1625 << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001626 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Stephen Hines651f13c2014-04-23 16:59:28 -07001627 << *PossibleMatch);
Stephen Hines176edba2014-12-01 14:53:08 -08001628 if (Verbose && POK == POK_VarAccess) {
1629 PartialDiagnosticAt VNote(D->getLocation(),
1630 S.PDiag(diag::note_guarded_by_declared_here)
1631 << D->getNameAsString());
1632 Warnings.push_back(DelayedDiag(Warning, getNotes(Note, VNote)));
1633 } else
1634 Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001635 } else {
1636 switch (POK) {
1637 case POK_VarAccess:
1638 DiagID = diag::warn_variable_requires_lock;
1639 break;
1640 case POK_VarDereference:
1641 DiagID = diag::warn_var_deref_requires_lock;
1642 break;
1643 case POK_FunctionCall:
1644 DiagID = diag::warn_fun_requires_lock;
1645 break;
Stephen Hines176edba2014-12-01 14:53:08 -08001646 case POK_PassByRef:
1647 DiagID = diag::warn_guarded_pass_by_reference;
1648 break;
1649 case POK_PtPassByRef:
1650 DiagID = diag::warn_pt_guarded_pass_by_reference;
1651 break;
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001652 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001653 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1654 << D->getNameAsString()
1655 << LockName << LK);
Stephen Hines176edba2014-12-01 14:53:08 -08001656 if (Verbose && POK == POK_VarAccess) {
1657 PartialDiagnosticAt Note(D->getLocation(),
1658 S.PDiag(diag::note_guarded_by_declared_here)
1659 << D->getNameAsString());
1660 Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
1661 } else
1662 Warnings.push_back(DelayedDiag(Warning, getNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001663 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001664 }
1665
Stephen Hines176edba2014-12-01 14:53:08 -08001666
1667 virtual void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1668 SourceLocation Loc) override {
1669 PartialDiagnosticAt Warning(Loc,
1670 S.PDiag(diag::warn_acquire_requires_negative_cap)
1671 << Kind << LockName << Neg);
1672 Warnings.push_back(DelayedDiag(Warning, getNotes()));
1673 }
1674
1675
Stephen Hines651f13c2014-04-23 16:59:28 -07001676 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1677 SourceLocation Loc) override {
1678 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1679 << Kind << FunName << LockName);
Stephen Hines176edba2014-12-01 14:53:08 -08001680 Warnings.push_back(DelayedDiag(Warning, getNotes()));
1681 }
1682
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001683
1684 virtual void handleLockAcquiredBefore(StringRef Kind, Name L1Name,
1685 Name L2Name, SourceLocation Loc)
1686 override {
1687 PartialDiagnosticAt Warning(Loc,
1688 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1689 Warnings.push_back(DelayedDiag(Warning, getNotes()));
1690 }
1691
1692 virtual void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc)
1693 override {
1694 PartialDiagnosticAt Warning(Loc,
1695 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1696 Warnings.push_back(DelayedDiag(Warning, getNotes()));
1697 }
1698
Stephen Hines176edba2014-12-01 14:53:08 -08001699 void enterFunction(const FunctionDecl* FD) override {
1700 CurrentFunction = FD;
1701 }
1702
1703 void leaveFunction(const FunctionDecl* FD) override {
1704 CurrentFunction = 0;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001705 }
1706};
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001707} // namespace
1708} // namespace threadSafety
1709} // namespace clang
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001710
Ted Kremenek610068c2011-01-15 02:58:47 +00001711//===----------------------------------------------------------------------===//
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001712// -Wconsumed
1713//===----------------------------------------------------------------------===//
1714
1715namespace clang {
1716namespace consumed {
1717namespace {
1718class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1719
1720 Sema &S;
1721 DiagList Warnings;
1722
1723public:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001724
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001725 ConsumedWarningsHandler(Sema &S) : S(S) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001726
1727 void emitDiagnostics() override {
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001728 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001729 for (const auto &Diag : Warnings) {
1730 S.Diag(Diag.first.first, Diag.first.second);
1731 for (const auto &Note : Diag.second)
1732 S.Diag(Note.first, Note.second);
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001733 }
1734 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001735
1736 void warnLoopStateMismatch(SourceLocation Loc,
1737 StringRef VariableName) override {
DeLesley Hutchins73858402013-10-09 18:30:24 +00001738 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1739 VariableName);
1740
1741 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1742 }
1743
DeLesley Hutchinscd0f6d72013-10-17 22:53:04 +00001744 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1745 StringRef VariableName,
1746 StringRef ExpectedState,
Stephen Hines651f13c2014-04-23 16:59:28 -07001747 StringRef ObservedState) override {
DeLesley Hutchinscd0f6d72013-10-17 22:53:04 +00001748
1749 PartialDiagnosticAt Warning(Loc, S.PDiag(
1750 diag::warn_param_return_typestate_mismatch) << VariableName <<
1751 ExpectedState << ObservedState);
1752
1753 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1754 }
1755
DeLesley Hutchinsd4f0e192013-10-17 23:23:53 +00001756 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Stephen Hines651f13c2014-04-23 16:59:28 -07001757 StringRef ObservedState) override {
DeLesley Hutchinsd4f0e192013-10-17 23:23:53 +00001758
1759 PartialDiagnosticAt Warning(Loc, S.PDiag(
1760 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1761
1762 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1763 }
1764
DeLesley Hutchins0e8534e2013-09-03 20:11:38 +00001765 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Stephen Hines651f13c2014-04-23 16:59:28 -07001766 StringRef TypeName) override {
DeLesley Hutchins0e8534e2013-09-03 20:11:38 +00001767 PartialDiagnosticAt Warning(Loc, S.PDiag(
1768 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1769
1770 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1771 }
1772
1773 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Stephen Hines651f13c2014-04-23 16:59:28 -07001774 StringRef ObservedState) override {
DeLesley Hutchins0e8534e2013-09-03 20:11:38 +00001775
1776 PartialDiagnosticAt Warning(Loc, S.PDiag(
1777 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1778
1779 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1780 }
1781
DeLesley Hutchins66540852013-10-04 21:28:06 +00001782 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Stephen Hines651f13c2014-04-23 16:59:28 -07001783 SourceLocation Loc) override {
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001784
1785 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins66540852013-10-04 21:28:06 +00001786 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001787
1788 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1789 }
1790
DeLesley Hutchins66540852013-10-04 21:28:06 +00001791 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Stephen Hines651f13c2014-04-23 16:59:28 -07001792 StringRef State, SourceLocation Loc) override {
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001793
DeLesley Hutchins66540852013-10-04 21:28:06 +00001794 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1795 MethodName << VariableName << State);
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001796
1797 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1798 }
1799};
1800}}}
1801
1802//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001803// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1804// warnings on a function, method, or block.
1805//===----------------------------------------------------------------------===//
1806
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001807clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1808 enableCheckFallThrough = 1;
1809 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001810 enableThreadSafetyAnalysis = 0;
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001811 enableConsumedAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001812}
1813
Stephen Hines651f13c2014-04-23 16:59:28 -07001814static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001815 return (unsigned)!D.isIgnored(diag, SourceLocation());
Stephen Hines651f13c2014-04-23 16:59:28 -07001816}
1817
Chandler Carruth5d989942011-07-06 16:21:37 +00001818clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1819 : S(s),
1820 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001821 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001822 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001823 MaxCFGBlocksPerFunction(0),
1824 NumUninitAnalysisFunctions(0),
1825 NumUninitAnalysisVariables(0),
1826 MaxUninitAnalysisVariablesPerFunction(0),
1827 NumUninitAnalysisBlockVisits(0),
1828 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001829
1830 using namespace diag;
David Blaikied6471f72011-09-25 23:23:43 +00001831 DiagnosticsEngine &D = S.getDiagnostics();
Stephen Hines651f13c2014-04-23 16:59:28 -07001832
1833 DefaultPolicy.enableCheckUnreachable =
1834 isEnabled(D, warn_unreachable) ||
1835 isEnabled(D, warn_unreachable_break) ||
1836 isEnabled(D, warn_unreachable_return) ||
1837 isEnabled(D, warn_unreachable_loop_increment);
1838
1839 DefaultPolicy.enableThreadSafetyAnalysis =
1840 isEnabled(D, warn_double_lock);
1841
1842 DefaultPolicy.enableConsumedAnalysis =
1843 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001844}
1845
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001846static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1847 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek351ba912011-02-23 01:52:04 +00001848 S.Diag(D.Loc, D.PD);
Ted Kremenek351ba912011-02-23 01:52:04 +00001849}
1850
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001851void clang::sema::
1852AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001853 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001854 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001855
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001856 // We avoid doing analysis-based warnings when there are errors for
1857 // two reasons:
1858 // (1) The CFGs often can't be constructed (if the body is invalid), so
1859 // don't bother trying.
1860 // (2) The code already has problems; running the analysis just takes more
1861 // time.
David Blaikied6471f72011-09-25 23:23:43 +00001862 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +00001863
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001864 // Do not do any analysis for declarations in system headers if we are
1865 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001866 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001867 S.SourceMgr.isInSystemHeader(D->getLocation()))
1868 return;
1869
John McCalle0054f62010-08-25 05:56:39 +00001870 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +00001871 if (cast<DeclContext>(D)->isDependentContext())
1872 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001873
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00001874 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001875 // Flush out any possibly unreachable diagnostics.
1876 flushDiagnostics(S, fscope);
1877 return;
1878 }
1879
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001880 const Stmt *Body = D->getBody();
1881 assert(Body);
1882
Ted Kremenek0cd72312013-10-14 19:11:25 +00001883 // Construct the analysis context with the specified CFG build options.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001884 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001885
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001886 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramere5753592013-09-09 14:48:42 +00001887 // explosion for destructors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001888 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1889 AC.getCFGBuildOptions().AddEHEdges = false;
1890 AC.getCFGBuildOptions().AddInitializers = true;
1891 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rosefaadf482012-09-05 23:11:06 +00001892 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001893 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rosefaadf482012-09-05 23:11:06 +00001894
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001895 // Force that certain expressions appear as CFGElements in the CFG. This
1896 // is used to speed up various analyses.
1897 // FIXME: This isn't the right factoring. This is here for initial
1898 // prototyping, but we need a way for analyses to say what expressions they
1899 // expect to always be CFGElements and then fill in the BuildOptions
1900 // appropriately. This is essentially a layering violation.
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00001901 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1902 P.enableConsumedAnalysis) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001903 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001904 AC.getCFGBuildOptions().setAllAlwaysAdd();
1905 }
1906 else {
1907 AC.getCFGBuildOptions()
1908 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smith6cfa78f2012-07-17 01:27:33 +00001909 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001910 .setAlwaysAdd(Stmt::BlockExprClass)
1911 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1912 .setAlwaysAdd(Stmt::DeclRefExprClass)
1913 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001914 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1915 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001916 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001917
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001918 // Install the logical handler for -Wtautological-overlap-compare
1919 std::unique_ptr<LogicalErrorHandler> LEH;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001920 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1921 D->getLocStart())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001922 LEH.reset(new LogicalErrorHandler(S));
1923 AC.getCFGBuildOptions().Observer = LEH.get();
1924 }
Ted Kremenek0cd72312013-10-14 19:11:25 +00001925
Ted Kremenek351ba912011-02-23 01:52:04 +00001926 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +00001927 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001928 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001929
1930 // Register the expressions with the CFGBuilder.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001931 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1932 if (D.stmt)
1933 AC.registerForcedBlockExpression(D.stmt);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001934 }
1935
1936 if (AC.getCFG()) {
1937 analyzed = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001938 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremenek0d28d362011-03-10 03:50:34 +00001939 bool processed = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001940 if (D.stmt) {
1941 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +00001942 CFGReverseBlockReachabilityAnalysis *cra =
1943 AC.getCFGReachablityAnalysis();
1944 // FIXME: We should be able to assert that block is non-null, but
1945 // the CFG analysis can skip potentially-evaluated expressions in
1946 // edge cases; see test/Sema/vla-2.c.
1947 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001948 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001949 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001950 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001951 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001952 }
1953 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001954 if (!processed) {
1955 // Emit the warning anyway if we cannot map to a basic block.
1956 S.Diag(D.Loc, D.PD);
1957 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001958 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001959 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001960
1961 if (!analyzed)
1962 flushDiagnostics(S, fscope);
1963 }
1964
1965
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001966 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +00001967 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001968 const CheckFallThroughDiagnostics &CD =
1969 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +00001970 : (isa<CXXMethodDecl>(D) &&
1971 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1972 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1973 ? CheckFallThroughDiagnostics::MakeForLambda()
1974 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001975 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001976 }
1977
1978 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +00001979 if (P.enableCheckUnreachable) {
1980 // Only check for unreachable code on non-template instantiations.
1981 // Different template instantiations can effectively change the control-flow
1982 // and it is very difficult to prove that a snippet of code in a template
1983 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +00001984 bool isTemplateInstantiation = false;
1985 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1986 isTemplateInstantiation = Function->isTemplateInstantiation();
1987 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +00001988 CheckUnreachable(S, AC);
1989 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001990
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001991 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +00001992 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001993 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +00001994 SourceLocation FEL = AC.getDecl()->getLocEnd();
Stephen Hines176edba2014-12-01 14:53:08 -08001995 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001996 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchinsfb4afc22012-12-05 00:06:15 +00001997 Reporter.setIssueBetaWarnings(true);
Stephen Hines176edba2014-12-01 14:53:08 -08001998 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
1999 Reporter.setVerbose(true);
DeLesley Hutchinsfb4afc22012-12-05 00:06:15 +00002000
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002001 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2002 &S.ThreadSafetyDeclCache);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00002003 Reporter.emitDiagnostics();
2004 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00002005
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00002006 // Check for violations of consumed properties.
2007 if (P.enableConsumedAnalysis) {
2008 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Kleckner2d84f6b2013-08-12 23:49:39 +00002009 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchinsdf7bef02013-08-12 21:20:55 +00002010 Analyzer.run(AC);
2011 }
2012
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002013 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2014 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2015 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00002016 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00002017 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00002018 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00002019 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00002020 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00002021 reporter, stats);
2022
2023 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2024 ++NumUninitAnalysisFunctions;
2025 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2026 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2027 MaxUninitAnalysisVariablesPerFunction =
2028 std::max(MaxUninitAnalysisVariablesPerFunction,
2029 stats.NumVariablesAnalyzed);
2030 MaxUninitAnalysisBlockVisitsPerFunction =
2031 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2032 stats.NumBlockVisits);
2033 }
Ted Kremenek610068c2011-01-15 02:58:47 +00002034 }
2035 }
Chandler Carruth5d989942011-07-06 16:21:37 +00002036
Alexander Kornienko19736342012-06-02 01:01:07 +00002037 bool FallThroughDiagFull =
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002038 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2039 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2040 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Sean Huntc2f51cf2012-06-15 21:22:05 +00002041 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko19736342012-06-02 01:01:07 +00002042 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00002043 }
2044
Jordan Rose58b6bdc2012-09-28 22:21:30 +00002045 if (S.getLangOpts().ObjCARCWeak &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002046 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Roseb5cd1222012-10-11 16:10:19 +00002047 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rose58b6bdc2012-09-28 22:21:30 +00002048
Stephen Hines651f13c2014-04-23 16:59:28 -07002049
2050 // Check for infinite self-recursion in functions
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002051 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2052 D->getLocStart())) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002053 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2054 checkRecursiveFunction(S, FD, Body, AC);
2055 }
2056 }
2057
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002058 // If none of the previous checks caused a CFG build, trigger one here
2059 // for -Wtautological-overlap-compare
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002060 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002061 D->getLocStart())) {
2062 AC.getCFG();
2063 }
2064
Chandler Carruth5d989942011-07-06 16:21:37 +00002065 // Collect statistics about the CFG if it was built.
2066 if (S.CollectStats && AC.isCFGBuilt()) {
2067 ++NumFunctionsAnalyzed;
2068 if (CFG *cfg = AC.getCFG()) {
2069 // If we successfully built a CFG for this context, record some more
2070 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00002071 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00002072 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00002073 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00002074 } else {
2075 ++NumFunctionsWithBadCFGs;
2076 }
2077 }
2078}
2079
2080void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2081 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2082
2083 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2084 unsigned AvgCFGBlocksPerFunction =
2085 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2086 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2087 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2088 << " " << NumCFGBlocks << " CFG blocks built.\n"
2089 << " " << AvgCFGBlocksPerFunction
2090 << " average CFG blocks per function.\n"
2091 << " " << MaxCFGBlocksPerFunction
2092 << " max CFG blocks per function.\n";
2093
2094 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2095 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2096 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2097 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2098 llvm::errs() << NumUninitAnalysisFunctions
2099 << " functions analyzed for uninitialiazed variables\n"
2100 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2101 << " " << AvgUninitVariablesPerFunction
2102 << " average variables per function.\n"
2103 << " " << MaxUninitAnalysisVariablesPerFunction
2104 << " max variables per function.\n"
2105 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2106 << " " << AvgUninitBlockVisitsPerFunction
2107 << " average block visits per function.\n"
2108 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2109 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00002110}