blob: 59c25d235a6eacfe42434f03a8379c5ddb6ad83f [file] [log] [blame]
Ted Kremenek918fe842010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Rose76831c62012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smith84837d52012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
DeLesley Hutchins48a31762013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/ReachableCode.h"
30#include "clang/Analysis/Analyses/ThreadSafety.h"
31#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
Ted Kremenek3427fac2011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
Alexander Kornienkoe61e5622012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenek918fe842010-03-20 21:06:02 +000055
56using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Unreachable code analysis.
60//===----------------------------------------------------------------------===//
61
62namespace {
63 class UnreachableCodeHandler : public reachable_code::Callback {
64 Sema &S;
65 public:
66 UnreachableCodeHandler(Sema &s) : S(s) {}
67
Ted Kremenek1a8641c2014-03-15 01:26:32 +000068 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000069 SourceLocation L,
70 SourceRange SilenceableCondVal,
71 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000072 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000073 unsigned diag = diag::warn_unreachable;
74 switch (UK) {
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
77 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000078 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000079 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000080 break;
Ted Kremenek14210372014-03-21 06:02:36 +000081 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
83 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 case reachable_code::UK_Other:
85 break;
86 }
87
88 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000089
90 SourceLocation Open = SilenceableCondVal.getBegin();
91 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000092 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000094 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
98 }
99 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000100 }
101 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000102}
Ted Kremenek918fe842010-03-20 21:06:02 +0000103
104/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000105static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000106 // As a heuristic prune all diagnostics not in the main file. Currently
107 // the majority of warnings in headers are false positives. These
108 // are largely caused by configuration state, e.g. preprocessor
109 // defined code, etc.
110 //
111 // Note that this is also a performance optimization. Analyzing
112 // headers many times can be expensive.
113 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
114 return;
115
Ted Kremenek918fe842010-03-20 21:06:02 +0000116 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000118}
119
Benjamin Kramer3a002252015-02-16 16:53:12 +0000120namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000121/// \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.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000133 for (const Stmt *SubStmt : E->children())
134 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
135 if (HasMacroID(SubExpr))
136 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000137
138 return false;
139 }
140
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000141 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000142 if (HasMacroID(B))
143 return;
144
145 SourceRange DiagRange = B->getSourceRange();
146 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
147 << DiagRange << isAlwaysTrue;
148 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000149
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000150 void compareBitwiseEquality(const BinaryOperator *B,
151 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000152 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 }
Richard Trieuf935b562014-04-05 05:17:01 +0000159};
Benjamin Kramer3a002252015-02-16 16:53:12 +0000160} // namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000161
Ted Kremenek918fe842010-03-20 21:06:02 +0000162//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000163// 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
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000174static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
175 // Since the current state is FoundPathWithNoRecursiveCall, the successors
176 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
177 // which, process all the Stmt's in this block to find any recursive calls.
178 for (const auto &B : Block) {
179 if (B.getKind() != CFGElement::Statement)
180 continue;
181
182 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
183 if (!CE || !CE->getCalleeDecl() ||
184 CE->getCalleeDecl()->getCanonicalDecl() != FD)
185 continue;
186
187 // Skip function calls which are qualified with a templated class.
188 if (const DeclRefExpr *DRE =
189 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
190 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
191 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
192 isa<TemplateSpecializationType>(NNS->getAsType())) {
193 continue;
194 }
195 }
196 }
197
198 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
199 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
200 !MCE->getMethodDecl()->isVirtual())
201 return true;
202 }
203 return false;
204}
205
Richard Trieu2f024f42013-12-21 02:33:43 +0000206static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
207 CFGBlock &Block, unsigned ExitID,
208 llvm::SmallVectorImpl<RecursiveState> &States,
209 RecursiveState State) {
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000210 SmallVector<std::pair<CFGBlock *, RecursiveState>, 16> Stack;
211 Stack.emplace_back(&Block, State);
Richard Trieu2f024f42013-12-21 02:33:43 +0000212
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000213 while (!Stack.empty()) {
214 CFGBlock &CurBlock = *Stack.back().first;
215 RecursiveState CurState = Stack.back().second;
216 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000217
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000218 unsigned ID = CurBlock.getBlockID();
Richard Trieu2f024f42013-12-21 02:33:43 +0000219
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000220 // A block's state can only move to a higher state.
221 if (States[ID] >= CurState)
222 continue;
Richard Trieu2f024f42013-12-21 02:33:43 +0000223
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000224 States[ID] = CurState;
225
226 if (CurState == FoundPathWithNoRecursiveCall) {
227 // Found a path to the exit node without a recursive call.
228 if (ExitID == ID)
229 continue;
230
231 if (hasRecursiveCallInPath(FD, CurBlock))
232 CurState = FoundPath;
233 }
234
235 for (auto I = CurBlock.succ_begin(), E = CurBlock.succ_end(); I != E; ++I)
236 if (*I)
237 Stack.emplace_back(*I, CurState);
Richard Trieu2f024f42013-12-21 02:33:43 +0000238 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000239}
240
241static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
242 const Stmt *Body,
243 AnalysisDeclContext &AC) {
244 FD = FD->getCanonicalDecl();
245
246 // Only run on non-templated functions and non-templated members of
247 // templated classes.
248 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
249 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
250 return;
251
252 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000254
255 // If the exit block is unreachable, skip processing the function.
256 if (cfg->getExit().pred_empty())
257 return;
258
259 // Mark all nodes as FoundNoPath, then begin processing the entry block.
260 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
261 FoundNoPath);
262 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
263 states, FoundPathWithNoRecursiveCall);
264
265 // Check that the exit block is reachable. This prevents triggering the
266 // warning on functions that do not terminate.
267 if (states[cfg->getExit().getBlockID()] == FoundPath)
268 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
269}
270
271//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000272// Check for missing return value.
273//===----------------------------------------------------------------------===//
274
John McCall5c6ec8c2010-05-16 09:34:11 +0000275enum ControlFlowKind {
276 UnknownFallThrough,
277 NeverFallThrough,
278 MaybeFallThrough,
279 AlwaysFallThrough,
280 NeverFallThroughOrReturn
281};
Ted Kremenek918fe842010-03-20 21:06:02 +0000282
283/// CheckFallThrough - Check that we don't fall off the end of a
284/// Statement that should return a value.
285///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000286/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
287/// MaybeFallThrough iff we might or might not fall off the end,
288/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
289/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000290/// statement but we may return. We assume that functions not marked noreturn
291/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000292static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000293 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000294 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000295
296 // The CFG leaves in dead things, and we don't want the dead code paths to
297 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000298 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000299 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000300 live);
301
302 bool AddEHEdges = AC.getAddEHEdges();
303 if (!AddEHEdges && count != cfg->getNumBlockIDs())
304 // When there are things remaining dead, and we didn't add EH edges
305 // from CallExprs to the catch clauses, we have to go back and
306 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000307 for (const auto *B : *cfg) {
308 if (!live[B->getBlockID()]) {
309 if (B->pred_begin() == B->pred_end()) {
310 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000311 // When not adding EH edges from calls, catch clauses
312 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000313 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000314 continue;
315 }
316 }
317 }
318
319 // Now we know what is live, we check the live precessors of the exit block
320 // and look for fall through paths, being careful to ignore normal returns,
321 // and exceptional paths.
322 bool HasLiveReturn = false;
323 bool HasFakeEdge = false;
324 bool HasPlainEdge = false;
325 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000326
327 // Ignore default cases that aren't likely to be reachable because all
328 // enums in a switch(X) have explicit case statements.
329 CFGBlock::FilterOptions FO;
330 FO.IgnoreDefaultsWithCoveredEnums = 1;
331
332 for (CFGBlock::filtered_pred_iterator
333 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
334 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000335 if (!live[B.getBlockID()])
336 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000337
Chandler Carruth03faf782011-09-13 09:53:58 +0000338 // Skip blocks which contain an element marked as no-return. They don't
339 // represent actually viable edges into the exit block, so mark them as
340 // abnormal.
341 if (B.hasNoReturnElement()) {
342 HasAbnormalEdge = true;
343 continue;
344 }
345
Ted Kremenek5d068492011-01-26 04:49:52 +0000346 // Destructors can appear after the 'return' in the CFG. This is
347 // normal. We need to look pass the destructors for the return
348 // statement (if it exists).
349 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000350
Chandler Carruth03faf782011-09-13 09:53:58 +0000351 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000352 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000353 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000354
Ted Kremenek5d068492011-01-26 04:49:52 +0000355 // No more CFGElements in the block?
356 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000357 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
358 HasAbnormalEdge = true;
359 continue;
360 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000361 // A labeled empty statement, or the entry block...
362 HasPlainEdge = true;
363 continue;
364 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000365
David Blaikie2a01f5d2013-02-21 20:58:29 +0000366 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000367 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000368 if (isa<ReturnStmt>(S)) {
369 HasLiveReturn = true;
370 continue;
371 }
372 if (isa<ObjCAtThrowStmt>(S)) {
373 HasFakeEdge = true;
374 continue;
375 }
376 if (isa<CXXThrowExpr>(S)) {
377 HasFakeEdge = true;
378 continue;
379 }
Chad Rosier32503022012-06-11 20:47:18 +0000380 if (isa<MSAsmStmt>(S)) {
381 // TODO: Verify this is correct.
382 HasFakeEdge = true;
383 HasLiveReturn = true;
384 continue;
385 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000386 if (isa<CXXTryStmt>(S)) {
387 HasAbnormalEdge = true;
388 continue;
389 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000390 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
391 == B.succ_end()) {
392 HasAbnormalEdge = true;
393 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000394 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000395
396 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000397 }
398 if (!HasPlainEdge) {
399 if (HasLiveReturn)
400 return NeverFallThrough;
401 return NeverFallThroughOrReturn;
402 }
403 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
404 return MaybeFallThrough;
405 // This says AlwaysFallThrough for calls to functions that are not marked
406 // noreturn, that don't return. If people would like this warning to be more
407 // accurate, such functions should be marked as noreturn.
408 return AlwaysFallThrough;
409}
410
Dan Gohman28ade552010-07-26 21:25:24 +0000411namespace {
412
Ted Kremenek918fe842010-03-20 21:06:02 +0000413struct CheckFallThroughDiagnostics {
414 unsigned diag_MaybeFallThrough_HasNoReturn;
415 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
416 unsigned diag_AlwaysFallThrough_HasNoReturn;
417 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
418 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000419 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000420 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000421
Douglas Gregor24f27692010-04-16 23:28:44 +0000422 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000423 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000424 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000425 D.diag_MaybeFallThrough_HasNoReturn =
426 diag::warn_falloff_noreturn_function;
427 D.diag_MaybeFallThrough_ReturnsNonVoid =
428 diag::warn_maybe_falloff_nonvoid_function;
429 D.diag_AlwaysFallThrough_HasNoReturn =
430 diag::warn_falloff_noreturn_function;
431 D.diag_AlwaysFallThrough_ReturnsNonVoid =
432 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000433
434 // Don't suggest that virtual functions be marked "noreturn", since they
435 // might be overridden by non-noreturn functions.
436 bool isVirtualMethod = false;
437 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
438 isVirtualMethod = Method->isVirtual();
439
Douglas Gregor0de57202011-10-10 18:15:57 +0000440 // Don't suggest that template instantiations be marked "noreturn"
441 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000442 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
443 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000444
445 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000446 D.diag_NeverFallThroughOrReturn =
447 diag::warn_suggest_noreturn_function;
448 else
449 D.diag_NeverFallThroughOrReturn = 0;
450
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000451 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000452 return D;
453 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000454
Ted Kremenek918fe842010-03-20 21:06:02 +0000455 static CheckFallThroughDiagnostics MakeForBlock() {
456 CheckFallThroughDiagnostics D;
457 D.diag_MaybeFallThrough_HasNoReturn =
458 diag::err_noreturn_block_has_return_expr;
459 D.diag_MaybeFallThrough_ReturnsNonVoid =
460 diag::err_maybe_falloff_nonvoid_block;
461 D.diag_AlwaysFallThrough_HasNoReturn =
462 diag::err_noreturn_block_has_return_expr;
463 D.diag_AlwaysFallThrough_ReturnsNonVoid =
464 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000465 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000466 D.funMode = Block;
467 return D;
468 }
469
470 static CheckFallThroughDiagnostics MakeForLambda() {
471 CheckFallThroughDiagnostics D;
472 D.diag_MaybeFallThrough_HasNoReturn =
473 diag::err_noreturn_lambda_has_return_expr;
474 D.diag_MaybeFallThrough_ReturnsNonVoid =
475 diag::warn_maybe_falloff_nonvoid_lambda;
476 D.diag_AlwaysFallThrough_HasNoReturn =
477 diag::err_noreturn_lambda_has_return_expr;
478 D.diag_AlwaysFallThrough_ReturnsNonVoid =
479 diag::warn_falloff_nonvoid_lambda;
480 D.diag_NeverFallThroughOrReturn = 0;
481 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000482 return D;
483 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000484
David Blaikie9c902b52011-09-25 23:23:43 +0000485 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000486 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000487 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000488 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000489 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
490 FuncLoc)) &&
491 (!HasNoReturn ||
492 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
493 FuncLoc)) &&
494 (!ReturnsVoid ||
495 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000496 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000497
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000498 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000499 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000500 }
501};
502
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000503}
Dan Gohman28ade552010-07-26 21:25:24 +0000504
Ted Kremenek918fe842010-03-20 21:06:02 +0000505/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
506/// function that should return a value. Check that we don't fall off the end
507/// of a noreturn function. We assume that functions and blocks not marked
508/// noreturn will return.
509static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000510 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000511 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000512 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000513
514 bool ReturnsVoid = false;
515 bool HasNoReturn = false;
516
517 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000518 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000519 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000520 }
521 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000522 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000523 HasNoReturn = MD->hasAttr<NoReturnAttr>();
524 }
525 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000526 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000527 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000528 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000529 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000530 ReturnsVoid = true;
531 if (FT->getNoReturnAttr())
532 HasNoReturn = true;
533 }
534 }
535
David Blaikie9c902b52011-09-25 23:23:43 +0000536 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000537
538 // Short circuit for compilation speed.
539 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
540 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000541
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000542 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
543 // Either in a function body compound statement, or a function-try-block.
544 switch (CheckFallThrough(AC)) {
545 case UnknownFallThrough:
546 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000547
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000548 case MaybeFallThrough:
549 if (HasNoReturn)
550 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
551 else if (!ReturnsVoid)
552 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
553 break;
554 case AlwaysFallThrough:
555 if (HasNoReturn)
556 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
557 else if (!ReturnsVoid)
558 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
559 break;
560 case NeverFallThroughOrReturn:
561 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
562 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
563 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
564 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
565 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
566 } else {
567 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000568 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000569 }
570 break;
571 case NeverFallThrough:
572 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000573 }
574}
575
576//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000577// -Wuninitialized
578//===----------------------------------------------------------------------===//
579
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000580namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000581/// ContainsReference - A visitor class to search for references to
582/// a particular declaration (the needle) within any evaluated component of an
583/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000584class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000585 bool FoundReference;
586 const DeclRefExpr *Needle;
587
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000588public:
Scott Douglass503fc392015-06-10 13:53:15 +0000589 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000590
Scott Douglass503fc392015-06-10 13:53:15 +0000591 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
592 : Inherited(Context), FoundReference(false), Needle(Needle) {}
593
594 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000595 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000596 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000597 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000598
Scott Douglass503fc392015-06-10 13:53:15 +0000599 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000600 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000601
Scott Douglass503fc392015-06-10 13:53:15 +0000602 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000603 if (E == Needle)
604 FoundReference = true;
605 else
Scott Douglass503fc392015-06-10 13:53:15 +0000606 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000607 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000608
609 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000610};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000611}
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000612
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000613static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000614 QualType VariableTy = VD->getType().getCanonicalType();
615 if (VariableTy->isBlockPointerType() &&
616 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000617 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
618 << VD->getDeclName()
619 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000620 return true;
621 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000622
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000623 // Don't issue a fixit if there is already an initializer.
624 if (VD->getInit())
625 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000626
627 // Don't suggest a fixit inside macros.
628 if (VD->getLocEnd().isMacroID())
629 return false;
630
Alp Tokerb6cc5922014-05-03 03:45:55 +0000631 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000632
633 // Suggest possible initialization (if any).
634 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
635 if (Init.empty())
636 return false;
637
Richard Smith8d06f422012-01-12 23:53:29 +0000638 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
639 << FixItHint::CreateInsertion(Loc, Init);
640 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000641}
642
Richard Smith1bb8edb82012-05-26 06:20:46 +0000643/// Create a fixit to remove an if-like statement, on the assumption that its
644/// condition is CondVal.
645static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
646 const Stmt *Else, bool CondVal,
647 FixItHint &Fixit1, FixItHint &Fixit2) {
648 if (CondVal) {
649 // If condition is always true, remove all but the 'then'.
650 Fixit1 = FixItHint::CreateRemoval(
651 CharSourceRange::getCharRange(If->getLocStart(),
652 Then->getLocStart()));
653 if (Else) {
654 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
655 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
656 Fixit2 = FixItHint::CreateRemoval(
657 SourceRange(ElseKwLoc, Else->getLocEnd()));
658 }
659 } else {
660 // If condition is always false, remove all but the 'else'.
661 if (Else)
662 Fixit1 = FixItHint::CreateRemoval(
663 CharSourceRange::getCharRange(If->getLocStart(),
664 Else->getLocStart()));
665 else
666 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
667 }
668}
669
670/// DiagUninitUse -- Helper function to produce a diagnostic for an
671/// uninitialized use of a variable.
672static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
673 bool IsCapturedByBlock) {
674 bool Diagnosed = false;
675
Richard Smithba8071e2013-09-12 18:49:10 +0000676 switch (Use.getKind()) {
677 case UninitUse::Always:
678 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
679 << VD->getDeclName() << IsCapturedByBlock
680 << Use.getUser()->getSourceRange();
681 return;
682
683 case UninitUse::AfterDecl:
684 case UninitUse::AfterCall:
685 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
686 << VD->getDeclName() << IsCapturedByBlock
687 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
688 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
689 << VD->getSourceRange();
690 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
691 << IsCapturedByBlock << Use.getUser()->getSourceRange();
692 return;
693
694 case UninitUse::Maybe:
695 case UninitUse::Sometimes:
696 // Carry on to report sometimes-uninitialized branches, if possible,
697 // or a 'may be used uninitialized' diagnostic otherwise.
698 break;
699 }
700
Richard Smith1bb8edb82012-05-26 06:20:46 +0000701 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000702 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
703 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000704 assert(Use.getKind() == UninitUse::Sometimes);
705
706 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000707 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000708
709 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000710 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000711 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000712 SourceRange Range;
713
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000714 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000715 // For all binary terminators, branch 0 is taken if the condition is true,
716 // and branch 1 is taken if the condition is false.
717 int RemoveDiagKind = -1;
718 const char *FixitStr =
719 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
720 : (I->Output ? "1" : "0");
721 FixItHint Fixit1, Fixit2;
722
Richard Smithba8071e2013-09-12 18:49:10 +0000723 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000724 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000725 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000726 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000727 continue;
728
729 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000730 case Stmt::IfStmtClass: {
731 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000732 DiagKind = 0;
733 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000734 Range = IS->getCond()->getSourceRange();
735 RemoveDiagKind = 0;
736 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
737 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000738 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000739 }
740 case Stmt::ConditionalOperatorClass: {
741 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000742 DiagKind = 0;
743 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000744 Range = CO->getCond()->getSourceRange();
745 RemoveDiagKind = 0;
746 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
747 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000748 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000749 }
Richard Smith4323bf82012-05-25 02:17:09 +0000750 case Stmt::BinaryOperatorClass: {
751 const BinaryOperator *BO = cast<BinaryOperator>(Term);
752 if (!BO->isLogicalOp())
753 continue;
754 DiagKind = 0;
755 Str = BO->getOpcodeStr();
756 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000757 RemoveDiagKind = 0;
758 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
759 (BO->getOpcode() == BO_LOr && !I->Output))
760 // true && y -> y, false || y -> y.
761 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
762 BO->getOperatorLoc()));
763 else
764 // false && y -> false, true || y -> true.
765 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000766 break;
767 }
768
769 // "loop is entered / loop is exited".
770 case Stmt::WhileStmtClass:
771 DiagKind = 1;
772 Str = "while";
773 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000774 RemoveDiagKind = 1;
775 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000776 break;
777 case Stmt::ForStmtClass:
778 DiagKind = 1;
779 Str = "for";
780 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000781 RemoveDiagKind = 1;
782 if (I->Output)
783 Fixit1 = FixItHint::CreateRemoval(Range);
784 else
785 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000786 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000787 case Stmt::CXXForRangeStmtClass:
788 if (I->Output == 1) {
789 // The use occurs if a range-based for loop's body never executes.
790 // That may be impossible, and there's no syntactic fix for this,
791 // so treat it as a 'may be uninitialized' case.
792 continue;
793 }
794 DiagKind = 1;
795 Str = "for";
796 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
797 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000798
799 // "condition is true / loop is exited".
800 case Stmt::DoStmtClass:
801 DiagKind = 2;
802 Str = "do";
803 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000804 RemoveDiagKind = 1;
805 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000806 break;
807
808 // "switch case is taken".
809 case Stmt::CaseStmtClass:
810 DiagKind = 3;
811 Str = "case";
812 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
813 break;
814 case Stmt::DefaultStmtClass:
815 DiagKind = 3;
816 Str = "default";
817 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
818 break;
819 }
820
Richard Smith1bb8edb82012-05-26 06:20:46 +0000821 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
822 << VD->getDeclName() << IsCapturedByBlock << DiagKind
823 << Str << I->Output << Range;
824 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
825 << IsCapturedByBlock << User->getSourceRange();
826 if (RemoveDiagKind != -1)
827 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
828 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
829
830 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000831 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000832
833 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000834 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000835 << VD->getDeclName() << IsCapturedByBlock
836 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000837}
838
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000839/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
840/// uninitialized variable. This manages the different forms of diagnostic
841/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000842/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000843/// false.
844static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000845 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000846 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000847
Richard Smith4323bf82012-05-25 02:17:09 +0000848 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000849 // Inspect the initializer of the variable declaration which is
850 // being referenced prior to its initialization. We emit
851 // specialized diagnostics for self-initialization, and we
852 // specifically avoid warning about self references which take the
853 // form of:
854 //
855 // int x = x;
856 //
857 // This is used to indicate to GCC that 'x' is intentionally left
858 // uninitialized. Proven code paths which access 'x' in
859 // an uninitialized state after this will still warn.
860 if (const Expr *Initializer = VD->getInit()) {
861 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
862 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000863
Richard Trieu43a2fc72012-05-09 21:08:22 +0000864 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +0000865 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +0000866 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000867 S.Diag(DRE->getLocStart(),
868 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000869 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
870 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000871 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000872 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000873
Richard Smith1bb8edb82012-05-26 06:20:46 +0000874 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000875 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000876 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000877 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
878 S.Diag(BE->getLocStart(),
879 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000880 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000881 else
882 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000883 }
884
885 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000886 // the initializer of that declaration & we didn't already suggest
887 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000888 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000889 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
890 << VD->getDeclName();
891
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000892 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000893}
894
Richard Smith84837d52012-05-03 18:27:39 +0000895namespace {
896 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
897 public:
898 FallthroughMapper(Sema &S)
899 : FoundSwitchStatements(false),
900 S(S) {
901 }
902
903 bool foundSwitchStatements() const { return FoundSwitchStatements; }
904
905 void markFallthroughVisited(const AttributedStmt *Stmt) {
906 bool Found = FallthroughStmts.erase(Stmt);
907 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000908 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000909 }
910
911 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
912
913 const AttrStmts &getFallthroughStmts() const {
914 return FallthroughStmts;
915 }
916
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000917 void fillReachableBlocks(CFG *Cfg) {
918 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
919 std::deque<const CFGBlock *> BlockQueue;
920
921 ReachableBlocks.insert(&Cfg->getEntry());
922 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000923 // Mark all case blocks reachable to avoid problems with switching on
924 // constants, covered enums, etc.
925 // These blocks can contain fall-through annotations, and we don't want to
926 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +0000927 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000928 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +0000929 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000930 BlockQueue.push_back(B);
931 }
932
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000933 while (!BlockQueue.empty()) {
934 const CFGBlock *P = BlockQueue.front();
935 BlockQueue.pop_front();
936 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
937 E = P->succ_end();
938 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +0000939 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000940 BlockQueue.push_back(*I);
941 }
942 }
943 }
944
Richard Smith84837d52012-05-03 18:27:39 +0000945 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000946 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
947
Richard Smith84837d52012-05-03 18:27:39 +0000948 int UnannotatedCnt = 0;
949 AnnotatedCnt = 0;
950
Aaron Ballmane5195222014-05-15 20:50:47 +0000951 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +0000952 while (!BlockQueue.empty()) {
953 const CFGBlock *P = BlockQueue.front();
954 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000955 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000956
957 const Stmt *Term = P->getTerminator();
958 if (Term && isa<SwitchStmt>(Term))
959 continue; // Switch statement, good.
960
961 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
962 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
963 continue; // Previous case label has no statements, good.
964
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000965 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
966 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
967 continue; // Case label is preceded with a normal label, good.
968
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000969 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000970 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
971 ElemEnd = P->rend();
972 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000973 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
974 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000975 S.Diag(AS->getLocStart(),
976 diag::warn_fallthrough_attr_unreachable);
977 markFallthroughVisited(AS);
978 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000979 break;
Richard Smith84837d52012-05-03 18:27:39 +0000980 }
981 // Don't care about other unreachable statements.
982 }
983 }
984 // If there are no unreachable statements, this may be a special
985 // case in CFG:
986 // case X: {
987 // A a; // A has a destructor.
988 // break;
989 // }
990 // // <<<< This place is represented by a 'hanging' CFG block.
991 // case Y:
992 continue;
993 }
994
995 const Stmt *LastStmt = getLastStmt(*P);
996 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
997 markFallthroughVisited(AS);
998 ++AnnotatedCnt;
999 continue; // Fallthrough annotation, good.
1000 }
1001
1002 if (!LastStmt) { // This block contains no executable statements.
1003 // Traverse its predecessors.
1004 std::copy(P->pred_begin(), P->pred_end(),
1005 std::back_inserter(BlockQueue));
1006 continue;
1007 }
1008
1009 ++UnannotatedCnt;
1010 }
1011 return !!UnannotatedCnt;
1012 }
1013
1014 // RecursiveASTVisitor setup.
1015 bool shouldWalkTypesOfTypeLocs() const { return false; }
1016
1017 bool VisitAttributedStmt(AttributedStmt *S) {
1018 if (asFallThroughAttr(S))
1019 FallthroughStmts.insert(S);
1020 return true;
1021 }
1022
1023 bool VisitSwitchStmt(SwitchStmt *S) {
1024 FoundSwitchStatements = true;
1025 return true;
1026 }
1027
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001028 // We don't want to traverse local type declarations. We analyze their
1029 // methods separately.
1030 bool TraverseDecl(Decl *D) { return true; }
1031
Alexander Kornienkobf911642014-06-24 15:28:21 +00001032 // We analyze lambda bodies separately. Skip them here.
1033 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1034
Richard Smith84837d52012-05-03 18:27:39 +00001035 private:
1036
1037 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1038 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1039 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1040 return AS;
1041 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001042 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001043 }
1044
1045 static const Stmt *getLastStmt(const CFGBlock &B) {
1046 if (const Stmt *Term = B.getTerminator())
1047 return Term;
1048 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1049 ElemEnd = B.rend();
1050 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001051 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1052 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001053 }
1054 // Workaround to detect a statement thrown out by CFGBuilder:
1055 // case X: {} case Y:
1056 // case X: ; case Y:
1057 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1058 if (!isa<SwitchCase>(SW->getSubStmt()))
1059 return SW->getSubStmt();
1060
Craig Topperc3ec1492014-05-26 06:22:03 +00001061 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001062 }
1063
1064 bool FoundSwitchStatements;
1065 AttrStmts FallthroughStmts;
1066 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001067 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001068 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001069}
Richard Smith84837d52012-05-03 18:27:39 +00001070
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001071static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001072 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001073 // Only perform this analysis when using C++11. There is no good workflow
1074 // for this warning when not using C++11. There is no good way to silence
1075 // the warning (no attribute is available) unless we are using C++11's support
1076 // for generalized attributes. Once could use pragmas to silence the warning,
1077 // but as a general solution that is gross and not in the spirit of this
1078 // warning.
1079 //
1080 // NOTE: This an intermediate solution. There are on-going discussions on
1081 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001082 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001083 return;
1084
Richard Smith84837d52012-05-03 18:27:39 +00001085 FallthroughMapper FM(S);
1086 FM.TraverseStmt(AC.getBody());
1087
1088 if (!FM.foundSwitchStatements())
1089 return;
1090
Alexis Hunt2178f142012-06-15 21:22:05 +00001091 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001092 return;
1093
Richard Smith84837d52012-05-03 18:27:39 +00001094 CFG *Cfg = AC.getCFG();
1095
1096 if (!Cfg)
1097 return;
1098
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001099 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001100
1101 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001102 const CFGBlock *B = *I;
1103 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001104
1105 if (!Label || !isa<SwitchCase>(Label))
1106 continue;
1107
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001108 int AnnotatedCnt;
1109
Alexander Kornienko55488792013-01-25 15:49:34 +00001110 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001111 continue;
1112
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001113 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001114 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1115 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001116
1117 if (!AnnotatedCnt) {
1118 SourceLocation L = Label->getLocStart();
1119 if (L.isMacroID())
1120 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001121 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001122 const Stmt *Term = B->getTerminator();
1123 // Skip empty cases.
1124 while (B->empty() && !Term && B->succ_size() == 1) {
1125 B = *B->succ_begin();
1126 Term = B->getTerminator();
1127 }
1128 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001129 Preprocessor &PP = S.getPreprocessor();
1130 TokenValue Tokens[] = {
1131 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1132 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1133 tok::r_square, tok::r_square
1134 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001135 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1136 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1137 if (!MacroName.empty())
1138 AnnotationSpelling = MacroName;
1139 SmallString<64> TextToInsert(AnnotationSpelling);
1140 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001141 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001142 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001143 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001144 }
Richard Smith84837d52012-05-03 18:27:39 +00001145 }
1146 S.Diag(L, diag::note_insert_break_fixit) <<
1147 FixItHint::CreateInsertion(L, "break; ");
1148 }
1149 }
1150
Aaron Ballmane5195222014-05-15 20:50:47 +00001151 for (const auto *F : FM.getFallthroughStmts())
1152 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001153}
1154
Jordan Rose25c0ea82012-10-29 17:46:47 +00001155static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1156 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001157 assert(S);
1158
1159 do {
1160 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001161 case Stmt::ForStmtClass:
1162 case Stmt::WhileStmtClass:
1163 case Stmt::CXXForRangeStmtClass:
1164 case Stmt::ObjCForCollectionStmtClass:
1165 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001166 case Stmt::DoStmtClass: {
1167 const Expr *Cond = cast<DoStmt>(S)->getCond();
1168 llvm::APSInt Val;
1169 if (!Cond->EvaluateAsInt(Val, Ctx))
1170 return true;
1171 return Val.getBoolValue();
1172 }
Jordan Rose76831c62012-10-11 16:10:19 +00001173 default:
1174 break;
1175 }
1176 } while ((S = PM.getParent(S)));
1177
1178 return false;
1179}
1180
Jordan Rosed3934582012-09-28 22:21:30 +00001181
1182static void diagnoseRepeatedUseOfWeak(Sema &S,
1183 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001184 const Decl *D,
1185 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001186 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1187 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1188 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001189 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1190 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001191
Jordan Rose25c0ea82012-10-29 17:46:47 +00001192 ASTContext &Ctx = S.getASTContext();
1193
Jordan Rosed3934582012-09-28 22:21:30 +00001194 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1195
1196 // Extract all weak objects that are referenced more than once.
1197 SmallVector<StmtUsesPair, 8> UsesByStmt;
1198 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1199 I != E; ++I) {
1200 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001201
1202 // Find the first read of the weak object.
1203 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1204 for ( ; UI != UE; ++UI) {
1205 if (UI->isUnsafe())
1206 break;
1207 }
1208
1209 // If there were only writes to this object, don't warn.
1210 if (UI == UE)
1211 continue;
1212
Jordan Rose76831c62012-10-11 16:10:19 +00001213 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001214 // read is not within a loop, don't warn. Additionally, don't warn in a
1215 // loop if the base object is a local variable -- local variables are often
1216 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001217 if (UI == Uses.begin()) {
1218 WeakUseVector::const_iterator UI2 = UI;
1219 for (++UI2; UI2 != UE; ++UI2)
1220 if (UI2->isUnsafe())
1221 break;
1222
Jordan Rose25c0ea82012-10-29 17:46:47 +00001223 if (UI2 == UE) {
1224 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001225 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001226
1227 const WeakObjectProfileTy &Profile = I->first;
1228 if (!Profile.isExactProfile())
1229 continue;
1230
1231 const NamedDecl *Base = Profile.getBase();
1232 if (!Base)
1233 Base = Profile.getProperty();
1234 assert(Base && "A profile always has a base or property.");
1235
1236 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1237 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1238 continue;
1239 }
Jordan Rose76831c62012-10-11 16:10:19 +00001240 }
1241
Jordan Rosed3934582012-09-28 22:21:30 +00001242 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1243 }
1244
1245 if (UsesByStmt.empty())
1246 return;
1247
1248 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001249 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001250 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001251 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1252 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1253 RHS.first->getLocStart());
1254 });
Jordan Rosed3934582012-09-28 22:21:30 +00001255
1256 // Classify the current code body for better warning text.
1257 // This enum should stay in sync with the cases in
1258 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1259 // FIXME: Should we use a common classification enum and the same set of
1260 // possibilities all throughout Sema?
1261 enum {
1262 Function,
1263 Method,
1264 Block,
1265 Lambda
1266 } FunctionKind;
1267
1268 if (isa<sema::BlockScopeInfo>(CurFn))
1269 FunctionKind = Block;
1270 else if (isa<sema::LambdaScopeInfo>(CurFn))
1271 FunctionKind = Lambda;
1272 else if (isa<ObjCMethodDecl>(D))
1273 FunctionKind = Method;
1274 else
1275 FunctionKind = Function;
1276
1277 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001278 for (const auto &P : UsesByStmt) {
1279 const Stmt *FirstRead = P.first;
1280 const WeakObjectProfileTy &Key = P.second->first;
1281 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001282
Jordan Rose657b5f42012-09-28 22:21:35 +00001283 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1284 // may not contain enough information to determine that these are different
1285 // properties. We can only be 100% sure of a repeated use in certain cases,
1286 // and we adjust the diagnostic kind accordingly so that the less certain
1287 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001288 unsigned DiagKind;
1289 if (Key.isExactProfile())
1290 DiagKind = diag::warn_arc_repeated_use_of_weak;
1291 else
1292 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1293
Jordan Rose657b5f42012-09-28 22:21:35 +00001294 // Classify the weak object being accessed for better warning text.
1295 // This enum should stay in sync with the cases in
1296 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1297 enum {
1298 Variable,
1299 Property,
1300 ImplicitProperty,
1301 Ivar
1302 } ObjectKind;
1303
1304 const NamedDecl *D = Key.getProperty();
1305 if (isa<VarDecl>(D))
1306 ObjectKind = Variable;
1307 else if (isa<ObjCPropertyDecl>(D))
1308 ObjectKind = Property;
1309 else if (isa<ObjCMethodDecl>(D))
1310 ObjectKind = ImplicitProperty;
1311 else if (isa<ObjCIvarDecl>(D))
1312 ObjectKind = Ivar;
1313 else
1314 llvm_unreachable("Unexpected weak object kind!");
1315
Jordan Rosed3934582012-09-28 22:21:30 +00001316 // Show the first time the object was read.
1317 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001318 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001319 << FirstRead->getSourceRange();
1320
1321 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001322 for (const auto &Use : Uses) {
1323 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001324 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001325 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001326 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001327 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001328 }
1329 }
1330}
1331
Jordan Rosed3934582012-09-28 22:21:30 +00001332namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001333class UninitValsDiagReporter : public UninitVariablesHandler {
1334 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001335 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001336 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001337 // Prefer using MapVector to DenseMap, so that iteration order will be
1338 // the same as insertion order. This is needed to obtain a deterministic
1339 // order of diagnostics when calling flushDiagnostics().
1340 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001341 UsesMap *uses;
1342
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001343public:
Craig Topperc3ec1492014-05-26 06:22:03 +00001344 UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001345 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001346
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001347 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001348 if (!uses)
1349 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001350
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001351 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001352 if (!V.getPointer())
1353 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001354
Ted Kremenek596fa162011-10-13 18:50:06 +00001355 return V;
1356 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001357
1358 void handleUseOfUninitVariable(const VarDecl *vd,
1359 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001360 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001361 }
1362
Craig Toppere14c0f82014-03-12 04:55:44 +00001363 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001364 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001365 }
1366
1367 void flushDiagnostics() {
1368 if (!uses)
1369 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001370
Aaron Ballmane5195222014-05-15 20:50:47 +00001371 for (const auto &P : *uses) {
1372 const VarDecl *vd = P.first;
1373 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001374
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001375 UsesVec *vec = V.getPointer();
1376 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001377
1378 // Specially handle the case where we have uses of an uninitialized
1379 // variable, but the root cause is an idiomatic self-init. We want
1380 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001381 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001382 DiagnoseUninitializedUse(S, vd,
1383 UninitUse(vd->getInit()->IgnoreParenCasts(),
1384 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001385 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001386 else {
1387 // Sort the uses by their SourceLocations. While not strictly
1388 // guaranteed to produce them in line/column order, this will provide
1389 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001390 std::sort(vec->begin(), vec->end(),
1391 [](const UninitUse &a, const UninitUse &b) {
1392 // Prefer a more confident report over a less confident one.
1393 if (a.getKind() != b.getKind())
1394 return a.getKind() > b.getKind();
1395 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1396 });
1397
Aaron Ballmane5195222014-05-15 20:50:47 +00001398 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001399 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001400 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001401
1402 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001403 // Skip further diagnostics for this variable. We try to warn only
1404 // on the first point at which a variable is used uninitialized.
1405 break;
1406 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001407 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001408
1409 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001410 delete vec;
1411 }
1412 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001413 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001414
1415private:
1416 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001417 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1418 return U.getKind() == UninitUse::Always ||
1419 U.getKind() == UninitUse::AfterCall ||
1420 U.getKind() == UninitUse::AfterDecl;
1421 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001422 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001423};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001424}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001425
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001426namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001427namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001428typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001429typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001430typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001431
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001432struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001433 SourceManager &SM;
1434 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001435
1436 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1437 // Although this call will be slow, this is only called when outputting
1438 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001439 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001440 }
1441};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001442}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001443
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001444//===----------------------------------------------------------------------===//
1445// -Wthread-safety
1446//===----------------------------------------------------------------------===//
1447namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001448namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001449namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001450class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001451 Sema &S;
1452 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001453 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001454
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001455 const FunctionDecl *CurrentFunction;
1456 bool Verbose;
1457
Aaron Ballman71291bc2014-08-15 12:38:17 +00001458 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001459 if (Verbose && CurrentFunction) {
1460 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001461 S.PDiag(diag::note_thread_warning_in_fun)
1462 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001463 return OptionalNotes(1, FNote);
1464 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001465 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001466 }
1467
Aaron Ballman71291bc2014-08-15 12:38:17 +00001468 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001469 OptionalNotes ONS(1, Note);
1470 if (Verbose && CurrentFunction) {
1471 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001472 S.PDiag(diag::note_thread_warning_in_fun)
1473 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001474 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001475 }
1476 return ONS;
1477 }
1478
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001479 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1480 const PartialDiagnosticAt &Note2) const {
1481 OptionalNotes ONS;
1482 ONS.push_back(Note1);
1483 ONS.push_back(Note2);
1484 if (Verbose && CurrentFunction) {
1485 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1486 S.PDiag(diag::note_thread_warning_in_fun)
1487 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001488 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001489 }
1490 return ONS;
1491 }
1492
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001493 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001494 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1495 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001496 // Gracefully handle rare cases when the analysis can't get a more
1497 // precise source location.
1498 if (!Loc.isValid())
1499 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001500 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001501 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001502 }
1503
1504 public:
Richard Smith92286672012-02-03 04:45:26 +00001505 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001506 : S(S), FunLocation(FL), FunEndLocation(FEL),
1507 CurrentFunction(nullptr), Verbose(false) {}
1508
1509 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001510
1511 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1512 /// We need to output diagnostics produced while iterating through
1513 /// the lockset in deterministic order, so this function orders diagnostics
1514 /// and outputs them.
1515 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001516 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001517 for (const auto &Diag : Warnings) {
1518 S.Diag(Diag.first.first, Diag.first.second);
1519 for (const auto &Note : Diag.second)
1520 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001521 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001522 }
1523
Aaron Ballmane0449042014-04-01 21:43:23 +00001524 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1525 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1526 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001527 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001528 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001529
Aaron Ballmane0449042014-04-01 21:43:23 +00001530 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1531 SourceLocation Loc) override {
1532 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001533 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001534
Aaron Ballmane0449042014-04-01 21:43:23 +00001535 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1536 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001537 SourceLocation Loc) override {
1538 if (Loc.isInvalid())
1539 Loc = FunLocation;
1540 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001541 << Kind << LockName << Received
1542 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001543 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001544 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001545
Aaron Ballmane0449042014-04-01 21:43:23 +00001546 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1547 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001548 }
1549
Aaron Ballmane0449042014-04-01 21:43:23 +00001550 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1551 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001552 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001553 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001554 unsigned DiagID = 0;
1555 switch (LEK) {
1556 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001557 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001558 break;
1559 case LEK_LockedSomeLoopIterations:
1560 DiagID = diag::warn_expecting_lock_held_on_loop;
1561 break;
1562 case LEK_LockedAtEndOfFunction:
1563 DiagID = diag::warn_no_unlock;
1564 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001565 case LEK_NotLockedAtEndOfFunction:
1566 DiagID = diag::warn_expecting_locked;
1567 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001568 }
Richard Smith92286672012-02-03 04:45:26 +00001569 if (LocEndOfScope.isInvalid())
1570 LocEndOfScope = FunEndLocation;
1571
Aaron Ballmane0449042014-04-01 21:43:23 +00001572 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1573 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001574 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001575 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1576 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001577 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001578 return;
1579 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001580 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001581 }
1582
Aaron Ballmane0449042014-04-01 21:43:23 +00001583 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1584 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001585 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001586 PartialDiagnosticAt Warning(Loc1,
1587 S.PDiag(diag::warn_lock_exclusive_and_shared)
1588 << Kind << LockName);
1589 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1590 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001591 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001592 }
1593
Aaron Ballmane0449042014-04-01 21:43:23 +00001594 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1595 ProtectedOperationKind POK, AccessKind AK,
1596 SourceLocation Loc) override {
1597 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1598 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001599 unsigned DiagID = POK == POK_VarAccess?
1600 diag::warn_variable_requires_any_lock:
1601 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001602 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001603 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001604 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001605 }
1606
Aaron Ballmane0449042014-04-01 21:43:23 +00001607 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1608 ProtectedOperationKind POK, Name LockName,
1609 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001610 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001611 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001612 if (PossibleMatch) {
1613 switch (POK) {
1614 case POK_VarAccess:
1615 DiagID = diag::warn_variable_requires_lock_precise;
1616 break;
1617 case POK_VarDereference:
1618 DiagID = diag::warn_var_deref_requires_lock_precise;
1619 break;
1620 case POK_FunctionCall:
1621 DiagID = diag::warn_fun_requires_lock_precise;
1622 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001623 case POK_PassByRef:
1624 DiagID = diag::warn_guarded_pass_by_reference;
1625 break;
1626 case POK_PtPassByRef:
1627 DiagID = diag::warn_pt_guarded_pass_by_reference;
1628 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001629 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001630 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1631 << D->getNameAsString()
1632 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001633 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001634 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001635 if (Verbose && POK == POK_VarAccess) {
1636 PartialDiagnosticAt VNote(D->getLocation(),
1637 S.PDiag(diag::note_guarded_by_declared_here)
1638 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001639 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001640 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001641 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001642 } else {
1643 switch (POK) {
1644 case POK_VarAccess:
1645 DiagID = diag::warn_variable_requires_lock;
1646 break;
1647 case POK_VarDereference:
1648 DiagID = diag::warn_var_deref_requires_lock;
1649 break;
1650 case POK_FunctionCall:
1651 DiagID = diag::warn_fun_requires_lock;
1652 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001653 case POK_PassByRef:
1654 DiagID = diag::warn_guarded_pass_by_reference;
1655 break;
1656 case POK_PtPassByRef:
1657 DiagID = diag::warn_pt_guarded_pass_by_reference;
1658 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001659 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001660 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1661 << D->getNameAsString()
1662 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001663 if (Verbose && POK == POK_VarAccess) {
1664 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001665 S.PDiag(diag::note_guarded_by_declared_here)
1666 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001667 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001668 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001669 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001670 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001671 }
1672
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001673 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1674 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001675 PartialDiagnosticAt Warning(Loc,
1676 S.PDiag(diag::warn_acquire_requires_negative_cap)
1677 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001678 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001679 }
1680
1681
Aaron Ballmane0449042014-04-01 21:43:23 +00001682 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001683 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001684 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1685 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001686 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001687 }
1688
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001689 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1690 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001691 PartialDiagnosticAt Warning(Loc,
1692 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001693 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001694 }
1695
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001696 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001697 PartialDiagnosticAt Warning(Loc,
1698 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001699 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001700 }
1701
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001702 void enterFunction(const FunctionDecl* FD) override {
1703 CurrentFunction = FD;
1704 }
1705
1706 void leaveFunction(const FunctionDecl* FD) override {
1707 CurrentFunction = 0;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001708 }
1709};
Benjamin Kramer539803c2015-03-19 14:23:45 +00001710} // namespace
1711} // namespace threadSafety
1712} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001713
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001714//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001715// -Wconsumed
1716//===----------------------------------------------------------------------===//
1717
1718namespace clang {
1719namespace consumed {
1720namespace {
1721class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1722
1723 Sema &S;
1724 DiagList Warnings;
1725
1726public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001727
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001728 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001729
1730 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001731 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001732 for (const auto &Diag : Warnings) {
1733 S.Diag(Diag.first.first, Diag.first.second);
1734 for (const auto &Note : Diag.second)
1735 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001736 }
1737 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001738
1739 void warnLoopStateMismatch(SourceLocation Loc,
1740 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001741 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1742 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001743
1744 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001745 }
1746
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001747 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1748 StringRef VariableName,
1749 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001750 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001751
1752 PartialDiagnosticAt Warning(Loc, S.PDiag(
1753 diag::warn_param_return_typestate_mismatch) << VariableName <<
1754 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001755
1756 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001757 }
1758
DeLesley Hutchins69391772013-10-17 23:23:53 +00001759 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001760 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001761
1762 PartialDiagnosticAt Warning(Loc, S.PDiag(
1763 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001764
1765 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001766 }
1767
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001768 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001769 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001770 PartialDiagnosticAt Warning(Loc, S.PDiag(
1771 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001772
1773 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001774 }
1775
1776 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001777 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001778
1779 PartialDiagnosticAt Warning(Loc, S.PDiag(
1780 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001781
1782 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001783 }
1784
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001785 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001786 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001787
1788 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001789 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001790
1791 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001792 }
1793
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001794 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001795 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001796
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001797 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1798 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001799
1800 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001801 }
1802};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001803}}}
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001804
1805//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001806// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1807// warnings on a function, method, or block.
1808//===----------------------------------------------------------------------===//
1809
Ted Kremenek0b405322010-03-23 00:13:23 +00001810clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1811 enableCheckFallThrough = 1;
1812 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001813 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001814 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001815}
1816
Ted Kremenekad8753c2014-03-15 05:47:06 +00001817static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001818 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001819}
1820
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001821clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1822 : S(s),
1823 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001824 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001825 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001826 MaxCFGBlocksPerFunction(0),
1827 NumUninitAnalysisFunctions(0),
1828 NumUninitAnalysisVariables(0),
1829 MaxUninitAnalysisVariablesPerFunction(0),
1830 NumUninitAnalysisBlockVisits(0),
1831 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001832
1833 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001834 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001835
1836 DefaultPolicy.enableCheckUnreachable =
1837 isEnabled(D, warn_unreachable) ||
1838 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001839 isEnabled(D, warn_unreachable_return) ||
1840 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001841
1842 DefaultPolicy.enableThreadSafetyAnalysis =
1843 isEnabled(D, warn_double_lock);
1844
1845 DefaultPolicy.enableConsumedAnalysis =
1846 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001847}
1848
Aaron Ballmane5195222014-05-15 20:50:47 +00001849static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1850 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001851 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001852}
1853
Ted Kremenek0b405322010-03-23 00:13:23 +00001854void clang::sema::
1855AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001856 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001857 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001858
Ted Kremenek918fe842010-03-20 21:06:02 +00001859 // We avoid doing analysis-based warnings when there are errors for
1860 // two reasons:
1861 // (1) The CFGs often can't be constructed (if the body is invalid), so
1862 // don't bother trying.
1863 // (2) The code already has problems; running the analysis just takes more
1864 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001865 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001866
Ted Kremenek0b405322010-03-23 00:13:23 +00001867 // Do not do any analysis for declarations in system headers if we are
1868 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001869 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001870 S.SourceMgr.isInSystemHeader(D->getLocation()))
1871 return;
1872
John McCall1d570a72010-08-25 05:56:39 +00001873 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001874 if (cast<DeclContext>(D)->isDependentContext())
1875 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001876
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001877 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001878 // Flush out any possibly unreachable diagnostics.
1879 flushDiagnostics(S, fscope);
1880 return;
1881 }
1882
Ted Kremenek918fe842010-03-20 21:06:02 +00001883 const Stmt *Body = D->getBody();
1884 assert(Body);
1885
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001886 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00001887 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001888
Ted Kremenek918fe842010-03-20 21:06:02 +00001889 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001890 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001891 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1892 AC.getCFGBuildOptions().AddEHEdges = false;
1893 AC.getCFGBuildOptions().AddInitializers = true;
1894 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001895 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001896 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00001897 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001898
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001899 // Force that certain expressions appear as CFGElements in the CFG. This
1900 // is used to speed up various analyses.
1901 // FIXME: This isn't the right factoring. This is here for initial
1902 // prototyping, but we need a way for analyses to say what expressions they
1903 // expect to always be CFGElements and then fill in the BuildOptions
1904 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001905 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1906 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001907 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001908 AC.getCFGBuildOptions().setAllAlwaysAdd();
1909 }
1910 else {
1911 AC.getCFGBuildOptions()
1912 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001913 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001914 .setAlwaysAdd(Stmt::BlockExprClass)
1915 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1916 .setAlwaysAdd(Stmt::DeclRefExprClass)
1917 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001918 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1919 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001920 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001921
Richard Trieue9fa2662014-04-15 00:57:50 +00001922 // Install the logical handler for -Wtautological-overlap-compare
1923 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001924 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1925 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00001926 LEH.reset(new LogicalErrorHandler(S));
1927 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00001928 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001929
Ted Kremenek3427fac2011-02-23 01:52:04 +00001930 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001931 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001932 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001933
1934 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00001935 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1936 if (D.stmt)
1937 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00001938 }
1939
1940 if (AC.getCFG()) {
1941 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00001942 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00001943 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00001944 if (D.stmt) {
1945 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001946 CFGReverseBlockReachabilityAnalysis *cra =
1947 AC.getCFGReachablityAnalysis();
1948 // FIXME: We should be able to assert that block is non-null, but
1949 // the CFG analysis can skip potentially-evaluated expressions in
1950 // edge cases; see test/Sema/vla-2.c.
1951 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001952 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001953 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001954 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001955 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001956 }
1957 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001958 if (!processed) {
1959 // Emit the warning anyway if we cannot map to a basic block.
1960 S.Diag(D.Loc, D.PD);
1961 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001962 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001963 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001964
1965 if (!analyzed)
1966 flushDiagnostics(S, fscope);
1967 }
1968
1969
Ted Kremenek918fe842010-03-20 21:06:02 +00001970 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001971 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001972 const CheckFallThroughDiagnostics &CD =
1973 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001974 : (isa<CXXMethodDecl>(D) &&
1975 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1976 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1977 ? CheckFallThroughDiagnostics::MakeForLambda()
1978 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001979 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001980 }
1981
1982 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001983 if (P.enableCheckUnreachable) {
1984 // Only check for unreachable code on non-template instantiations.
1985 // Different template instantiations can effectively change the control-flow
1986 // and it is very difficult to prove that a snippet of code in a template
1987 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001988 bool isTemplateInstantiation = false;
1989 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1990 isTemplateInstantiation = Function->isTemplateInstantiation();
1991 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001992 CheckUnreachable(S, AC);
1993 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001994
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001995 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001996 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001997 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001998 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001999 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002000 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002001 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002002 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2003 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002004
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002005 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2006 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002007 Reporter.emitDiagnostics();
2008 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002009
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002010 // Check for violations of consumed properties.
2011 if (P.enableConsumedAnalysis) {
2012 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002013 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002014 Analyzer.run(AC);
2015 }
2016
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002017 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2018 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2019 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002020 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002021 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002022 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002023 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002024 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002025 reporter, stats);
2026
2027 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2028 ++NumUninitAnalysisFunctions;
2029 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2030 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2031 MaxUninitAnalysisVariablesPerFunction =
2032 std::max(MaxUninitAnalysisVariablesPerFunction,
2033 stats.NumVariablesAnalyzed);
2034 MaxUninitAnalysisBlockVisitsPerFunction =
2035 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2036 stats.NumBlockVisits);
2037 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002038 }
2039 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002040
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002041 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002042 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2043 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2044 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Alexis Hunt2178f142012-06-15 21:22:05 +00002045 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002046 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002047 }
2048
Jordan Rosed3934582012-09-28 22:21:30 +00002049 if (S.getLangOpts().ObjCARCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002050 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002051 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002052
Richard Trieu2f024f42013-12-21 02:33:43 +00002053
2054 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002055 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2056 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002057 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2058 checkRecursiveFunction(S, FD, Body, AC);
2059 }
2060 }
2061
Richard Trieue9fa2662014-04-15 00:57:50 +00002062 // If none of the previous checks caused a CFG build, trigger one here
2063 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002064 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002065 D->getLocStart())) {
2066 AC.getCFG();
2067 }
2068
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002069 // Collect statistics about the CFG if it was built.
2070 if (S.CollectStats && AC.isCFGBuilt()) {
2071 ++NumFunctionsAnalyzed;
2072 if (CFG *cfg = AC.getCFG()) {
2073 // If we successfully built a CFG for this context, record some more
2074 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002075 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002076 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002077 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002078 } else {
2079 ++NumFunctionsWithBadCFGs;
2080 }
2081 }
2082}
2083
2084void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2085 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2086
2087 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2088 unsigned AvgCFGBlocksPerFunction =
2089 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2090 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2091 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2092 << " " << NumCFGBlocks << " CFG blocks built.\n"
2093 << " " << AvgCFGBlocksPerFunction
2094 << " average CFG blocks per function.\n"
2095 << " " << MaxCFGBlocksPerFunction
2096 << " max CFG blocks per function.\n";
2097
2098 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2099 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2100 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2101 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2102 llvm::errs() << NumUninitAnalysisFunctions
2103 << " functions analyzed for uninitialiazed variables\n"
2104 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2105 << " " << AvgUninitVariablesPerFunction
2106 << " average variables per function.\n"
2107 << " " << MaxUninitAnalysisVariablesPerFunction
2108 << " max variables per function.\n"
2109 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2110 << " " << AvgUninitBlockVisitsPerFunction
2111 << " average block visits per function.\n"
2112 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2113 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002114}