blob: 3f2c41b67bcc0ce0d48519d3084137e6962b2a2e [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Lex/Preprocessor.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
Alexander Kornienkoe61e5622012-09-28 22:24:03 +000040#include "llvm/ADT/ArrayRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000041#include "llvm/ADT/BitVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000042#include "llvm/ADT/FoldingSet.h"
43#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000044#include "llvm/ADT/MapVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000045#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000046#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000047#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000048#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000049#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000050#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000051#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000052#include <iterator>
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000053#include <vector>
Ted Kremenek918fe842010-03-20 21:06:02 +000054
55using namespace clang;
56
57//===----------------------------------------------------------------------===//
58// Unreachable code analysis.
59//===----------------------------------------------------------------------===//
60
61namespace {
62 class UnreachableCodeHandler : public reachable_code::Callback {
63 Sema &S;
64 public:
65 UnreachableCodeHandler(Sema &s) : S(s) {}
66
Ted Kremenek1a8641c2014-03-15 01:26:32 +000067 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000068 SourceLocation L,
69 SourceRange SilenceableCondVal,
70 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000071 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000072 unsigned diag = diag::warn_unreachable;
73 switch (UK) {
74 case reachable_code::UK_Break:
75 diag = diag::warn_unreachable_break;
76 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000077 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000078 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000079 break;
Ted Kremenek14210372014-03-21 06:02:36 +000080 case reachable_code::UK_Loop_Increment:
81 diag = diag::warn_unreachable_loop_increment;
82 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000083 case reachable_code::UK_Other:
84 break;
85 }
86
87 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000088
89 SourceLocation Open = SilenceableCondVal.getBegin();
90 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000091 SourceLocation Close = SilenceableCondVal.getEnd();
92 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000093 if (Close.isValid()) {
94 S.Diag(Open, diag::note_unreachable_silence)
95 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
96 << FixItHint::CreateInsertion(Close, ")");
97 }
98 }
Ted Kremenek918fe842010-03-20 21:06:02 +000099 }
100 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000101} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +0000102
103/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000104static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000105 // As a heuristic prune all diagnostics not in the main file. Currently
106 // the majority of warnings in headers are false positives. These
107 // are largely caused by configuration state, e.g. preprocessor
108 // defined code, etc.
109 //
110 // Note that this is also a performance optimization. Analyzing
111 // headers many times can be expensive.
112 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
113 return;
114
Ted Kremenek918fe842010-03-20 21:06:02 +0000115 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000116 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000117}
118
Benjamin Kramer3a002252015-02-16 16:53:12 +0000119namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000120/// \brief Warn on logical operator errors in CFGBuilder
121class LogicalErrorHandler : public CFGCallback {
122 Sema &S;
123
124public:
125 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
126
127 static bool HasMacroID(const Expr *E) {
128 if (E->getExprLoc().isMacroID())
129 return true;
130
131 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000132 for (const Stmt *SubStmt : E->children())
133 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
134 if (HasMacroID(SubExpr))
135 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000136
137 return false;
138 }
139
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000140 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000141 if (HasMacroID(B))
142 return;
143
144 SourceRange DiagRange = B->getSourceRange();
145 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
146 << DiagRange << isAlwaysTrue;
147 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000148
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000149 void compareBitwiseEquality(const BinaryOperator *B,
150 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000151 if (HasMacroID(B))
152 return;
153
154 SourceRange DiagRange = B->getSourceRange();
155 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
156 << DiagRange << isAlwaysTrue;
157 }
Richard Trieuf935b562014-04-05 05:17:01 +0000158};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000159} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000160
Ted Kremenek918fe842010-03-20 21:06:02 +0000161//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000162// Check for infinite self-recursion in functions
163//===----------------------------------------------------------------------===//
164
Richard Trieu6995de92015-08-21 03:43:09 +0000165// Returns true if the function is called anywhere within the CFGBlock.
166// For member functions, the additional condition of being call from the
167// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000168static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000169 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000170 for (const auto &B : Block) {
171 if (B.getKind() != CFGElement::Statement)
172 continue;
173
174 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
175 if (!CE || !CE->getCalleeDecl() ||
176 CE->getCalleeDecl()->getCanonicalDecl() != FD)
177 continue;
178
179 // Skip function calls which are qualified with a templated class.
180 if (const DeclRefExpr *DRE =
181 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
182 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
183 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
184 isa<TemplateSpecializationType>(NNS->getAsType())) {
185 continue;
186 }
187 }
188 }
189
190 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
191 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
192 !MCE->getMethodDecl()->isVirtual())
193 return true;
194 }
195 return false;
196}
197
Richard Trieu6995de92015-08-21 03:43:09 +0000198// All blocks are in one of three states. States are ordered so that blocks
199// can only move to higher states.
200enum RecursiveState {
201 FoundNoPath,
202 FoundPath,
203 FoundPathWithNoRecursiveCall
204};
205
206// Returns true if there exists a path to the exit block and every path
207// to the exit block passes through a call to FD.
208static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
209
210 const unsigned ExitID = cfg->getExit().getBlockID();
211
212 // Mark all nodes as FoundNoPath, then set the status of the entry block.
213 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
214 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
215
216 // Make the processing stack and seed it with the entry block.
217 SmallVector<CFGBlock *, 16> Stack;
218 Stack.push_back(&cfg->getEntry());
Richard Trieu2f024f42013-12-21 02:33:43 +0000219
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000220 while (!Stack.empty()) {
Richard Trieu6995de92015-08-21 03:43:09 +0000221 CFGBlock *CurBlock = Stack.back();
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000222 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000223
Richard Trieu6995de92015-08-21 03:43:09 +0000224 unsigned ID = CurBlock->getBlockID();
225 RecursiveState CurState = States[ID];
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000226
227 if (CurState == FoundPathWithNoRecursiveCall) {
228 // Found a path to the exit node without a recursive call.
229 if (ExitID == ID)
Richard Trieu6995de92015-08-21 03:43:09 +0000230 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000231
Richard Trieu6995de92015-08-21 03:43:09 +0000232 // Only change state if the block has a recursive call.
233 if (hasRecursiveCallInPath(FD, *CurBlock))
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000234 CurState = FoundPath;
235 }
236
Richard Trieu6995de92015-08-21 03:43:09 +0000237 // Loop over successor blocks and add them to the Stack if their state
238 // changes.
239 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
240 if (*I) {
241 unsigned next_ID = (*I)->getBlockID();
242 if (States[next_ID] < CurState) {
243 States[next_ID] = CurState;
244 Stack.push_back(*I);
245 }
246 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000247 }
Richard Trieu6995de92015-08-21 03:43:09 +0000248
249 // Return true if the exit node is reachable, and only reachable through
250 // a recursive call.
251 return States[ExitID] == FoundPath;
Richard Trieu2f024f42013-12-21 02:33:43 +0000252}
253
254static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000255 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000256 FD = FD->getCanonicalDecl();
257
258 // Only run on non-templated functions and non-templated members of
259 // templated classes.
260 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
261 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
262 return;
263
264 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000265 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000266
267 // If the exit block is unreachable, skip processing the function.
268 if (cfg->getExit().pred_empty())
269 return;
270
Richard Trieu6995de92015-08-21 03:43:09 +0000271 // Emit diagnostic if a recursive function call is detected for all paths.
272 if (checkForRecursiveFunctionCall(FD, cfg))
Richard Trieu2f024f42013-12-21 02:33:43 +0000273 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
274}
275
276//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000277// Check for missing return value.
278//===----------------------------------------------------------------------===//
279
John McCall5c6ec8c2010-05-16 09:34:11 +0000280enum ControlFlowKind {
281 UnknownFallThrough,
282 NeverFallThrough,
283 MaybeFallThrough,
284 AlwaysFallThrough,
285 NeverFallThroughOrReturn
286};
Ted Kremenek918fe842010-03-20 21:06:02 +0000287
288/// CheckFallThrough - Check that we don't fall off the end of a
289/// Statement that should return a value.
290///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000291/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
292/// MaybeFallThrough iff we might or might not fall off the end,
293/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
294/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000295/// statement but we may return. We assume that functions not marked noreturn
296/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000297static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000298 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000299 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000300
301 // The CFG leaves in dead things, and we don't want the dead code paths to
302 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000303 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000304 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000305 live);
306
307 bool AddEHEdges = AC.getAddEHEdges();
308 if (!AddEHEdges && count != cfg->getNumBlockIDs())
309 // When there are things remaining dead, and we didn't add EH edges
310 // from CallExprs to the catch clauses, we have to go back and
311 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000312 for (const auto *B : *cfg) {
313 if (!live[B->getBlockID()]) {
314 if (B->pred_begin() == B->pred_end()) {
315 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000316 // When not adding EH edges from calls, catch clauses
317 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000318 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000319 continue;
320 }
321 }
322 }
323
324 // Now we know what is live, we check the live precessors of the exit block
325 // and look for fall through paths, being careful to ignore normal returns,
326 // and exceptional paths.
327 bool HasLiveReturn = false;
328 bool HasFakeEdge = false;
329 bool HasPlainEdge = false;
330 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000331
332 // Ignore default cases that aren't likely to be reachable because all
333 // enums in a switch(X) have explicit case statements.
334 CFGBlock::FilterOptions FO;
335 FO.IgnoreDefaultsWithCoveredEnums = 1;
336
337 for (CFGBlock::filtered_pred_iterator
338 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
339 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000340 if (!live[B.getBlockID()])
341 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000342
Chandler Carruth03faf782011-09-13 09:53:58 +0000343 // Skip blocks which contain an element marked as no-return. They don't
344 // represent actually viable edges into the exit block, so mark them as
345 // abnormal.
346 if (B.hasNoReturnElement()) {
347 HasAbnormalEdge = true;
348 continue;
349 }
350
Ted Kremenek5d068492011-01-26 04:49:52 +0000351 // Destructors can appear after the 'return' in the CFG. This is
352 // normal. We need to look pass the destructors for the return
353 // statement (if it exists).
354 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000355
Chandler Carruth03faf782011-09-13 09:53:58 +0000356 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000357 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000358 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000359
Ted Kremenek5d068492011-01-26 04:49:52 +0000360 // No more CFGElements in the block?
361 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000362 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
363 HasAbnormalEdge = true;
364 continue;
365 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000366 // A labeled empty statement, or the entry block...
367 HasPlainEdge = true;
368 continue;
369 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000370
David Blaikie2a01f5d2013-02-21 20:58:29 +0000371 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000372 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000373 if (isa<ReturnStmt>(S)) {
374 HasLiveReturn = true;
375 continue;
376 }
377 if (isa<ObjCAtThrowStmt>(S)) {
378 HasFakeEdge = true;
379 continue;
380 }
381 if (isa<CXXThrowExpr>(S)) {
382 HasFakeEdge = true;
383 continue;
384 }
Chad Rosier32503022012-06-11 20:47:18 +0000385 if (isa<MSAsmStmt>(S)) {
386 // TODO: Verify this is correct.
387 HasFakeEdge = true;
388 HasLiveReturn = true;
389 continue;
390 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000391 if (isa<CXXTryStmt>(S)) {
392 HasAbnormalEdge = true;
393 continue;
394 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000395 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
396 == B.succ_end()) {
397 HasAbnormalEdge = true;
398 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000399 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000400
401 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000402 }
403 if (!HasPlainEdge) {
404 if (HasLiveReturn)
405 return NeverFallThrough;
406 return NeverFallThroughOrReturn;
407 }
408 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
409 return MaybeFallThrough;
410 // This says AlwaysFallThrough for calls to functions that are not marked
411 // noreturn, that don't return. If people would like this warning to be more
412 // accurate, such functions should be marked as noreturn.
413 return AlwaysFallThrough;
414}
415
Dan Gohman28ade552010-07-26 21:25:24 +0000416namespace {
417
Ted Kremenek918fe842010-03-20 21:06:02 +0000418struct CheckFallThroughDiagnostics {
419 unsigned diag_MaybeFallThrough_HasNoReturn;
420 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
421 unsigned diag_AlwaysFallThrough_HasNoReturn;
422 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
423 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000424 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000425 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000426
Douglas Gregor24f27692010-04-16 23:28:44 +0000427 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000428 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000429 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000430 D.diag_MaybeFallThrough_HasNoReturn =
431 diag::warn_falloff_noreturn_function;
432 D.diag_MaybeFallThrough_ReturnsNonVoid =
433 diag::warn_maybe_falloff_nonvoid_function;
434 D.diag_AlwaysFallThrough_HasNoReturn =
435 diag::warn_falloff_noreturn_function;
436 D.diag_AlwaysFallThrough_ReturnsNonVoid =
437 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000438
439 // Don't suggest that virtual functions be marked "noreturn", since they
440 // might be overridden by non-noreturn functions.
441 bool isVirtualMethod = false;
442 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
443 isVirtualMethod = Method->isVirtual();
444
Douglas Gregor0de57202011-10-10 18:15:57 +0000445 // Don't suggest that template instantiations be marked "noreturn"
446 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000447 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
448 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000449
450 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000451 D.diag_NeverFallThroughOrReturn =
452 diag::warn_suggest_noreturn_function;
453 else
454 D.diag_NeverFallThroughOrReturn = 0;
455
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000456 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000457 return D;
458 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000459
Ted Kremenek918fe842010-03-20 21:06:02 +0000460 static CheckFallThroughDiagnostics MakeForBlock() {
461 CheckFallThroughDiagnostics D;
462 D.diag_MaybeFallThrough_HasNoReturn =
463 diag::err_noreturn_block_has_return_expr;
464 D.diag_MaybeFallThrough_ReturnsNonVoid =
465 diag::err_maybe_falloff_nonvoid_block;
466 D.diag_AlwaysFallThrough_HasNoReturn =
467 diag::err_noreturn_block_has_return_expr;
468 D.diag_AlwaysFallThrough_ReturnsNonVoid =
469 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000470 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000471 D.funMode = Block;
472 return D;
473 }
474
475 static CheckFallThroughDiagnostics MakeForLambda() {
476 CheckFallThroughDiagnostics D;
477 D.diag_MaybeFallThrough_HasNoReturn =
478 diag::err_noreturn_lambda_has_return_expr;
479 D.diag_MaybeFallThrough_ReturnsNonVoid =
480 diag::warn_maybe_falloff_nonvoid_lambda;
481 D.diag_AlwaysFallThrough_HasNoReturn =
482 diag::err_noreturn_lambda_has_return_expr;
483 D.diag_AlwaysFallThrough_ReturnsNonVoid =
484 diag::warn_falloff_nonvoid_lambda;
485 D.diag_NeverFallThroughOrReturn = 0;
486 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000487 return D;
488 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000489
David Blaikie9c902b52011-09-25 23:23:43 +0000490 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000491 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000492 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000493 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000494 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
495 FuncLoc)) &&
496 (!HasNoReturn ||
497 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
498 FuncLoc)) &&
499 (!ReturnsVoid ||
500 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000501 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000502
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000503 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000504 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000505 }
506};
507
Hans Wennborgdcfba332015-10-06 23:40:43 +0000508} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000509
Ted Kremenek918fe842010-03-20 21:06:02 +0000510/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
511/// function that should return a value. Check that we don't fall off the end
512/// of a noreturn function. We assume that functions and blocks not marked
513/// noreturn will return.
514static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000515 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000516 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000517 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000518
519 bool ReturnsVoid = false;
520 bool HasNoReturn = false;
521
522 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000523 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000524 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000525 }
526 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000527 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000528 HasNoReturn = MD->hasAttr<NoReturnAttr>();
529 }
530 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000531 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000532 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000533 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000534 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000535 ReturnsVoid = true;
536 if (FT->getNoReturnAttr())
537 HasNoReturn = true;
538 }
539 }
540
David Blaikie9c902b52011-09-25 23:23:43 +0000541 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000542
543 // Short circuit for compilation speed.
544 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
545 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000546
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000547 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
548 // Either in a function body compound statement, or a function-try-block.
549 switch (CheckFallThrough(AC)) {
550 case UnknownFallThrough:
551 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000552
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000553 case MaybeFallThrough:
554 if (HasNoReturn)
555 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
556 else if (!ReturnsVoid)
557 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
558 break;
559 case AlwaysFallThrough:
560 if (HasNoReturn)
561 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
562 else if (!ReturnsVoid)
563 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
564 break;
565 case NeverFallThroughOrReturn:
566 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
568 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
569 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
570 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
571 } else {
572 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000573 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000574 }
575 break;
576 case NeverFallThrough:
577 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000578 }
579}
580
581//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000582// -Wuninitialized
583//===----------------------------------------------------------------------===//
584
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000585namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000586/// ContainsReference - A visitor class to search for references to
587/// a particular declaration (the needle) within any evaluated component of an
588/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000589class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000590 bool FoundReference;
591 const DeclRefExpr *Needle;
592
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000593public:
Scott Douglass503fc392015-06-10 13:53:15 +0000594 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000595
Scott Douglass503fc392015-06-10 13:53:15 +0000596 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
597 : Inherited(Context), FoundReference(false), Needle(Needle) {}
598
599 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000600 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000601 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000602 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000603
Scott Douglass503fc392015-06-10 13:53:15 +0000604 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000605 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000606
Scott Douglass503fc392015-06-10 13:53:15 +0000607 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000608 if (E == Needle)
609 FoundReference = true;
610 else
Scott Douglass503fc392015-06-10 13:53:15 +0000611 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000612 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000613
614 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000615};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000616} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000617
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000618static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000619 QualType VariableTy = VD->getType().getCanonicalType();
620 if (VariableTy->isBlockPointerType() &&
621 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000622 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
623 << VD->getDeclName()
624 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000625 return true;
626 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000627
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000628 // Don't issue a fixit if there is already an initializer.
629 if (VD->getInit())
630 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000631
632 // Don't suggest a fixit inside macros.
633 if (VD->getLocEnd().isMacroID())
634 return false;
635
Alp Tokerb6cc5922014-05-03 03:45:55 +0000636 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000637
638 // Suggest possible initialization (if any).
639 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
640 if (Init.empty())
641 return false;
642
Richard Smith8d06f422012-01-12 23:53:29 +0000643 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
644 << FixItHint::CreateInsertion(Loc, Init);
645 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000646}
647
Richard Smith1bb8edb82012-05-26 06:20:46 +0000648/// Create a fixit to remove an if-like statement, on the assumption that its
649/// condition is CondVal.
650static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
651 const Stmt *Else, bool CondVal,
652 FixItHint &Fixit1, FixItHint &Fixit2) {
653 if (CondVal) {
654 // If condition is always true, remove all but the 'then'.
655 Fixit1 = FixItHint::CreateRemoval(
656 CharSourceRange::getCharRange(If->getLocStart(),
657 Then->getLocStart()));
658 if (Else) {
Craig Topper07fa1762015-11-15 02:31:46 +0000659 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000660 Fixit2 = FixItHint::CreateRemoval(
661 SourceRange(ElseKwLoc, Else->getLocEnd()));
662 }
663 } else {
664 // If condition is always false, remove all but the 'else'.
665 if (Else)
666 Fixit1 = FixItHint::CreateRemoval(
667 CharSourceRange::getCharRange(If->getLocStart(),
668 Else->getLocStart()));
669 else
670 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
671 }
672}
673
674/// DiagUninitUse -- Helper function to produce a diagnostic for an
675/// uninitialized use of a variable.
676static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
677 bool IsCapturedByBlock) {
678 bool Diagnosed = false;
679
Richard Smithba8071e2013-09-12 18:49:10 +0000680 switch (Use.getKind()) {
681 case UninitUse::Always:
682 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
683 << VD->getDeclName() << IsCapturedByBlock
684 << Use.getUser()->getSourceRange();
685 return;
686
687 case UninitUse::AfterDecl:
688 case UninitUse::AfterCall:
689 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
690 << VD->getDeclName() << IsCapturedByBlock
691 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
692 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
693 << VD->getSourceRange();
694 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
695 << IsCapturedByBlock << Use.getUser()->getSourceRange();
696 return;
697
698 case UninitUse::Maybe:
699 case UninitUse::Sometimes:
700 // Carry on to report sometimes-uninitialized branches, if possible,
701 // or a 'may be used uninitialized' diagnostic otherwise.
702 break;
703 }
704
Richard Smith1bb8edb82012-05-26 06:20:46 +0000705 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000706 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
707 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000708 assert(Use.getKind() == UninitUse::Sometimes);
709
710 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000711 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000712
713 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000714 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000715 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000716 SourceRange Range;
717
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000718 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000719 // For all binary terminators, branch 0 is taken if the condition is true,
720 // and branch 1 is taken if the condition is false.
721 int RemoveDiagKind = -1;
722 const char *FixitStr =
723 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
724 : (I->Output ? "1" : "0");
725 FixItHint Fixit1, Fixit2;
726
Richard Smithba8071e2013-09-12 18:49:10 +0000727 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000728 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000729 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000730 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000731 continue;
732
733 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000734 case Stmt::IfStmtClass: {
735 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000736 DiagKind = 0;
737 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000738 Range = IS->getCond()->getSourceRange();
739 RemoveDiagKind = 0;
740 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
741 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000742 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000743 }
744 case Stmt::ConditionalOperatorClass: {
745 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000746 DiagKind = 0;
747 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000748 Range = CO->getCond()->getSourceRange();
749 RemoveDiagKind = 0;
750 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
751 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000752 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000753 }
Richard Smith4323bf82012-05-25 02:17:09 +0000754 case Stmt::BinaryOperatorClass: {
755 const BinaryOperator *BO = cast<BinaryOperator>(Term);
756 if (!BO->isLogicalOp())
757 continue;
758 DiagKind = 0;
759 Str = BO->getOpcodeStr();
760 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000761 RemoveDiagKind = 0;
762 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
763 (BO->getOpcode() == BO_LOr && !I->Output))
764 // true && y -> y, false || y -> y.
765 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
766 BO->getOperatorLoc()));
767 else
768 // false && y -> false, true || y -> true.
769 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000770 break;
771 }
772
773 // "loop is entered / loop is exited".
774 case Stmt::WhileStmtClass:
775 DiagKind = 1;
776 Str = "while";
777 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000778 RemoveDiagKind = 1;
779 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000780 break;
781 case Stmt::ForStmtClass:
782 DiagKind = 1;
783 Str = "for";
784 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000785 RemoveDiagKind = 1;
786 if (I->Output)
787 Fixit1 = FixItHint::CreateRemoval(Range);
788 else
789 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000790 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000791 case Stmt::CXXForRangeStmtClass:
792 if (I->Output == 1) {
793 // The use occurs if a range-based for loop's body never executes.
794 // That may be impossible, and there's no syntactic fix for this,
795 // so treat it as a 'may be uninitialized' case.
796 continue;
797 }
798 DiagKind = 1;
799 Str = "for";
800 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
801 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000802
803 // "condition is true / loop is exited".
804 case Stmt::DoStmtClass:
805 DiagKind = 2;
806 Str = "do";
807 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000808 RemoveDiagKind = 1;
809 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000810 break;
811
812 // "switch case is taken".
813 case Stmt::CaseStmtClass:
814 DiagKind = 3;
815 Str = "case";
816 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
817 break;
818 case Stmt::DefaultStmtClass:
819 DiagKind = 3;
820 Str = "default";
821 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
822 break;
823 }
824
Richard Smith1bb8edb82012-05-26 06:20:46 +0000825 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
826 << VD->getDeclName() << IsCapturedByBlock << DiagKind
827 << Str << I->Output << Range;
828 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
829 << IsCapturedByBlock << User->getSourceRange();
830 if (RemoveDiagKind != -1)
831 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
832 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
833
834 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000835 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000836
837 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000838 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000839 << VD->getDeclName() << IsCapturedByBlock
840 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000841}
842
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000843/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
844/// uninitialized variable. This manages the different forms of diagnostic
845/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000846/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000847/// false.
848static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000849 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000850 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +0000851 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000852 // Inspect the initializer of the variable declaration which is
853 // being referenced prior to its initialization. We emit
854 // specialized diagnostics for self-initialization, and we
855 // specifically avoid warning about self references which take the
856 // form of:
857 //
858 // int x = x;
859 //
860 // This is used to indicate to GCC that 'x' is intentionally left
861 // uninitialized. Proven code paths which access 'x' in
862 // an uninitialized state after this will still warn.
863 if (const Expr *Initializer = VD->getInit()) {
864 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
865 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000866
Richard Trieu43a2fc72012-05-09 21:08:22 +0000867 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +0000868 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +0000869 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000870 S.Diag(DRE->getLocStart(),
871 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000872 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
873 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000874 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000875 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000876
Richard Smith1bb8edb82012-05-26 06:20:46 +0000877 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000878 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000879 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000880 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
881 S.Diag(BE->getLocStart(),
882 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000883 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000884 else
885 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000886 }
887
888 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000889 // the initializer of that declaration & we didn't already suggest
890 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000891 if (!SuggestInitializationFixit(S, VD))
Reid Klecknerf463a8a2016-04-29 00:37:43 +0000892 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
Chandler Carruth895904da2011-04-05 18:18:05 +0000893 << VD->getDeclName();
894
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000895 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000896}
897
Richard Smith84837d52012-05-03 18:27:39 +0000898namespace {
899 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
900 public:
901 FallthroughMapper(Sema &S)
902 : FoundSwitchStatements(false),
903 S(S) {
904 }
905
906 bool foundSwitchStatements() const { return FoundSwitchStatements; }
907
908 void markFallthroughVisited(const AttributedStmt *Stmt) {
909 bool Found = FallthroughStmts.erase(Stmt);
910 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000911 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000912 }
913
914 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
915
916 const AttrStmts &getFallthroughStmts() const {
917 return FallthroughStmts;
918 }
919
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000920 void fillReachableBlocks(CFG *Cfg) {
921 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
922 std::deque<const CFGBlock *> BlockQueue;
923
924 ReachableBlocks.insert(&Cfg->getEntry());
925 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000926 // Mark all case blocks reachable to avoid problems with switching on
927 // constants, covered enums, etc.
928 // These blocks can contain fall-through annotations, and we don't want to
929 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +0000930 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000931 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +0000932 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000933 BlockQueue.push_back(B);
934 }
935
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000936 while (!BlockQueue.empty()) {
937 const CFGBlock *P = BlockQueue.front();
938 BlockQueue.pop_front();
939 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
940 E = P->succ_end();
941 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +0000942 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000943 BlockQueue.push_back(*I);
944 }
945 }
946 }
947
Richard Smith84837d52012-05-03 18:27:39 +0000948 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000949 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
950
Richard Smith84837d52012-05-03 18:27:39 +0000951 int UnannotatedCnt = 0;
952 AnnotatedCnt = 0;
953
Aaron Ballmane5195222014-05-15 20:50:47 +0000954 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +0000955 while (!BlockQueue.empty()) {
956 const CFGBlock *P = BlockQueue.front();
957 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000958 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000959
960 const Stmt *Term = P->getTerminator();
961 if (Term && isa<SwitchStmt>(Term))
962 continue; // Switch statement, good.
963
964 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
965 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
966 continue; // Previous case label has no statements, good.
967
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000968 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
969 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
970 continue; // Case label is preceded with a normal label, good.
971
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000972 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000973 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
974 ElemEnd = P->rend();
975 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000976 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
977 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000978 S.Diag(AS->getLocStart(),
979 diag::warn_fallthrough_attr_unreachable);
980 markFallthroughVisited(AS);
981 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000982 break;
Richard Smith84837d52012-05-03 18:27:39 +0000983 }
984 // Don't care about other unreachable statements.
985 }
986 }
987 // If there are no unreachable statements, this may be a special
988 // case in CFG:
989 // case X: {
990 // A a; // A has a destructor.
991 // break;
992 // }
993 // // <<<< This place is represented by a 'hanging' CFG block.
994 // case Y:
995 continue;
996 }
997
998 const Stmt *LastStmt = getLastStmt(*P);
999 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1000 markFallthroughVisited(AS);
1001 ++AnnotatedCnt;
1002 continue; // Fallthrough annotation, good.
1003 }
1004
1005 if (!LastStmt) { // This block contains no executable statements.
1006 // Traverse its predecessors.
1007 std::copy(P->pred_begin(), P->pred_end(),
1008 std::back_inserter(BlockQueue));
1009 continue;
1010 }
1011
1012 ++UnannotatedCnt;
1013 }
1014 return !!UnannotatedCnt;
1015 }
1016
1017 // RecursiveASTVisitor setup.
1018 bool shouldWalkTypesOfTypeLocs() const { return false; }
1019
1020 bool VisitAttributedStmt(AttributedStmt *S) {
1021 if (asFallThroughAttr(S))
1022 FallthroughStmts.insert(S);
1023 return true;
1024 }
1025
1026 bool VisitSwitchStmt(SwitchStmt *S) {
1027 FoundSwitchStatements = true;
1028 return true;
1029 }
1030
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001031 // We don't want to traverse local type declarations. We analyze their
1032 // methods separately.
1033 bool TraverseDecl(Decl *D) { return true; }
1034
Alexander Kornienkobf911642014-06-24 15:28:21 +00001035 // We analyze lambda bodies separately. Skip them here.
1036 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1037
Richard Smith84837d52012-05-03 18:27:39 +00001038 private:
1039
1040 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1041 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1042 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1043 return AS;
1044 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001045 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001046 }
1047
1048 static const Stmt *getLastStmt(const CFGBlock &B) {
1049 if (const Stmt *Term = B.getTerminator())
1050 return Term;
1051 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1052 ElemEnd = B.rend();
1053 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001054 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1055 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001056 }
1057 // Workaround to detect a statement thrown out by CFGBuilder:
1058 // case X: {} case Y:
1059 // case X: ; case Y:
1060 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1061 if (!isa<SwitchCase>(SW->getSubStmt()))
1062 return SW->getSubStmt();
1063
Craig Topperc3ec1492014-05-26 06:22:03 +00001064 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001065 }
1066
1067 bool FoundSwitchStatements;
1068 AttrStmts FallthroughStmts;
1069 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001070 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001071 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001072} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001073
Richard Smith4f902c72016-03-08 00:32:55 +00001074static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1075 SourceLocation Loc) {
1076 TokenValue FallthroughTokens[] = {
1077 tok::l_square, tok::l_square,
1078 PP.getIdentifierInfo("fallthrough"),
1079 tok::r_square, tok::r_square
1080 };
1081
1082 TokenValue ClangFallthroughTokens[] = {
1083 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1084 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1085 tok::r_square, tok::r_square
1086 };
1087
1088 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1089
1090 StringRef MacroName;
1091 if (PreferClangAttr)
1092 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1093 if (MacroName.empty())
1094 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1095 if (MacroName.empty() && !PreferClangAttr)
1096 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1097 if (MacroName.empty())
1098 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1099 return MacroName;
1100}
1101
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001102static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001103 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001104 // Only perform this analysis when using C++11. There is no good workflow
1105 // for this warning when not using C++11. There is no good way to silence
1106 // the warning (no attribute is available) unless we are using C++11's support
1107 // for generalized attributes. Once could use pragmas to silence the warning,
1108 // but as a general solution that is gross and not in the spirit of this
1109 // warning.
1110 //
1111 // NOTE: This an intermediate solution. There are on-going discussions on
1112 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001113 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001114 return;
1115
Richard Smith84837d52012-05-03 18:27:39 +00001116 FallthroughMapper FM(S);
1117 FM.TraverseStmt(AC.getBody());
1118
1119 if (!FM.foundSwitchStatements())
1120 return;
1121
Alexis Hunt2178f142012-06-15 21:22:05 +00001122 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001123 return;
1124
Richard Smith84837d52012-05-03 18:27:39 +00001125 CFG *Cfg = AC.getCFG();
1126
1127 if (!Cfg)
1128 return;
1129
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001130 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001131
Pete Cooper57d3f142015-07-30 17:22:52 +00001132 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001133 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001134
1135 if (!Label || !isa<SwitchCase>(Label))
1136 continue;
1137
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001138 int AnnotatedCnt;
1139
Alexander Kornienko55488792013-01-25 15:49:34 +00001140 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001141 continue;
1142
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001143 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001144 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1145 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001146
1147 if (!AnnotatedCnt) {
1148 SourceLocation L = Label->getLocStart();
1149 if (L.isMacroID())
1150 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001151 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001152 const Stmt *Term = B->getTerminator();
1153 // Skip empty cases.
1154 while (B->empty() && !Term && B->succ_size() == 1) {
1155 B = *B->succ_begin();
1156 Term = B->getTerminator();
1157 }
1158 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001159 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001160 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001161 SmallString<64> TextToInsert(AnnotationSpelling);
1162 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001163 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001164 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001165 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001166 }
Richard Smith84837d52012-05-03 18:27:39 +00001167 }
1168 S.Diag(L, diag::note_insert_break_fixit) <<
1169 FixItHint::CreateInsertion(L, "break; ");
1170 }
1171 }
1172
Aaron Ballmane5195222014-05-15 20:50:47 +00001173 for (const auto *F : FM.getFallthroughStmts())
Richard Smith4f902c72016-03-08 00:32:55 +00001174 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001175}
1176
Jordan Rose25c0ea82012-10-29 17:46:47 +00001177static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1178 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001179 assert(S);
1180
1181 do {
1182 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001183 case Stmt::ForStmtClass:
1184 case Stmt::WhileStmtClass:
1185 case Stmt::CXXForRangeStmtClass:
1186 case Stmt::ObjCForCollectionStmtClass:
1187 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001188 case Stmt::DoStmtClass: {
1189 const Expr *Cond = cast<DoStmt>(S)->getCond();
1190 llvm::APSInt Val;
1191 if (!Cond->EvaluateAsInt(Val, Ctx))
1192 return true;
1193 return Val.getBoolValue();
1194 }
Jordan Rose76831c62012-10-11 16:10:19 +00001195 default:
1196 break;
1197 }
1198 } while ((S = PM.getParent(S)));
1199
1200 return false;
1201}
1202
Jordan Rosed3934582012-09-28 22:21:30 +00001203static void diagnoseRepeatedUseOfWeak(Sema &S,
1204 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001205 const Decl *D,
1206 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001207 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1208 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1209 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001210 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1211 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001212
Jordan Rose25c0ea82012-10-29 17:46:47 +00001213 ASTContext &Ctx = S.getASTContext();
1214
Jordan Rosed3934582012-09-28 22:21:30 +00001215 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1216
1217 // Extract all weak objects that are referenced more than once.
1218 SmallVector<StmtUsesPair, 8> UsesByStmt;
1219 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1220 I != E; ++I) {
1221 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001222
1223 // Find the first read of the weak object.
1224 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1225 for ( ; UI != UE; ++UI) {
1226 if (UI->isUnsafe())
1227 break;
1228 }
1229
1230 // If there were only writes to this object, don't warn.
1231 if (UI == UE)
1232 continue;
1233
Jordan Rose76831c62012-10-11 16:10:19 +00001234 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001235 // read is not within a loop, don't warn. Additionally, don't warn in a
1236 // loop if the base object is a local variable -- local variables are often
1237 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001238 if (UI == Uses.begin()) {
1239 WeakUseVector::const_iterator UI2 = UI;
1240 for (++UI2; UI2 != UE; ++UI2)
1241 if (UI2->isUnsafe())
1242 break;
1243
Jordan Rose25c0ea82012-10-29 17:46:47 +00001244 if (UI2 == UE) {
1245 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001246 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001247
1248 const WeakObjectProfileTy &Profile = I->first;
1249 if (!Profile.isExactProfile())
1250 continue;
1251
1252 const NamedDecl *Base = Profile.getBase();
1253 if (!Base)
1254 Base = Profile.getProperty();
1255 assert(Base && "A profile always has a base or property.");
1256
1257 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1258 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1259 continue;
1260 }
Jordan Rose76831c62012-10-11 16:10:19 +00001261 }
1262
Jordan Rosed3934582012-09-28 22:21:30 +00001263 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1264 }
1265
1266 if (UsesByStmt.empty())
1267 return;
1268
1269 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001270 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001271 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001272 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1273 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1274 RHS.first->getLocStart());
1275 });
Jordan Rosed3934582012-09-28 22:21:30 +00001276
1277 // Classify the current code body for better warning text.
1278 // This enum should stay in sync with the cases in
1279 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1280 // FIXME: Should we use a common classification enum and the same set of
1281 // possibilities all throughout Sema?
1282 enum {
1283 Function,
1284 Method,
1285 Block,
1286 Lambda
1287 } FunctionKind;
1288
1289 if (isa<sema::BlockScopeInfo>(CurFn))
1290 FunctionKind = Block;
1291 else if (isa<sema::LambdaScopeInfo>(CurFn))
1292 FunctionKind = Lambda;
1293 else if (isa<ObjCMethodDecl>(D))
1294 FunctionKind = Method;
1295 else
1296 FunctionKind = Function;
1297
1298 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001299 for (const auto &P : UsesByStmt) {
1300 const Stmt *FirstRead = P.first;
1301 const WeakObjectProfileTy &Key = P.second->first;
1302 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001303
Jordan Rose657b5f42012-09-28 22:21:35 +00001304 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1305 // may not contain enough information to determine that these are different
1306 // properties. We can only be 100% sure of a repeated use in certain cases,
1307 // and we adjust the diagnostic kind accordingly so that the less certain
1308 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001309 unsigned DiagKind;
1310 if (Key.isExactProfile())
1311 DiagKind = diag::warn_arc_repeated_use_of_weak;
1312 else
1313 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1314
Jordan Rose657b5f42012-09-28 22:21:35 +00001315 // Classify the weak object being accessed for better warning text.
1316 // This enum should stay in sync with the cases in
1317 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1318 enum {
1319 Variable,
1320 Property,
1321 ImplicitProperty,
1322 Ivar
1323 } ObjectKind;
1324
1325 const NamedDecl *D = Key.getProperty();
1326 if (isa<VarDecl>(D))
1327 ObjectKind = Variable;
1328 else if (isa<ObjCPropertyDecl>(D))
1329 ObjectKind = Property;
1330 else if (isa<ObjCMethodDecl>(D))
1331 ObjectKind = ImplicitProperty;
1332 else if (isa<ObjCIvarDecl>(D))
1333 ObjectKind = Ivar;
1334 else
1335 llvm_unreachable("Unexpected weak object kind!");
1336
Jordan Rosed3934582012-09-28 22:21:30 +00001337 // Show the first time the object was read.
1338 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001339 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001340 << FirstRead->getSourceRange();
1341
1342 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001343 for (const auto &Use : Uses) {
1344 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001345 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001346 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001347 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001348 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001349 }
1350 }
1351}
1352
Jordan Rosed3934582012-09-28 22:21:30 +00001353namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001354class UninitValsDiagReporter : public UninitVariablesHandler {
1355 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001356 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001357 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001358 // Prefer using MapVector to DenseMap, so that iteration order will be
1359 // the same as insertion order. This is needed to obtain a deterministic
1360 // order of diagnostics when calling flushDiagnostics().
1361 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001362 UsesMap uses;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001363
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001364public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001365 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001366 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001367
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001368 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001369 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001370 if (!V.getPointer())
1371 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001372 return V;
1373 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001374
1375 void handleUseOfUninitVariable(const VarDecl *vd,
1376 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001377 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001378 }
1379
Craig Toppere14c0f82014-03-12 04:55:44 +00001380 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001381 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001382 }
1383
1384 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001385 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001386 const VarDecl *vd = P.first;
1387 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001388
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001389 UsesVec *vec = V.getPointer();
1390 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001391
1392 // Specially handle the case where we have uses of an uninitialized
1393 // variable, but the root cause is an idiomatic self-init. We want
1394 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001395 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001396 DiagnoseUninitializedUse(S, vd,
1397 UninitUse(vd->getInit()->IgnoreParenCasts(),
1398 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001399 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001400 else {
1401 // Sort the uses by their SourceLocations. While not strictly
1402 // guaranteed to produce them in line/column order, this will provide
1403 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001404 std::sort(vec->begin(), vec->end(),
1405 [](const UninitUse &a, const UninitUse &b) {
1406 // Prefer a more confident report over a less confident one.
1407 if (a.getKind() != b.getKind())
1408 return a.getKind() > b.getKind();
1409 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1410 });
1411
Aaron Ballmane5195222014-05-15 20:50:47 +00001412 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001413 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001414 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001415
1416 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001417 // Skip further diagnostics for this variable. We try to warn only
1418 // on the first point at which a variable is used uninitialized.
1419 break;
1420 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001421 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001422
1423 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001424 delete vec;
1425 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001426
1427 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001428 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001429
1430private:
1431 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001432 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1433 return U.getKind() == UninitUse::Always ||
1434 U.getKind() == UninitUse::AfterCall ||
1435 U.getKind() == UninitUse::AfterDecl;
1436 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001437 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001438};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001439} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001440
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001441namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001442namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001443typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001444typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001445typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001446
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001447struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001448 SourceManager &SM;
1449 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001450
1451 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1452 // Although this call will be slow, this is only called when outputting
1453 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001454 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001455 }
1456};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001457} // anonymous namespace
1458} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001459
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001460//===----------------------------------------------------------------------===//
1461// -Wthread-safety
1462//===----------------------------------------------------------------------===//
1463namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001464namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001465namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001466class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001467 Sema &S;
1468 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001469 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001470
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001471 const FunctionDecl *CurrentFunction;
1472 bool Verbose;
1473
Aaron Ballman71291bc2014-08-15 12:38:17 +00001474 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001475 if (Verbose && CurrentFunction) {
1476 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001477 S.PDiag(diag::note_thread_warning_in_fun)
1478 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001479 return OptionalNotes(1, FNote);
1480 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001481 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001482 }
1483
Aaron Ballman71291bc2014-08-15 12:38:17 +00001484 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001485 OptionalNotes ONS(1, Note);
1486 if (Verbose && CurrentFunction) {
1487 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001488 S.PDiag(diag::note_thread_warning_in_fun)
1489 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001490 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001491 }
1492 return ONS;
1493 }
1494
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001495 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1496 const PartialDiagnosticAt &Note2) const {
1497 OptionalNotes ONS;
1498 ONS.push_back(Note1);
1499 ONS.push_back(Note2);
1500 if (Verbose && CurrentFunction) {
1501 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1502 S.PDiag(diag::note_thread_warning_in_fun)
1503 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001504 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001505 }
1506 return ONS;
1507 }
1508
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001509 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001510 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1511 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001512 // Gracefully handle rare cases when the analysis can't get a more
1513 // precise source location.
1514 if (!Loc.isValid())
1515 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001516 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001517 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001518 }
1519
1520 public:
Richard Smith92286672012-02-03 04:45:26 +00001521 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001522 : S(S), FunLocation(FL), FunEndLocation(FEL),
1523 CurrentFunction(nullptr), Verbose(false) {}
1524
1525 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001526
1527 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1528 /// We need to output diagnostics produced while iterating through
1529 /// the lockset in deterministic order, so this function orders diagnostics
1530 /// and outputs them.
1531 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001532 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001533 for (const auto &Diag : Warnings) {
1534 S.Diag(Diag.first.first, Diag.first.second);
1535 for (const auto &Note : Diag.second)
1536 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001537 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001538 }
1539
Aaron Ballmane0449042014-04-01 21:43:23 +00001540 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1541 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1542 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001543 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001544 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001545
Aaron Ballmane0449042014-04-01 21:43:23 +00001546 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1547 SourceLocation Loc) override {
1548 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001549 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001550
Aaron Ballmane0449042014-04-01 21:43:23 +00001551 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1552 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001553 SourceLocation Loc) override {
1554 if (Loc.isInvalid())
1555 Loc = FunLocation;
1556 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001557 << Kind << LockName << Received
1558 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001559 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001560 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001561
Aaron Ballmane0449042014-04-01 21:43:23 +00001562 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1563 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001564 }
1565
Aaron Ballmane0449042014-04-01 21:43:23 +00001566 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1567 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001568 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001569 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001570 unsigned DiagID = 0;
1571 switch (LEK) {
1572 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001573 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001574 break;
1575 case LEK_LockedSomeLoopIterations:
1576 DiagID = diag::warn_expecting_lock_held_on_loop;
1577 break;
1578 case LEK_LockedAtEndOfFunction:
1579 DiagID = diag::warn_no_unlock;
1580 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001581 case LEK_NotLockedAtEndOfFunction:
1582 DiagID = diag::warn_expecting_locked;
1583 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001584 }
Richard Smith92286672012-02-03 04:45:26 +00001585 if (LocEndOfScope.isInvalid())
1586 LocEndOfScope = FunEndLocation;
1587
Aaron Ballmane0449042014-04-01 21:43:23 +00001588 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1589 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001590 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001591 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1592 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001593 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001594 return;
1595 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001596 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001597 }
1598
Aaron Ballmane0449042014-04-01 21:43:23 +00001599 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1600 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001601 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001602 PartialDiagnosticAt Warning(Loc1,
1603 S.PDiag(diag::warn_lock_exclusive_and_shared)
1604 << Kind << LockName);
1605 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1606 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001607 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001608 }
1609
Aaron Ballmane0449042014-04-01 21:43:23 +00001610 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1611 ProtectedOperationKind POK, AccessKind AK,
1612 SourceLocation Loc) override {
1613 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1614 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001615 unsigned DiagID = POK == POK_VarAccess?
1616 diag::warn_variable_requires_any_lock:
1617 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001618 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001619 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001620 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001621 }
1622
Aaron Ballmane0449042014-04-01 21:43:23 +00001623 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1624 ProtectedOperationKind POK, Name LockName,
1625 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001626 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001627 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001628 if (PossibleMatch) {
1629 switch (POK) {
1630 case POK_VarAccess:
1631 DiagID = diag::warn_variable_requires_lock_precise;
1632 break;
1633 case POK_VarDereference:
1634 DiagID = diag::warn_var_deref_requires_lock_precise;
1635 break;
1636 case POK_FunctionCall:
1637 DiagID = diag::warn_fun_requires_lock_precise;
1638 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001639 case POK_PassByRef:
1640 DiagID = diag::warn_guarded_pass_by_reference;
1641 break;
1642 case POK_PtPassByRef:
1643 DiagID = diag::warn_pt_guarded_pass_by_reference;
1644 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001645 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001646 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1647 << D->getNameAsString()
1648 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001649 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001650 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001651 if (Verbose && POK == POK_VarAccess) {
1652 PartialDiagnosticAt VNote(D->getLocation(),
1653 S.PDiag(diag::note_guarded_by_declared_here)
1654 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001655 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001656 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001657 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001658 } else {
1659 switch (POK) {
1660 case POK_VarAccess:
1661 DiagID = diag::warn_variable_requires_lock;
1662 break;
1663 case POK_VarDereference:
1664 DiagID = diag::warn_var_deref_requires_lock;
1665 break;
1666 case POK_FunctionCall:
1667 DiagID = diag::warn_fun_requires_lock;
1668 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001669 case POK_PassByRef:
1670 DiagID = diag::warn_guarded_pass_by_reference;
1671 break;
1672 case POK_PtPassByRef:
1673 DiagID = diag::warn_pt_guarded_pass_by_reference;
1674 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001675 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001676 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1677 << D->getNameAsString()
1678 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001679 if (Verbose && POK == POK_VarAccess) {
1680 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001681 S.PDiag(diag::note_guarded_by_declared_here)
1682 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001683 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001684 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001685 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001686 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001687 }
1688
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001689 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1690 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001691 PartialDiagnosticAt Warning(Loc,
1692 S.PDiag(diag::warn_acquire_requires_negative_cap)
1693 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001694 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001695 }
1696
Aaron Ballmane0449042014-04-01 21:43:23 +00001697 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001698 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001699 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1700 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001701 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001702 }
1703
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001704 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1705 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001706 PartialDiagnosticAt Warning(Loc,
1707 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001708 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001709 }
1710
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001711 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001712 PartialDiagnosticAt Warning(Loc,
1713 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001714 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001715 }
1716
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001717 void enterFunction(const FunctionDecl* FD) override {
1718 CurrentFunction = FD;
1719 }
1720
1721 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001722 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001723 }
1724};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001725} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001726} // namespace threadSafety
1727} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001728
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001729//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001730// -Wconsumed
1731//===----------------------------------------------------------------------===//
1732
1733namespace clang {
1734namespace consumed {
1735namespace {
1736class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1737
1738 Sema &S;
1739 DiagList Warnings;
1740
1741public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001742
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001743 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001744
1745 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001746 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001747 for (const auto &Diag : Warnings) {
1748 S.Diag(Diag.first.first, Diag.first.second);
1749 for (const auto &Note : Diag.second)
1750 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001751 }
1752 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001753
1754 void warnLoopStateMismatch(SourceLocation Loc,
1755 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001756 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1757 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001758
1759 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001760 }
1761
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001762 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1763 StringRef VariableName,
1764 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001765 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001766
1767 PartialDiagnosticAt Warning(Loc, S.PDiag(
1768 diag::warn_param_return_typestate_mismatch) << VariableName <<
1769 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001770
1771 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001772 }
1773
DeLesley Hutchins69391772013-10-17 23:23:53 +00001774 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001775 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001776
1777 PartialDiagnosticAt Warning(Loc, S.PDiag(
1778 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001779
1780 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001781 }
1782
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001783 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001784 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001785 PartialDiagnosticAt Warning(Loc, S.PDiag(
1786 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001787
1788 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001789 }
1790
1791 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001792 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001793
1794 PartialDiagnosticAt Warning(Loc, S.PDiag(
1795 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001796
1797 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001798 }
1799
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001800 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001801 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001802
1803 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001804 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001805
1806 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001807 }
1808
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001809 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001810 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001811
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001812 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1813 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001814
1815 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001816 }
1817};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001818} // anonymous namespace
1819} // namespace consumed
1820} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001821
1822//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001823// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1824// warnings on a function, method, or block.
1825//===----------------------------------------------------------------------===//
1826
Ted Kremenek0b405322010-03-23 00:13:23 +00001827clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1828 enableCheckFallThrough = 1;
1829 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001830 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001831 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001832}
1833
Ted Kremenekad8753c2014-03-15 05:47:06 +00001834static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001835 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001836}
1837
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001838clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1839 : S(s),
1840 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001841 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001842 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001843 MaxCFGBlocksPerFunction(0),
1844 NumUninitAnalysisFunctions(0),
1845 NumUninitAnalysisVariables(0),
1846 MaxUninitAnalysisVariablesPerFunction(0),
1847 NumUninitAnalysisBlockVisits(0),
1848 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001849
1850 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001851 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001852
1853 DefaultPolicy.enableCheckUnreachable =
1854 isEnabled(D, warn_unreachable) ||
1855 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001856 isEnabled(D, warn_unreachable_return) ||
1857 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001858
1859 DefaultPolicy.enableThreadSafetyAnalysis =
1860 isEnabled(D, warn_double_lock);
1861
1862 DefaultPolicy.enableConsumedAnalysis =
1863 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001864}
1865
Aaron Ballmane5195222014-05-15 20:50:47 +00001866static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1867 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001868 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001869}
1870
Ted Kremenek0b405322010-03-23 00:13:23 +00001871void clang::sema::
1872AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001873 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001874 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001875
Ted Kremenek918fe842010-03-20 21:06:02 +00001876 // We avoid doing analysis-based warnings when there are errors for
1877 // two reasons:
1878 // (1) The CFGs often can't be constructed (if the body is invalid), so
1879 // don't bother trying.
1880 // (2) The code already has problems; running the analysis just takes more
1881 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001882 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001883
Ted Kremenek0b405322010-03-23 00:13:23 +00001884 // Do not do any analysis for declarations in system headers if we are
1885 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001886 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001887 S.SourceMgr.isInSystemHeader(D->getLocation()))
1888 return;
1889
John McCall1d570a72010-08-25 05:56:39 +00001890 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001891 if (cast<DeclContext>(D)->isDependentContext())
1892 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001893
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001894 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001895 // Flush out any possibly unreachable diagnostics.
1896 flushDiagnostics(S, fscope);
1897 return;
1898 }
1899
Ted Kremenek918fe842010-03-20 21:06:02 +00001900 const Stmt *Body = D->getBody();
1901 assert(Body);
1902
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001903 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00001904 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001905
Ted Kremenek918fe842010-03-20 21:06:02 +00001906 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001907 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001908 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1909 AC.getCFGBuildOptions().AddEHEdges = false;
1910 AC.getCFGBuildOptions().AddInitializers = true;
1911 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001912 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001913 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00001914 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001915
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001916 // Force that certain expressions appear as CFGElements in the CFG. This
1917 // is used to speed up various analyses.
1918 // FIXME: This isn't the right factoring. This is here for initial
1919 // prototyping, but we need a way for analyses to say what expressions they
1920 // expect to always be CFGElements and then fill in the BuildOptions
1921 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001922 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1923 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001924 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001925 AC.getCFGBuildOptions().setAllAlwaysAdd();
1926 }
1927 else {
1928 AC.getCFGBuildOptions()
1929 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001930 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001931 .setAlwaysAdd(Stmt::BlockExprClass)
1932 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1933 .setAlwaysAdd(Stmt::DeclRefExprClass)
1934 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001935 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1936 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001937 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001938
Richard Trieue9fa2662014-04-15 00:57:50 +00001939 // Install the logical handler for -Wtautological-overlap-compare
1940 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001941 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1942 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00001943 LEH.reset(new LogicalErrorHandler(S));
1944 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00001945 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001946
Ted Kremenek3427fac2011-02-23 01:52:04 +00001947 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001948 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001949 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001950
1951 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00001952 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1953 if (D.stmt)
1954 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00001955 }
1956
1957 if (AC.getCFG()) {
1958 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00001959 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00001960 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00001961 if (D.stmt) {
1962 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001963 CFGReverseBlockReachabilityAnalysis *cra =
1964 AC.getCFGReachablityAnalysis();
1965 // FIXME: We should be able to assert that block is non-null, but
1966 // the CFG analysis can skip potentially-evaluated expressions in
1967 // edge cases; see test/Sema/vla-2.c.
1968 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001969 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001970 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001971 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001972 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001973 }
1974 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001975 if (!processed) {
1976 // Emit the warning anyway if we cannot map to a basic block.
1977 S.Diag(D.Loc, D.PD);
1978 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001979 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001980 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001981
1982 if (!analyzed)
1983 flushDiagnostics(S, fscope);
1984 }
1985
Ted Kremenek918fe842010-03-20 21:06:02 +00001986 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001987 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001988 const CheckFallThroughDiagnostics &CD =
1989 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001990 : (isa<CXXMethodDecl>(D) &&
1991 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1992 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1993 ? CheckFallThroughDiagnostics::MakeForLambda()
1994 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001995 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001996 }
1997
1998 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001999 if (P.enableCheckUnreachable) {
2000 // Only check for unreachable code on non-template instantiations.
2001 // Different template instantiations can effectively change the control-flow
2002 // and it is very difficult to prove that a snippet of code in a template
2003 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002004 bool isTemplateInstantiation = false;
2005 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2006 isTemplateInstantiation = Function->isTemplateInstantiation();
2007 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002008 CheckUnreachable(S, AC);
2009 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002010
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002011 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002012 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002013 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00002014 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002015 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002016 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002017 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002018 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2019 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002020
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002021 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2022 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002023 Reporter.emitDiagnostics();
2024 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002025
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002026 // Check for violations of consumed properties.
2027 if (P.enableConsumedAnalysis) {
2028 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002029 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002030 Analyzer.run(AC);
2031 }
2032
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002033 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2034 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2035 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002036 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002037 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002038 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002039 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002040 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002041 reporter, stats);
2042
2043 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2044 ++NumUninitAnalysisFunctions;
2045 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2046 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2047 MaxUninitAnalysisVariablesPerFunction =
2048 std::max(MaxUninitAnalysisVariablesPerFunction,
2049 stats.NumVariablesAnalyzed);
2050 MaxUninitAnalysisBlockVisitsPerFunction =
2051 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2052 stats.NumBlockVisits);
2053 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002054 }
2055 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002056
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002057 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002058 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2059 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2060 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Richard Smith4f902c72016-03-08 00:32:55 +00002061 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2062 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002063 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002064 }
2065
John McCall460ce582015-10-22 18:38:17 +00002066 if (S.getLangOpts().ObjCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002067 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002068 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002069
Richard Trieu2f024f42013-12-21 02:33:43 +00002070
2071 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002072 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2073 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2075 checkRecursiveFunction(S, FD, Body, AC);
2076 }
2077 }
2078
Richard Trieue9fa2662014-04-15 00:57:50 +00002079 // If none of the previous checks caused a CFG build, trigger one here
2080 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002081 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002082 D->getLocStart())) {
2083 AC.getCFG();
2084 }
2085
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002086 // Collect statistics about the CFG if it was built.
2087 if (S.CollectStats && AC.isCFGBuilt()) {
2088 ++NumFunctionsAnalyzed;
2089 if (CFG *cfg = AC.getCFG()) {
2090 // If we successfully built a CFG for this context, record some more
2091 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002092 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002093 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002094 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002095 } else {
2096 ++NumFunctionsWithBadCFGs;
2097 }
2098 }
2099}
2100
2101void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2102 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2103
2104 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2105 unsigned AvgCFGBlocksPerFunction =
2106 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2107 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2108 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2109 << " " << NumCFGBlocks << " CFG blocks built.\n"
2110 << " " << AvgCFGBlocksPerFunction
2111 << " average CFG blocks per function.\n"
2112 << " " << MaxCFGBlocksPerFunction
2113 << " max CFG blocks per function.\n";
2114
2115 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2116 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2117 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2118 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2119 llvm::errs() << NumUninitAnalysisFunctions
2120 << " functions analyzed for uninitialiazed variables\n"
2121 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2122 << " " << AvgUninitVariablesPerFunction
2123 << " average variables per function.\n"
2124 << " " << MaxUninitAnalysisVariablesPerFunction
2125 << " max variables per function.\n"
2126 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2127 << " " << AvgUninitBlockVisitsPerFunction
2128 << " average block visits per function.\n"
2129 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2130 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002131}