blob: 3b6cbe9469b70c574fbf03ccb79d8e52eeec6781 [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"
George Karpenkov50657f62017-09-06 21:45:03 +000032#include "clang/Analysis/AnalysisDeclContext.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000033#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;
Alex Lorenz569ad732017-01-12 10:48:03 +000059 SourceRange PreviousSilenceableCondVal;
60
Ted Kremenek918fe842010-03-20 21:06:02 +000061 public:
62 UnreachableCodeHandler(Sema &s) : S(s) {}
63
Ted Kremenek1a8641c2014-03-15 01:26:32 +000064 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000065 SourceLocation L,
66 SourceRange SilenceableCondVal,
67 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000068 SourceRange R2) override {
Alex Lorenz569ad732017-01-12 10:48:03 +000069 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
74 return;
75 PreviousSilenceableCondVal = SilenceableCondVal;
76
Ted Kremenek1a8641c2014-03-15 01:26:32 +000077 unsigned diag = diag::warn_unreachable;
78 switch (UK) {
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
81 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000082 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000083 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 break;
Ted Kremenek14210372014-03-21 06:02:36 +000085 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
87 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000088 case reachable_code::UK_Other:
89 break;
90 }
91
92 S.Diag(L, diag) << R1 << R2;
Fangrui Song6907ce22018-07-30 19:24:48 +000093
Ted Kremenekec3bbf42014-03-29 00:35:20 +000094 SourceLocation Open = SilenceableCondVal.getBegin();
95 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000096 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000098 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
102 }
103 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000104 }
105 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000106} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +0000107
108/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000109static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
114 //
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
Ted Kremenekc1b28752014-02-25 22:35:37 +0000118 return;
119
Ted Kremenek918fe842010-03-20 21:06:02 +0000120 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000122}
123
Benjamin Kramer3a002252015-02-16 16:53:12 +0000124namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000125/// Warn on logical operator errors in CFGBuilder
Richard Trieuf935b562014-04-05 05:17:01 +0000126class LogicalErrorHandler : public CFGCallback {
127 Sema &S;
128
129public:
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
131
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
134 return true;
135
136 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000137 for (const Stmt *SubStmt : E->children())
138 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
139 if (HasMacroID(SubExpr))
140 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000141
142 return false;
143 }
144
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000146 if (HasMacroID(B))
147 return;
148
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
152 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000153
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000156 if (HasMacroID(B))
157 return;
158
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
162 }
Richard Trieuf935b562014-04-05 05:17:01 +0000163};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000164} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000165
Ted Kremenek918fe842010-03-20 21:06:02 +0000166//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000167// Check for infinite self-recursion in functions
168//===----------------------------------------------------------------------===//
169
Richard Trieu6995de92015-08-21 03:43:09 +0000170// Returns true if the function is called anywhere within the CFGBlock.
171// For member functions, the additional condition of being call from the
172// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000173static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000174 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000175 for (const auto &B : Block) {
176 if (B.getKind() != CFGElement::Statement)
177 continue;
178
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
182 continue;
183
184 // Skip function calls which are qualified with a templated class.
185 if (const DeclRefExpr *DRE =
186 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
187 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
188 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
189 isa<TemplateSpecializationType>(NNS->getAsType())) {
190 continue;
191 }
192 }
193 }
194
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
198 return true;
199 }
200 return false;
201}
202
Robert Widmann97608442018-03-22 03:16:23 +0000203// Returns true if every path from the entry block passes through a call to FD.
Richard Trieu6995de92015-08-21 03:43:09 +0000204static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
Robert Widmann97608442018-03-22 03:16:23 +0000205 llvm::SmallPtrSet<CFGBlock *, 16> Visited;
206 llvm::SmallVector<CFGBlock *, 16> WorkList;
207 // Keep track of whether we found at least one recursive path.
208 bool foundRecursion = false;
Richard Trieu6995de92015-08-21 03:43:09 +0000209
210 const unsigned ExitID = cfg->getExit().getBlockID();
211
Robert Widmann97608442018-03-22 03:16:23 +0000212 // Seed the work list with the entry block.
213 WorkList.push_back(&cfg->getEntry());
Richard Trieu6995de92015-08-21 03:43:09 +0000214
Robert Widmann97608442018-03-22 03:16:23 +0000215 while (!WorkList.empty()) {
216 CFGBlock *Block = WorkList.pop_back_val();
Richard Trieu2f024f42013-12-21 02:33:43 +0000217
Robert Widmann97608442018-03-22 03:16:23 +0000218 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
219 if (CFGBlock *SuccBlock = *I) {
220 if (!Visited.insert(SuccBlock).second)
221 continue;
Richard Trieu2f024f42013-12-21 02:33:43 +0000222
Robert Widmann97608442018-03-22 03:16:23 +0000223 // Found a path to the exit node without a recursive call.
224 if (ExitID == SuccBlock->getBlockID())
225 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000226
Robert Widmann97608442018-03-22 03:16:23 +0000227 // If the successor block contains a recursive call, end analysis there.
228 if (hasRecursiveCallInPath(FD, *SuccBlock)) {
229 foundRecursion = true;
230 continue;
Richard Trieu6995de92015-08-21 03:43:09 +0000231 }
Richard Trieu6995de92015-08-21 03:43:09 +0000232
Robert Widmann97608442018-03-22 03:16:23 +0000233 WorkList.push_back(SuccBlock);
234 }
235 }
236 }
237 return foundRecursion;
Richard Trieu2f024f42013-12-21 02:33:43 +0000238}
239
240static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000241 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000242 FD = FD->getCanonicalDecl();
243
244 // Only run on non-templated functions and non-templated members of
245 // templated classes.
246 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
247 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
248 return;
249
250 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000251 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000252
Richard Trieu6995de92015-08-21 03:43:09 +0000253 // Emit diagnostic if a recursive function call is detected for all paths.
254 if (checkForRecursiveFunctionCall(FD, cfg))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000255 S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
Richard Trieu2f024f42013-12-21 02:33:43 +0000256}
257
258//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000259// Check for throw in a non-throwing function.
260//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000261
Richard Smith08482102018-02-20 02:32:30 +0000262/// Determine whether an exception thrown by E, unwinding from ThrowBlock,
263/// can reach ExitBlock.
264static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
265 CFG *Body) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000266 SmallVector<CFGBlock *, 16> Stack;
Richard Smith08482102018-02-20 02:32:30 +0000267 llvm::BitVector Queued(Body->getNumBlockIDs());
Erich Keane89fe9c22017-06-23 20:22:19 +0000268
Richard Smith08482102018-02-20 02:32:30 +0000269 Stack.push_back(&ThrowBlock);
270 Queued[ThrowBlock.getBlockID()] = true;
271
272 while (!Stack.empty()) {
273 CFGBlock &UnwindBlock = *Stack.back();
274 Stack.pop_back();
275
276 for (auto &Succ : UnwindBlock.succs()) {
277 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
Erich Keane89fe9c22017-06-23 20:22:19 +0000278 continue;
279
Richard Smith08482102018-02-20 02:32:30 +0000280 if (Succ->getBlockID() == Body->getExit().getBlockID())
281 return true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000282
Richard Smith08482102018-02-20 02:32:30 +0000283 if (auto *Catch =
284 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
285 QualType Caught = Catch->getCaughtType();
286 if (Caught.isNull() || // catch (...) catches everything
287 !E->getSubExpr() || // throw; is considered cuaght by any handler
288 S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
289 // Exception doesn't escape via this path.
290 break;
291 } else {
292 Stack.push_back(Succ);
293 Queued[Succ->getBlockID()] = true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000294 }
Richard Smith08482102018-02-20 02:32:30 +0000295 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000296 }
Richard Smith08482102018-02-20 02:32:30 +0000297
298 return false;
299}
300
301static void visitReachableThrows(
302 CFG *BodyCFG,
303 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
304 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
305 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
306 for (CFGBlock *B : *BodyCFG) {
307 if (!Reachable[B->getBlockID()])
308 continue;
309 for (CFGElement &E : *B) {
310 Optional<CFGStmt> S = E.getAs<CFGStmt>();
311 if (!S)
312 continue;
313 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
314 Visit(Throw, *B);
315 }
316 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000317}
318
319static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
320 const FunctionDecl *FD) {
Erich Keane7538b352017-07-05 16:43:45 +0000321 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
322 FD->getTypeSourceInfo()) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000323 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
324 if (S.getLangOpts().CPlusPlus11 &&
325 (isa<CXXDestructorDecl>(FD) ||
326 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
Erich Keane7538b352017-07-05 16:43:45 +0000327 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
328 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
329 getAs<FunctionProtoType>())
330 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
331 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
332 << FD->getExceptionSpecSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +0000333 } else
Erich Keane7538b352017-07-05 16:43:45 +0000334 S.Diag(FD->getLocation(), diag::note_throw_in_function)
335 << FD->getExceptionSpecSourceRange();
Erich Keane89fe9c22017-06-23 20:22:19 +0000336 }
337}
338
339static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
340 AnalysisDeclContext &AC) {
341 CFG *BodyCFG = AC.getCFG();
342 if (!BodyCFG)
343 return;
344 if (BodyCFG->getExit().pred_empty())
345 return;
Richard Smith08482102018-02-20 02:32:30 +0000346 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
347 if (throwEscapes(S, Throw, Block, BodyCFG))
348 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
349 });
Erich Keane89fe9c22017-06-23 20:22:19 +0000350}
351
352static bool isNoexcept(const FunctionDecl *FD) {
353 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000354 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
Erich Keane89fe9c22017-06-23 20:22:19 +0000355 return true;
356 return false;
357}
358
359//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000360// Check for missing return value.
361//===----------------------------------------------------------------------===//
362
John McCall5c6ec8c2010-05-16 09:34:11 +0000363enum ControlFlowKind {
364 UnknownFallThrough,
365 NeverFallThrough,
366 MaybeFallThrough,
367 AlwaysFallThrough,
368 NeverFallThroughOrReturn
369};
Ted Kremenek918fe842010-03-20 21:06:02 +0000370
371/// CheckFallThrough - Check that we don't fall off the end of a
372/// Statement that should return a value.
373///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000374/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
375/// MaybeFallThrough iff we might or might not fall off the end,
376/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
377/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000378/// statement but we may return. We assume that functions not marked noreturn
379/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000380static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000381 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000382 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000383
384 // The CFG leaves in dead things, and we don't want the dead code paths to
385 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000386 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000387 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000388 live);
389
390 bool AddEHEdges = AC.getAddEHEdges();
391 if (!AddEHEdges && count != cfg->getNumBlockIDs())
392 // When there are things remaining dead, and we didn't add EH edges
393 // from CallExprs to the catch clauses, we have to go back and
394 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000395 for (const auto *B : *cfg) {
396 if (!live[B->getBlockID()]) {
397 if (B->pred_begin() == B->pred_end()) {
398 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000399 // When not adding EH edges from calls, catch clauses
400 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000401 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000402 continue;
403 }
404 }
405 }
406
407 // Now we know what is live, we check the live precessors of the exit block
408 // and look for fall through paths, being careful to ignore normal returns,
409 // and exceptional paths.
410 bool HasLiveReturn = false;
411 bool HasFakeEdge = false;
412 bool HasPlainEdge = false;
413 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000414
415 // Ignore default cases that aren't likely to be reachable because all
416 // enums in a switch(X) have explicit case statements.
417 CFGBlock::FilterOptions FO;
418 FO.IgnoreDefaultsWithCoveredEnums = 1;
419
Fangrui Song99337e22018-07-20 08:19:20 +0000420 for (CFGBlock::filtered_pred_iterator I =
421 cfg->getExit().filtered_pred_start_end(FO);
422 I.hasMore(); ++I) {
423 const CFGBlock &B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000424 if (!live[B.getBlockID()])
425 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000426
Chandler Carruth03faf782011-09-13 09:53:58 +0000427 // Skip blocks which contain an element marked as no-return. They don't
428 // represent actually viable edges into the exit block, so mark them as
429 // abnormal.
430 if (B.hasNoReturnElement()) {
431 HasAbnormalEdge = true;
432 continue;
433 }
434
Ted Kremenek5d068492011-01-26 04:49:52 +0000435 // Destructors can appear after the 'return' in the CFG. This is
436 // normal. We need to look pass the destructors for the return
437 // statement (if it exists).
438 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000439
Chandler Carruth03faf782011-09-13 09:53:58 +0000440 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000441 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000442 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000443
Ted Kremenek5d068492011-01-26 04:49:52 +0000444 // No more CFGElements in the block?
445 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000446 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
447 HasAbnormalEdge = true;
448 continue;
449 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000450 // A labeled empty statement, or the entry block...
451 HasPlainEdge = true;
452 continue;
453 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000454
David Blaikie2a01f5d2013-02-21 20:58:29 +0000455 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000456 const Stmt *S = CS.getStmt();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000457 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000458 HasLiveReturn = true;
459 continue;
460 }
461 if (isa<ObjCAtThrowStmt>(S)) {
462 HasFakeEdge = true;
463 continue;
464 }
465 if (isa<CXXThrowExpr>(S)) {
466 HasFakeEdge = true;
467 continue;
468 }
Chad Rosier32503022012-06-11 20:47:18 +0000469 if (isa<MSAsmStmt>(S)) {
470 // TODO: Verify this is correct.
471 HasFakeEdge = true;
472 HasLiveReturn = true;
473 continue;
474 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000475 if (isa<CXXTryStmt>(S)) {
476 HasAbnormalEdge = true;
477 continue;
478 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000479 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
480 == B.succ_end()) {
481 HasAbnormalEdge = true;
482 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000483 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000484
485 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000486 }
487 if (!HasPlainEdge) {
488 if (HasLiveReturn)
489 return NeverFallThrough;
490 return NeverFallThroughOrReturn;
491 }
492 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
493 return MaybeFallThrough;
494 // This says AlwaysFallThrough for calls to functions that are not marked
495 // noreturn, that don't return. If people would like this warning to be more
496 // accurate, such functions should be marked as noreturn.
497 return AlwaysFallThrough;
498}
499
Dan Gohman28ade552010-07-26 21:25:24 +0000500namespace {
501
Ted Kremenek918fe842010-03-20 21:06:02 +0000502struct CheckFallThroughDiagnostics {
503 unsigned diag_MaybeFallThrough_HasNoReturn;
504 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
505 unsigned diag_AlwaysFallThrough_HasNoReturn;
506 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
507 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000508 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000509 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000510
Douglas Gregor24f27692010-04-16 23:28:44 +0000511 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000512 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000513 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000514 D.diag_MaybeFallThrough_HasNoReturn =
515 diag::warn_falloff_noreturn_function;
516 D.diag_MaybeFallThrough_ReturnsNonVoid =
517 diag::warn_maybe_falloff_nonvoid_function;
518 D.diag_AlwaysFallThrough_HasNoReturn =
519 diag::warn_falloff_noreturn_function;
520 D.diag_AlwaysFallThrough_ReturnsNonVoid =
521 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000522
523 // Don't suggest that virtual functions be marked "noreturn", since they
524 // might be overridden by non-noreturn functions.
525 bool isVirtualMethod = false;
526 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
527 isVirtualMethod = Method->isVirtual();
Fangrui Song6907ce22018-07-30 19:24:48 +0000528
Douglas Gregor0de57202011-10-10 18:15:57 +0000529 // Don't suggest that template instantiations be marked "noreturn"
530 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000531 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
532 isTemplateInstantiation = Function->isTemplateInstantiation();
Fangrui Song6907ce22018-07-30 19:24:48 +0000533
Douglas Gregor0de57202011-10-10 18:15:57 +0000534 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000535 D.diag_NeverFallThroughOrReturn =
536 diag::warn_suggest_noreturn_function;
537 else
538 D.diag_NeverFallThroughOrReturn = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +0000539
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000540 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000541 return D;
542 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000543
Eric Fiselier709d1b32016-10-27 07:30:31 +0000544 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
545 CheckFallThroughDiagnostics D;
546 D.FuncLoc = Func->getLocation();
547 D.diag_MaybeFallThrough_HasNoReturn = 0;
548 D.diag_MaybeFallThrough_ReturnsNonVoid =
549 diag::warn_maybe_falloff_nonvoid_coroutine;
550 D.diag_AlwaysFallThrough_HasNoReturn = 0;
551 D.diag_AlwaysFallThrough_ReturnsNonVoid =
552 diag::warn_falloff_nonvoid_coroutine;
553 D.funMode = Coroutine;
554 return D;
555 }
556
Ted Kremenek918fe842010-03-20 21:06:02 +0000557 static CheckFallThroughDiagnostics MakeForBlock() {
558 CheckFallThroughDiagnostics D;
559 D.diag_MaybeFallThrough_HasNoReturn =
560 diag::err_noreturn_block_has_return_expr;
561 D.diag_MaybeFallThrough_ReturnsNonVoid =
562 diag::err_maybe_falloff_nonvoid_block;
563 D.diag_AlwaysFallThrough_HasNoReturn =
564 diag::err_noreturn_block_has_return_expr;
565 D.diag_AlwaysFallThrough_ReturnsNonVoid =
566 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000567 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000568 D.funMode = Block;
569 return D;
570 }
571
572 static CheckFallThroughDiagnostics MakeForLambda() {
573 CheckFallThroughDiagnostics D;
574 D.diag_MaybeFallThrough_HasNoReturn =
575 diag::err_noreturn_lambda_has_return_expr;
576 D.diag_MaybeFallThrough_ReturnsNonVoid =
577 diag::warn_maybe_falloff_nonvoid_lambda;
578 D.diag_AlwaysFallThrough_HasNoReturn =
579 diag::err_noreturn_lambda_has_return_expr;
580 D.diag_AlwaysFallThrough_ReturnsNonVoid =
581 diag::warn_falloff_nonvoid_lambda;
582 D.diag_NeverFallThroughOrReturn = 0;
583 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000584 return D;
585 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000586
David Blaikie9c902b52011-09-25 23:23:43 +0000587 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000588 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000589 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000590 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000591 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
592 FuncLoc)) &&
593 (!HasNoReturn ||
594 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
595 FuncLoc)) &&
596 (!ReturnsVoid ||
597 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000598 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000599 if (funMode == Coroutine) {
600 return (ReturnsVoid ||
601 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
602 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
603 FuncLoc)) &&
604 (!HasNoReturn);
605 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000606 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000607 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000608 }
609};
610
Hans Wennborgdcfba332015-10-06 23:40:43 +0000611} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000612
Reid Kleckner87a31802018-03-12 21:43:02 +0000613/// CheckFallThroughForBody - Check that we don't fall off the end of a
Ted Kremenek918fe842010-03-20 21:06:02 +0000614/// function that should return a value. Check that we don't fall off the end
615/// of a noreturn function. We assume that functions and blocks not marked
616/// noreturn will return.
617static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000618 const BlockExpr *blkExpr,
Reid Kleckner87a31802018-03-12 21:43:02 +0000619 const CheckFallThroughDiagnostics &CD,
620 AnalysisDeclContext &AC,
621 sema::FunctionScopeInfo *FSI) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000622
623 bool ReturnsVoid = false;
624 bool HasNoReturn = false;
Reid Kleckner87a31802018-03-12 21:43:02 +0000625 bool IsCoroutine = FSI->isCoroutine();
Ted Kremenek918fe842010-03-20 21:06:02 +0000626
Eric Fiselier709d1b32016-10-27 07:30:31 +0000627 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
628 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
629 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
630 else
631 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000632 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000633 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000634 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000635 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000636 HasNoReturn = MD->hasAttr<NoReturnAttr>();
637 }
638 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000639 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000640 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000641 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000642 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000643 ReturnsVoid = true;
644 if (FT->getNoReturnAttr())
645 HasNoReturn = true;
646 }
647 }
648
David Blaikie9c902b52011-09-25 23:23:43 +0000649 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000650
651 // Short circuit for compilation speed.
652 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
653 return;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000654 SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000655 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
656 if (IsCoroutine)
Reid Kleckner87a31802018-03-12 21:43:02 +0000657 S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000658 else
659 S.Diag(Loc, DiagID);
660 };
Erich Keane3efe0022018-07-20 14:13:28 +0000661
662 // cpu_dispatch functions permit empty function bodies for ICC compatibility.
663 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
664 return;
665
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000666 // Either in a function body compound statement, or a function-try-block.
667 switch (CheckFallThrough(AC)) {
668 case UnknownFallThrough:
669 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000670
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000671 case MaybeFallThrough:
672 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000673 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000674 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000675 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000676 break;
677 case AlwaysFallThrough:
678 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000679 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000680 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000681 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000682 break;
683 case NeverFallThroughOrReturn:
684 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
685 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
686 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
687 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
688 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
689 } else {
690 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000691 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000692 }
693 break;
694 case NeverFallThrough:
695 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000696 }
697}
698
699//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000700// -Wuninitialized
701//===----------------------------------------------------------------------===//
702
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000703namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000704/// ContainsReference - A visitor class to search for references to
705/// a particular declaration (the needle) within any evaluated component of an
706/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000707class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000708 bool FoundReference;
709 const DeclRefExpr *Needle;
710
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000711public:
Scott Douglass503fc392015-06-10 13:53:15 +0000712 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000713
Scott Douglass503fc392015-06-10 13:53:15 +0000714 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
715 : Inherited(Context), FoundReference(false), Needle(Needle) {}
716
717 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000718 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000719 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000720 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000721
Scott Douglass503fc392015-06-10 13:53:15 +0000722 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000723 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000724
Scott Douglass503fc392015-06-10 13:53:15 +0000725 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000726 if (E == Needle)
727 FoundReference = true;
728 else
Scott Douglass503fc392015-06-10 13:53:15 +0000729 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000730 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000731
732 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000733};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000734} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000735
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000736static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000737 QualType VariableTy = VD->getType().getCanonicalType();
738 if (VariableTy->isBlockPointerType() &&
739 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000740 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
741 << VD->getDeclName()
742 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000743 return true;
744 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000745
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000746 // Don't issue a fixit if there is already an initializer.
747 if (VD->getInit())
748 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000749
750 // Don't suggest a fixit inside macros.
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000751 if (VD->getEndLoc().isMacroID())
Richard Trieu2cdcf822012-05-03 01:09:59 +0000752 return false;
753
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000754 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000755
756 // Suggest possible initialization (if any).
757 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
758 if (Init.empty())
759 return false;
760
Richard Smith8d06f422012-01-12 23:53:29 +0000761 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
762 << FixItHint::CreateInsertion(Loc, Init);
763 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000764}
765
Richard Smith1bb8edb82012-05-26 06:20:46 +0000766/// Create a fixit to remove an if-like statement, on the assumption that its
767/// condition is CondVal.
768static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
769 const Stmt *Else, bool CondVal,
770 FixItHint &Fixit1, FixItHint &Fixit2) {
771 if (CondVal) {
772 // If condition is always true, remove all but the 'then'.
773 Fixit1 = FixItHint::CreateRemoval(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000774 CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000775 if (Else) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000776 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
777 Fixit2 =
778 FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000779 }
780 } else {
781 // If condition is always false, remove all but the 'else'.
782 if (Else)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000783 Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
784 If->getBeginLoc(), Else->getBeginLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000785 else
786 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
787 }
788}
789
790/// DiagUninitUse -- Helper function to produce a diagnostic for an
791/// uninitialized use of a variable.
792static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
793 bool IsCapturedByBlock) {
794 bool Diagnosed = false;
795
Richard Smithba8071e2013-09-12 18:49:10 +0000796 switch (Use.getKind()) {
797 case UninitUse::Always:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000798 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
Richard Smithba8071e2013-09-12 18:49:10 +0000799 << VD->getDeclName() << IsCapturedByBlock
800 << Use.getUser()->getSourceRange();
801 return;
802
803 case UninitUse::AfterDecl:
804 case UninitUse::AfterCall:
805 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
806 << VD->getDeclName() << IsCapturedByBlock
807 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
808 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
809 << VD->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000810 S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
811 << IsCapturedByBlock << Use.getUser()->getSourceRange();
Richard Smithba8071e2013-09-12 18:49:10 +0000812 return;
813
814 case UninitUse::Maybe:
815 case UninitUse::Sometimes:
816 // Carry on to report sometimes-uninitialized branches, if possible,
817 // or a 'may be used uninitialized' diagnostic otherwise.
818 break;
819 }
820
Richard Smith1bb8edb82012-05-26 06:20:46 +0000821 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000822 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
823 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000824 assert(Use.getKind() == UninitUse::Sometimes);
825
826 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000827 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000828
829 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000830 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000831 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000832 SourceRange Range;
833
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000834 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000835 // For all binary terminators, branch 0 is taken if the condition is true,
836 // and branch 1 is taken if the condition is false.
837 int RemoveDiagKind = -1;
838 const char *FixitStr =
839 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
840 : (I->Output ? "1" : "0");
841 FixItHint Fixit1, Fixit2;
842
Richard Smithba8071e2013-09-12 18:49:10 +0000843 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000844 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000845 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000846 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000847 continue;
848
849 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000850 case Stmt::IfStmtClass: {
851 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000852 DiagKind = 0;
853 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000854 Range = IS->getCond()->getSourceRange();
855 RemoveDiagKind = 0;
856 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
857 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000858 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000859 }
860 case Stmt::ConditionalOperatorClass: {
861 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000862 DiagKind = 0;
863 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000864 Range = CO->getCond()->getSourceRange();
865 RemoveDiagKind = 0;
866 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
867 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000868 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000869 }
Richard Smith4323bf82012-05-25 02:17:09 +0000870 case Stmt::BinaryOperatorClass: {
871 const BinaryOperator *BO = cast<BinaryOperator>(Term);
872 if (!BO->isLogicalOp())
873 continue;
874 DiagKind = 0;
875 Str = BO->getOpcodeStr();
876 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000877 RemoveDiagKind = 0;
878 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
879 (BO->getOpcode() == BO_LOr && !I->Output))
880 // true && y -> y, false || y -> y.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000881 Fixit1 = FixItHint::CreateRemoval(
882 SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000883 else
884 // false && y -> false, true || y -> true.
885 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000886 break;
887 }
888
889 // "loop is entered / loop is exited".
890 case Stmt::WhileStmtClass:
891 DiagKind = 1;
892 Str = "while";
893 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000894 RemoveDiagKind = 1;
895 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000896 break;
897 case Stmt::ForStmtClass:
898 DiagKind = 1;
899 Str = "for";
900 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000901 RemoveDiagKind = 1;
902 if (I->Output)
903 Fixit1 = FixItHint::CreateRemoval(Range);
904 else
905 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000906 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000907 case Stmt::CXXForRangeStmtClass:
908 if (I->Output == 1) {
909 // The use occurs if a range-based for loop's body never executes.
910 // That may be impossible, and there's no syntactic fix for this,
911 // so treat it as a 'may be uninitialized' case.
912 continue;
913 }
914 DiagKind = 1;
915 Str = "for";
916 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
917 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000918
919 // "condition is true / loop is exited".
920 case Stmt::DoStmtClass:
921 DiagKind = 2;
922 Str = "do";
923 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000924 RemoveDiagKind = 1;
925 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000926 break;
927
928 // "switch case is taken".
929 case Stmt::CaseStmtClass:
930 DiagKind = 3;
931 Str = "case";
932 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
933 break;
934 case Stmt::DefaultStmtClass:
935 DiagKind = 3;
936 Str = "default";
937 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
938 break;
939 }
940
Richard Smith1bb8edb82012-05-26 06:20:46 +0000941 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
942 << VD->getDeclName() << IsCapturedByBlock << DiagKind
943 << Str << I->Output << Range;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000944 S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
945 << IsCapturedByBlock << User->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000946 if (RemoveDiagKind != -1)
947 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
948 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
949
950 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000951 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000952
953 if (!Diagnosed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000954 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000955 << VD->getDeclName() << IsCapturedByBlock
956 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000957}
958
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000959/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
960/// uninitialized variable. This manages the different forms of diagnostic
961/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000962/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000963/// false.
964static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000965 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000966 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +0000967 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000968 // Inspect the initializer of the variable declaration which is
969 // being referenced prior to its initialization. We emit
970 // specialized diagnostics for self-initialization, and we
971 // specifically avoid warning about self references which take the
972 // form of:
973 //
974 // int x = x;
975 //
976 // This is used to indicate to GCC that 'x' is intentionally left
977 // uninitialized. Proven code paths which access 'x' in
978 // an uninitialized state after this will still warn.
979 if (const Expr *Initializer = VD->getInit()) {
980 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
981 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000982
Richard Trieu43a2fc72012-05-09 21:08:22 +0000983 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +0000984 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +0000985 if (CR.doesContainReference()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000986 S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
987 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
Richard Trieu43a2fc72012-05-09 21:08:22 +0000988 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000989 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000990 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000991
Richard Smith1bb8edb82012-05-26 06:20:46 +0000992 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000993 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000994 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000995 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000996 S.Diag(BE->getBeginLoc(),
Richard Smith1bb8edb82012-05-26 06:20:46 +0000997 diag::warn_uninit_byref_blockvar_captured_by_block)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000998 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000999 else
1000 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +00001001 }
1002
1003 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +00001004 // the initializer of that declaration & we didn't already suggest
1005 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +00001006 if (!SuggestInitializationFixit(S, VD))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001007 S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
1008 << VD->getDeclName();
Chandler Carruth895904da2011-04-05 18:18:05 +00001009
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001010 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +00001011}
1012
Richard Smith84837d52012-05-03 18:27:39 +00001013namespace {
1014 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1015 public:
1016 FallthroughMapper(Sema &S)
1017 : FoundSwitchStatements(false),
1018 S(S) {
1019 }
1020
1021 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1022
1023 void markFallthroughVisited(const AttributedStmt *Stmt) {
1024 bool Found = FallthroughStmts.erase(Stmt);
1025 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +00001026 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +00001027 }
1028
1029 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1030
1031 const AttrStmts &getFallthroughStmts() const {
1032 return FallthroughStmts;
1033 }
1034
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001035 void fillReachableBlocks(CFG *Cfg) {
1036 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1037 std::deque<const CFGBlock *> BlockQueue;
1038
1039 ReachableBlocks.insert(&Cfg->getEntry());
1040 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001041 // Mark all case blocks reachable to avoid problems with switching on
1042 // constants, covered enums, etc.
1043 // These blocks can contain fall-through annotations, and we don't want to
1044 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +00001045 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001046 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +00001047 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001048 BlockQueue.push_back(B);
1049 }
1050
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001051 while (!BlockQueue.empty()) {
1052 const CFGBlock *P = BlockQueue.front();
1053 BlockQueue.pop_front();
1054 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1055 E = P->succ_end();
1056 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001057 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001058 BlockQueue.push_back(*I);
1059 }
1060 }
1061 }
1062
Richard Smith7532d372017-03-22 01:49:19 +00001063 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1064 bool IsTemplateInstantiation) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001065 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1066
Richard Smith84837d52012-05-03 18:27:39 +00001067 int UnannotatedCnt = 0;
1068 AnnotatedCnt = 0;
1069
Aaron Ballmane5195222014-05-15 20:50:47 +00001070 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +00001071 while (!BlockQueue.empty()) {
1072 const CFGBlock *P = BlockQueue.front();
1073 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +00001074 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +00001075
1076 const Stmt *Term = P->getTerminator();
1077 if (Term && isa<SwitchStmt>(Term))
1078 continue; // Switch statement, good.
1079
1080 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1081 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1082 continue; // Previous case label has no statements, good.
1083
Alexander Kornienko09f15f32013-01-25 20:44:56 +00001084 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1085 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1086 continue; // Case label is preceded with a normal label, good.
1087
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001088 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001089 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1090 ElemEnd = P->rend();
1091 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001092 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1093 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith7532d372017-03-22 01:49:19 +00001094 // Don't issue a warning for an unreachable fallthrough
1095 // attribute in template instantiations as it may not be
1096 // unreachable in all instantiations of the template.
1097 if (!IsTemplateInstantiation)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001098 S.Diag(AS->getBeginLoc(),
Richard Smith7532d372017-03-22 01:49:19 +00001099 diag::warn_fallthrough_attr_unreachable);
Richard Smith84837d52012-05-03 18:27:39 +00001100 markFallthroughVisited(AS);
1101 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001102 break;
Richard Smith84837d52012-05-03 18:27:39 +00001103 }
1104 // Don't care about other unreachable statements.
1105 }
1106 }
1107 // If there are no unreachable statements, this may be a special
1108 // case in CFG:
1109 // case X: {
1110 // A a; // A has a destructor.
1111 // break;
1112 // }
1113 // // <<<< This place is represented by a 'hanging' CFG block.
1114 // case Y:
1115 continue;
1116 }
1117
1118 const Stmt *LastStmt = getLastStmt(*P);
1119 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1120 markFallthroughVisited(AS);
1121 ++AnnotatedCnt;
1122 continue; // Fallthrough annotation, good.
1123 }
1124
1125 if (!LastStmt) { // This block contains no executable statements.
1126 // Traverse its predecessors.
1127 std::copy(P->pred_begin(), P->pred_end(),
1128 std::back_inserter(BlockQueue));
1129 continue;
1130 }
1131
1132 ++UnannotatedCnt;
1133 }
1134 return !!UnannotatedCnt;
1135 }
1136
1137 // RecursiveASTVisitor setup.
1138 bool shouldWalkTypesOfTypeLocs() const { return false; }
1139
1140 bool VisitAttributedStmt(AttributedStmt *S) {
1141 if (asFallThroughAttr(S))
1142 FallthroughStmts.insert(S);
1143 return true;
1144 }
1145
1146 bool VisitSwitchStmt(SwitchStmt *S) {
1147 FoundSwitchStatements = true;
1148 return true;
1149 }
1150
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001151 // We don't want to traverse local type declarations. We analyze their
1152 // methods separately.
1153 bool TraverseDecl(Decl *D) { return true; }
1154
Alexander Kornienkobf911642014-06-24 15:28:21 +00001155 // We analyze lambda bodies separately. Skip them here.
1156 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1157
Richard Smith84837d52012-05-03 18:27:39 +00001158 private:
1159
1160 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1161 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1162 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1163 return AS;
1164 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001165 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001166 }
1167
1168 static const Stmt *getLastStmt(const CFGBlock &B) {
1169 if (const Stmt *Term = B.getTerminator())
1170 return Term;
1171 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1172 ElemEnd = B.rend();
1173 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001174 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1175 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001176 }
1177 // Workaround to detect a statement thrown out by CFGBuilder:
1178 // case X: {} case Y:
1179 // case X: ; case Y:
1180 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1181 if (!isa<SwitchCase>(SW->getSubStmt()))
1182 return SW->getSubStmt();
1183
Craig Topperc3ec1492014-05-26 06:22:03 +00001184 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001185 }
1186
1187 bool FoundSwitchStatements;
1188 AttrStmts FallthroughStmts;
1189 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001190 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001191 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001192} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001193
Richard Smith4f902c72016-03-08 00:32:55 +00001194static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1195 SourceLocation Loc) {
1196 TokenValue FallthroughTokens[] = {
1197 tok::l_square, tok::l_square,
1198 PP.getIdentifierInfo("fallthrough"),
1199 tok::r_square, tok::r_square
1200 };
1201
1202 TokenValue ClangFallthroughTokens[] = {
1203 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1204 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1205 tok::r_square, tok::r_square
1206 };
1207
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001208 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
Richard Smith4f902c72016-03-08 00:32:55 +00001209
1210 StringRef MacroName;
1211 if (PreferClangAttr)
1212 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1213 if (MacroName.empty())
1214 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1215 if (MacroName.empty() && !PreferClangAttr)
1216 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1217 if (MacroName.empty())
1218 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1219 return MacroName;
1220}
1221
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001222static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001223 bool PerFunction) {
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001224 // Only perform this analysis when using [[]] attributes. There is no good
1225 // workflow for this warning when not using C++11. There is no good way to
Fangrui Song6907ce22018-07-30 19:24:48 +00001226 // silence the warning (no attribute is available) unless we are using
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001227 // [[]] attributes. One could use pragmas to silence the warning, but as a
1228 // general solution that is gross and not in the spirit of this warning.
Ted Kremenekda5919f2012-11-12 21:20:48 +00001229 //
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001230 // NOTE: This an intermediate solution. There are on-going discussions on
Ted Kremenekda5919f2012-11-12 21:20:48 +00001231 // how to properly support this warning outside of C++11 with an annotation.
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001232 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001233 return;
1234
Richard Smith84837d52012-05-03 18:27:39 +00001235 FallthroughMapper FM(S);
1236 FM.TraverseStmt(AC.getBody());
1237
1238 if (!FM.foundSwitchStatements())
1239 return;
1240
Alexis Hunt2178f142012-06-15 21:22:05 +00001241 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001242 return;
1243
Richard Smith84837d52012-05-03 18:27:39 +00001244 CFG *Cfg = AC.getCFG();
1245
1246 if (!Cfg)
1247 return;
1248
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001249 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001250
Pete Cooper57d3f142015-07-30 17:22:52 +00001251 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001252 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001253
1254 if (!Label || !isa<SwitchCase>(Label))
1255 continue;
1256
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001257 int AnnotatedCnt;
1258
Richard Smith7532d372017-03-22 01:49:19 +00001259 bool IsTemplateInstantiation = false;
1260 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1261 IsTemplateInstantiation = Function->isTemplateInstantiation();
1262 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1263 IsTemplateInstantiation))
Richard Smith84837d52012-05-03 18:27:39 +00001264 continue;
1265
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001266 S.Diag(Label->getBeginLoc(),
1267 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1268 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001269
1270 if (!AnnotatedCnt) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001271 SourceLocation L = Label->getBeginLoc();
Richard Smith84837d52012-05-03 18:27:39 +00001272 if (L.isMacroID())
1273 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001274 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001275 const Stmt *Term = B->getTerminator();
1276 // Skip empty cases.
1277 while (B->empty() && !Term && B->succ_size() == 1) {
1278 B = *B->succ_begin();
1279 Term = B->getTerminator();
1280 }
1281 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001282 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001283 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001284 SmallString<64> TextToInsert(AnnotationSpelling);
1285 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001286 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001287 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001288 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001289 }
Richard Smith84837d52012-05-03 18:27:39 +00001290 }
1291 S.Diag(L, diag::note_insert_break_fixit) <<
1292 FixItHint::CreateInsertion(L, "break; ");
1293 }
1294 }
1295
Aaron Ballmane5195222014-05-15 20:50:47 +00001296 for (const auto *F : FM.getFallthroughStmts())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001297 S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001298}
1299
Jordan Rose25c0ea82012-10-29 17:46:47 +00001300static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1301 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001302 assert(S);
1303
1304 do {
1305 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001306 case Stmt::ForStmtClass:
1307 case Stmt::WhileStmtClass:
1308 case Stmt::CXXForRangeStmtClass:
1309 case Stmt::ObjCForCollectionStmtClass:
1310 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001311 case Stmt::DoStmtClass: {
Fangrui Song407659a2018-11-30 23:41:18 +00001312 Expr::EvalResult Result;
1313 if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx))
Jordan Rose25c0ea82012-10-29 17:46:47 +00001314 return true;
Fangrui Song407659a2018-11-30 23:41:18 +00001315 return Result.Val.getInt().getBoolValue();
Jordan Rose25c0ea82012-10-29 17:46:47 +00001316 }
Jordan Rose76831c62012-10-11 16:10:19 +00001317 default:
1318 break;
1319 }
1320 } while ((S = PM.getParent(S)));
1321
1322 return false;
1323}
1324
Jordan Rosed3934582012-09-28 22:21:30 +00001325static void diagnoseRepeatedUseOfWeak(Sema &S,
1326 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001327 const Decl *D,
1328 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001329 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1330 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1331 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001332 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1333 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001334
Jordan Rose25c0ea82012-10-29 17:46:47 +00001335 ASTContext &Ctx = S.getASTContext();
1336
Jordan Rosed3934582012-09-28 22:21:30 +00001337 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1338
1339 // Extract all weak objects that are referenced more than once.
1340 SmallVector<StmtUsesPair, 8> UsesByStmt;
1341 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1342 I != E; ++I) {
1343 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001344
1345 // Find the first read of the weak object.
1346 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1347 for ( ; UI != UE; ++UI) {
1348 if (UI->isUnsafe())
1349 break;
1350 }
1351
1352 // If there were only writes to this object, don't warn.
1353 if (UI == UE)
1354 continue;
1355
Jordan Rose76831c62012-10-11 16:10:19 +00001356 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001357 // read is not within a loop, don't warn. Additionally, don't warn in a
1358 // loop if the base object is a local variable -- local variables are often
1359 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001360 if (UI == Uses.begin()) {
1361 WeakUseVector::const_iterator UI2 = UI;
1362 for (++UI2; UI2 != UE; ++UI2)
1363 if (UI2->isUnsafe())
1364 break;
1365
Jordan Rose25c0ea82012-10-29 17:46:47 +00001366 if (UI2 == UE) {
1367 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001368 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001369
1370 const WeakObjectProfileTy &Profile = I->first;
1371 if (!Profile.isExactProfile())
1372 continue;
1373
1374 const NamedDecl *Base = Profile.getBase();
1375 if (!Base)
1376 Base = Profile.getProperty();
1377 assert(Base && "A profile always has a base or property.");
1378
1379 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1380 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1381 continue;
1382 }
Jordan Rose76831c62012-10-11 16:10:19 +00001383 }
1384
Jordan Rosed3934582012-09-28 22:21:30 +00001385 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1386 }
1387
1388 if (UsesByStmt.empty())
1389 return;
1390
1391 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001392 SourceManager &SM = S.getSourceManager();
Fangrui Song55fab262018-09-26 22:16:28 +00001393 llvm::sort(UsesByStmt,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001394 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001395 return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
1396 RHS.first->getBeginLoc());
1397 });
Jordan Rosed3934582012-09-28 22:21:30 +00001398
1399 // Classify the current code body for better warning text.
1400 // This enum should stay in sync with the cases in
1401 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1402 // FIXME: Should we use a common classification enum and the same set of
1403 // possibilities all throughout Sema?
1404 enum {
1405 Function,
1406 Method,
1407 Block,
1408 Lambda
1409 } FunctionKind;
1410
1411 if (isa<sema::BlockScopeInfo>(CurFn))
1412 FunctionKind = Block;
1413 else if (isa<sema::LambdaScopeInfo>(CurFn))
1414 FunctionKind = Lambda;
1415 else if (isa<ObjCMethodDecl>(D))
1416 FunctionKind = Method;
1417 else
1418 FunctionKind = Function;
1419
1420 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001421 for (const auto &P : UsesByStmt) {
1422 const Stmt *FirstRead = P.first;
1423 const WeakObjectProfileTy &Key = P.second->first;
1424 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001425
Jordan Rose657b5f42012-09-28 22:21:35 +00001426 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1427 // may not contain enough information to determine that these are different
1428 // properties. We can only be 100% sure of a repeated use in certain cases,
1429 // and we adjust the diagnostic kind accordingly so that the less certain
1430 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001431 unsigned DiagKind;
1432 if (Key.isExactProfile())
1433 DiagKind = diag::warn_arc_repeated_use_of_weak;
1434 else
1435 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1436
Jordan Rose657b5f42012-09-28 22:21:35 +00001437 // Classify the weak object being accessed for better warning text.
1438 // This enum should stay in sync with the cases in
1439 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1440 enum {
1441 Variable,
1442 Property,
1443 ImplicitProperty,
1444 Ivar
1445 } ObjectKind;
1446
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001447 const NamedDecl *KeyProp = Key.getProperty();
1448 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001449 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001450 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001451 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001452 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001453 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001454 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001455 ObjectKind = Ivar;
1456 else
1457 llvm_unreachable("Unexpected weak object kind!");
1458
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001459 // Do not warn about IBOutlet weak property receivers being set to null
1460 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001461 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001462 if (Prop->hasAttr<IBOutletAttr>())
1463 continue;
1464
Jordan Rosed3934582012-09-28 22:21:30 +00001465 // Show the first time the object was read.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001466 S.Diag(FirstRead->getBeginLoc(), DiagKind)
1467 << int(ObjectKind) << KeyProp << int(FunctionKind)
1468 << FirstRead->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001469
1470 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001471 for (const auto &Use : Uses) {
1472 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001473 continue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001474 S.Diag(Use.getUseExpr()->getBeginLoc(),
Jordan Rosed3934582012-09-28 22:21:30 +00001475 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001476 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001477 }
1478 }
1479}
1480
Jordan Rosed3934582012-09-28 22:21:30 +00001481namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001482class UninitValsDiagReporter : public UninitVariablesHandler {
1483 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001484 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001485 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001486 // Prefer using MapVector to DenseMap, so that iteration order will be
1487 // the same as insertion order. This is needed to obtain a deterministic
1488 // order of diagnostics when calling flushDiagnostics().
1489 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001490 UsesMap uses;
Fangrui Song6907ce22018-07-30 19:24:48 +00001491
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001492public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001493 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001494 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001495
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001496 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001497 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001498 if (!V.getPointer())
1499 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001500 return V;
1501 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001502
1503 void handleUseOfUninitVariable(const VarDecl *vd,
1504 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001505 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001506 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001507
Craig Toppere14c0f82014-03-12 04:55:44 +00001508 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001509 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001510 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001511
Ted Kremenek39fa0562011-01-21 19:41:41 +00001512 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001513 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001514 const VarDecl *vd = P.first;
1515 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001516
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001517 UsesVec *vec = V.getPointer();
1518 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001519
Fangrui Song6907ce22018-07-30 19:24:48 +00001520 // Specially handle the case where we have uses of an uninitialized
Ted Kremenek596fa162011-10-13 18:50:06 +00001521 // variable, but the root cause is an idiomatic self-init. We want
1522 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001523 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001524 DiagnoseUninitializedUse(S, vd,
1525 UninitUse(vd->getInit()->IgnoreParenCasts(),
1526 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001527 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001528 else {
1529 // Sort the uses by their SourceLocations. While not strictly
1530 // guaranteed to produce them in line/column order, this will provide
1531 // a stable ordering.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001532 llvm::sort(vec->begin(), vec->end(),
1533 [](const UninitUse &a, const UninitUse &b) {
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001534 // Prefer a more confident report over a less confident one.
1535 if (a.getKind() != b.getKind())
1536 return a.getKind() > b.getKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001537 return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001538 });
1539
Aaron Ballmane5195222014-05-15 20:50:47 +00001540 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001541 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001542 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001543
1544 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001545 // Skip further diagnostics for this variable. We try to warn only
1546 // on the first point at which a variable is used uninitialized.
1547 break;
1548 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001549 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001550
Ted Kremenek596fa162011-10-13 18:50:06 +00001551 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001552 delete vec;
1553 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001554
1555 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001556 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001557
1558private:
1559 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001560 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1561 return U.getKind() == UninitUse::Always ||
1562 U.getKind() == UninitUse::AfterCall ||
1563 U.getKind() == UninitUse::AfterDecl;
1564 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001565 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001566};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001567} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001568
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001569namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001570namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001571typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001572typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001573typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001574
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001575struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001576 SourceManager &SM;
1577 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001578
1579 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1580 // Although this call will be slow, this is only called when outputting
1581 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001582 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001583 }
1584};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001585} // anonymous namespace
1586} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001587
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001588//===----------------------------------------------------------------------===//
1589// -Wthread-safety
1590//===----------------------------------------------------------------------===//
1591namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001592namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001593namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001594class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001595 Sema &S;
1596 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001597 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001598
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001599 const FunctionDecl *CurrentFunction;
1600 bool Verbose;
1601
Aaron Ballman71291bc2014-08-15 12:38:17 +00001602 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001603 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001604 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001605 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001606 << CurrentFunction);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001607 return OptionalNotes(1, FNote);
1608 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001609 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001610 }
1611
Aaron Ballman71291bc2014-08-15 12:38:17 +00001612 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001613 OptionalNotes ONS(1, Note);
1614 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001615 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001616 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001617 << CurrentFunction);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001618 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001619 }
1620 return ONS;
1621 }
1622
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001623 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1624 const PartialDiagnosticAt &Note2) const {
1625 OptionalNotes ONS;
1626 ONS.push_back(Note1);
1627 ONS.push_back(Note2);
1628 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001629 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001630 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001631 << CurrentFunction);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001632 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001633 }
1634 return ONS;
1635 }
1636
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001637 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001638 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1639 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001640 // Gracefully handle rare cases when the analysis can't get a more
1641 // precise source location.
1642 if (!Loc.isValid())
1643 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001644 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001645 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001646 }
1647
1648 public:
Richard Smith92286672012-02-03 04:45:26 +00001649 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001650 : S(S), FunLocation(FL), FunEndLocation(FEL),
1651 CurrentFunction(nullptr), Verbose(false) {}
1652
1653 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001655 /// Emit all buffered diagnostics in order of sourcelocation.
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001656 /// We need to output diagnostics produced while iterating through
1657 /// the lockset in deterministic order, so this function orders diagnostics
1658 /// and outputs them.
1659 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001660 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001661 for (const auto &Diag : Warnings) {
1662 S.Diag(Diag.first.first, Diag.first.second);
1663 for (const auto &Note : Diag.second)
1664 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001665 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001666 }
1667
Aaron Ballmane0449042014-04-01 21:43:23 +00001668 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1669 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1670 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001671 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001672 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001673
Aaron Ballmane0449042014-04-01 21:43:23 +00001674 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1675 SourceLocation Loc) override {
1676 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001677 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001678
Aaron Ballmane0449042014-04-01 21:43:23 +00001679 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1680 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001681 SourceLocation Loc) override {
1682 if (Loc.isInvalid())
1683 Loc = FunLocation;
1684 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001685 << Kind << LockName << Received
1686 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001687 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001688 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001689
Aaron Ballmane0449042014-04-01 21:43:23 +00001690 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1691 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001692 }
1693
Aaron Ballmane0449042014-04-01 21:43:23 +00001694 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1695 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001696 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001697 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001698 unsigned DiagID = 0;
1699 switch (LEK) {
1700 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001701 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001702 break;
1703 case LEK_LockedSomeLoopIterations:
1704 DiagID = diag::warn_expecting_lock_held_on_loop;
1705 break;
1706 case LEK_LockedAtEndOfFunction:
1707 DiagID = diag::warn_no_unlock;
1708 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001709 case LEK_NotLockedAtEndOfFunction:
1710 DiagID = diag::warn_expecting_locked;
1711 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001712 }
Richard Smith92286672012-02-03 04:45:26 +00001713 if (LocEndOfScope.isInvalid())
1714 LocEndOfScope = FunEndLocation;
1715
Aaron Ballmane0449042014-04-01 21:43:23 +00001716 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1717 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001718 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001719 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1720 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001721 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001722 return;
1723 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001724 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001725 }
1726
Aaron Ballmane0449042014-04-01 21:43:23 +00001727 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1728 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001729 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001730 PartialDiagnosticAt Warning(Loc1,
1731 S.PDiag(diag::warn_lock_exclusive_and_shared)
1732 << Kind << LockName);
1733 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1734 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001735 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001736 }
1737
Aaron Ballmane0449042014-04-01 21:43:23 +00001738 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1739 ProtectedOperationKind POK, AccessKind AK,
1740 SourceLocation Loc) override {
1741 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1742 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001743 unsigned DiagID = POK == POK_VarAccess?
1744 diag::warn_variable_requires_any_lock:
1745 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001746 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
Richard Trieub4025802018-03-28 04:16:13 +00001747 << D << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001748 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001749 }
1750
Aaron Ballmane0449042014-04-01 21:43:23 +00001751 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1752 ProtectedOperationKind POK, Name LockName,
1753 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001754 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001755 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001756 if (PossibleMatch) {
1757 switch (POK) {
1758 case POK_VarAccess:
1759 DiagID = diag::warn_variable_requires_lock_precise;
1760 break;
1761 case POK_VarDereference:
1762 DiagID = diag::warn_var_deref_requires_lock_precise;
1763 break;
1764 case POK_FunctionCall:
1765 DiagID = diag::warn_fun_requires_lock_precise;
1766 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001767 case POK_PassByRef:
1768 DiagID = diag::warn_guarded_pass_by_reference;
1769 break;
1770 case POK_PtPassByRef:
1771 DiagID = diag::warn_pt_guarded_pass_by_reference;
1772 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001773 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001774 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
Richard Trieub4025802018-03-28 04:16:13 +00001775 << D
Aaron Ballmane0449042014-04-01 21:43:23 +00001776 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001777 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001778 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001779 if (Verbose && POK == POK_VarAccess) {
1780 PartialDiagnosticAt VNote(D->getLocation(),
1781 S.PDiag(diag::note_guarded_by_declared_here)
1782 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001783 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001784 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001785 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001786 } else {
1787 switch (POK) {
1788 case POK_VarAccess:
1789 DiagID = diag::warn_variable_requires_lock;
1790 break;
1791 case POK_VarDereference:
1792 DiagID = diag::warn_var_deref_requires_lock;
1793 break;
1794 case POK_FunctionCall:
1795 DiagID = diag::warn_fun_requires_lock;
1796 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001797 case POK_PassByRef:
1798 DiagID = diag::warn_guarded_pass_by_reference;
1799 break;
1800 case POK_PtPassByRef:
1801 DiagID = diag::warn_pt_guarded_pass_by_reference;
1802 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001803 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001804 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
Richard Trieub4025802018-03-28 04:16:13 +00001805 << D
Aaron Ballmane0449042014-04-01 21:43:23 +00001806 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001807 if (Verbose && POK == POK_VarAccess) {
1808 PartialDiagnosticAt Note(D->getLocation(),
Richard Trieub4025802018-03-28 04:16:13 +00001809 S.PDiag(diag::note_guarded_by_declared_here));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001810 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001811 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001812 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001813 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001814 }
1815
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001816 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1817 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001818 PartialDiagnosticAt Warning(Loc,
1819 S.PDiag(diag::warn_acquire_requires_negative_cap)
1820 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001821 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001822 }
1823
Aaron Ballmane0449042014-04-01 21:43:23 +00001824 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001825 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001826 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1827 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001828 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001829 }
1830
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001831 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1832 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001833 PartialDiagnosticAt Warning(Loc,
1834 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001835 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001836 }
1837
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001838 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001839 PartialDiagnosticAt Warning(Loc,
1840 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001841 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001842 }
1843
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001844 void enterFunction(const FunctionDecl* FD) override {
1845 CurrentFunction = FD;
1846 }
1847
1848 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001849 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001850 }
1851};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001852} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001853} // namespace threadSafety
1854} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001855
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001856//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001857// -Wconsumed
1858//===----------------------------------------------------------------------===//
1859
1860namespace clang {
1861namespace consumed {
1862namespace {
1863class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
Fangrui Song6907ce22018-07-30 19:24:48 +00001864
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001865 Sema &S;
1866 DiagList Warnings;
Fangrui Song6907ce22018-07-30 19:24:48 +00001867
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001868public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001869
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001870 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001871
1872 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001873 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001874 for (const auto &Diag : Warnings) {
1875 S.Diag(Diag.first.first, Diag.first.second);
1876 for (const auto &Note : Diag.second)
1877 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001878 }
1879 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001880
1881 void warnLoopStateMismatch(SourceLocation Loc,
1882 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001883 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1884 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001885
1886 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001887 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001888
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001889 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1890 StringRef VariableName,
1891 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001892 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001893
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001894 PartialDiagnosticAt Warning(Loc, S.PDiag(
1895 diag::warn_param_return_typestate_mismatch) << VariableName <<
1896 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001897
1898 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001899 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001900
DeLesley Hutchins69391772013-10-17 23:23:53 +00001901 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001902 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001903
DeLesley Hutchins69391772013-10-17 23:23:53 +00001904 PartialDiagnosticAt Warning(Loc, S.PDiag(
1905 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001906
1907 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001908 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001909
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001910 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001911 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001912 PartialDiagnosticAt Warning(Loc, S.PDiag(
1913 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001914
1915 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001916 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001917
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001918 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001919 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001920
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001921 PartialDiagnosticAt Warning(Loc, S.PDiag(
1922 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001923
1924 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001925 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001926
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001927 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001928 SourceLocation Loc) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001929
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001930 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001931 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001932
1933 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001934 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001935
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001936 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001937 StringRef State, SourceLocation Loc) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001938
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001939 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1940 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001941
1942 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001943 }
1944};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001945} // anonymous namespace
1946} // namespace consumed
1947} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001948
1949//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001950// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1951// warnings on a function, method, or block.
1952//===----------------------------------------------------------------------===//
1953
Ted Kremenek0b405322010-03-23 00:13:23 +00001954clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1955 enableCheckFallThrough = 1;
1956 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001957 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001958 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001959}
1960
Ted Kremenekad8753c2014-03-15 05:47:06 +00001961static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001962 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001963}
1964
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001965clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1966 : S(s),
1967 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001968 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001969 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001970 MaxCFGBlocksPerFunction(0),
1971 NumUninitAnalysisFunctions(0),
1972 NumUninitAnalysisVariables(0),
1973 MaxUninitAnalysisVariablesPerFunction(0),
1974 NumUninitAnalysisBlockVisits(0),
1975 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001976
1977 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001978 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001979
1980 DefaultPolicy.enableCheckUnreachable =
1981 isEnabled(D, warn_unreachable) ||
1982 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001983 isEnabled(D, warn_unreachable_return) ||
1984 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001985
1986 DefaultPolicy.enableThreadSafetyAnalysis =
1987 isEnabled(D, warn_double_lock);
1988
1989 DefaultPolicy.enableConsumedAnalysis =
1990 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001991}
1992
Aaron Ballmane5195222014-05-15 20:50:47 +00001993static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1994 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001995 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001996}
1997
Ted Kremenek0b405322010-03-23 00:13:23 +00001998void clang::sema::
1999AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00002000 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00002001 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00002002
Ted Kremenek918fe842010-03-20 21:06:02 +00002003 // We avoid doing analysis-based warnings when there are errors for
2004 // two reasons:
2005 // (1) The CFGs often can't be constructed (if the body is invalid), so
2006 // don't bother trying.
2007 // (2) The code already has problems; running the analysis just takes more
2008 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00002009 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00002010
Olivier Goffart270ced22017-11-23 08:15:22 +00002011 // Do not do any analysis if we are going to just ignore them.
2012 if (Diags.getIgnoreAllWarnings() ||
2013 (Diags.getSuppressSystemWarnings() &&
2014 S.SourceMgr.isInSystemHeader(D->getLocation())))
Ted Kremenek0b405322010-03-23 00:13:23 +00002015 return;
2016
John McCall1d570a72010-08-25 05:56:39 +00002017 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00002018 if (cast<DeclContext>(D)->isDependentContext())
2019 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00002020
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002021 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002022 // Flush out any possibly unreachable diagnostics.
2023 flushDiagnostics(S, fscope);
2024 return;
2025 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002026
Ted Kremenek918fe842010-03-20 21:06:02 +00002027 const Stmt *Body = D->getBody();
2028 assert(Body);
2029
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002030 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00002031 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00002032
Ted Kremenek918fe842010-03-20 21:06:02 +00002033 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00002034 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00002035 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2036 AC.getCFGBuildOptions().AddEHEdges = false;
2037 AC.getCFGBuildOptions().AddInitializers = true;
2038 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002039 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00002040 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00002041 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002042
Ted Kremenek9e100ea2011-07-19 14:18:48 +00002043 // Force that certain expressions appear as CFGElements in the CFG. This
2044 // is used to speed up various analyses.
2045 // FIXME: This isn't the right factoring. This is here for initial
2046 // prototyping, but we need a way for analyses to say what expressions they
2047 // expect to always be CFGElements and then fill in the BuildOptions
2048 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002049 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2050 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002051 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00002052 AC.getCFGBuildOptions().setAllAlwaysAdd();
2053 }
2054 else {
2055 AC.getCFGBuildOptions()
2056 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00002057 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00002058 .setAlwaysAdd(Stmt::BlockExprClass)
2059 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2060 .setAlwaysAdd(Stmt::DeclRefExprClass)
2061 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00002062 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2063 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00002064 }
Ted Kremenek918fe842010-03-20 21:06:02 +00002065
Richard Trieue9fa2662014-04-15 00:57:50 +00002066 // Install the logical handler for -Wtautological-overlap-compare
George Burgess IVb65955e2018-08-05 01:37:07 +00002067 llvm::Optional<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002068 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002069 D->getBeginLoc())) {
George Burgess IVb65955e2018-08-05 01:37:07 +00002070 LEH.emplace(S);
2071 AC.getCFGBuildOptions().Observer = &*LEH;
Richard Trieuf935b562014-04-05 05:17:01 +00002072 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002073
Ted Kremenek3427fac2011-02-23 01:52:04 +00002074 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00002075 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002076 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00002077
2078 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00002079 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2080 if (D.stmt)
2081 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00002082 }
2083
2084 if (AC.getCFG()) {
2085 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00002086 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00002087 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00002088 if (D.stmt) {
2089 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00002090 CFGReverseBlockReachabilityAnalysis *cra =
2091 AC.getCFGReachablityAnalysis();
2092 // FIXME: We should be able to assert that block is non-null, but
2093 // the CFG analysis can skip potentially-evaluated expressions in
2094 // edge cases; see test/Sema/vla-2.c.
2095 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002096 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00002097 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00002098 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00002099 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00002100 }
2101 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002102 if (!processed) {
2103 // Emit the warning anyway if we cannot map to a basic block.
2104 S.Diag(D.Loc, D.PD);
2105 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002106 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002107 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002108
2109 if (!analyzed)
2110 flushDiagnostics(S, fscope);
2111 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002112
Ted Kremenek918fe842010-03-20 21:06:02 +00002113 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002114 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00002115 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002116 (isa<BlockDecl>(D)
2117 ? CheckFallThroughDiagnostics::MakeForBlock()
2118 : (isa<CXXMethodDecl>(D) &&
2119 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2120 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2121 ? CheckFallThroughDiagnostics::MakeForLambda()
Eric Fiselierda8f9b52017-05-25 02:16:53 +00002122 : (fscope->isCoroutine()
Eric Fiselier709d1b32016-10-27 07:30:31 +00002123 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2124 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Reid Kleckner87a31802018-03-12 21:43:02 +00002125 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
Ted Kremenek918fe842010-03-20 21:06:02 +00002126 }
2127
2128 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002129 if (P.enableCheckUnreachable) {
2130 // Only check for unreachable code on non-template instantiations.
2131 // Different template instantiations can effectively change the control-flow
2132 // and it is very difficult to prove that a snippet of code in a template
2133 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002134 bool isTemplateInstantiation = false;
2135 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2136 isTemplateInstantiation = Function->isTemplateInstantiation();
2137 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002138 CheckUnreachable(S, AC);
2139 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002140
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002141 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002142 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002143 SourceLocation FL = AC.getDecl()->getLocation();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002144 SourceLocation FEL = AC.getDecl()->getEndLoc();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002145 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002146 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002147 Reporter.setIssueBetaWarnings(true);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002148 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002149 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002150
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002151 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2152 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002153 Reporter.emitDiagnostics();
2154 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002155
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002156 // Check for violations of consumed properties.
2157 if (P.enableConsumedAnalysis) {
2158 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002159 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002160 Analyzer.run(AC);
2161 }
2162
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002163 if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
2164 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
2165 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002166 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002167 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002168 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002169 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002170 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002171 reporter, stats);
2172
2173 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2174 ++NumUninitAnalysisFunctions;
2175 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2176 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2177 MaxUninitAnalysisVariablesPerFunction =
2178 std::max(MaxUninitAnalysisVariablesPerFunction,
2179 stats.NumVariablesAnalyzed);
2180 MaxUninitAnalysisBlockVisitsPerFunction =
2181 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2182 stats.NumBlockVisits);
2183 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002184 }
2185 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002186
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002187 bool FallThroughDiagFull =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002188 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002189 bool FallThroughDiagPerFunction = !Diags.isIgnored(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002190 diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
Richard Smith4f902c72016-03-08 00:32:55 +00002191 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2192 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002193 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002194 }
2195
John McCall460ce582015-10-22 18:38:17 +00002196 if (S.getLangOpts().ObjCWeak &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002197 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
Jordan Rose76831c62012-10-11 16:10:19 +00002198 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002199
Richard Trieu2f024f42013-12-21 02:33:43 +00002200
2201 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002202 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002203 D->getBeginLoc())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002204 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2205 checkRecursiveFunction(S, FD, Body, AC);
2206 }
2207 }
2208
Erich Keane89fe9c22017-06-23 20:22:19 +00002209 // Check for throw out of non-throwing function.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002210 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
Erich Keane89fe9c22017-06-23 20:22:19 +00002211 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2212 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2213 checkThrowInNonThrowingFunc(S, FD, AC);
2214
Richard Trieue9fa2662014-04-15 00:57:50 +00002215 // If none of the previous checks caused a CFG build, trigger one here
2216 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002217 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002218 D->getBeginLoc())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00002219 AC.getCFG();
2220 }
2221
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002222 // Collect statistics about the CFG if it was built.
2223 if (S.CollectStats && AC.isCFGBuilt()) {
2224 ++NumFunctionsAnalyzed;
2225 if (CFG *cfg = AC.getCFG()) {
2226 // If we successfully built a CFG for this context, record some more
2227 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002228 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002229 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002230 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002231 } else {
2232 ++NumFunctionsWithBadCFGs;
2233 }
2234 }
2235}
2236
2237void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2238 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2239
2240 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2241 unsigned AvgCFGBlocksPerFunction =
2242 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2243 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2244 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2245 << " " << NumCFGBlocks << " CFG blocks built.\n"
2246 << " " << AvgCFGBlocksPerFunction
2247 << " average CFG blocks per function.\n"
2248 << " " << MaxCFGBlocksPerFunction
2249 << " max CFG blocks per function.\n";
2250
2251 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2252 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2253 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2254 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2255 llvm::errs() << NumUninitAnalysisFunctions
2256 << " functions analyzed for uninitialiazed variables\n"
2257 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2258 << " " << AvgUninitVariablesPerFunction
2259 << " average variables per function.\n"
2260 << " " << MaxUninitAnalysisVariablesPerFunction
2261 << " max variables per function.\n"
2262 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2263 << " " << AvgUninitBlockVisitsPerFunction
2264 << " average block visits per function.\n"
2265 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2266 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002267}