blob: 5953d020b4fbcf460378e45e1af0eb96ae5f4a85 [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"
Ted Kremenek918fe842010-03-20 21:06:02 +000040#include "llvm/ADT/BitVector.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000041#include "llvm/ADT/MapVector.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000042#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000044#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000045#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000047#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000048#include <iterator>
Ted Kremenek918fe842010-03-20 21:06:02 +000049
50using namespace clang;
51
52//===----------------------------------------------------------------------===//
53// Unreachable code analysis.
54//===----------------------------------------------------------------------===//
55
56namespace {
57 class UnreachableCodeHandler : public reachable_code::Callback {
58 Sema &S;
59 public:
60 UnreachableCodeHandler(Sema &s) : S(s) {}
61
Ted Kremenek1a8641c2014-03-15 01:26:32 +000062 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000063 SourceLocation L,
64 SourceRange SilenceableCondVal,
65 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000066 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000067 unsigned diag = diag::warn_unreachable;
68 switch (UK) {
69 case reachable_code::UK_Break:
70 diag = diag::warn_unreachable_break;
71 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000072 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000073 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000074 break;
Ted Kremenek14210372014-03-21 06:02:36 +000075 case reachable_code::UK_Loop_Increment:
76 diag = diag::warn_unreachable_loop_increment;
77 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000078 case reachable_code::UK_Other:
79 break;
80 }
81
82 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000083
84 SourceLocation Open = SilenceableCondVal.getBegin();
85 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000086 SourceLocation Close = SilenceableCondVal.getEnd();
87 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000088 if (Close.isValid()) {
89 S.Diag(Open, diag::note_unreachable_silence)
90 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
91 << FixItHint::CreateInsertion(Close, ")");
92 }
93 }
Ted Kremenek918fe842010-03-20 21:06:02 +000094 }
95 };
Hans Wennborgdcfba332015-10-06 23:40:43 +000096} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +000097
98/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +000099static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000100 // As a heuristic prune all diagnostics not in the main file. Currently
101 // the majority of warnings in headers are false positives. These
102 // are largely caused by configuration state, e.g. preprocessor
103 // defined code, etc.
104 //
105 // Note that this is also a performance optimization. Analyzing
106 // headers many times can be expensive.
107 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
108 return;
109
Ted Kremenek918fe842010-03-20 21:06:02 +0000110 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000111 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000112}
113
Benjamin Kramer3a002252015-02-16 16:53:12 +0000114namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000115/// \brief Warn on logical operator errors in CFGBuilder
116class LogicalErrorHandler : public CFGCallback {
117 Sema &S;
118
119public:
120 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
121
122 static bool HasMacroID(const Expr *E) {
123 if (E->getExprLoc().isMacroID())
124 return true;
125
126 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000127 for (const Stmt *SubStmt : E->children())
128 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
129 if (HasMacroID(SubExpr))
130 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000131
132 return false;
133 }
134
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000135 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000136 if (HasMacroID(B))
137 return;
138
139 SourceRange DiagRange = B->getSourceRange();
140 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
141 << DiagRange << isAlwaysTrue;
142 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000143
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000144 void compareBitwiseEquality(const BinaryOperator *B,
145 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000146 if (HasMacroID(B))
147 return;
148
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
151 << DiagRange << isAlwaysTrue;
152 }
Richard Trieuf935b562014-04-05 05:17:01 +0000153};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000154} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000155
Ted Kremenek918fe842010-03-20 21:06:02 +0000156//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000157// Check for infinite self-recursion in functions
158//===----------------------------------------------------------------------===//
159
Richard Trieu6995de92015-08-21 03:43:09 +0000160// Returns true if the function is called anywhere within the CFGBlock.
161// For member functions, the additional condition of being call from the
162// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000163static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000164 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000165 for (const auto &B : Block) {
166 if (B.getKind() != CFGElement::Statement)
167 continue;
168
169 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
170 if (!CE || !CE->getCalleeDecl() ||
171 CE->getCalleeDecl()->getCanonicalDecl() != FD)
172 continue;
173
174 // Skip function calls which are qualified with a templated class.
175 if (const DeclRefExpr *DRE =
176 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
177 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
178 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
179 isa<TemplateSpecializationType>(NNS->getAsType())) {
180 continue;
181 }
182 }
183 }
184
185 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
186 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
187 !MCE->getMethodDecl()->isVirtual())
188 return true;
189 }
190 return false;
191}
192
Richard Trieu6995de92015-08-21 03:43:09 +0000193// All blocks are in one of three states. States are ordered so that blocks
194// can only move to higher states.
195enum RecursiveState {
196 FoundNoPath,
197 FoundPath,
198 FoundPathWithNoRecursiveCall
199};
200
201// Returns true if there exists a path to the exit block and every path
202// to the exit block passes through a call to FD.
203static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
204
205 const unsigned ExitID = cfg->getExit().getBlockID();
206
207 // Mark all nodes as FoundNoPath, then set the status of the entry block.
208 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
209 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
210
211 // Make the processing stack and seed it with the entry block.
212 SmallVector<CFGBlock *, 16> Stack;
213 Stack.push_back(&cfg->getEntry());
Richard Trieu2f024f42013-12-21 02:33:43 +0000214
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000215 while (!Stack.empty()) {
Richard Trieu6995de92015-08-21 03:43:09 +0000216 CFGBlock *CurBlock = Stack.back();
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000217 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000218
Richard Trieu6995de92015-08-21 03:43:09 +0000219 unsigned ID = CurBlock->getBlockID();
220 RecursiveState CurState = States[ID];
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000221
222 if (CurState == FoundPathWithNoRecursiveCall) {
223 // Found a path to the exit node without a recursive call.
224 if (ExitID == ID)
Richard Trieu6995de92015-08-21 03:43:09 +0000225 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000226
Richard Trieu6995de92015-08-21 03:43:09 +0000227 // Only change state if the block has a recursive call.
228 if (hasRecursiveCallInPath(FD, *CurBlock))
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000229 CurState = FoundPath;
230 }
231
Richard Trieu6995de92015-08-21 03:43:09 +0000232 // Loop over successor blocks and add them to the Stack if their state
233 // changes.
234 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
235 if (*I) {
236 unsigned next_ID = (*I)->getBlockID();
237 if (States[next_ID] < CurState) {
238 States[next_ID] = CurState;
239 Stack.push_back(*I);
240 }
241 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000242 }
Richard Trieu6995de92015-08-21 03:43:09 +0000243
244 // Return true if the exit node is reachable, and only reachable through
245 // a recursive call.
246 return States[ExitID] == FoundPath;
Richard Trieu2f024f42013-12-21 02:33:43 +0000247}
248
249static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000250 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000251 FD = FD->getCanonicalDecl();
252
253 // Only run on non-templated functions and non-templated members of
254 // templated classes.
255 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
256 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
257 return;
258
259 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000260 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000261
262 // If the exit block is unreachable, skip processing the function.
263 if (cfg->getExit().pred_empty())
264 return;
265
Richard Trieu6995de92015-08-21 03:43:09 +0000266 // Emit diagnostic if a recursive function call is detected for all paths.
267 if (checkForRecursiveFunctionCall(FD, cfg))
Richard Trieu2f024f42013-12-21 02:33:43 +0000268 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
269}
270
271//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000272// Check for missing return value.
273//===----------------------------------------------------------------------===//
274
John McCall5c6ec8c2010-05-16 09:34:11 +0000275enum ControlFlowKind {
276 UnknownFallThrough,
277 NeverFallThrough,
278 MaybeFallThrough,
279 AlwaysFallThrough,
280 NeverFallThroughOrReturn
281};
Ted Kremenek918fe842010-03-20 21:06:02 +0000282
283/// CheckFallThrough - Check that we don't fall off the end of a
284/// Statement that should return a value.
285///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000286/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
287/// MaybeFallThrough iff we might or might not fall off the end,
288/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
289/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000290/// statement but we may return. We assume that functions not marked noreturn
291/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000292static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000293 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000294 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000295
296 // The CFG leaves in dead things, and we don't want the dead code paths to
297 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000298 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000299 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000300 live);
301
302 bool AddEHEdges = AC.getAddEHEdges();
303 if (!AddEHEdges && count != cfg->getNumBlockIDs())
304 // When there are things remaining dead, and we didn't add EH edges
305 // from CallExprs to the catch clauses, we have to go back and
306 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000307 for (const auto *B : *cfg) {
308 if (!live[B->getBlockID()]) {
309 if (B->pred_begin() == B->pred_end()) {
310 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000311 // When not adding EH edges from calls, catch clauses
312 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000313 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000314 continue;
315 }
316 }
317 }
318
319 // Now we know what is live, we check the live precessors of the exit block
320 // and look for fall through paths, being careful to ignore normal returns,
321 // and exceptional paths.
322 bool HasLiveReturn = false;
323 bool HasFakeEdge = false;
324 bool HasPlainEdge = false;
325 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000326
327 // Ignore default cases that aren't likely to be reachable because all
328 // enums in a switch(X) have explicit case statements.
329 CFGBlock::FilterOptions FO;
330 FO.IgnoreDefaultsWithCoveredEnums = 1;
331
332 for (CFGBlock::filtered_pred_iterator
333 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
334 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000335 if (!live[B.getBlockID()])
336 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000337
Chandler Carruth03faf782011-09-13 09:53:58 +0000338 // Skip blocks which contain an element marked as no-return. They don't
339 // represent actually viable edges into the exit block, so mark them as
340 // abnormal.
341 if (B.hasNoReturnElement()) {
342 HasAbnormalEdge = true;
343 continue;
344 }
345
Ted Kremenek5d068492011-01-26 04:49:52 +0000346 // Destructors can appear after the 'return' in the CFG. This is
347 // normal. We need to look pass the destructors for the return
348 // statement (if it exists).
349 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000350
Chandler Carruth03faf782011-09-13 09:53:58 +0000351 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000352 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000353 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000354
Ted Kremenek5d068492011-01-26 04:49:52 +0000355 // No more CFGElements in the block?
356 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000357 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
358 HasAbnormalEdge = true;
359 continue;
360 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000361 // A labeled empty statement, or the entry block...
362 HasPlainEdge = true;
363 continue;
364 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000365
David Blaikie2a01f5d2013-02-21 20:58:29 +0000366 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000367 const Stmt *S = CS.getStmt();
Eric Fiselier709d1b32016-10-27 07:30:31 +0000368 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000369 HasLiveReturn = true;
370 continue;
371 }
372 if (isa<ObjCAtThrowStmt>(S)) {
373 HasFakeEdge = true;
374 continue;
375 }
376 if (isa<CXXThrowExpr>(S)) {
377 HasFakeEdge = true;
378 continue;
379 }
Chad Rosier32503022012-06-11 20:47:18 +0000380 if (isa<MSAsmStmt>(S)) {
381 // TODO: Verify this is correct.
382 HasFakeEdge = true;
383 HasLiveReturn = true;
384 continue;
385 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000386 if (isa<CXXTryStmt>(S)) {
387 HasAbnormalEdge = true;
388 continue;
389 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000390 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
391 == B.succ_end()) {
392 HasAbnormalEdge = true;
393 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000394 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000395
396 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000397 }
398 if (!HasPlainEdge) {
399 if (HasLiveReturn)
400 return NeverFallThrough;
401 return NeverFallThroughOrReturn;
402 }
403 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
404 return MaybeFallThrough;
405 // This says AlwaysFallThrough for calls to functions that are not marked
406 // noreturn, that don't return. If people would like this warning to be more
407 // accurate, such functions should be marked as noreturn.
408 return AlwaysFallThrough;
409}
410
Dan Gohman28ade552010-07-26 21:25:24 +0000411namespace {
412
Ted Kremenek918fe842010-03-20 21:06:02 +0000413struct CheckFallThroughDiagnostics {
414 unsigned diag_MaybeFallThrough_HasNoReturn;
415 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
416 unsigned diag_AlwaysFallThrough_HasNoReturn;
417 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
418 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000419 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000420 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000421
Douglas Gregor24f27692010-04-16 23:28:44 +0000422 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000423 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000424 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000425 D.diag_MaybeFallThrough_HasNoReturn =
426 diag::warn_falloff_noreturn_function;
427 D.diag_MaybeFallThrough_ReturnsNonVoid =
428 diag::warn_maybe_falloff_nonvoid_function;
429 D.diag_AlwaysFallThrough_HasNoReturn =
430 diag::warn_falloff_noreturn_function;
431 D.diag_AlwaysFallThrough_ReturnsNonVoid =
432 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000433
434 // Don't suggest that virtual functions be marked "noreturn", since they
435 // might be overridden by non-noreturn functions.
436 bool isVirtualMethod = false;
437 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
438 isVirtualMethod = Method->isVirtual();
439
Douglas Gregor0de57202011-10-10 18:15:57 +0000440 // Don't suggest that template instantiations be marked "noreturn"
441 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000442 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
443 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000444
445 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000446 D.diag_NeverFallThroughOrReturn =
447 diag::warn_suggest_noreturn_function;
448 else
449 D.diag_NeverFallThroughOrReturn = 0;
450
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000451 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000452 return D;
453 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000454
Eric Fiselier709d1b32016-10-27 07:30:31 +0000455 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
456 CheckFallThroughDiagnostics D;
457 D.FuncLoc = Func->getLocation();
458 D.diag_MaybeFallThrough_HasNoReturn = 0;
459 D.diag_MaybeFallThrough_ReturnsNonVoid =
460 diag::warn_maybe_falloff_nonvoid_coroutine;
461 D.diag_AlwaysFallThrough_HasNoReturn = 0;
462 D.diag_AlwaysFallThrough_ReturnsNonVoid =
463 diag::warn_falloff_nonvoid_coroutine;
464 D.funMode = Coroutine;
465 return D;
466 }
467
Ted Kremenek918fe842010-03-20 21:06:02 +0000468 static CheckFallThroughDiagnostics MakeForBlock() {
469 CheckFallThroughDiagnostics D;
470 D.diag_MaybeFallThrough_HasNoReturn =
471 diag::err_noreturn_block_has_return_expr;
472 D.diag_MaybeFallThrough_ReturnsNonVoid =
473 diag::err_maybe_falloff_nonvoid_block;
474 D.diag_AlwaysFallThrough_HasNoReturn =
475 diag::err_noreturn_block_has_return_expr;
476 D.diag_AlwaysFallThrough_ReturnsNonVoid =
477 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000478 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000479 D.funMode = Block;
480 return D;
481 }
482
483 static CheckFallThroughDiagnostics MakeForLambda() {
484 CheckFallThroughDiagnostics D;
485 D.diag_MaybeFallThrough_HasNoReturn =
486 diag::err_noreturn_lambda_has_return_expr;
487 D.diag_MaybeFallThrough_ReturnsNonVoid =
488 diag::warn_maybe_falloff_nonvoid_lambda;
489 D.diag_AlwaysFallThrough_HasNoReturn =
490 diag::err_noreturn_lambda_has_return_expr;
491 D.diag_AlwaysFallThrough_ReturnsNonVoid =
492 diag::warn_falloff_nonvoid_lambda;
493 D.diag_NeverFallThroughOrReturn = 0;
494 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000495 return D;
496 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000497
David Blaikie9c902b52011-09-25 23:23:43 +0000498 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000499 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000500 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000501 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000502 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
503 FuncLoc)) &&
504 (!HasNoReturn ||
505 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
506 FuncLoc)) &&
507 (!ReturnsVoid ||
508 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000509 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000510 if (funMode == Coroutine) {
511 return (ReturnsVoid ||
512 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
513 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
514 FuncLoc)) &&
515 (!HasNoReturn);
516 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000517 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000518 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000519 }
520};
521
Hans Wennborgdcfba332015-10-06 23:40:43 +0000522} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000523
Ted Kremenek918fe842010-03-20 21:06:02 +0000524/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
525/// function that should return a value. Check that we don't fall off the end
526/// of a noreturn function. We assume that functions and blocks not marked
527/// noreturn will return.
528static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000529 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000530 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000531 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000532
533 bool ReturnsVoid = false;
534 bool HasNoReturn = false;
535
Eric Fiselier709d1b32016-10-27 07:30:31 +0000536 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
537 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
538 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
539 else
540 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000541 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000542 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000543 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000544 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000545 HasNoReturn = MD->hasAttr<NoReturnAttr>();
546 }
547 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000548 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000549 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000550 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000551 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000552 ReturnsVoid = true;
553 if (FT->getNoReturnAttr())
554 HasNoReturn = true;
555 }
556 }
557
David Blaikie9c902b52011-09-25 23:23:43 +0000558 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000559
560 // Short circuit for compilation speed.
561 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
562 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000563
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000564 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
565 // Either in a function body compound statement, or a function-try-block.
566 switch (CheckFallThrough(AC)) {
567 case UnknownFallThrough:
568 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000569
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000570 case MaybeFallThrough:
571 if (HasNoReturn)
572 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
573 else if (!ReturnsVoid)
574 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
575 break;
576 case AlwaysFallThrough:
577 if (HasNoReturn)
578 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
579 else if (!ReturnsVoid)
580 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
581 break;
582 case NeverFallThroughOrReturn:
583 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
584 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
585 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
586 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
587 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
588 } else {
589 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000590 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000591 }
592 break;
593 case NeverFallThrough:
594 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000595 }
596}
597
598//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000599// -Wuninitialized
600//===----------------------------------------------------------------------===//
601
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000602namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000603/// ContainsReference - A visitor class to search for references to
604/// a particular declaration (the needle) within any evaluated component of an
605/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000606class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000607 bool FoundReference;
608 const DeclRefExpr *Needle;
609
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000610public:
Scott Douglass503fc392015-06-10 13:53:15 +0000611 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000612
Scott Douglass503fc392015-06-10 13:53:15 +0000613 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
614 : Inherited(Context), FoundReference(false), Needle(Needle) {}
615
616 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000617 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000618 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000619 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000620
Scott Douglass503fc392015-06-10 13:53:15 +0000621 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000622 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000623
Scott Douglass503fc392015-06-10 13:53:15 +0000624 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000625 if (E == Needle)
626 FoundReference = true;
627 else
Scott Douglass503fc392015-06-10 13:53:15 +0000628 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000629 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000630
631 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000632};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000633} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000634
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000635static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000636 QualType VariableTy = VD->getType().getCanonicalType();
637 if (VariableTy->isBlockPointerType() &&
638 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000639 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
640 << VD->getDeclName()
641 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000642 return true;
643 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000644
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000645 // Don't issue a fixit if there is already an initializer.
646 if (VD->getInit())
647 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000648
649 // Don't suggest a fixit inside macros.
650 if (VD->getLocEnd().isMacroID())
651 return false;
652
Alp Tokerb6cc5922014-05-03 03:45:55 +0000653 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000654
655 // Suggest possible initialization (if any).
656 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
657 if (Init.empty())
658 return false;
659
Richard Smith8d06f422012-01-12 23:53:29 +0000660 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
661 << FixItHint::CreateInsertion(Loc, Init);
662 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000663}
664
Richard Smith1bb8edb82012-05-26 06:20:46 +0000665/// Create a fixit to remove an if-like statement, on the assumption that its
666/// condition is CondVal.
667static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
668 const Stmt *Else, bool CondVal,
669 FixItHint &Fixit1, FixItHint &Fixit2) {
670 if (CondVal) {
671 // If condition is always true, remove all but the 'then'.
672 Fixit1 = FixItHint::CreateRemoval(
673 CharSourceRange::getCharRange(If->getLocStart(),
674 Then->getLocStart()));
675 if (Else) {
Craig Topper07fa1762015-11-15 02:31:46 +0000676 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000677 Fixit2 = FixItHint::CreateRemoval(
678 SourceRange(ElseKwLoc, Else->getLocEnd()));
679 }
680 } else {
681 // If condition is always false, remove all but the 'else'.
682 if (Else)
683 Fixit1 = FixItHint::CreateRemoval(
684 CharSourceRange::getCharRange(If->getLocStart(),
685 Else->getLocStart()));
686 else
687 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
688 }
689}
690
691/// DiagUninitUse -- Helper function to produce a diagnostic for an
692/// uninitialized use of a variable.
693static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
694 bool IsCapturedByBlock) {
695 bool Diagnosed = false;
696
Richard Smithba8071e2013-09-12 18:49:10 +0000697 switch (Use.getKind()) {
698 case UninitUse::Always:
699 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
700 << VD->getDeclName() << IsCapturedByBlock
701 << Use.getUser()->getSourceRange();
702 return;
703
704 case UninitUse::AfterDecl:
705 case UninitUse::AfterCall:
706 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
707 << VD->getDeclName() << IsCapturedByBlock
708 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
709 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
710 << VD->getSourceRange();
711 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
712 << IsCapturedByBlock << Use.getUser()->getSourceRange();
713 return;
714
715 case UninitUse::Maybe:
716 case UninitUse::Sometimes:
717 // Carry on to report sometimes-uninitialized branches, if possible,
718 // or a 'may be used uninitialized' diagnostic otherwise.
719 break;
720 }
721
Richard Smith1bb8edb82012-05-26 06:20:46 +0000722 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000723 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
724 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000725 assert(Use.getKind() == UninitUse::Sometimes);
726
727 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000728 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000729
730 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000731 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000732 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000733 SourceRange Range;
734
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000735 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000736 // For all binary terminators, branch 0 is taken if the condition is true,
737 // and branch 1 is taken if the condition is false.
738 int RemoveDiagKind = -1;
739 const char *FixitStr =
740 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
741 : (I->Output ? "1" : "0");
742 FixItHint Fixit1, Fixit2;
743
Richard Smithba8071e2013-09-12 18:49:10 +0000744 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000745 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000746 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000747 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000748 continue;
749
750 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000751 case Stmt::IfStmtClass: {
752 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000753 DiagKind = 0;
754 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000755 Range = IS->getCond()->getSourceRange();
756 RemoveDiagKind = 0;
757 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
758 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000759 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000760 }
761 case Stmt::ConditionalOperatorClass: {
762 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000763 DiagKind = 0;
764 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000765 Range = CO->getCond()->getSourceRange();
766 RemoveDiagKind = 0;
767 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
768 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000769 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000770 }
Richard Smith4323bf82012-05-25 02:17:09 +0000771 case Stmt::BinaryOperatorClass: {
772 const BinaryOperator *BO = cast<BinaryOperator>(Term);
773 if (!BO->isLogicalOp())
774 continue;
775 DiagKind = 0;
776 Str = BO->getOpcodeStr();
777 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000778 RemoveDiagKind = 0;
779 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
780 (BO->getOpcode() == BO_LOr && !I->Output))
781 // true && y -> y, false || y -> y.
782 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
783 BO->getOperatorLoc()));
784 else
785 // false && y -> false, true || y -> true.
786 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000787 break;
788 }
789
790 // "loop is entered / loop is exited".
791 case Stmt::WhileStmtClass:
792 DiagKind = 1;
793 Str = "while";
794 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000795 RemoveDiagKind = 1;
796 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000797 break;
798 case Stmt::ForStmtClass:
799 DiagKind = 1;
800 Str = "for";
801 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000802 RemoveDiagKind = 1;
803 if (I->Output)
804 Fixit1 = FixItHint::CreateRemoval(Range);
805 else
806 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000807 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000808 case Stmt::CXXForRangeStmtClass:
809 if (I->Output == 1) {
810 // The use occurs if a range-based for loop's body never executes.
811 // That may be impossible, and there's no syntactic fix for this,
812 // so treat it as a 'may be uninitialized' case.
813 continue;
814 }
815 DiagKind = 1;
816 Str = "for";
817 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
818 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000819
820 // "condition is true / loop is exited".
821 case Stmt::DoStmtClass:
822 DiagKind = 2;
823 Str = "do";
824 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000825 RemoveDiagKind = 1;
826 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000827 break;
828
829 // "switch case is taken".
830 case Stmt::CaseStmtClass:
831 DiagKind = 3;
832 Str = "case";
833 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
834 break;
835 case Stmt::DefaultStmtClass:
836 DiagKind = 3;
837 Str = "default";
838 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
839 break;
840 }
841
Richard Smith1bb8edb82012-05-26 06:20:46 +0000842 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
843 << VD->getDeclName() << IsCapturedByBlock << DiagKind
844 << Str << I->Output << Range;
845 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
846 << IsCapturedByBlock << User->getSourceRange();
847 if (RemoveDiagKind != -1)
848 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
849 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
850
851 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000852 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000853
854 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000855 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000856 << VD->getDeclName() << IsCapturedByBlock
857 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000858}
859
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000860/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
861/// uninitialized variable. This manages the different forms of diagnostic
862/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000863/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000864/// false.
865static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000866 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000867 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +0000868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000869 // Inspect the initializer of the variable declaration which is
870 // being referenced prior to its initialization. We emit
871 // specialized diagnostics for self-initialization, and we
872 // specifically avoid warning about self references which take the
873 // form of:
874 //
875 // int x = x;
876 //
877 // This is used to indicate to GCC that 'x' is intentionally left
878 // uninitialized. Proven code paths which access 'x' in
879 // an uninitialized state after this will still warn.
880 if (const Expr *Initializer = VD->getInit()) {
881 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
882 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000883
Richard Trieu43a2fc72012-05-09 21:08:22 +0000884 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +0000885 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +0000886 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000887 S.Diag(DRE->getLocStart(),
888 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000889 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
890 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000891 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000892 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000893
Richard Smith1bb8edb82012-05-26 06:20:46 +0000894 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000895 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000896 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000897 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
898 S.Diag(BE->getLocStart(),
899 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000900 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000901 else
902 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000903 }
904
905 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000906 // the initializer of that declaration & we didn't already suggest
907 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000908 if (!SuggestInitializationFixit(S, VD))
Reid Klecknerf463a8a2016-04-29 00:37:43 +0000909 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
Chandler Carruth895904da2011-04-05 18:18:05 +0000910 << VD->getDeclName();
911
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000912 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000913}
914
Richard Smith84837d52012-05-03 18:27:39 +0000915namespace {
916 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
917 public:
918 FallthroughMapper(Sema &S)
919 : FoundSwitchStatements(false),
920 S(S) {
921 }
922
923 bool foundSwitchStatements() const { return FoundSwitchStatements; }
924
925 void markFallthroughVisited(const AttributedStmt *Stmt) {
926 bool Found = FallthroughStmts.erase(Stmt);
927 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000928 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000929 }
930
931 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
932
933 const AttrStmts &getFallthroughStmts() const {
934 return FallthroughStmts;
935 }
936
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000937 void fillReachableBlocks(CFG *Cfg) {
938 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
939 std::deque<const CFGBlock *> BlockQueue;
940
941 ReachableBlocks.insert(&Cfg->getEntry());
942 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000943 // Mark all case blocks reachable to avoid problems with switching on
944 // constants, covered enums, etc.
945 // These blocks can contain fall-through annotations, and we don't want to
946 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +0000947 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000948 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +0000949 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000950 BlockQueue.push_back(B);
951 }
952
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000953 while (!BlockQueue.empty()) {
954 const CFGBlock *P = BlockQueue.front();
955 BlockQueue.pop_front();
956 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
957 E = P->succ_end();
958 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +0000959 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000960 BlockQueue.push_back(*I);
961 }
962 }
963 }
964
Richard Smith84837d52012-05-03 18:27:39 +0000965 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000966 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
967
Richard Smith84837d52012-05-03 18:27:39 +0000968 int UnannotatedCnt = 0;
969 AnnotatedCnt = 0;
970
Aaron Ballmane5195222014-05-15 20:50:47 +0000971 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +0000972 while (!BlockQueue.empty()) {
973 const CFGBlock *P = BlockQueue.front();
974 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000975 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000976
977 const Stmt *Term = P->getTerminator();
978 if (Term && isa<SwitchStmt>(Term))
979 continue; // Switch statement, good.
980
981 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
982 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
983 continue; // Previous case label has no statements, good.
984
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000985 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
986 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
987 continue; // Case label is preceded with a normal label, good.
988
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000989 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000990 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
991 ElemEnd = P->rend();
992 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000993 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
994 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000995 S.Diag(AS->getLocStart(),
996 diag::warn_fallthrough_attr_unreachable);
997 markFallthroughVisited(AS);
998 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000999 break;
Richard Smith84837d52012-05-03 18:27:39 +00001000 }
1001 // Don't care about other unreachable statements.
1002 }
1003 }
1004 // If there are no unreachable statements, this may be a special
1005 // case in CFG:
1006 // case X: {
1007 // A a; // A has a destructor.
1008 // break;
1009 // }
1010 // // <<<< This place is represented by a 'hanging' CFG block.
1011 // case Y:
1012 continue;
1013 }
1014
1015 const Stmt *LastStmt = getLastStmt(*P);
1016 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1017 markFallthroughVisited(AS);
1018 ++AnnotatedCnt;
1019 continue; // Fallthrough annotation, good.
1020 }
1021
1022 if (!LastStmt) { // This block contains no executable statements.
1023 // Traverse its predecessors.
1024 std::copy(P->pred_begin(), P->pred_end(),
1025 std::back_inserter(BlockQueue));
1026 continue;
1027 }
1028
1029 ++UnannotatedCnt;
1030 }
1031 return !!UnannotatedCnt;
1032 }
1033
1034 // RecursiveASTVisitor setup.
1035 bool shouldWalkTypesOfTypeLocs() const { return false; }
1036
1037 bool VisitAttributedStmt(AttributedStmt *S) {
1038 if (asFallThroughAttr(S))
1039 FallthroughStmts.insert(S);
1040 return true;
1041 }
1042
1043 bool VisitSwitchStmt(SwitchStmt *S) {
1044 FoundSwitchStatements = true;
1045 return true;
1046 }
1047
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001048 // We don't want to traverse local type declarations. We analyze their
1049 // methods separately.
1050 bool TraverseDecl(Decl *D) { return true; }
1051
Alexander Kornienkobf911642014-06-24 15:28:21 +00001052 // We analyze lambda bodies separately. Skip them here.
1053 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1054
Richard Smith84837d52012-05-03 18:27:39 +00001055 private:
1056
1057 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1058 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1059 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1060 return AS;
1061 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001062 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001063 }
1064
1065 static const Stmt *getLastStmt(const CFGBlock &B) {
1066 if (const Stmt *Term = B.getTerminator())
1067 return Term;
1068 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1069 ElemEnd = B.rend();
1070 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001071 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1072 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001073 }
1074 // Workaround to detect a statement thrown out by CFGBuilder:
1075 // case X: {} case Y:
1076 // case X: ; case Y:
1077 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1078 if (!isa<SwitchCase>(SW->getSubStmt()))
1079 return SW->getSubStmt();
1080
Craig Topperc3ec1492014-05-26 06:22:03 +00001081 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001082 }
1083
1084 bool FoundSwitchStatements;
1085 AttrStmts FallthroughStmts;
1086 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001087 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001088 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001089} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001090
Richard Smith4f902c72016-03-08 00:32:55 +00001091static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1092 SourceLocation Loc) {
1093 TokenValue FallthroughTokens[] = {
1094 tok::l_square, tok::l_square,
1095 PP.getIdentifierInfo("fallthrough"),
1096 tok::r_square, tok::r_square
1097 };
1098
1099 TokenValue ClangFallthroughTokens[] = {
1100 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1101 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1102 tok::r_square, tok::r_square
1103 };
1104
1105 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1106
1107 StringRef MacroName;
1108 if (PreferClangAttr)
1109 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1110 if (MacroName.empty())
1111 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1112 if (MacroName.empty() && !PreferClangAttr)
1113 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1114 if (MacroName.empty())
1115 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1116 return MacroName;
1117}
1118
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001119static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001120 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001121 // Only perform this analysis when using C++11. There is no good workflow
1122 // for this warning when not using C++11. There is no good way to silence
1123 // the warning (no attribute is available) unless we are using C++11's support
1124 // for generalized attributes. Once could use pragmas to silence the warning,
1125 // but as a general solution that is gross and not in the spirit of this
1126 // warning.
1127 //
1128 // NOTE: This an intermediate solution. There are on-going discussions on
1129 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001130 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001131 return;
1132
Richard Smith84837d52012-05-03 18:27:39 +00001133 FallthroughMapper FM(S);
1134 FM.TraverseStmt(AC.getBody());
1135
1136 if (!FM.foundSwitchStatements())
1137 return;
1138
Alexis Hunt2178f142012-06-15 21:22:05 +00001139 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001140 return;
1141
Richard Smith84837d52012-05-03 18:27:39 +00001142 CFG *Cfg = AC.getCFG();
1143
1144 if (!Cfg)
1145 return;
1146
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001147 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001148
Pete Cooper57d3f142015-07-30 17:22:52 +00001149 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001150 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001151
1152 if (!Label || !isa<SwitchCase>(Label))
1153 continue;
1154
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001155 int AnnotatedCnt;
1156
Alexander Kornienko55488792013-01-25 15:49:34 +00001157 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001158 continue;
1159
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001160 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001161 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1162 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001163
1164 if (!AnnotatedCnt) {
1165 SourceLocation L = Label->getLocStart();
1166 if (L.isMacroID())
1167 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001168 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001169 const Stmt *Term = B->getTerminator();
1170 // Skip empty cases.
1171 while (B->empty() && !Term && B->succ_size() == 1) {
1172 B = *B->succ_begin();
1173 Term = B->getTerminator();
1174 }
1175 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001176 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001177 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001178 SmallString<64> TextToInsert(AnnotationSpelling);
1179 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001180 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001181 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001182 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001183 }
Richard Smith84837d52012-05-03 18:27:39 +00001184 }
1185 S.Diag(L, diag::note_insert_break_fixit) <<
1186 FixItHint::CreateInsertion(L, "break; ");
1187 }
1188 }
1189
Aaron Ballmane5195222014-05-15 20:50:47 +00001190 for (const auto *F : FM.getFallthroughStmts())
Richard Smith4f902c72016-03-08 00:32:55 +00001191 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001192}
1193
Jordan Rose25c0ea82012-10-29 17:46:47 +00001194static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1195 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001196 assert(S);
1197
1198 do {
1199 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001200 case Stmt::ForStmtClass:
1201 case Stmt::WhileStmtClass:
1202 case Stmt::CXXForRangeStmtClass:
1203 case Stmt::ObjCForCollectionStmtClass:
1204 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001205 case Stmt::DoStmtClass: {
1206 const Expr *Cond = cast<DoStmt>(S)->getCond();
1207 llvm::APSInt Val;
1208 if (!Cond->EvaluateAsInt(Val, Ctx))
1209 return true;
1210 return Val.getBoolValue();
1211 }
Jordan Rose76831c62012-10-11 16:10:19 +00001212 default:
1213 break;
1214 }
1215 } while ((S = PM.getParent(S)));
1216
1217 return false;
1218}
1219
Jordan Rosed3934582012-09-28 22:21:30 +00001220static void diagnoseRepeatedUseOfWeak(Sema &S,
1221 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001222 const Decl *D,
1223 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001224 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1225 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1226 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001227 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1228 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001229
Jordan Rose25c0ea82012-10-29 17:46:47 +00001230 ASTContext &Ctx = S.getASTContext();
1231
Jordan Rosed3934582012-09-28 22:21:30 +00001232 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1233
1234 // Extract all weak objects that are referenced more than once.
1235 SmallVector<StmtUsesPair, 8> UsesByStmt;
1236 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1237 I != E; ++I) {
1238 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001239
1240 // Find the first read of the weak object.
1241 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1242 for ( ; UI != UE; ++UI) {
1243 if (UI->isUnsafe())
1244 break;
1245 }
1246
1247 // If there were only writes to this object, don't warn.
1248 if (UI == UE)
1249 continue;
1250
Jordan Rose76831c62012-10-11 16:10:19 +00001251 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001252 // read is not within a loop, don't warn. Additionally, don't warn in a
1253 // loop if the base object is a local variable -- local variables are often
1254 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001255 if (UI == Uses.begin()) {
1256 WeakUseVector::const_iterator UI2 = UI;
1257 for (++UI2; UI2 != UE; ++UI2)
1258 if (UI2->isUnsafe())
1259 break;
1260
Jordan Rose25c0ea82012-10-29 17:46:47 +00001261 if (UI2 == UE) {
1262 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001263 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001264
1265 const WeakObjectProfileTy &Profile = I->first;
1266 if (!Profile.isExactProfile())
1267 continue;
1268
1269 const NamedDecl *Base = Profile.getBase();
1270 if (!Base)
1271 Base = Profile.getProperty();
1272 assert(Base && "A profile always has a base or property.");
1273
1274 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1275 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1276 continue;
1277 }
Jordan Rose76831c62012-10-11 16:10:19 +00001278 }
1279
Jordan Rosed3934582012-09-28 22:21:30 +00001280 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1281 }
1282
1283 if (UsesByStmt.empty())
1284 return;
1285
1286 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001287 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001288 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001289 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1290 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1291 RHS.first->getLocStart());
1292 });
Jordan Rosed3934582012-09-28 22:21:30 +00001293
1294 // Classify the current code body for better warning text.
1295 // This enum should stay in sync with the cases in
1296 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1297 // FIXME: Should we use a common classification enum and the same set of
1298 // possibilities all throughout Sema?
1299 enum {
1300 Function,
1301 Method,
1302 Block,
1303 Lambda
1304 } FunctionKind;
1305
1306 if (isa<sema::BlockScopeInfo>(CurFn))
1307 FunctionKind = Block;
1308 else if (isa<sema::LambdaScopeInfo>(CurFn))
1309 FunctionKind = Lambda;
1310 else if (isa<ObjCMethodDecl>(D))
1311 FunctionKind = Method;
1312 else
1313 FunctionKind = Function;
1314
1315 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001316 for (const auto &P : UsesByStmt) {
1317 const Stmt *FirstRead = P.first;
1318 const WeakObjectProfileTy &Key = P.second->first;
1319 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001320
Jordan Rose657b5f42012-09-28 22:21:35 +00001321 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1322 // may not contain enough information to determine that these are different
1323 // properties. We can only be 100% sure of a repeated use in certain cases,
1324 // and we adjust the diagnostic kind accordingly so that the less certain
1325 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001326 unsigned DiagKind;
1327 if (Key.isExactProfile())
1328 DiagKind = diag::warn_arc_repeated_use_of_weak;
1329 else
1330 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1331
Jordan Rose657b5f42012-09-28 22:21:35 +00001332 // Classify the weak object being accessed for better warning text.
1333 // This enum should stay in sync with the cases in
1334 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1335 enum {
1336 Variable,
1337 Property,
1338 ImplicitProperty,
1339 Ivar
1340 } ObjectKind;
1341
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001342 const NamedDecl *KeyProp = Key.getProperty();
1343 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001344 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001345 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001346 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001347 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001348 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001349 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001350 ObjectKind = Ivar;
1351 else
1352 llvm_unreachable("Unexpected weak object kind!");
1353
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001354 // Do not warn about IBOutlet weak property receivers being set to null
1355 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001356 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001357 if (Prop->hasAttr<IBOutletAttr>())
1358 continue;
1359
Jordan Rosed3934582012-09-28 22:21:30 +00001360 // Show the first time the object was read.
1361 S.Diag(FirstRead->getLocStart(), DiagKind)
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001362 << int(ObjectKind) << KeyProp << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001363 << FirstRead->getSourceRange();
1364
1365 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001366 for (const auto &Use : Uses) {
1367 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001368 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001369 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001370 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001371 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001372 }
1373 }
1374}
1375
Jordan Rosed3934582012-09-28 22:21:30 +00001376namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001377class UninitValsDiagReporter : public UninitVariablesHandler {
1378 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001379 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001380 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001381 // Prefer using MapVector to DenseMap, so that iteration order will be
1382 // the same as insertion order. This is needed to obtain a deterministic
1383 // order of diagnostics when calling flushDiagnostics().
1384 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001385 UsesMap uses;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001386
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001387public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001388 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001389 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001390
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001391 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001392 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001393 if (!V.getPointer())
1394 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001395 return V;
1396 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001397
1398 void handleUseOfUninitVariable(const VarDecl *vd,
1399 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001400 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001401 }
1402
Craig Toppere14c0f82014-03-12 04:55:44 +00001403 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001404 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001405 }
1406
1407 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001408 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001409 const VarDecl *vd = P.first;
1410 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001411
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001412 UsesVec *vec = V.getPointer();
1413 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001414
1415 // Specially handle the case where we have uses of an uninitialized
1416 // variable, but the root cause is an idiomatic self-init. We want
1417 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001418 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001419 DiagnoseUninitializedUse(S, vd,
1420 UninitUse(vd->getInit()->IgnoreParenCasts(),
1421 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001422 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001423 else {
1424 // Sort the uses by their SourceLocations. While not strictly
1425 // guaranteed to produce them in line/column order, this will provide
1426 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001427 std::sort(vec->begin(), vec->end(),
1428 [](const UninitUse &a, const UninitUse &b) {
1429 // Prefer a more confident report over a less confident one.
1430 if (a.getKind() != b.getKind())
1431 return a.getKind() > b.getKind();
1432 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1433 });
1434
Aaron Ballmane5195222014-05-15 20:50:47 +00001435 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001436 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001437 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001438
1439 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001440 // Skip further diagnostics for this variable. We try to warn only
1441 // on the first point at which a variable is used uninitialized.
1442 break;
1443 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001444 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001445
1446 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001447 delete vec;
1448 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001449
1450 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001451 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001452
1453private:
1454 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001455 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1456 return U.getKind() == UninitUse::Always ||
1457 U.getKind() == UninitUse::AfterCall ||
1458 U.getKind() == UninitUse::AfterDecl;
1459 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001460 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001461};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001462} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001463
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001464namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001465namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001466typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001467typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001468typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001469
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001470struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001471 SourceManager &SM;
1472 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001473
1474 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1475 // Although this call will be slow, this is only called when outputting
1476 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001477 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001478 }
1479};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001480} // anonymous namespace
1481} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001482
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001483//===----------------------------------------------------------------------===//
1484// -Wthread-safety
1485//===----------------------------------------------------------------------===//
1486namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001487namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001488namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001489class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001490 Sema &S;
1491 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001492 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001493
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001494 const FunctionDecl *CurrentFunction;
1495 bool Verbose;
1496
Aaron Ballman71291bc2014-08-15 12:38:17 +00001497 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001498 if (Verbose && CurrentFunction) {
1499 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001500 S.PDiag(diag::note_thread_warning_in_fun)
1501 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001502 return OptionalNotes(1, FNote);
1503 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001504 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001505 }
1506
Aaron Ballman71291bc2014-08-15 12:38:17 +00001507 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001508 OptionalNotes ONS(1, Note);
1509 if (Verbose && CurrentFunction) {
1510 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001511 S.PDiag(diag::note_thread_warning_in_fun)
1512 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001513 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001514 }
1515 return ONS;
1516 }
1517
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001518 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1519 const PartialDiagnosticAt &Note2) const {
1520 OptionalNotes ONS;
1521 ONS.push_back(Note1);
1522 ONS.push_back(Note2);
1523 if (Verbose && CurrentFunction) {
1524 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1525 S.PDiag(diag::note_thread_warning_in_fun)
1526 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001527 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001528 }
1529 return ONS;
1530 }
1531
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001532 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001533 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1534 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001535 // Gracefully handle rare cases when the analysis can't get a more
1536 // precise source location.
1537 if (!Loc.isValid())
1538 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001539 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001540 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001541 }
1542
1543 public:
Richard Smith92286672012-02-03 04:45:26 +00001544 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001545 : S(S), FunLocation(FL), FunEndLocation(FEL),
1546 CurrentFunction(nullptr), Verbose(false) {}
1547
1548 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001549
1550 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1551 /// We need to output diagnostics produced while iterating through
1552 /// the lockset in deterministic order, so this function orders diagnostics
1553 /// and outputs them.
1554 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001555 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001556 for (const auto &Diag : Warnings) {
1557 S.Diag(Diag.first.first, Diag.first.second);
1558 for (const auto &Note : Diag.second)
1559 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001560 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001561 }
1562
Aaron Ballmane0449042014-04-01 21:43:23 +00001563 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1564 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1565 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001566 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001567 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001568
Aaron Ballmane0449042014-04-01 21:43:23 +00001569 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1570 SourceLocation Loc) override {
1571 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001572 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001573
Aaron Ballmane0449042014-04-01 21:43:23 +00001574 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1575 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001576 SourceLocation Loc) override {
1577 if (Loc.isInvalid())
1578 Loc = FunLocation;
1579 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001580 << Kind << LockName << Received
1581 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001582 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001583 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001584
Aaron Ballmane0449042014-04-01 21:43:23 +00001585 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1586 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001587 }
1588
Aaron Ballmane0449042014-04-01 21:43:23 +00001589 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1590 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001591 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001592 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001593 unsigned DiagID = 0;
1594 switch (LEK) {
1595 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001596 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001597 break;
1598 case LEK_LockedSomeLoopIterations:
1599 DiagID = diag::warn_expecting_lock_held_on_loop;
1600 break;
1601 case LEK_LockedAtEndOfFunction:
1602 DiagID = diag::warn_no_unlock;
1603 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001604 case LEK_NotLockedAtEndOfFunction:
1605 DiagID = diag::warn_expecting_locked;
1606 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001607 }
Richard Smith92286672012-02-03 04:45:26 +00001608 if (LocEndOfScope.isInvalid())
1609 LocEndOfScope = FunEndLocation;
1610
Aaron Ballmane0449042014-04-01 21:43:23 +00001611 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1612 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001613 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001614 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1615 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001616 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001617 return;
1618 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001619 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001620 }
1621
Aaron Ballmane0449042014-04-01 21:43:23 +00001622 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1623 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001624 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001625 PartialDiagnosticAt Warning(Loc1,
1626 S.PDiag(diag::warn_lock_exclusive_and_shared)
1627 << Kind << LockName);
1628 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1629 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001630 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001631 }
1632
Aaron Ballmane0449042014-04-01 21:43:23 +00001633 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1634 ProtectedOperationKind POK, AccessKind AK,
1635 SourceLocation Loc) override {
1636 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1637 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001638 unsigned DiagID = POK == POK_VarAccess?
1639 diag::warn_variable_requires_any_lock:
1640 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001641 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001642 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001643 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001644 }
1645
Aaron Ballmane0449042014-04-01 21:43:23 +00001646 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1647 ProtectedOperationKind POK, Name LockName,
1648 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001649 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001650 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001651 if (PossibleMatch) {
1652 switch (POK) {
1653 case POK_VarAccess:
1654 DiagID = diag::warn_variable_requires_lock_precise;
1655 break;
1656 case POK_VarDereference:
1657 DiagID = diag::warn_var_deref_requires_lock_precise;
1658 break;
1659 case POK_FunctionCall:
1660 DiagID = diag::warn_fun_requires_lock_precise;
1661 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001662 case POK_PassByRef:
1663 DiagID = diag::warn_guarded_pass_by_reference;
1664 break;
1665 case POK_PtPassByRef:
1666 DiagID = diag::warn_pt_guarded_pass_by_reference;
1667 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001668 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001669 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1670 << D->getNameAsString()
1671 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001672 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001673 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001674 if (Verbose && POK == POK_VarAccess) {
1675 PartialDiagnosticAt VNote(D->getLocation(),
1676 S.PDiag(diag::note_guarded_by_declared_here)
1677 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001678 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001679 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001680 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001681 } else {
1682 switch (POK) {
1683 case POK_VarAccess:
1684 DiagID = diag::warn_variable_requires_lock;
1685 break;
1686 case POK_VarDereference:
1687 DiagID = diag::warn_var_deref_requires_lock;
1688 break;
1689 case POK_FunctionCall:
1690 DiagID = diag::warn_fun_requires_lock;
1691 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001692 case POK_PassByRef:
1693 DiagID = diag::warn_guarded_pass_by_reference;
1694 break;
1695 case POK_PtPassByRef:
1696 DiagID = diag::warn_pt_guarded_pass_by_reference;
1697 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001698 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001699 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1700 << D->getNameAsString()
1701 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001702 if (Verbose && POK == POK_VarAccess) {
1703 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001704 S.PDiag(diag::note_guarded_by_declared_here)
1705 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001706 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001707 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001708 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001709 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001710 }
1711
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001712 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1713 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001714 PartialDiagnosticAt Warning(Loc,
1715 S.PDiag(diag::warn_acquire_requires_negative_cap)
1716 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001717 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001718 }
1719
Aaron Ballmane0449042014-04-01 21:43:23 +00001720 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001721 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001722 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1723 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001724 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001725 }
1726
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001727 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1728 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001729 PartialDiagnosticAt Warning(Loc,
1730 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001731 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001732 }
1733
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001734 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001735 PartialDiagnosticAt Warning(Loc,
1736 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001737 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001738 }
1739
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001740 void enterFunction(const FunctionDecl* FD) override {
1741 CurrentFunction = FD;
1742 }
1743
1744 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001745 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001746 }
1747};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001748} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001749} // namespace threadSafety
1750} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001751
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001752//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001753// -Wconsumed
1754//===----------------------------------------------------------------------===//
1755
1756namespace clang {
1757namespace consumed {
1758namespace {
1759class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1760
1761 Sema &S;
1762 DiagList Warnings;
1763
1764public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001765
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001766 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001767
1768 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001769 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001770 for (const auto &Diag : Warnings) {
1771 S.Diag(Diag.first.first, Diag.first.second);
1772 for (const auto &Note : Diag.second)
1773 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001774 }
1775 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001776
1777 void warnLoopStateMismatch(SourceLocation Loc,
1778 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001779 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1780 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001781
1782 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001783 }
1784
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001785 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1786 StringRef VariableName,
1787 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001788 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001789
1790 PartialDiagnosticAt Warning(Loc, S.PDiag(
1791 diag::warn_param_return_typestate_mismatch) << VariableName <<
1792 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001793
1794 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001795 }
1796
DeLesley Hutchins69391772013-10-17 23:23:53 +00001797 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001798 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001799
1800 PartialDiagnosticAt Warning(Loc, S.PDiag(
1801 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001802
1803 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001804 }
1805
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001806 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001807 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001808 PartialDiagnosticAt Warning(Loc, S.PDiag(
1809 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001810
1811 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001812 }
1813
1814 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001815 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001816
1817 PartialDiagnosticAt Warning(Loc, S.PDiag(
1818 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001819
1820 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001821 }
1822
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001823 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001824 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001825
1826 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001827 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001828
1829 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001830 }
1831
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001832 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001833 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001834
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001835 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1836 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001837
1838 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001839 }
1840};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001841} // anonymous namespace
1842} // namespace consumed
1843} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001844
1845//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001846// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1847// warnings on a function, method, or block.
1848//===----------------------------------------------------------------------===//
1849
Ted Kremenek0b405322010-03-23 00:13:23 +00001850clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1851 enableCheckFallThrough = 1;
1852 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001853 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001854 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001855}
1856
Ted Kremenekad8753c2014-03-15 05:47:06 +00001857static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001858 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001859}
1860
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001861clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1862 : S(s),
1863 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001864 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001865 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001866 MaxCFGBlocksPerFunction(0),
1867 NumUninitAnalysisFunctions(0),
1868 NumUninitAnalysisVariables(0),
1869 MaxUninitAnalysisVariablesPerFunction(0),
1870 NumUninitAnalysisBlockVisits(0),
1871 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001872
1873 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001874 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001875
1876 DefaultPolicy.enableCheckUnreachable =
1877 isEnabled(D, warn_unreachable) ||
1878 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001879 isEnabled(D, warn_unreachable_return) ||
1880 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001881
1882 DefaultPolicy.enableThreadSafetyAnalysis =
1883 isEnabled(D, warn_double_lock);
1884
1885 DefaultPolicy.enableConsumedAnalysis =
1886 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001887}
1888
Aaron Ballmane5195222014-05-15 20:50:47 +00001889static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1890 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001891 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001892}
1893
Ted Kremenek0b405322010-03-23 00:13:23 +00001894void clang::sema::
1895AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001896 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001897 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001898
Ted Kremenek918fe842010-03-20 21:06:02 +00001899 // We avoid doing analysis-based warnings when there are errors for
1900 // two reasons:
1901 // (1) The CFGs often can't be constructed (if the body is invalid), so
1902 // don't bother trying.
1903 // (2) The code already has problems; running the analysis just takes more
1904 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001905 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001906
Ted Kremenek0b405322010-03-23 00:13:23 +00001907 // Do not do any analysis for declarations in system headers if we are
1908 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001909 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001910 S.SourceMgr.isInSystemHeader(D->getLocation()))
1911 return;
1912
John McCall1d570a72010-08-25 05:56:39 +00001913 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001914 if (cast<DeclContext>(D)->isDependentContext())
1915 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001916
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00001917 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001918 // Flush out any possibly unreachable diagnostics.
1919 flushDiagnostics(S, fscope);
1920 return;
1921 }
1922
Ted Kremenek918fe842010-03-20 21:06:02 +00001923 const Stmt *Body = D->getBody();
1924 assert(Body);
1925
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001926 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00001927 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001928
Ted Kremenek918fe842010-03-20 21:06:02 +00001929 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001930 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001931 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1932 AC.getCFGBuildOptions().AddEHEdges = false;
1933 AC.getCFGBuildOptions().AddInitializers = true;
1934 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001935 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001936 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00001937 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001938
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001939 // Force that certain expressions appear as CFGElements in the CFG. This
1940 // is used to speed up various analyses.
1941 // FIXME: This isn't the right factoring. This is here for initial
1942 // prototyping, but we need a way for analyses to say what expressions they
1943 // expect to always be CFGElements and then fill in the BuildOptions
1944 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001945 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1946 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001947 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001948 AC.getCFGBuildOptions().setAllAlwaysAdd();
1949 }
1950 else {
1951 AC.getCFGBuildOptions()
1952 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001953 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001954 .setAlwaysAdd(Stmt::BlockExprClass)
1955 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1956 .setAlwaysAdd(Stmt::DeclRefExprClass)
1957 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001958 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1959 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001960 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001961
Richard Trieue9fa2662014-04-15 00:57:50 +00001962 // Install the logical handler for -Wtautological-overlap-compare
1963 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001964 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1965 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00001966 LEH.reset(new LogicalErrorHandler(S));
1967 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00001968 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001969
Ted Kremenek3427fac2011-02-23 01:52:04 +00001970 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001971 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001972 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001973
1974 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00001975 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1976 if (D.stmt)
1977 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00001978 }
1979
1980 if (AC.getCFG()) {
1981 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00001982 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00001983 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00001984 if (D.stmt) {
1985 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001986 CFGReverseBlockReachabilityAnalysis *cra =
1987 AC.getCFGReachablityAnalysis();
1988 // FIXME: We should be able to assert that block is non-null, but
1989 // the CFG analysis can skip potentially-evaluated expressions in
1990 // edge cases; see test/Sema/vla-2.c.
1991 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001992 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001993 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001994 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001995 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001996 }
1997 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001998 if (!processed) {
1999 // Emit the warning anyway if we cannot map to a basic block.
2000 S.Diag(D.Loc, D.PD);
2001 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002002 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002003 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002004
2005 if (!analyzed)
2006 flushDiagnostics(S, fscope);
2007 }
2008
Ted Kremenek918fe842010-03-20 21:06:02 +00002009 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002010 if (P.enableCheckFallThrough) {
Eric Fiselier709d1b32016-10-27 07:30:31 +00002011 auto IsCoro = [&]() {
2012 if (auto *FD = dyn_cast<FunctionDecl>(D))
2013 if (FD->getBody() && isa<CoroutineBodyStmt>(FD->getBody()))
2014 return true;
2015 return false;
2016 };
Ted Kremenek918fe842010-03-20 21:06:02 +00002017 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002018 (isa<BlockDecl>(D)
2019 ? CheckFallThroughDiagnostics::MakeForBlock()
2020 : (isa<CXXMethodDecl>(D) &&
2021 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2022 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2023 ? CheckFallThroughDiagnostics::MakeForLambda()
2024 : (IsCoro()
2025 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2026 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Ted Kremenek1767a272011-02-23 01:51:48 +00002027 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00002028 }
2029
2030 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002031 if (P.enableCheckUnreachable) {
2032 // Only check for unreachable code on non-template instantiations.
2033 // Different template instantiations can effectively change the control-flow
2034 // and it is very difficult to prove that a snippet of code in a template
2035 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002036 bool isTemplateInstantiation = false;
2037 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2038 isTemplateInstantiation = Function->isTemplateInstantiation();
2039 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002040 CheckUnreachable(S, AC);
2041 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002042
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002043 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002044 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002045 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00002046 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002047 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002048 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002049 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002050 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2051 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002052
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002053 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2054 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002055 Reporter.emitDiagnostics();
2056 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002057
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002058 // Check for violations of consumed properties.
2059 if (P.enableConsumedAnalysis) {
2060 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002061 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002062 Analyzer.run(AC);
2063 }
2064
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002065 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2066 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2067 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002068 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002069 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002070 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002071 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002072 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002073 reporter, stats);
2074
2075 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2076 ++NumUninitAnalysisFunctions;
2077 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2078 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2079 MaxUninitAnalysisVariablesPerFunction =
2080 std::max(MaxUninitAnalysisVariablesPerFunction,
2081 stats.NumVariablesAnalyzed);
2082 MaxUninitAnalysisBlockVisitsPerFunction =
2083 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2084 stats.NumBlockVisits);
2085 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002086 }
2087 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002088
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002089 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002090 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2091 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2092 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Richard Smith4f902c72016-03-08 00:32:55 +00002093 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2094 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002095 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002096 }
2097
John McCall460ce582015-10-22 18:38:17 +00002098 if (S.getLangOpts().ObjCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002099 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002100 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002101
Richard Trieu2f024f42013-12-21 02:33:43 +00002102
2103 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002104 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2105 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002106 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2107 checkRecursiveFunction(S, FD, Body, AC);
2108 }
2109 }
2110
Richard Trieue9fa2662014-04-15 00:57:50 +00002111 // If none of the previous checks caused a CFG build, trigger one here
2112 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002113 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002114 D->getLocStart())) {
2115 AC.getCFG();
2116 }
2117
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002118 // Collect statistics about the CFG if it was built.
2119 if (S.CollectStats && AC.isCFGBuilt()) {
2120 ++NumFunctionsAnalyzed;
2121 if (CFG *cfg = AC.getCFG()) {
2122 // If we successfully built a CFG for this context, record some more
2123 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002124 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002125 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002126 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002127 } else {
2128 ++NumFunctionsWithBadCFGs;
2129 }
2130 }
2131}
2132
2133void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2134 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2135
2136 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2137 unsigned AvgCFGBlocksPerFunction =
2138 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2139 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2140 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2141 << " " << NumCFGBlocks << " CFG blocks built.\n"
2142 << " " << AvgCFGBlocksPerFunction
2143 << " average CFG blocks per function.\n"
2144 << " " << MaxCFGBlocksPerFunction
2145 << " max CFG blocks per function.\n";
2146
2147 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2148 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2149 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2150 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2151 llvm::errs() << NumUninitAnalysisFunctions
2152 << " functions analyzed for uninitialiazed variables\n"
2153 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2154 << " " << AvgUninitVariablesPerFunction
2155 << " average variables per function.\n"
2156 << " " << MaxUninitAnalysisVariablesPerFunction
2157 << " max variables per function.\n"
2158 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2159 << " " << AvgUninitBlockVisitsPerFunction
2160 << " average block visits per function.\n"
2161 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2162 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002163}