blob: 1e5aa1224ba34f35b4b06677408bb58e0a91f49e [file] [log] [blame]
Ted Kremenek7296de92010-02-23 02:39:16 +00001//=- ReachableCodePathInsensitive.cpp ---------------------------*- 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 implements a flow-sensitive, path-insensitive analysis of
11// determining reachable blocks within a CFG.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/ExprObjC.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000019#include "clang/AST/StmtCXX.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000020#include "clang/Analysis/AnalysisContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Analysis/CFG.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000022#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/SmallVector.h"
Ted Kremenek7296de92010-02-23 02:39:16 +000025
26using namespace clang;
27
Ted Kremenek7d47cac2014-03-07 07:14:36 +000028//===----------------------------------------------------------------------===//
29// Core Reachability Analysis routines.
30//===----------------------------------------------------------------------===//
Ted Kremenek552eeaa2010-02-23 05:59:20 +000031
Ted Kremenekcc893382014-02-27 00:24:08 +000032static bool bodyEndsWithNoReturn(const CFGBlock *B) {
33 for (CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
34 I != E; ++I) {
35 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
Ted Kremenekec2dc732014-03-06 06:50:46 +000036 const Stmt *S = CS->getStmt();
37 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S))
38 S = EWC->getSubExpr();
39 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekcc893382014-02-27 00:24:08 +000040 QualType CalleeType = CE->getCallee()->getType();
41 if (getFunctionExtInfo(*CalleeType).getNoReturn())
42 return true;
43 }
44 break;
45 }
46 }
47 return false;
48}
49
Ted Kremenek5441c182014-02-27 06:32:32 +000050static bool bodyEndsWithNoReturn(const CFGBlock::AdjacentBlock &AB) {
Ted Kremenekeb862842014-03-04 21:41:38 +000051 // If the predecessor is a normal CFG edge, then by definition
52 // the predecessor did not end with a 'noreturn'.
53 if (AB.getReachableBlock())
54 return false;
55
Ted Kremenek5441c182014-02-27 06:32:32 +000056 const CFGBlock *Pred = AB.getPossiblyUnreachableBlock();
57 assert(!AB.isReachable() && Pred);
58 return bodyEndsWithNoReturn(Pred);
59}
60
Ted Kremenekcc893382014-02-27 00:24:08 +000061static bool isBreakPrecededByNoReturn(const CFGBlock *B,
62 const Stmt *S) {
63 if (!isa<BreakStmt>(S) || B->pred_empty())
64 return false;
65
66 assert(B->empty());
67 assert(B->pred_size() == 1);
Ted Kremenek5441c182014-02-27 06:32:32 +000068 return bodyEndsWithNoReturn(*B->pred_begin());
69}
70
71static bool isEnumConstant(const Expr *Ex) {
72 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex);
73 if (!DR)
74 return false;
75 return isa<EnumConstantDecl>(DR->getDecl());
76}
77
Ted Kremenekec2dc732014-03-06 06:50:46 +000078static const Expr *stripStdStringCtor(const Expr *Ex) {
79 // Go crazy pattern matching an implicit construction of std::string("").
80 const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex);
81 if (!EWC)
82 return 0;
83 const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(EWC->getSubExpr());
84 if (!CCE)
85 return 0;
86 QualType Ty = CCE->getType();
87 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty))
88 Ty = ET->getNamedType();
89 const TypedefType *TT = dyn_cast<TypedefType>(Ty);
90 StringRef Name = TT->getDecl()->getName();
91 if (Name != "string")
92 return 0;
93 if (CCE->getNumArgs() != 1)
94 return 0;
95 const MaterializeTemporaryExpr *MTE =
96 dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0));
97 if (!MTE)
98 return 0;
99 CXXBindTemporaryExpr *CBT =
100 dyn_cast<CXXBindTemporaryExpr>(MTE->GetTemporaryExpr()->IgnoreParenCasts());
101 if (!CBT)
102 return 0;
103 Ex = CBT->getSubExpr()->IgnoreParenCasts();
104 CCE = dyn_cast<CXXConstructExpr>(Ex);
105 if (!CCE)
106 return 0;
107 if (CCE->getNumArgs() != 1)
108 return 0;
109 return dyn_cast<StringLiteral>(CCE->getArg(0)->IgnoreParenCasts());
110}
111
112/// Strip away "sugar" around trivial expressions that are for the
113/// purpose of this analysis considered uninteresting for dead code warnings.
114static const Expr *stripExprSugar(const Expr *Ex) {
115 Ex = Ex->IgnoreParenCasts();
116 // If 'Ex' is a constructor for a std::string, strip that
117 // away. We can only get here if the trivial expression was
118 // something like a C string literal, with the std::string
119 // just wrapping that value.
120 if (const Expr *StdStringVal = stripStdStringCtor(Ex))
121 return StdStringVal;
122 return Ex;
123}
124
Ted Kremenek5441c182014-02-27 06:32:32 +0000125static bool isTrivialExpression(const Expr *Ex) {
Ted Kremenek0a69cab2014-03-05 23:46:07 +0000126 Ex = Ex->IgnoreParenCasts();
Ted Kremenek5441c182014-02-27 06:32:32 +0000127 return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
Ted Kremenekc10830b2014-03-07 02:25:50 +0000128 isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
129 isa<CharacterLiteral>(Ex) ||
Ted Kremenek5441c182014-02-27 06:32:32 +0000130 isEnumConstant(Ex);
131}
132
Ted Kremenek1de2e142014-03-06 00:17:44 +0000133static bool isTrivialReturnOrDoWhile(const CFGBlock *B, const Stmt *S) {
Ted Kremenek5441c182014-02-27 06:32:32 +0000134 const Expr *Ex = dyn_cast<Expr>(S);
135 if (!Ex)
136 return false;
137
Ted Kremenek5441c182014-02-27 06:32:32 +0000138 if (!isTrivialExpression(Ex))
139 return false;
140
Ted Kremenek1de2e142014-03-06 00:17:44 +0000141 // Check if the block ends with a do...while() and see if 'S' is the
142 // condition.
143 if (const Stmt *Term = B->getTerminator()) {
144 if (const DoStmt *DS = dyn_cast<DoStmt>(Term))
145 if (DS->getCond() == S)
146 return true;
147 }
148
Ted Kremenek7549f0f2014-03-06 01:09:45 +0000149 if (B->pred_size() != 1)
150 return false;
Ted Kremenek1de2e142014-03-06 00:17:44 +0000151
Ted Kremenek5441c182014-02-27 06:32:32 +0000152 // Look to see if the block ends with a 'return', and see if 'S'
153 // is a substatement. The 'return' may not be the last element in
154 // the block because of destructors.
155 assert(!B->empty());
156 for (CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
157 I != E; ++I) {
158 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
159 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
160 const Expr *RE = RS->getRetValue();
Ted Kremenekec2dc732014-03-06 06:50:46 +0000161 if (RE && stripExprSugar(RE->IgnoreParenCasts()) == Ex)
Ted Kremenek7549f0f2014-03-06 01:09:45 +0000162 return bodyEndsWithNoReturn(*B->pred_begin());
Ted Kremenek5441c182014-02-27 06:32:32 +0000163 }
Ted Kremenek7549f0f2014-03-06 01:09:45 +0000164 break;
Ted Kremenek5441c182014-02-27 06:32:32 +0000165 }
166 }
Ted Kremenek0a69cab2014-03-05 23:46:07 +0000167 return false;
Ted Kremenekcc893382014-02-27 00:24:08 +0000168}
169
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000170/// Returns true if the statement is expanded from a configuration macro.
171static bool isExpandedFromConfigurationMacro(const Stmt *S) {
172 // FIXME: This is not very precise. Here we just check to see if the
173 // value comes from a macro, but we can do much better. This is likely
174 // to be over conservative. This logic is factored into a separate function
175 // so that we can refine it later.
176 SourceLocation L = S->getLocStart();
177 return L.isMacroID();
178}
179
180/// Returns true if the statement represents a configuration value.
181///
182/// A configuration value is something usually determined at compile-time
183/// to conditionally always execute some branch. Such guards are for
184/// "sometimes unreachable" code. Such code is usually not interesting
185/// to report as unreachable, and may mask truly unreachable code within
186/// those blocks.
187static bool isConfigurationValue(const Stmt *S) {
188 if (!S)
189 return false;
190
191 if (const Expr *Ex = dyn_cast<Expr>(S))
192 S = Ex->IgnoreParenCasts();
193
194 switch (S->getStmtClass()) {
Ted Kremenek01a39b62014-03-05 23:38:41 +0000195 case Stmt::DeclRefExprClass: {
196 const DeclRefExpr *DR = cast<DeclRefExpr>(S);
Ted Kremenek94d16172014-03-07 20:51:13 +0000197 const ValueDecl *D = DR->getDecl();
198 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D))
199 return ED ? isConfigurationValue(ED->getInitExpr()) : false;
200 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
201 // As a heuristic, treat globals as configuration values. Note
202 // that we only will get here if Sema evaluated this
203 // condition to a constant expression, which means the global
204 // had to be declared in a way to be a truly constant value.
205 // We could generalize this to local variables, but it isn't
206 // clear if those truly represent configuration values that
207 // gate unreachable code.
208 return !VD->hasLocalStorage();
209 }
210 return false;
Ted Kremenek01a39b62014-03-05 23:38:41 +0000211 }
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000212 case Stmt::IntegerLiteralClass:
213 return isExpandedFromConfigurationMacro(S);
214 case Stmt::UnaryExprOrTypeTraitExprClass:
215 return true;
216 case Stmt::BinaryOperatorClass: {
217 const BinaryOperator *B = cast<BinaryOperator>(S);
Ted Kremenek3cdbc392014-03-05 22:32:39 +0000218 return (B->isLogicalOp() || B->isComparisonOp()) &&
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000219 (isConfigurationValue(B->getLHS()) ||
220 isConfigurationValue(B->getRHS()));
221 }
222 case Stmt::UnaryOperatorClass: {
223 const UnaryOperator *UO = cast<UnaryOperator>(S);
224 return UO->getOpcode() == UO_LNot &&
225 isConfigurationValue(UO->getSubExpr());
226 }
227 default:
228 return false;
229 }
230}
231
232/// Returns true if we should always explore all successors of a block.
233static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B) {
Ted Kremenek782f0032014-03-07 02:25:53 +0000234 if (const Stmt *Term = B->getTerminator()) {
Ted Kremenek6999d022014-03-06 08:09:00 +0000235 if (isa<SwitchStmt>(Term))
236 return true;
Ted Kremenek782f0032014-03-07 02:25:53 +0000237 // Specially handle '||' and '&&'.
238 if (isa<BinaryOperator>(Term))
239 return isConfigurationValue(Term);
240 }
Ted Kremenek6999d022014-03-06 08:09:00 +0000241
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000242 return isConfigurationValue(B->getTerminatorCondition());
243}
244
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000245static unsigned scanFromBlock(const CFGBlock *Start,
246 llvm::BitVector &Reachable,
247 bool IncludeSometimesUnreachableEdges) {
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000248 unsigned count = 0;
Ted Kremenekbd913712011-08-23 23:05:11 +0000249
Nico Webercc2b8712011-04-02 19:45:15 +0000250 // Prep work queue
Ted Kremenekbd913712011-08-23 23:05:11 +0000251 SmallVector<const CFGBlock*, 32> WL;
252
253 // The entry block may have already been marked reachable
254 // by the caller.
255 if (!Reachable[Start->getBlockID()]) {
256 ++count;
257 Reachable[Start->getBlockID()] = true;
258 }
259
260 WL.push_back(Start);
261
Ted Kremenekf2b0a1b2010-09-09 00:06:10 +0000262 // Find the reachable blocks from 'Start'.
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000263 while (!WL.empty()) {
Ted Kremenekbd913712011-08-23 23:05:11 +0000264 const CFGBlock *item = WL.pop_back_val();
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000265
266 // There are cases where we want to treat all successors as reachable.
267 // The idea is that some "sometimes unreachable" code is not interesting,
268 // and that we should forge ahead and explore those branches anyway.
269 // This allows us to potentially uncover some "always unreachable" code
270 // within the "sometimes unreachable" code.
Ted Kremenekbd913712011-08-23 23:05:11 +0000271 // Look at the successors and mark then reachable.
Ted Kremenek782f0032014-03-07 02:25:53 +0000272 Optional<bool> TreatAllSuccessorsAsReachable;
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000273 if (!IncludeSometimesUnreachableEdges)
274 TreatAllSuccessorsAsReachable = false;
Ted Kremenek782f0032014-03-07 02:25:53 +0000275
Ted Kremenekbd913712011-08-23 23:05:11 +0000276 for (CFGBlock::const_succ_iterator I = item->succ_begin(),
Ted Kremenek08da9782014-02-27 21:56:47 +0000277 E = item->succ_end(); I != E; ++I) {
278 const CFGBlock *B = *I;
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000279 if (!B) do {
280 const CFGBlock *UB = I->getPossiblyUnreachableBlock();
281 if (!UB)
282 break;
283
Ted Kremenek782f0032014-03-07 02:25:53 +0000284 if (!TreatAllSuccessorsAsReachable.hasValue())
285 TreatAllSuccessorsAsReachable =
286 shouldTreatSuccessorsAsReachable(item);
287
288 if (TreatAllSuccessorsAsReachable.getValue()) {
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000289 B = UB;
290 break;
291 }
Ted Kremenek08da9782014-02-27 21:56:47 +0000292 }
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000293 while (false);
294
Ted Kremenek08da9782014-02-27 21:56:47 +0000295 if (B) {
Ted Kremenek7296de92010-02-23 02:39:16 +0000296 unsigned blockID = B->getBlockID();
297 if (!Reachable[blockID]) {
298 Reachable.set(blockID);
Ted Kremenek7296de92010-02-23 02:39:16 +0000299 WL.push_back(B);
Ted Kremenekbd913712011-08-23 23:05:11 +0000300 ++count;
Ted Kremenek7296de92010-02-23 02:39:16 +0000301 }
302 }
Ted Kremenek08da9782014-02-27 21:56:47 +0000303 }
Ted Kremenek7296de92010-02-23 02:39:16 +0000304 }
305 return count;
306}
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000307
308static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start,
309 llvm::BitVector &Reachable) {
310 return scanFromBlock(Start, Reachable, true);
311}
312
313//===----------------------------------------------------------------------===//
314// Dead Code Scanner.
315//===----------------------------------------------------------------------===//
316
317namespace {
318 class DeadCodeScan {
319 llvm::BitVector Visited;
320 llvm::BitVector &Reachable;
321 SmallVector<const CFGBlock *, 10> WorkList;
322
323 typedef SmallVector<std::pair<const CFGBlock *, const Stmt *>, 12>
324 DeferredLocsTy;
325
326 DeferredLocsTy DeferredLocs;
327
328 public:
329 DeadCodeScan(llvm::BitVector &reachable)
330 : Visited(reachable.size()),
331 Reachable(reachable) {}
332
333 void enqueue(const CFGBlock *block);
334 unsigned scanBackwards(const CFGBlock *Start,
335 clang::reachable_code::Callback &CB);
336
337 bool isDeadCodeRoot(const CFGBlock *Block);
338
339 const Stmt *findDeadCode(const CFGBlock *Block);
340
341 void reportDeadCode(const CFGBlock *B,
342 const Stmt *S,
343 clang::reachable_code::Callback &CB);
344 };
345}
346
347void DeadCodeScan::enqueue(const CFGBlock *block) {
348 unsigned blockID = block->getBlockID();
349 if (Reachable[blockID] || Visited[blockID])
350 return;
351 Visited[blockID] = true;
352 WorkList.push_back(block);
353}
354
355bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) {
356 bool isDeadRoot = true;
357
358 for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
359 E = Block->pred_end(); I != E; ++I) {
360 if (const CFGBlock *PredBlock = *I) {
361 unsigned blockID = PredBlock->getBlockID();
362 if (Visited[blockID]) {
363 isDeadRoot = false;
364 continue;
365 }
366 if (!Reachable[blockID]) {
367 isDeadRoot = false;
368 Visited[blockID] = true;
369 WorkList.push_back(PredBlock);
370 continue;
371 }
372 }
373 }
374
375 return isDeadRoot;
376}
377
378static bool isValidDeadStmt(const Stmt *S) {
379 if (S->getLocStart().isInvalid())
380 return false;
381 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S))
382 return BO->getOpcode() != BO_Comma;
383 return true;
384}
385
386const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) {
387 for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I)
388 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
389 const Stmt *S = CS->getStmt();
390 if (isValidDeadStmt(S))
391 return S;
392 }
393
394 if (CFGTerminator T = Block->getTerminator()) {
395 const Stmt *S = T.getStmt();
396 if (isValidDeadStmt(S))
397 return S;
398 }
399
400 return 0;
401}
402
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000403unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start,
404 clang::reachable_code::Callback &CB) {
405
406 unsigned count = 0;
407 enqueue(Start);
408
409 while (!WorkList.empty()) {
410 const CFGBlock *Block = WorkList.pop_back_val();
411
412 // It is possible that this block has been marked reachable after
413 // it was enqueued.
414 if (Reachable[Block->getBlockID()])
415 continue;
416
417 // Look for any dead code within the block.
418 const Stmt *S = findDeadCode(Block);
419
420 if (!S) {
421 // No dead code. Possibly an empty block. Look at dead predecessors.
422 for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
423 E = Block->pred_end(); I != E; ++I) {
424 if (const CFGBlock *predBlock = *I)
425 enqueue(predBlock);
426 }
427 continue;
428 }
429
430 // Specially handle macro-expanded code.
431 if (S->getLocStart().isMacroID()) {
432 count += scanMaybeReachableFromBlock(Block, Reachable);
433 continue;
434 }
435
436 if (isDeadCodeRoot(Block)) {
437 reportDeadCode(Block, S, CB);
438 count += scanMaybeReachableFromBlock(Block, Reachable);
439 }
440 else {
441 // Record this statement as the possibly best location in a
442 // strongly-connected component of dead code for emitting a
443 // warning.
444 DeferredLocs.push_back(std::make_pair(Block, S));
445 }
446 }
447
448 // If we didn't find a dead root, then report the dead code with the
449 // earliest location.
450 if (!DeferredLocs.empty()) {
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000451 llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(),
452 [](const DeferredLocsTy::value_type *p1,
453 const DeferredLocsTy::value_type *p2) {
454 if (p1->second->getLocStart() != p2->second->getLocStart())
455 return p1->second->getLocStart() < p2->second->getLocStart() ? -1 : 1;
456 return 0;
457 });
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000458 for (DeferredLocsTy::iterator I = DeferredLocs.begin(),
459 E = DeferredLocs.end(); I != E; ++I) {
460 const CFGBlock *Block = I->first;
461 if (Reachable[Block->getBlockID()])
462 continue;
463 reportDeadCode(Block, I->second, CB);
464 count += scanMaybeReachableFromBlock(Block, Reachable);
465 }
466 }
467
468 return count;
469}
470
471static SourceLocation GetUnreachableLoc(const Stmt *S,
472 SourceRange &R1,
473 SourceRange &R2) {
474 R1 = R2 = SourceRange();
475
476 if (const Expr *Ex = dyn_cast<Expr>(S))
477 S = Ex->IgnoreParenImpCasts();
478
479 switch (S->getStmtClass()) {
480 case Expr::BinaryOperatorClass: {
481 const BinaryOperator *BO = cast<BinaryOperator>(S);
482 return BO->getOperatorLoc();
483 }
484 case Expr::UnaryOperatorClass: {
485 const UnaryOperator *UO = cast<UnaryOperator>(S);
486 R1 = UO->getSubExpr()->getSourceRange();
487 return UO->getOperatorLoc();
488 }
489 case Expr::CompoundAssignOperatorClass: {
490 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
491 R1 = CAO->getLHS()->getSourceRange();
492 R2 = CAO->getRHS()->getSourceRange();
493 return CAO->getOperatorLoc();
494 }
495 case Expr::BinaryConditionalOperatorClass:
496 case Expr::ConditionalOperatorClass: {
497 const AbstractConditionalOperator *CO =
498 cast<AbstractConditionalOperator>(S);
499 return CO->getQuestionLoc();
500 }
501 case Expr::MemberExprClass: {
502 const MemberExpr *ME = cast<MemberExpr>(S);
503 R1 = ME->getSourceRange();
504 return ME->getMemberLoc();
505 }
506 case Expr::ArraySubscriptExprClass: {
507 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
508 R1 = ASE->getLHS()->getSourceRange();
509 R2 = ASE->getRHS()->getSourceRange();
510 return ASE->getRBracketLoc();
511 }
512 case Expr::CStyleCastExprClass: {
513 const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
514 R1 = CSC->getSubExpr()->getSourceRange();
515 return CSC->getLParenLoc();
516 }
517 case Expr::CXXFunctionalCastExprClass: {
518 const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
519 R1 = CE->getSubExpr()->getSourceRange();
520 return CE->getLocStart();
521 }
522 case Stmt::CXXTryStmtClass: {
523 return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
524 }
525 case Expr::ObjCBridgedCastExprClass: {
526 const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
527 R1 = CSC->getSubExpr()->getSourceRange();
528 return CSC->getLParenLoc();
529 }
530 default: ;
531 }
532 R1 = S->getSourceRange();
533 return S->getLocStart();
534}
535
536void DeadCodeScan::reportDeadCode(const CFGBlock *B,
537 const Stmt *S,
538 clang::reachable_code::Callback &CB) {
539 // Suppress idiomatic cases of calling a noreturn function just
540 // before executing a 'break'. If there is other code after the 'break'
541 // in the block then don't suppress the warning.
542 if (isBreakPrecededByNoReturn(B, S))
543 return;
544
545 // Suppress trivial 'return' statements that are dead.
546 if (isTrivialReturnOrDoWhile(B, S))
547 return;
548
549 SourceRange R1, R2;
550 SourceLocation Loc = GetUnreachableLoc(S, R1, R2);
551 CB.HandleUnreachable(Loc, R1, R2);
552}
553
554//===----------------------------------------------------------------------===//
555// Reachability APIs.
556//===----------------------------------------------------------------------===//
557
558namespace clang { namespace reachable_code {
559
560void Callback::anchor() { }
561
562unsigned ScanReachableFromBlock(const CFGBlock *Start,
563 llvm::BitVector &Reachable) {
564 return scanFromBlock(Start, Reachable, false);
565}
566
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000567void FindUnreachableCode(AnalysisDeclContext &AC, Callback &CB) {
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000568 CFG *cfg = AC.getCFG();
569 if (!cfg)
570 return;
571
Ted Kremenekbd913712011-08-23 23:05:11 +0000572 // Scan for reachable blocks from the entrance of the CFG.
573 // If there are no unreachable blocks, we're done.
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000574 llvm::BitVector reachable(cfg->getNumBlockIDs());
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000575 unsigned numReachable =
576 scanMaybeReachableFromBlock(&cfg->getEntry(), reachable);
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000577 if (numReachable == cfg->getNumBlockIDs())
578 return;
Ted Kremenekbd913712011-08-23 23:05:11 +0000579
580 // If there aren't explicit EH edges, we should include the 'try' dispatch
581 // blocks as roots.
582 if (!AC.getCFGBuildOptions().AddEHEdges) {
583 for (CFG::try_block_iterator I = cfg->try_blocks_begin(),
584 E = cfg->try_blocks_end() ; I != E; ++I) {
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000585 numReachable += scanMaybeReachableFromBlock(*I, reachable);
Ted Kremenekbd913712011-08-23 23:05:11 +0000586 }
587 if (numReachable == cfg->getNumBlockIDs())
588 return;
589 }
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000590
Ted Kremenekbd913712011-08-23 23:05:11 +0000591 // There are some unreachable blocks. We need to find the root blocks that
592 // contain code that should be considered unreachable.
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000593 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
Ted Kremenekbd913712011-08-23 23:05:11 +0000594 const CFGBlock *block = *I;
595 // A block may have been marked reachable during this loop.
596 if (reachable[block->getBlockID()])
597 continue;
598
599 DeadCodeScan DS(reachable);
600 numReachable += DS.scanBackwards(block, CB);
601
602 if (numReachable == cfg->getNumBlockIDs())
603 return;
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000604 }
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000605}
606
607}} // end namespace clang::reachable_code