blob: aaed8f9827328199b6ee62139477f15ce5387924 [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;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000093
94 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.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
118 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 {
Richard Trieuf935b562014-04-05 05:17:01 +0000125/// \brief Warn on logical operator errors in CFGBuilder
126class 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
Richard Trieu6995de92015-08-21 03:43:09 +0000203// All blocks are in one of three states. States are ordered so that blocks
204// can only move to higher states.
205enum RecursiveState {
206 FoundNoPath,
207 FoundPath,
208 FoundPathWithNoRecursiveCall
209};
210
211// Returns true if there exists a path to the exit block and every path
212// to the exit block passes through a call to FD.
213static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
214
215 const unsigned ExitID = cfg->getExit().getBlockID();
216
217 // Mark all nodes as FoundNoPath, then set the status of the entry block.
218 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
219 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
220
221 // Make the processing stack and seed it with the entry block.
222 SmallVector<CFGBlock *, 16> Stack;
223 Stack.push_back(&cfg->getEntry());
Richard Trieu2f024f42013-12-21 02:33:43 +0000224
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000225 while (!Stack.empty()) {
Richard Trieu6995de92015-08-21 03:43:09 +0000226 CFGBlock *CurBlock = Stack.back();
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000227 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000228
Richard Trieu6995de92015-08-21 03:43:09 +0000229 unsigned ID = CurBlock->getBlockID();
230 RecursiveState CurState = States[ID];
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000231
232 if (CurState == FoundPathWithNoRecursiveCall) {
233 // Found a path to the exit node without a recursive call.
234 if (ExitID == ID)
Richard Trieu6995de92015-08-21 03:43:09 +0000235 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000236
Richard Trieu6995de92015-08-21 03:43:09 +0000237 // Only change state if the block has a recursive call.
238 if (hasRecursiveCallInPath(FD, *CurBlock))
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000239 CurState = FoundPath;
240 }
241
Richard Trieu6995de92015-08-21 03:43:09 +0000242 // Loop over successor blocks and add them to the Stack if their state
243 // changes.
244 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
245 if (*I) {
246 unsigned next_ID = (*I)->getBlockID();
247 if (States[next_ID] < CurState) {
248 States[next_ID] = CurState;
249 Stack.push_back(*I);
250 }
251 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000252 }
Richard Trieu6995de92015-08-21 03:43:09 +0000253
254 // Return true if the exit node is reachable, and only reachable through
255 // a recursive call.
256 return States[ExitID] == FoundPath;
Richard Trieu2f024f42013-12-21 02:33:43 +0000257}
258
259static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000260 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000261 FD = FD->getCanonicalDecl();
262
263 // Only run on non-templated functions and non-templated members of
264 // templated classes.
265 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
266 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
267 return;
268
269 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000270 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000271
272 // If the exit block is unreachable, skip processing the function.
273 if (cfg->getExit().pred_empty())
274 return;
275
Richard Trieu6995de92015-08-21 03:43:09 +0000276 // Emit diagnostic if a recursive function call is detected for all paths.
277 if (checkForRecursiveFunctionCall(FD, cfg))
Richard Trieu2f024f42013-12-21 02:33:43 +0000278 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
279}
280
281//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000282// Check for throw in a non-throwing function.
283//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000284
Richard Smith08482102018-02-20 02:32:30 +0000285/// Determine whether an exception thrown by E, unwinding from ThrowBlock,
286/// can reach ExitBlock.
287static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
288 CFG *Body) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000289 SmallVector<CFGBlock *, 16> Stack;
Richard Smith08482102018-02-20 02:32:30 +0000290 llvm::BitVector Queued(Body->getNumBlockIDs());
Erich Keane89fe9c22017-06-23 20:22:19 +0000291
Richard Smith08482102018-02-20 02:32:30 +0000292 Stack.push_back(&ThrowBlock);
293 Queued[ThrowBlock.getBlockID()] = true;
294
295 while (!Stack.empty()) {
296 CFGBlock &UnwindBlock = *Stack.back();
297 Stack.pop_back();
298
299 for (auto &Succ : UnwindBlock.succs()) {
300 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
Erich Keane89fe9c22017-06-23 20:22:19 +0000301 continue;
302
Richard Smith08482102018-02-20 02:32:30 +0000303 if (Succ->getBlockID() == Body->getExit().getBlockID())
304 return true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000305
Richard Smith08482102018-02-20 02:32:30 +0000306 if (auto *Catch =
307 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
308 QualType Caught = Catch->getCaughtType();
309 if (Caught.isNull() || // catch (...) catches everything
310 !E->getSubExpr() || // throw; is considered cuaght by any handler
311 S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
312 // Exception doesn't escape via this path.
313 break;
314 } else {
315 Stack.push_back(Succ);
316 Queued[Succ->getBlockID()] = true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000317 }
Richard Smith08482102018-02-20 02:32:30 +0000318 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000319 }
Richard Smith08482102018-02-20 02:32:30 +0000320
321 return false;
322}
323
324static void visitReachableThrows(
325 CFG *BodyCFG,
326 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
327 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
328 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
329 for (CFGBlock *B : *BodyCFG) {
330 if (!Reachable[B->getBlockID()])
331 continue;
332 for (CFGElement &E : *B) {
333 Optional<CFGStmt> S = E.getAs<CFGStmt>();
334 if (!S)
335 continue;
336 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
337 Visit(Throw, *B);
338 }
339 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000340}
341
342static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
343 const FunctionDecl *FD) {
Erich Keane7538b352017-07-05 16:43:45 +0000344 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
345 FD->getTypeSourceInfo()) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000346 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
347 if (S.getLangOpts().CPlusPlus11 &&
348 (isa<CXXDestructorDecl>(FD) ||
349 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
Erich Keane7538b352017-07-05 16:43:45 +0000350 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
351 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
352 getAs<FunctionProtoType>())
353 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
354 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
355 << FD->getExceptionSpecSourceRange();
356 } else
357 S.Diag(FD->getLocation(), diag::note_throw_in_function)
358 << FD->getExceptionSpecSourceRange();
Erich Keane89fe9c22017-06-23 20:22:19 +0000359 }
360}
361
362static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
363 AnalysisDeclContext &AC) {
364 CFG *BodyCFG = AC.getCFG();
365 if (!BodyCFG)
366 return;
367 if (BodyCFG->getExit().pred_empty())
368 return;
369 SourceLocation OpLoc;
Richard Smith08482102018-02-20 02:32:30 +0000370 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
371 if (throwEscapes(S, Throw, Block, BodyCFG))
372 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
373 });
Erich Keane89fe9c22017-06-23 20:22:19 +0000374}
375
376static bool isNoexcept(const FunctionDecl *FD) {
377 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Erich Keane9d10bdf2017-09-26 18:20:39 +0000378 if (FPT->isNothrow(FD->getASTContext()) || FD->hasAttr<NoThrowAttr>())
Erich Keane89fe9c22017-06-23 20:22:19 +0000379 return true;
380 return false;
381}
382
383//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000384// Check for missing return value.
385//===----------------------------------------------------------------------===//
386
John McCall5c6ec8c2010-05-16 09:34:11 +0000387enum ControlFlowKind {
388 UnknownFallThrough,
389 NeverFallThrough,
390 MaybeFallThrough,
391 AlwaysFallThrough,
392 NeverFallThroughOrReturn
393};
Ted Kremenek918fe842010-03-20 21:06:02 +0000394
395/// CheckFallThrough - Check that we don't fall off the end of a
396/// Statement that should return a value.
397///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000398/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
399/// MaybeFallThrough iff we might or might not fall off the end,
400/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
401/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000402/// statement but we may return. We assume that functions not marked noreturn
403/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000404static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000405 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000406 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000407
408 // The CFG leaves in dead things, and we don't want the dead code paths to
409 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000410 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000411 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000412 live);
413
414 bool AddEHEdges = AC.getAddEHEdges();
415 if (!AddEHEdges && count != cfg->getNumBlockIDs())
416 // When there are things remaining dead, and we didn't add EH edges
417 // from CallExprs to the catch clauses, we have to go back and
418 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000419 for (const auto *B : *cfg) {
420 if (!live[B->getBlockID()]) {
421 if (B->pred_begin() == B->pred_end()) {
422 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000423 // When not adding EH edges from calls, catch clauses
424 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000425 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000426 continue;
427 }
428 }
429 }
430
431 // Now we know what is live, we check the live precessors of the exit block
432 // and look for fall through paths, being careful to ignore normal returns,
433 // and exceptional paths.
434 bool HasLiveReturn = false;
435 bool HasFakeEdge = false;
436 bool HasPlainEdge = false;
437 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000438
439 // Ignore default cases that aren't likely to be reachable because all
440 // enums in a switch(X) have explicit case statements.
441 CFGBlock::FilterOptions FO;
442 FO.IgnoreDefaultsWithCoveredEnums = 1;
443
444 for (CFGBlock::filtered_pred_iterator
445 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
446 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000447 if (!live[B.getBlockID()])
448 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000449
Chandler Carruth03faf782011-09-13 09:53:58 +0000450 // Skip blocks which contain an element marked as no-return. They don't
451 // represent actually viable edges into the exit block, so mark them as
452 // abnormal.
453 if (B.hasNoReturnElement()) {
454 HasAbnormalEdge = true;
455 continue;
456 }
457
Ted Kremenek5d068492011-01-26 04:49:52 +0000458 // Destructors can appear after the 'return' in the CFG. This is
459 // normal. We need to look pass the destructors for the return
460 // statement (if it exists).
461 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000462
Chandler Carruth03faf782011-09-13 09:53:58 +0000463 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000464 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000465 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000466
Ted Kremenek5d068492011-01-26 04:49:52 +0000467 // No more CFGElements in the block?
468 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000469 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
470 HasAbnormalEdge = true;
471 continue;
472 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000473 // A labeled empty statement, or the entry block...
474 HasPlainEdge = true;
475 continue;
476 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000477
David Blaikie2a01f5d2013-02-21 20:58:29 +0000478 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000479 const Stmt *S = CS.getStmt();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000480 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000481 HasLiveReturn = true;
482 continue;
483 }
484 if (isa<ObjCAtThrowStmt>(S)) {
485 HasFakeEdge = true;
486 continue;
487 }
488 if (isa<CXXThrowExpr>(S)) {
489 HasFakeEdge = true;
490 continue;
491 }
Chad Rosier32503022012-06-11 20:47:18 +0000492 if (isa<MSAsmStmt>(S)) {
493 // TODO: Verify this is correct.
494 HasFakeEdge = true;
495 HasLiveReturn = true;
496 continue;
497 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000498 if (isa<CXXTryStmt>(S)) {
499 HasAbnormalEdge = true;
500 continue;
501 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000502 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
503 == B.succ_end()) {
504 HasAbnormalEdge = true;
505 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000506 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000507
508 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000509 }
510 if (!HasPlainEdge) {
511 if (HasLiveReturn)
512 return NeverFallThrough;
513 return NeverFallThroughOrReturn;
514 }
515 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
516 return MaybeFallThrough;
517 // This says AlwaysFallThrough for calls to functions that are not marked
518 // noreturn, that don't return. If people would like this warning to be more
519 // accurate, such functions should be marked as noreturn.
520 return AlwaysFallThrough;
521}
522
Dan Gohman28ade552010-07-26 21:25:24 +0000523namespace {
524
Ted Kremenek918fe842010-03-20 21:06:02 +0000525struct CheckFallThroughDiagnostics {
526 unsigned diag_MaybeFallThrough_HasNoReturn;
527 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
528 unsigned diag_AlwaysFallThrough_HasNoReturn;
529 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
530 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000531 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000532 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000533
Douglas Gregor24f27692010-04-16 23:28:44 +0000534 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000535 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000536 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000537 D.diag_MaybeFallThrough_HasNoReturn =
538 diag::warn_falloff_noreturn_function;
539 D.diag_MaybeFallThrough_ReturnsNonVoid =
540 diag::warn_maybe_falloff_nonvoid_function;
541 D.diag_AlwaysFallThrough_HasNoReturn =
542 diag::warn_falloff_noreturn_function;
543 D.diag_AlwaysFallThrough_ReturnsNonVoid =
544 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000545
546 // Don't suggest that virtual functions be marked "noreturn", since they
547 // might be overridden by non-noreturn functions.
548 bool isVirtualMethod = false;
549 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
550 isVirtualMethod = Method->isVirtual();
551
Douglas Gregor0de57202011-10-10 18:15:57 +0000552 // Don't suggest that template instantiations be marked "noreturn"
553 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000554 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
555 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000556
557 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000558 D.diag_NeverFallThroughOrReturn =
559 diag::warn_suggest_noreturn_function;
560 else
561 D.diag_NeverFallThroughOrReturn = 0;
562
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000563 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000564 return D;
565 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000566
Eric Fiselier709d1b32016-10-27 07:30:31 +0000567 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
568 CheckFallThroughDiagnostics D;
569 D.FuncLoc = Func->getLocation();
570 D.diag_MaybeFallThrough_HasNoReturn = 0;
571 D.diag_MaybeFallThrough_ReturnsNonVoid =
572 diag::warn_maybe_falloff_nonvoid_coroutine;
573 D.diag_AlwaysFallThrough_HasNoReturn = 0;
574 D.diag_AlwaysFallThrough_ReturnsNonVoid =
575 diag::warn_falloff_nonvoid_coroutine;
576 D.funMode = Coroutine;
577 return D;
578 }
579
Ted Kremenek918fe842010-03-20 21:06:02 +0000580 static CheckFallThroughDiagnostics MakeForBlock() {
581 CheckFallThroughDiagnostics D;
582 D.diag_MaybeFallThrough_HasNoReturn =
583 diag::err_noreturn_block_has_return_expr;
584 D.diag_MaybeFallThrough_ReturnsNonVoid =
585 diag::err_maybe_falloff_nonvoid_block;
586 D.diag_AlwaysFallThrough_HasNoReturn =
587 diag::err_noreturn_block_has_return_expr;
588 D.diag_AlwaysFallThrough_ReturnsNonVoid =
589 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000590 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000591 D.funMode = Block;
592 return D;
593 }
594
595 static CheckFallThroughDiagnostics MakeForLambda() {
596 CheckFallThroughDiagnostics D;
597 D.diag_MaybeFallThrough_HasNoReturn =
598 diag::err_noreturn_lambda_has_return_expr;
599 D.diag_MaybeFallThrough_ReturnsNonVoid =
600 diag::warn_maybe_falloff_nonvoid_lambda;
601 D.diag_AlwaysFallThrough_HasNoReturn =
602 diag::err_noreturn_lambda_has_return_expr;
603 D.diag_AlwaysFallThrough_ReturnsNonVoid =
604 diag::warn_falloff_nonvoid_lambda;
605 D.diag_NeverFallThroughOrReturn = 0;
606 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000607 return D;
608 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000609
David Blaikie9c902b52011-09-25 23:23:43 +0000610 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000611 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000612 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000613 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000614 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
615 FuncLoc)) &&
616 (!HasNoReturn ||
617 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
618 FuncLoc)) &&
619 (!ReturnsVoid ||
620 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000621 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000622 if (funMode == Coroutine) {
623 return (ReturnsVoid ||
624 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
625 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
626 FuncLoc)) &&
627 (!HasNoReturn);
628 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000629 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000630 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000631 }
632};
633
Hans Wennborgdcfba332015-10-06 23:40:43 +0000634} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000635
Ted Kremenek918fe842010-03-20 21:06:02 +0000636/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
637/// function that should return a value. Check that we don't fall off the end
638/// of a noreturn function. We assume that functions and blocks not marked
639/// noreturn will return.
640static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000641 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000642 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000643 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000644
645 bool ReturnsVoid = false;
646 bool HasNoReturn = false;
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000647 bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
Ted Kremenek918fe842010-03-20 21:06:02 +0000648
Eric Fiselier709d1b32016-10-27 07:30:31 +0000649 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
650 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
651 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
652 else
653 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000654 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000655 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000656 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000657 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000658 HasNoReturn = MD->hasAttr<NoReturnAttr>();
659 }
660 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000661 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000662 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000663 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000664 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000665 ReturnsVoid = true;
666 if (FT->getNoReturnAttr())
667 HasNoReturn = true;
668 }
669 }
670
David Blaikie9c902b52011-09-25 23:23:43 +0000671 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000672
673 // Short circuit for compilation speed.
674 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
675 return;
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000676 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000677 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
678 if (IsCoroutine)
679 S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
680 else
681 S.Diag(Loc, DiagID);
682 };
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000683 // Either in a function body compound statement, or a function-try-block.
684 switch (CheckFallThrough(AC)) {
685 case UnknownFallThrough:
686 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000687
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000688 case MaybeFallThrough:
689 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000690 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000691 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000692 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000693 break;
694 case AlwaysFallThrough:
695 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000696 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000697 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000698 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000699 break;
700 case NeverFallThroughOrReturn:
701 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
702 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
703 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
704 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
705 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
706 } else {
707 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000708 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000709 }
710 break;
711 case NeverFallThrough:
712 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000713 }
714}
715
716//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000717// -Wuninitialized
718//===----------------------------------------------------------------------===//
719
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000720namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000721/// ContainsReference - A visitor class to search for references to
722/// a particular declaration (the needle) within any evaluated component of an
723/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000724class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000725 bool FoundReference;
726 const DeclRefExpr *Needle;
727
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000728public:
Scott Douglass503fc392015-06-10 13:53:15 +0000729 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000730
Scott Douglass503fc392015-06-10 13:53:15 +0000731 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
732 : Inherited(Context), FoundReference(false), Needle(Needle) {}
733
734 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000735 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000736 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000737 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000738
Scott Douglass503fc392015-06-10 13:53:15 +0000739 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000740 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000741
Scott Douglass503fc392015-06-10 13:53:15 +0000742 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000743 if (E == Needle)
744 FoundReference = true;
745 else
Scott Douglass503fc392015-06-10 13:53:15 +0000746 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000747 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000748
749 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000750};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000751} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000752
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000753static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000754 QualType VariableTy = VD->getType().getCanonicalType();
755 if (VariableTy->isBlockPointerType() &&
756 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000757 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
758 << VD->getDeclName()
759 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000760 return true;
761 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000762
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000763 // Don't issue a fixit if there is already an initializer.
764 if (VD->getInit())
765 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000766
767 // Don't suggest a fixit inside macros.
768 if (VD->getLocEnd().isMacroID())
769 return false;
770
Alp Tokerb6cc5922014-05-03 03:45:55 +0000771 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000772
773 // Suggest possible initialization (if any).
774 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
775 if (Init.empty())
776 return false;
777
Richard Smith8d06f422012-01-12 23:53:29 +0000778 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
779 << FixItHint::CreateInsertion(Loc, Init);
780 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000781}
782
Richard Smith1bb8edb82012-05-26 06:20:46 +0000783/// Create a fixit to remove an if-like statement, on the assumption that its
784/// condition is CondVal.
785static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
786 const Stmt *Else, bool CondVal,
787 FixItHint &Fixit1, FixItHint &Fixit2) {
788 if (CondVal) {
789 // If condition is always true, remove all but the 'then'.
790 Fixit1 = FixItHint::CreateRemoval(
791 CharSourceRange::getCharRange(If->getLocStart(),
792 Then->getLocStart()));
793 if (Else) {
Craig Topper07fa1762015-11-15 02:31:46 +0000794 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000795 Fixit2 = FixItHint::CreateRemoval(
796 SourceRange(ElseKwLoc, Else->getLocEnd()));
797 }
798 } else {
799 // If condition is always false, remove all but the 'else'.
800 if (Else)
801 Fixit1 = FixItHint::CreateRemoval(
802 CharSourceRange::getCharRange(If->getLocStart(),
803 Else->getLocStart()));
804 else
805 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
806 }
807}
808
809/// DiagUninitUse -- Helper function to produce a diagnostic for an
810/// uninitialized use of a variable.
811static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
812 bool IsCapturedByBlock) {
813 bool Diagnosed = false;
814
Richard Smithba8071e2013-09-12 18:49:10 +0000815 switch (Use.getKind()) {
816 case UninitUse::Always:
817 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
818 << VD->getDeclName() << IsCapturedByBlock
819 << Use.getUser()->getSourceRange();
820 return;
821
822 case UninitUse::AfterDecl:
823 case UninitUse::AfterCall:
824 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
825 << VD->getDeclName() << IsCapturedByBlock
826 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
827 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
828 << VD->getSourceRange();
829 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
830 << IsCapturedByBlock << Use.getUser()->getSourceRange();
831 return;
832
833 case UninitUse::Maybe:
834 case UninitUse::Sometimes:
835 // Carry on to report sometimes-uninitialized branches, if possible,
836 // or a 'may be used uninitialized' diagnostic otherwise.
837 break;
838 }
839
Richard Smith1bb8edb82012-05-26 06:20:46 +0000840 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000841 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
842 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000843 assert(Use.getKind() == UninitUse::Sometimes);
844
845 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000846 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000847
848 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000849 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000850 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000851 SourceRange Range;
852
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000853 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000854 // For all binary terminators, branch 0 is taken if the condition is true,
855 // and branch 1 is taken if the condition is false.
856 int RemoveDiagKind = -1;
857 const char *FixitStr =
858 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
859 : (I->Output ? "1" : "0");
860 FixItHint Fixit1, Fixit2;
861
Richard Smithba8071e2013-09-12 18:49:10 +0000862 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000863 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000864 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000865 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000866 continue;
867
868 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000869 case Stmt::IfStmtClass: {
870 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000871 DiagKind = 0;
872 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000873 Range = IS->getCond()->getSourceRange();
874 RemoveDiagKind = 0;
875 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
876 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000877 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000878 }
879 case Stmt::ConditionalOperatorClass: {
880 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000881 DiagKind = 0;
882 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000883 Range = CO->getCond()->getSourceRange();
884 RemoveDiagKind = 0;
885 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
886 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000887 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000888 }
Richard Smith4323bf82012-05-25 02:17:09 +0000889 case Stmt::BinaryOperatorClass: {
890 const BinaryOperator *BO = cast<BinaryOperator>(Term);
891 if (!BO->isLogicalOp())
892 continue;
893 DiagKind = 0;
894 Str = BO->getOpcodeStr();
895 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000896 RemoveDiagKind = 0;
897 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
898 (BO->getOpcode() == BO_LOr && !I->Output))
899 // true && y -> y, false || y -> y.
900 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
901 BO->getOperatorLoc()));
902 else
903 // false && y -> false, true || y -> true.
904 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000905 break;
906 }
907
908 // "loop is entered / loop is exited".
909 case Stmt::WhileStmtClass:
910 DiagKind = 1;
911 Str = "while";
912 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000913 RemoveDiagKind = 1;
914 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000915 break;
916 case Stmt::ForStmtClass:
917 DiagKind = 1;
918 Str = "for";
919 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000920 RemoveDiagKind = 1;
921 if (I->Output)
922 Fixit1 = FixItHint::CreateRemoval(Range);
923 else
924 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000925 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000926 case Stmt::CXXForRangeStmtClass:
927 if (I->Output == 1) {
928 // The use occurs if a range-based for loop's body never executes.
929 // That may be impossible, and there's no syntactic fix for this,
930 // so treat it as a 'may be uninitialized' case.
931 continue;
932 }
933 DiagKind = 1;
934 Str = "for";
935 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
936 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000937
938 // "condition is true / loop is exited".
939 case Stmt::DoStmtClass:
940 DiagKind = 2;
941 Str = "do";
942 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000943 RemoveDiagKind = 1;
944 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000945 break;
946
947 // "switch case is taken".
948 case Stmt::CaseStmtClass:
949 DiagKind = 3;
950 Str = "case";
951 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
952 break;
953 case Stmt::DefaultStmtClass:
954 DiagKind = 3;
955 Str = "default";
956 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
957 break;
958 }
959
Richard Smith1bb8edb82012-05-26 06:20:46 +0000960 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
961 << VD->getDeclName() << IsCapturedByBlock << DiagKind
962 << Str << I->Output << Range;
963 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
964 << IsCapturedByBlock << User->getSourceRange();
965 if (RemoveDiagKind != -1)
966 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
967 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
968
969 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000970 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000971
972 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000973 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000974 << VD->getDeclName() << IsCapturedByBlock
975 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000976}
977
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000978/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
979/// uninitialized variable. This manages the different forms of diagnostic
980/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000981/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000982/// false.
983static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000984 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000985 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +0000986 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000987 // Inspect the initializer of the variable declaration which is
988 // being referenced prior to its initialization. We emit
989 // specialized diagnostics for self-initialization, and we
990 // specifically avoid warning about self references which take the
991 // form of:
992 //
993 // int x = x;
994 //
995 // This is used to indicate to GCC that 'x' is intentionally left
996 // uninitialized. Proven code paths which access 'x' in
997 // an uninitialized state after this will still warn.
998 if (const Expr *Initializer = VD->getInit()) {
999 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1000 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +00001001
Richard Trieu43a2fc72012-05-09 21:08:22 +00001002 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +00001003 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +00001004 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +00001005 S.Diag(DRE->getLocStart(),
1006 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +00001007 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1008 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +00001009 }
Chandler Carruth895904da2011-04-05 18:18:05 +00001010 }
Richard Trieu43a2fc72012-05-09 21:08:22 +00001011
Richard Smith1bb8edb82012-05-26 06:20:46 +00001012 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +00001013 } else {
Richard Smith4323bf82012-05-25 02:17:09 +00001014 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +00001015 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1016 S.Diag(BE->getLocStart(),
1017 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +00001018 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +00001019 else
1020 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +00001021 }
1022
1023 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +00001024 // the initializer of that declaration & we didn't already suggest
1025 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +00001026 if (!SuggestInitializationFixit(S, VD))
Reid Klecknerf463a8a2016-04-29 00:37:43 +00001027 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
Chandler Carruth895904da2011-04-05 18:18:05 +00001028 << VD->getDeclName();
1029
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001030 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +00001031}
1032
Richard Smith84837d52012-05-03 18:27:39 +00001033namespace {
1034 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1035 public:
1036 FallthroughMapper(Sema &S)
1037 : FoundSwitchStatements(false),
1038 S(S) {
1039 }
1040
1041 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1042
1043 void markFallthroughVisited(const AttributedStmt *Stmt) {
1044 bool Found = FallthroughStmts.erase(Stmt);
1045 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +00001046 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +00001047 }
1048
1049 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1050
1051 const AttrStmts &getFallthroughStmts() const {
1052 return FallthroughStmts;
1053 }
1054
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001055 void fillReachableBlocks(CFG *Cfg) {
1056 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1057 std::deque<const CFGBlock *> BlockQueue;
1058
1059 ReachableBlocks.insert(&Cfg->getEntry());
1060 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001061 // Mark all case blocks reachable to avoid problems with switching on
1062 // constants, covered enums, etc.
1063 // These blocks can contain fall-through annotations, and we don't want to
1064 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +00001065 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001066 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +00001067 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001068 BlockQueue.push_back(B);
1069 }
1070
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001071 while (!BlockQueue.empty()) {
1072 const CFGBlock *P = BlockQueue.front();
1073 BlockQueue.pop_front();
1074 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1075 E = P->succ_end();
1076 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001077 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001078 BlockQueue.push_back(*I);
1079 }
1080 }
1081 }
1082
Richard Smith7532d372017-03-22 01:49:19 +00001083 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1084 bool IsTemplateInstantiation) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001085 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1086
Richard Smith84837d52012-05-03 18:27:39 +00001087 int UnannotatedCnt = 0;
1088 AnnotatedCnt = 0;
1089
Aaron Ballmane5195222014-05-15 20:50:47 +00001090 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +00001091 while (!BlockQueue.empty()) {
1092 const CFGBlock *P = BlockQueue.front();
1093 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +00001094 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +00001095
1096 const Stmt *Term = P->getTerminator();
1097 if (Term && isa<SwitchStmt>(Term))
1098 continue; // Switch statement, good.
1099
1100 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1101 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1102 continue; // Previous case label has no statements, good.
1103
Alexander Kornienko09f15f32013-01-25 20:44:56 +00001104 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1105 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1106 continue; // Case label is preceded with a normal label, good.
1107
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001108 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001109 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1110 ElemEnd = P->rend();
1111 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001112 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1113 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith7532d372017-03-22 01:49:19 +00001114 // Don't issue a warning for an unreachable fallthrough
1115 // attribute in template instantiations as it may not be
1116 // unreachable in all instantiations of the template.
1117 if (!IsTemplateInstantiation)
1118 S.Diag(AS->getLocStart(),
1119 diag::warn_fallthrough_attr_unreachable);
Richard Smith84837d52012-05-03 18:27:39 +00001120 markFallthroughVisited(AS);
1121 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001122 break;
Richard Smith84837d52012-05-03 18:27:39 +00001123 }
1124 // Don't care about other unreachable statements.
1125 }
1126 }
1127 // If there are no unreachable statements, this may be a special
1128 // case in CFG:
1129 // case X: {
1130 // A a; // A has a destructor.
1131 // break;
1132 // }
1133 // // <<<< This place is represented by a 'hanging' CFG block.
1134 // case Y:
1135 continue;
1136 }
1137
1138 const Stmt *LastStmt = getLastStmt(*P);
1139 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1140 markFallthroughVisited(AS);
1141 ++AnnotatedCnt;
1142 continue; // Fallthrough annotation, good.
1143 }
1144
1145 if (!LastStmt) { // This block contains no executable statements.
1146 // Traverse its predecessors.
1147 std::copy(P->pred_begin(), P->pred_end(),
1148 std::back_inserter(BlockQueue));
1149 continue;
1150 }
1151
1152 ++UnannotatedCnt;
1153 }
1154 return !!UnannotatedCnt;
1155 }
1156
1157 // RecursiveASTVisitor setup.
1158 bool shouldWalkTypesOfTypeLocs() const { return false; }
1159
1160 bool VisitAttributedStmt(AttributedStmt *S) {
1161 if (asFallThroughAttr(S))
1162 FallthroughStmts.insert(S);
1163 return true;
1164 }
1165
1166 bool VisitSwitchStmt(SwitchStmt *S) {
1167 FoundSwitchStatements = true;
1168 return true;
1169 }
1170
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001171 // We don't want to traverse local type declarations. We analyze their
1172 // methods separately.
1173 bool TraverseDecl(Decl *D) { return true; }
1174
Alexander Kornienkobf911642014-06-24 15:28:21 +00001175 // We analyze lambda bodies separately. Skip them here.
1176 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1177
Richard Smith84837d52012-05-03 18:27:39 +00001178 private:
1179
1180 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1181 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1182 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1183 return AS;
1184 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001185 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001186 }
1187
1188 static const Stmt *getLastStmt(const CFGBlock &B) {
1189 if (const Stmt *Term = B.getTerminator())
1190 return Term;
1191 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1192 ElemEnd = B.rend();
1193 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001194 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1195 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001196 }
1197 // Workaround to detect a statement thrown out by CFGBuilder:
1198 // case X: {} case Y:
1199 // case X: ; case Y:
1200 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1201 if (!isa<SwitchCase>(SW->getSubStmt()))
1202 return SW->getSubStmt();
1203
Craig Topperc3ec1492014-05-26 06:22:03 +00001204 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001205 }
1206
1207 bool FoundSwitchStatements;
1208 AttrStmts FallthroughStmts;
1209 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001210 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001211 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001212} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001213
Richard Smith4f902c72016-03-08 00:32:55 +00001214static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1215 SourceLocation Loc) {
1216 TokenValue FallthroughTokens[] = {
1217 tok::l_square, tok::l_square,
1218 PP.getIdentifierInfo("fallthrough"),
1219 tok::r_square, tok::r_square
1220 };
1221
1222 TokenValue ClangFallthroughTokens[] = {
1223 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1224 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1225 tok::r_square, tok::r_square
1226 };
1227
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001228 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
Richard Smith4f902c72016-03-08 00:32:55 +00001229
1230 StringRef MacroName;
1231 if (PreferClangAttr)
1232 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1233 if (MacroName.empty())
1234 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1235 if (MacroName.empty() && !PreferClangAttr)
1236 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1237 if (MacroName.empty())
1238 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1239 return MacroName;
1240}
1241
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001242static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001243 bool PerFunction) {
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001244 // Only perform this analysis when using [[]] attributes. There is no good
1245 // workflow for this warning when not using C++11. There is no good way to
1246 // silence the warning (no attribute is available) unless we are using
1247 // [[]] attributes. One could use pragmas to silence the warning, but as a
1248 // general solution that is gross and not in the spirit of this warning.
Ted Kremenekda5919f2012-11-12 21:20:48 +00001249 //
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001250 // NOTE: This an intermediate solution. There are on-going discussions on
Ted Kremenekda5919f2012-11-12 21:20:48 +00001251 // how to properly support this warning outside of C++11 with an annotation.
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001252 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001253 return;
1254
Richard Smith84837d52012-05-03 18:27:39 +00001255 FallthroughMapper FM(S);
1256 FM.TraverseStmt(AC.getBody());
1257
1258 if (!FM.foundSwitchStatements())
1259 return;
1260
Alexis Hunt2178f142012-06-15 21:22:05 +00001261 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001262 return;
1263
Richard Smith84837d52012-05-03 18:27:39 +00001264 CFG *Cfg = AC.getCFG();
1265
1266 if (!Cfg)
1267 return;
1268
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001269 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001270
Pete Cooper57d3f142015-07-30 17:22:52 +00001271 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001272 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001273
1274 if (!Label || !isa<SwitchCase>(Label))
1275 continue;
1276
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001277 int AnnotatedCnt;
1278
Richard Smith7532d372017-03-22 01:49:19 +00001279 bool IsTemplateInstantiation = false;
1280 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1281 IsTemplateInstantiation = Function->isTemplateInstantiation();
1282 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1283 IsTemplateInstantiation))
Richard Smith84837d52012-05-03 18:27:39 +00001284 continue;
1285
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001286 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001287 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1288 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001289
1290 if (!AnnotatedCnt) {
1291 SourceLocation L = Label->getLocStart();
1292 if (L.isMacroID())
1293 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001294 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001295 const Stmt *Term = B->getTerminator();
1296 // Skip empty cases.
1297 while (B->empty() && !Term && B->succ_size() == 1) {
1298 B = *B->succ_begin();
1299 Term = B->getTerminator();
1300 }
1301 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001302 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001303 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001304 SmallString<64> TextToInsert(AnnotationSpelling);
1305 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001306 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001307 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001308 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001309 }
Richard Smith84837d52012-05-03 18:27:39 +00001310 }
1311 S.Diag(L, diag::note_insert_break_fixit) <<
1312 FixItHint::CreateInsertion(L, "break; ");
1313 }
1314 }
1315
Aaron Ballmane5195222014-05-15 20:50:47 +00001316 for (const auto *F : FM.getFallthroughStmts())
Richard Smith4f902c72016-03-08 00:32:55 +00001317 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001318}
1319
Jordan Rose25c0ea82012-10-29 17:46:47 +00001320static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1321 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001322 assert(S);
1323
1324 do {
1325 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001326 case Stmt::ForStmtClass:
1327 case Stmt::WhileStmtClass:
1328 case Stmt::CXXForRangeStmtClass:
1329 case Stmt::ObjCForCollectionStmtClass:
1330 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001331 case Stmt::DoStmtClass: {
1332 const Expr *Cond = cast<DoStmt>(S)->getCond();
1333 llvm::APSInt Val;
1334 if (!Cond->EvaluateAsInt(Val, Ctx))
1335 return true;
1336 return Val.getBoolValue();
1337 }
Jordan Rose76831c62012-10-11 16:10:19 +00001338 default:
1339 break;
1340 }
1341 } while ((S = PM.getParent(S)));
1342
1343 return false;
1344}
1345
Jordan Rosed3934582012-09-28 22:21:30 +00001346static void diagnoseRepeatedUseOfWeak(Sema &S,
1347 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001348 const Decl *D,
1349 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001350 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1351 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1352 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001353 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1354 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001355
Jordan Rose25c0ea82012-10-29 17:46:47 +00001356 ASTContext &Ctx = S.getASTContext();
1357
Jordan Rosed3934582012-09-28 22:21:30 +00001358 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1359
1360 // Extract all weak objects that are referenced more than once.
1361 SmallVector<StmtUsesPair, 8> UsesByStmt;
1362 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1363 I != E; ++I) {
1364 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001365
1366 // Find the first read of the weak object.
1367 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1368 for ( ; UI != UE; ++UI) {
1369 if (UI->isUnsafe())
1370 break;
1371 }
1372
1373 // If there were only writes to this object, don't warn.
1374 if (UI == UE)
1375 continue;
1376
Jordan Rose76831c62012-10-11 16:10:19 +00001377 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001378 // read is not within a loop, don't warn. Additionally, don't warn in a
1379 // loop if the base object is a local variable -- local variables are often
1380 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001381 if (UI == Uses.begin()) {
1382 WeakUseVector::const_iterator UI2 = UI;
1383 for (++UI2; UI2 != UE; ++UI2)
1384 if (UI2->isUnsafe())
1385 break;
1386
Jordan Rose25c0ea82012-10-29 17:46:47 +00001387 if (UI2 == UE) {
1388 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001389 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001390
1391 const WeakObjectProfileTy &Profile = I->first;
1392 if (!Profile.isExactProfile())
1393 continue;
1394
1395 const NamedDecl *Base = Profile.getBase();
1396 if (!Base)
1397 Base = Profile.getProperty();
1398 assert(Base && "A profile always has a base or property.");
1399
1400 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1401 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1402 continue;
1403 }
Jordan Rose76831c62012-10-11 16:10:19 +00001404 }
1405
Jordan Rosed3934582012-09-28 22:21:30 +00001406 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1407 }
1408
1409 if (UsesByStmt.empty())
1410 return;
1411
1412 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001413 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001414 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001415 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1416 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1417 RHS.first->getLocStart());
1418 });
Jordan Rosed3934582012-09-28 22:21:30 +00001419
1420 // Classify the current code body for better warning text.
1421 // This enum should stay in sync with the cases in
1422 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1423 // FIXME: Should we use a common classification enum and the same set of
1424 // possibilities all throughout Sema?
1425 enum {
1426 Function,
1427 Method,
1428 Block,
1429 Lambda
1430 } FunctionKind;
1431
1432 if (isa<sema::BlockScopeInfo>(CurFn))
1433 FunctionKind = Block;
1434 else if (isa<sema::LambdaScopeInfo>(CurFn))
1435 FunctionKind = Lambda;
1436 else if (isa<ObjCMethodDecl>(D))
1437 FunctionKind = Method;
1438 else
1439 FunctionKind = Function;
1440
1441 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001442 for (const auto &P : UsesByStmt) {
1443 const Stmt *FirstRead = P.first;
1444 const WeakObjectProfileTy &Key = P.second->first;
1445 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001446
Jordan Rose657b5f42012-09-28 22:21:35 +00001447 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1448 // may not contain enough information to determine that these are different
1449 // properties. We can only be 100% sure of a repeated use in certain cases,
1450 // and we adjust the diagnostic kind accordingly so that the less certain
1451 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001452 unsigned DiagKind;
1453 if (Key.isExactProfile())
1454 DiagKind = diag::warn_arc_repeated_use_of_weak;
1455 else
1456 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1457
Jordan Rose657b5f42012-09-28 22:21:35 +00001458 // Classify the weak object being accessed for better warning text.
1459 // This enum should stay in sync with the cases in
1460 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1461 enum {
1462 Variable,
1463 Property,
1464 ImplicitProperty,
1465 Ivar
1466 } ObjectKind;
1467
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001468 const NamedDecl *KeyProp = Key.getProperty();
1469 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001470 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001471 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001472 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001473 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001474 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001475 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001476 ObjectKind = Ivar;
1477 else
1478 llvm_unreachable("Unexpected weak object kind!");
1479
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001480 // Do not warn about IBOutlet weak property receivers being set to null
1481 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001482 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001483 if (Prop->hasAttr<IBOutletAttr>())
1484 continue;
1485
Jordan Rosed3934582012-09-28 22:21:30 +00001486 // Show the first time the object was read.
1487 S.Diag(FirstRead->getLocStart(), DiagKind)
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001488 << int(ObjectKind) << KeyProp << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001489 << FirstRead->getSourceRange();
1490
1491 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001492 for (const auto &Use : Uses) {
1493 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001494 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001495 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001496 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001497 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001498 }
1499 }
1500}
1501
Jordan Rosed3934582012-09-28 22:21:30 +00001502namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001503class UninitValsDiagReporter : public UninitVariablesHandler {
1504 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001505 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001506 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001507 // Prefer using MapVector to DenseMap, so that iteration order will be
1508 // the same as insertion order. This is needed to obtain a deterministic
1509 // order of diagnostics when calling flushDiagnostics().
1510 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001511 UsesMap uses;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001512
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001513public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001514 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001515 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001516
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001517 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001518 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001519 if (!V.getPointer())
1520 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001521 return V;
1522 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001523
1524 void handleUseOfUninitVariable(const VarDecl *vd,
1525 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001526 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001527 }
1528
Craig Toppere14c0f82014-03-12 04:55:44 +00001529 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001530 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001531 }
1532
1533 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001534 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001535 const VarDecl *vd = P.first;
1536 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001537
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001538 UsesVec *vec = V.getPointer();
1539 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001540
1541 // Specially handle the case where we have uses of an uninitialized
1542 // variable, but the root cause is an idiomatic self-init. We want
1543 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001544 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001545 DiagnoseUninitializedUse(S, vd,
1546 UninitUse(vd->getInit()->IgnoreParenCasts(),
1547 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001548 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001549 else {
1550 // Sort the uses by their SourceLocations. While not strictly
1551 // guaranteed to produce them in line/column order, this will provide
1552 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001553 std::sort(vec->begin(), vec->end(),
1554 [](const UninitUse &a, const UninitUse &b) {
1555 // Prefer a more confident report over a less confident one.
1556 if (a.getKind() != b.getKind())
1557 return a.getKind() > b.getKind();
1558 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1559 });
1560
Aaron Ballmane5195222014-05-15 20:50:47 +00001561 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001562 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001563 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001564
1565 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001566 // Skip further diagnostics for this variable. We try to warn only
1567 // on the first point at which a variable is used uninitialized.
1568 break;
1569 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001570 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001571
1572 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001573 delete vec;
1574 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001575
1576 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001577 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001578
1579private:
1580 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001581 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1582 return U.getKind() == UninitUse::Always ||
1583 U.getKind() == UninitUse::AfterCall ||
1584 U.getKind() == UninitUse::AfterDecl;
1585 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001586 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001587};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001588} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001589
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001590namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001591namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001592typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001593typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001594typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001595
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001596struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001597 SourceManager &SM;
1598 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001599
1600 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1601 // Although this call will be slow, this is only called when outputting
1602 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001603 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001604 }
1605};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001606} // anonymous namespace
1607} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001608
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001609//===----------------------------------------------------------------------===//
1610// -Wthread-safety
1611//===----------------------------------------------------------------------===//
1612namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001613namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001614namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001615class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001616 Sema &S;
1617 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001618 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001619
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001620 const FunctionDecl *CurrentFunction;
1621 bool Verbose;
1622
Aaron Ballman71291bc2014-08-15 12:38:17 +00001623 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001624 if (Verbose && CurrentFunction) {
1625 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001626 S.PDiag(diag::note_thread_warning_in_fun)
1627 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001628 return OptionalNotes(1, FNote);
1629 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001630 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001631 }
1632
Aaron Ballman71291bc2014-08-15 12:38:17 +00001633 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001634 OptionalNotes ONS(1, Note);
1635 if (Verbose && CurrentFunction) {
1636 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001637 S.PDiag(diag::note_thread_warning_in_fun)
1638 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001639 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001640 }
1641 return ONS;
1642 }
1643
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001644 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1645 const PartialDiagnosticAt &Note2) const {
1646 OptionalNotes ONS;
1647 ONS.push_back(Note1);
1648 ONS.push_back(Note2);
1649 if (Verbose && CurrentFunction) {
1650 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1651 S.PDiag(diag::note_thread_warning_in_fun)
1652 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001653 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001654 }
1655 return ONS;
1656 }
1657
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001658 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001659 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1660 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001661 // Gracefully handle rare cases when the analysis can't get a more
1662 // precise source location.
1663 if (!Loc.isValid())
1664 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001665 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001666 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001667 }
1668
1669 public:
Richard Smith92286672012-02-03 04:45:26 +00001670 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001671 : S(S), FunLocation(FL), FunEndLocation(FEL),
1672 CurrentFunction(nullptr), Verbose(false) {}
1673
1674 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001675
1676 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1677 /// We need to output diagnostics produced while iterating through
1678 /// the lockset in deterministic order, so this function orders diagnostics
1679 /// and outputs them.
1680 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001681 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001682 for (const auto &Diag : Warnings) {
1683 S.Diag(Diag.first.first, Diag.first.second);
1684 for (const auto &Note : Diag.second)
1685 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001686 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001687 }
1688
Aaron Ballmane0449042014-04-01 21:43:23 +00001689 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1690 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1691 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001692 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001693 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001694
Aaron Ballmane0449042014-04-01 21:43:23 +00001695 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1696 SourceLocation Loc) override {
1697 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001698 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001699
Aaron Ballmane0449042014-04-01 21:43:23 +00001700 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1701 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001702 SourceLocation Loc) override {
1703 if (Loc.isInvalid())
1704 Loc = FunLocation;
1705 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001706 << Kind << LockName << Received
1707 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001708 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001709 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001710
Aaron Ballmane0449042014-04-01 21:43:23 +00001711 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1712 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001713 }
1714
Aaron Ballmane0449042014-04-01 21:43:23 +00001715 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1716 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001717 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001718 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001719 unsigned DiagID = 0;
1720 switch (LEK) {
1721 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001722 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001723 break;
1724 case LEK_LockedSomeLoopIterations:
1725 DiagID = diag::warn_expecting_lock_held_on_loop;
1726 break;
1727 case LEK_LockedAtEndOfFunction:
1728 DiagID = diag::warn_no_unlock;
1729 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001730 case LEK_NotLockedAtEndOfFunction:
1731 DiagID = diag::warn_expecting_locked;
1732 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001733 }
Richard Smith92286672012-02-03 04:45:26 +00001734 if (LocEndOfScope.isInvalid())
1735 LocEndOfScope = FunEndLocation;
1736
Aaron Ballmane0449042014-04-01 21:43:23 +00001737 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1738 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001739 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001740 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1741 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001742 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001743 return;
1744 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001745 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001746 }
1747
Aaron Ballmane0449042014-04-01 21:43:23 +00001748 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1749 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001750 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001751 PartialDiagnosticAt Warning(Loc1,
1752 S.PDiag(diag::warn_lock_exclusive_and_shared)
1753 << Kind << LockName);
1754 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1755 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001756 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001757 }
1758
Aaron Ballmane0449042014-04-01 21:43:23 +00001759 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1760 ProtectedOperationKind POK, AccessKind AK,
1761 SourceLocation Loc) override {
1762 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1763 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001764 unsigned DiagID = POK == POK_VarAccess?
1765 diag::warn_variable_requires_any_lock:
1766 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001767 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001768 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001769 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001770 }
1771
Aaron Ballmane0449042014-04-01 21:43:23 +00001772 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1773 ProtectedOperationKind POK, Name LockName,
1774 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001775 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001776 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001777 if (PossibleMatch) {
1778 switch (POK) {
1779 case POK_VarAccess:
1780 DiagID = diag::warn_variable_requires_lock_precise;
1781 break;
1782 case POK_VarDereference:
1783 DiagID = diag::warn_var_deref_requires_lock_precise;
1784 break;
1785 case POK_FunctionCall:
1786 DiagID = diag::warn_fun_requires_lock_precise;
1787 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001788 case POK_PassByRef:
1789 DiagID = diag::warn_guarded_pass_by_reference;
1790 break;
1791 case POK_PtPassByRef:
1792 DiagID = diag::warn_pt_guarded_pass_by_reference;
1793 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001794 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001795 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1796 << D->getNameAsString()
1797 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001798 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001799 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001800 if (Verbose && POK == POK_VarAccess) {
1801 PartialDiagnosticAt VNote(D->getLocation(),
1802 S.PDiag(diag::note_guarded_by_declared_here)
1803 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001804 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001805 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001806 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001807 } else {
1808 switch (POK) {
1809 case POK_VarAccess:
1810 DiagID = diag::warn_variable_requires_lock;
1811 break;
1812 case POK_VarDereference:
1813 DiagID = diag::warn_var_deref_requires_lock;
1814 break;
1815 case POK_FunctionCall:
1816 DiagID = diag::warn_fun_requires_lock;
1817 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001818 case POK_PassByRef:
1819 DiagID = diag::warn_guarded_pass_by_reference;
1820 break;
1821 case POK_PtPassByRef:
1822 DiagID = diag::warn_pt_guarded_pass_by_reference;
1823 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001824 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001825 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1826 << D->getNameAsString()
1827 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001828 if (Verbose && POK == POK_VarAccess) {
1829 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001830 S.PDiag(diag::note_guarded_by_declared_here)
1831 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001832 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001833 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001834 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001835 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001836 }
1837
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001838 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1839 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001840 PartialDiagnosticAt Warning(Loc,
1841 S.PDiag(diag::warn_acquire_requires_negative_cap)
1842 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001843 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001844 }
1845
Aaron Ballmane0449042014-04-01 21:43:23 +00001846 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001847 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001848 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1849 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001850 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001851 }
1852
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001853 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1854 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001855 PartialDiagnosticAt Warning(Loc,
1856 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001857 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001858 }
1859
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001860 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001861 PartialDiagnosticAt Warning(Loc,
1862 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001863 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001864 }
1865
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001866 void enterFunction(const FunctionDecl* FD) override {
1867 CurrentFunction = FD;
1868 }
1869
1870 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001871 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001872 }
1873};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001874} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001875} // namespace threadSafety
1876} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001877
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001878//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001879// -Wconsumed
1880//===----------------------------------------------------------------------===//
1881
1882namespace clang {
1883namespace consumed {
1884namespace {
1885class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1886
1887 Sema &S;
1888 DiagList Warnings;
1889
1890public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001891
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001892 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001893
1894 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001895 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001896 for (const auto &Diag : Warnings) {
1897 S.Diag(Diag.first.first, Diag.first.second);
1898 for (const auto &Note : Diag.second)
1899 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001900 }
1901 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001902
1903 void warnLoopStateMismatch(SourceLocation Loc,
1904 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001905 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1906 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001907
1908 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001909 }
1910
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001911 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1912 StringRef VariableName,
1913 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001914 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001915
1916 PartialDiagnosticAt Warning(Loc, S.PDiag(
1917 diag::warn_param_return_typestate_mismatch) << VariableName <<
1918 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001919
1920 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001921 }
1922
DeLesley Hutchins69391772013-10-17 23:23:53 +00001923 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001924 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001925
1926 PartialDiagnosticAt Warning(Loc, S.PDiag(
1927 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001928
1929 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001930 }
1931
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001932 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001933 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001934 PartialDiagnosticAt Warning(Loc, S.PDiag(
1935 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001936
1937 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001938 }
1939
1940 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001941 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001942
1943 PartialDiagnosticAt Warning(Loc, S.PDiag(
1944 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001945
1946 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001947 }
1948
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001949 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001950 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001951
1952 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001953 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001954
1955 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001956 }
1957
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001958 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001959 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001960
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001961 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1962 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001963
1964 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001965 }
1966};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001967} // anonymous namespace
1968} // namespace consumed
1969} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001970
1971//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001972// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1973// warnings on a function, method, or block.
1974//===----------------------------------------------------------------------===//
1975
Ted Kremenek0b405322010-03-23 00:13:23 +00001976clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1977 enableCheckFallThrough = 1;
1978 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001979 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001980 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001981}
1982
Ted Kremenekad8753c2014-03-15 05:47:06 +00001983static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001984 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001985}
1986
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001987clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1988 : S(s),
1989 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001990 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001991 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001992 MaxCFGBlocksPerFunction(0),
1993 NumUninitAnalysisFunctions(0),
1994 NumUninitAnalysisVariables(0),
1995 MaxUninitAnalysisVariablesPerFunction(0),
1996 NumUninitAnalysisBlockVisits(0),
1997 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001998
1999 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00002000 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00002001
2002 DefaultPolicy.enableCheckUnreachable =
2003 isEnabled(D, warn_unreachable) ||
2004 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00002005 isEnabled(D, warn_unreachable_return) ||
2006 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00002007
2008 DefaultPolicy.enableThreadSafetyAnalysis =
2009 isEnabled(D, warn_double_lock);
2010
2011 DefaultPolicy.enableConsumedAnalysis =
2012 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00002013}
2014
Aaron Ballmane5195222014-05-15 20:50:47 +00002015static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2016 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00002017 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00002018}
2019
Ted Kremenek0b405322010-03-23 00:13:23 +00002020void clang::sema::
2021AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00002022 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00002023 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00002024
Ted Kremenek918fe842010-03-20 21:06:02 +00002025 // We avoid doing analysis-based warnings when there are errors for
2026 // two reasons:
2027 // (1) The CFGs often can't be constructed (if the body is invalid), so
2028 // don't bother trying.
2029 // (2) The code already has problems; running the analysis just takes more
2030 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00002031 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00002032
Olivier Goffart270ced22017-11-23 08:15:22 +00002033 // Do not do any analysis if we are going to just ignore them.
2034 if (Diags.getIgnoreAllWarnings() ||
2035 (Diags.getSuppressSystemWarnings() &&
2036 S.SourceMgr.isInSystemHeader(D->getLocation())))
Ted Kremenek0b405322010-03-23 00:13:23 +00002037 return;
2038
John McCall1d570a72010-08-25 05:56:39 +00002039 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00002040 if (cast<DeclContext>(D)->isDependentContext())
2041 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00002042
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002043 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002044 // Flush out any possibly unreachable diagnostics.
2045 flushDiagnostics(S, fscope);
2046 return;
2047 }
2048
Ted Kremenek918fe842010-03-20 21:06:02 +00002049 const Stmt *Body = D->getBody();
2050 assert(Body);
2051
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002052 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00002053 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00002054
Ted Kremenek918fe842010-03-20 21:06:02 +00002055 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00002056 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00002057 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2058 AC.getCFGBuildOptions().AddEHEdges = false;
2059 AC.getCFGBuildOptions().AddInitializers = true;
2060 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002061 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00002062 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00002063 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002064
Ted Kremenek9e100ea2011-07-19 14:18:48 +00002065 // Force that certain expressions appear as CFGElements in the CFG. This
2066 // is used to speed up various analyses.
2067 // FIXME: This isn't the right factoring. This is here for initial
2068 // prototyping, but we need a way for analyses to say what expressions they
2069 // expect to always be CFGElements and then fill in the BuildOptions
2070 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002071 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2072 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002073 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00002074 AC.getCFGBuildOptions().setAllAlwaysAdd();
2075 }
2076 else {
2077 AC.getCFGBuildOptions()
2078 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00002079 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00002080 .setAlwaysAdd(Stmt::BlockExprClass)
2081 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2082 .setAlwaysAdd(Stmt::DeclRefExprClass)
2083 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00002084 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2085 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00002086 }
Ted Kremenek918fe842010-03-20 21:06:02 +00002087
Richard Trieue9fa2662014-04-15 00:57:50 +00002088 // Install the logical handler for -Wtautological-overlap-compare
2089 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002090 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2091 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00002092 LEH.reset(new LogicalErrorHandler(S));
2093 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00002094 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002095
Ted Kremenek3427fac2011-02-23 01:52:04 +00002096 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00002097 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002098 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00002099
2100 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00002101 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2102 if (D.stmt)
2103 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00002104 }
2105
2106 if (AC.getCFG()) {
2107 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00002108 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00002109 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00002110 if (D.stmt) {
2111 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00002112 CFGReverseBlockReachabilityAnalysis *cra =
2113 AC.getCFGReachablityAnalysis();
2114 // FIXME: We should be able to assert that block is non-null, but
2115 // the CFG analysis can skip potentially-evaluated expressions in
2116 // edge cases; see test/Sema/vla-2.c.
2117 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002118 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00002119 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00002120 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00002121 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00002122 }
2123 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002124 if (!processed) {
2125 // Emit the warning anyway if we cannot map to a basic block.
2126 S.Diag(D.Loc, D.PD);
2127 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002128 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002129 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002130
2131 if (!analyzed)
2132 flushDiagnostics(S, fscope);
2133 }
2134
Ted Kremenek918fe842010-03-20 21:06:02 +00002135 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002136 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00002137 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002138 (isa<BlockDecl>(D)
2139 ? CheckFallThroughDiagnostics::MakeForBlock()
2140 : (isa<CXXMethodDecl>(D) &&
2141 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2142 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2143 ? CheckFallThroughDiagnostics::MakeForLambda()
Eric Fiselierda8f9b52017-05-25 02:16:53 +00002144 : (fscope->isCoroutine()
Eric Fiselier709d1b32016-10-27 07:30:31 +00002145 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2146 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Ted Kremenek1767a272011-02-23 01:51:48 +00002147 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00002148 }
2149
2150 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002151 if (P.enableCheckUnreachable) {
2152 // Only check for unreachable code on non-template instantiations.
2153 // Different template instantiations can effectively change the control-flow
2154 // and it is very difficult to prove that a snippet of code in a template
2155 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002156 bool isTemplateInstantiation = false;
2157 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2158 isTemplateInstantiation = Function->isTemplateInstantiation();
2159 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002160 CheckUnreachable(S, AC);
2161 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002162
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002163 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002164 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002165 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00002166 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002167 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002168 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002169 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002170 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2171 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002172
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002173 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2174 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002175 Reporter.emitDiagnostics();
2176 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002177
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002178 // Check for violations of consumed properties.
2179 if (P.enableConsumedAnalysis) {
2180 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002181 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002182 Analyzer.run(AC);
2183 }
2184
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002185 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2186 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2187 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002188 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002189 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002190 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002191 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002192 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002193 reporter, stats);
2194
2195 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2196 ++NumUninitAnalysisFunctions;
2197 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2198 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2199 MaxUninitAnalysisVariablesPerFunction =
2200 std::max(MaxUninitAnalysisVariablesPerFunction,
2201 stats.NumVariablesAnalyzed);
2202 MaxUninitAnalysisBlockVisitsPerFunction =
2203 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2204 stats.NumBlockVisits);
2205 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002206 }
2207 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002208
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002209 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002210 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2211 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2212 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Richard Smith4f902c72016-03-08 00:32:55 +00002213 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2214 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002215 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002216 }
2217
John McCall460ce582015-10-22 18:38:17 +00002218 if (S.getLangOpts().ObjCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002219 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002220 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002221
Richard Trieu2f024f42013-12-21 02:33:43 +00002222
2223 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002224 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2225 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002226 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2227 checkRecursiveFunction(S, FD, Body, AC);
2228 }
2229 }
2230
Erich Keane89fe9c22017-06-23 20:22:19 +00002231 // Check for throw out of non-throwing function.
2232 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2233 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2234 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2235 checkThrowInNonThrowingFunc(S, FD, AC);
2236
Richard Trieue9fa2662014-04-15 00:57:50 +00002237 // If none of the previous checks caused a CFG build, trigger one here
2238 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002239 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002240 D->getLocStart())) {
2241 AC.getCFG();
2242 }
2243
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002244 // Collect statistics about the CFG if it was built.
2245 if (S.CollectStats && AC.isCFGBuilt()) {
2246 ++NumFunctionsAnalyzed;
2247 if (CFG *cfg = AC.getCFG()) {
2248 // If we successfully built a CFG for this context, record some more
2249 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002250 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002251 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002252 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002253 } else {
2254 ++NumFunctionsWithBadCFGs;
2255 }
2256 }
2257}
2258
2259void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2260 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2261
2262 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2263 unsigned AvgCFGBlocksPerFunction =
2264 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2265 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2266 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2267 << " " << NumCFGBlocks << " CFG blocks built.\n"
2268 << " " << AvgCFGBlocksPerFunction
2269 << " average CFG blocks per function.\n"
2270 << " " << MaxCFGBlocksPerFunction
2271 << " max CFG blocks per function.\n";
2272
2273 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2274 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2275 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2276 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2277 llvm::errs() << NumUninitAnalysisFunctions
2278 << " functions analyzed for uninitialiazed variables\n"
2279 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2280 << " " << AvgUninitVariablesPerFunction
2281 << " average variables per function.\n"
2282 << " " << MaxUninitAnalysisVariablesPerFunction
2283 << " max variables per function.\n"
2284 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2285 << " " << AvgUninitBlockVisitsPerFunction
2286 << " average block visits per function.\n"
2287 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2288 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002289}