clang  14.0.0git
ReachableCode.cpp
Go to the documentation of this file.
1 //===-- ReachableCode.cpp - Code Reachability Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a flow-sensitive, path-insensitive analysis of
10 // determining reachable blocks within a CFG.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/AST/StmtCXX.h"
21 #include "clang/Analysis/CFG.h"
22 #include "clang/Basic/Builtins.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/SmallVector.h"
27 
28 using namespace clang;
29 
30 //===----------------------------------------------------------------------===//
31 // Core Reachability Analysis routines.
32 //===----------------------------------------------------------------------===//
33 
34 static bool isEnumConstant(const Expr *Ex) {
35  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex);
36  if (!DR)
37  return false;
38  return isa<EnumConstantDecl>(DR->getDecl());
39 }
40 
41 static bool isTrivialExpression(const Expr *Ex) {
42  Ex = Ex->IgnoreParenCasts();
43  return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
44  isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
45  isa<CharacterLiteral>(Ex) ||
46  isEnumConstant(Ex);
47 }
48 
49 static bool isTrivialDoWhile(const CFGBlock *B, const Stmt *S) {
50  // Check if the block ends with a do...while() and see if 'S' is the
51  // condition.
52  if (const Stmt *Term = B->getTerminatorStmt()) {
53  if (const DoStmt *DS = dyn_cast<DoStmt>(Term)) {
54  const Expr *Cond = DS->getCond()->IgnoreParenCasts();
55  return Cond == S && isTrivialExpression(Cond);
56  }
57  }
58  return false;
59 }
60 
61 static bool isBuiltinUnreachable(const Stmt *S) {
62  if (const auto *DRE = dyn_cast<DeclRefExpr>(S))
63  if (const auto *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()))
64  return FDecl->getIdentifier() &&
65  FDecl->getBuiltinID() == Builtin::BI__builtin_unreachable;
66  return false;
67 }
68 
69 static bool isBuiltinAssumeFalse(const CFGBlock *B, const Stmt *S,
70  ASTContext &C) {
71  if (B->empty()) {
72  // Happens if S is B's terminator and B contains nothing else
73  // (e.g. a CFGBlock containing only a goto).
74  return false;
75  }
76  if (Optional<CFGStmt> CS = B->back().getAs<CFGStmt>()) {
77  if (const auto *CE = dyn_cast<CallExpr>(CS->getStmt())) {
78  return CE->getCallee()->IgnoreCasts() == S && CE->isBuiltinAssumeFalse(C);
79  }
80  }
81  return false;
82 }
83 
84 static bool isDeadReturn(const CFGBlock *B, const Stmt *S) {
85  // Look to see if the current control flow ends with a 'return', and see if
86  // 'S' is a substatement. The 'return' may not be the last element in the
87  // block, or may be in a subsequent block because of destructors.
88  const CFGBlock *Current = B;
89  while (true) {
90  for (CFGBlock::const_reverse_iterator I = Current->rbegin(),
91  E = Current->rend();
92  I != E; ++I) {
93  if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
94  if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
95  if (RS == S)
96  return true;
97  if (const Expr *RE = RS->getRetValue()) {
98  RE = RE->IgnoreParenCasts();
99  if (RE == S)
100  return true;
101  ParentMap PM(const_cast<Expr *>(RE));
102  // If 'S' is in the ParentMap, it is a subexpression of
103  // the return statement.
104  return PM.getParent(S);
105  }
106  }
107  break;
108  }
109  }
110  // Note also that we are restricting the search for the return statement
111  // to stop at control-flow; only part of a return statement may be dead,
112  // without the whole return statement being dead.
113  if (Current->getTerminator().isTemporaryDtorsBranch()) {
114  // Temporary destructors have a predictable control flow, thus we want to
115  // look into the next block for the return statement.
116  // We look into the false branch, as we know the true branch only contains
117  // the call to the destructor.
118  assert(Current->succ_size() == 2);
119  Current = *(Current->succ_begin() + 1);
120  } else if (!Current->getTerminatorStmt() && Current->succ_size() == 1) {
121  // If there is only one successor, we're not dealing with outgoing control
122  // flow. Thus, look into the next block.
123  Current = *Current->succ_begin();
124  if (Current->pred_size() > 1) {
125  // If there is more than one predecessor, we're dealing with incoming
126  // control flow - if the return statement is in that block, it might
127  // well be reachable via a different control flow, thus it's not dead.
128  return false;
129  }
130  } else {
131  // We hit control flow or a dead end. Stop searching.
132  return false;
133  }
134  }
135  llvm_unreachable("Broke out of infinite loop.");
136 }
137 
139  assert(Loc.isMacroID());
141  do {
142  Last = Loc;
143  Loc = SM.getImmediateMacroCallerLoc(Loc);
144  } while (Loc.isMacroID());
145  return Last;
146 }
147 
148 /// Returns true if the statement is expanded from a configuration macro.
150  Preprocessor &PP,
151  bool IgnoreYES_NO = false) {
152  // FIXME: This is not very precise. Here we just check to see if the
153  // value comes from a macro, but we can do much better. This is likely
154  // to be over conservative. This logic is factored into a separate function
155  // so that we can refine it later.
156  SourceLocation L = S->getBeginLoc();
157  if (L.isMacroID()) {
159  if (IgnoreYES_NO) {
160  // The Objective-C constant 'YES' and 'NO'
161  // are defined as macros. Do not treat them
162  // as configuration values.
163  SourceLocation TopL = getTopMostMacro(L, SM);
164  StringRef MacroName = PP.getImmediateMacroName(TopL);
165  if (MacroName == "YES" || MacroName == "NO")
166  return false;
167  } else if (!PP.getLangOpts().CPlusPlus) {
168  // Do not treat C 'false' and 'true' macros as configuration values.
169  SourceLocation TopL = getTopMostMacro(L, SM);
170  StringRef MacroName = PP.getImmediateMacroName(TopL);
171  if (MacroName == "false" || MacroName == "true")
172  return false;
173  }
174  return true;
175  }
176  return false;
177 }
178 
179 static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP);
180 
181 /// Returns true if the statement represents a configuration value.
182 ///
183 /// A configuration value is something usually determined at compile-time
184 /// to conditionally always execute some branch. Such guards are for
185 /// "sometimes unreachable" code. Such code is usually not interesting
186 /// to report as unreachable, and may mask truly unreachable code within
187 /// those blocks.
188 static bool isConfigurationValue(const Stmt *S,
189  Preprocessor &PP,
190  SourceRange *SilenceableCondVal = nullptr,
191  bool IncludeIntegers = true,
192  bool WrappedInParens = false) {
193  if (!S)
194  return false;
195 
196  if (const auto *Ex = dyn_cast<Expr>(S))
197  S = Ex->IgnoreImplicit();
198 
199  if (const auto *Ex = dyn_cast<Expr>(S))
200  S = Ex->IgnoreCasts();
201 
202  // Special case looking for the sigil '()' around an integer literal.
203  if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
204  if (!PE->getBeginLoc().isMacroID())
205  return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal,
206  IncludeIntegers, true);
207 
208  if (const Expr *Ex = dyn_cast<Expr>(S))
209  S = Ex->IgnoreCasts();
210 
211  bool IgnoreYES_NO = false;
212 
213  switch (S->getStmtClass()) {
214  case Stmt::CallExprClass: {
215  const FunctionDecl *Callee =
216  dyn_cast_or_null<FunctionDecl>(cast<CallExpr>(S)->getCalleeDecl());
217  return Callee ? Callee->isConstexpr() : false;
218  }
219  case Stmt::DeclRefExprClass:
220  return isConfigurationValue(cast<DeclRefExpr>(S)->getDecl(), PP);
221  case Stmt::ObjCBoolLiteralExprClass:
222  IgnoreYES_NO = true;
223  LLVM_FALLTHROUGH;
224  case Stmt::CXXBoolLiteralExprClass:
225  case Stmt::IntegerLiteralClass: {
226  const Expr *E = cast<Expr>(S);
227  if (IncludeIntegers) {
228  if (SilenceableCondVal && !SilenceableCondVal->getBegin().isValid())
229  *SilenceableCondVal = E->getSourceRange();
230  return WrappedInParens ||
231  isExpandedFromConfigurationMacro(E, PP, IgnoreYES_NO);
232  }
233  return false;
234  }
235  case Stmt::MemberExprClass:
236  return isConfigurationValue(cast<MemberExpr>(S)->getMemberDecl(), PP);
237  case Stmt::UnaryExprOrTypeTraitExprClass:
238  return true;
239  case Stmt::BinaryOperatorClass: {
240  const BinaryOperator *B = cast<BinaryOperator>(S);
241  // Only include raw integers (not enums) as configuration
242  // values if they are used in a logical or comparison operator
243  // (not arithmetic).
244  IncludeIntegers &= (B->isLogicalOp() || B->isComparisonOp());
245  return isConfigurationValue(B->getLHS(), PP, SilenceableCondVal,
246  IncludeIntegers) ||
247  isConfigurationValue(B->getRHS(), PP, SilenceableCondVal,
248  IncludeIntegers);
249  }
250  case Stmt::UnaryOperatorClass: {
251  const UnaryOperator *UO = cast<UnaryOperator>(S);
252  if (UO->getOpcode() != UO_LNot && UO->getOpcode() != UO_Minus)
253  return false;
254  bool SilenceableCondValNotSet =
255  SilenceableCondVal && SilenceableCondVal->getBegin().isInvalid();
256  bool IsSubExprConfigValue =
257  isConfigurationValue(UO->getSubExpr(), PP, SilenceableCondVal,
258  IncludeIntegers, WrappedInParens);
259  // Update the silenceable condition value source range only if the range
260  // was set directly by the child expression.
261  if (SilenceableCondValNotSet &&
262  SilenceableCondVal->getBegin().isValid() &&
263  *SilenceableCondVal ==
265  *SilenceableCondVal = UO->getSourceRange();
266  return IsSubExprConfigValue;
267  }
268  default:
269  return false;
270  }
271 }
272 
273 static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP) {
274  if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D))
275  return isConfigurationValue(ED->getInitExpr(), PP);
276  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
277  // As a heuristic, treat globals as configuration values. Note
278  // that we only will get here if Sema evaluated this
279  // condition to a constant expression, which means the global
280  // had to be declared in a way to be a truly constant value.
281  // We could generalize this to local variables, but it isn't
282  // clear if those truly represent configuration values that
283  // gate unreachable code.
284  if (!VD->hasLocalStorage())
285  return true;
286 
287  // As a heuristic, locals that have been marked 'const' explicitly
288  // can be treated as configuration values as well.
289  return VD->getType().isLocalConstQualified();
290  }
291  return false;
292 }
293 
294 /// Returns true if we should always explore all successors of a block.
296  Preprocessor &PP) {
297  if (const Stmt *Term = B->getTerminatorStmt()) {
298  if (isa<SwitchStmt>(Term))
299  return true;
300  // Specially handle '||' and '&&'.
301  if (isa<BinaryOperator>(Term)) {
302  return isConfigurationValue(Term, PP);
303  }
304  }
305 
306  const Stmt *Cond = B->getTerminatorCondition(/* stripParens */ false);
307  return isConfigurationValue(Cond, PP);
308 }
309 
310 static unsigned scanFromBlock(const CFGBlock *Start,
311  llvm::BitVector &Reachable,
312  Preprocessor *PP,
313  bool IncludeSometimesUnreachableEdges) {
314  unsigned count = 0;
315 
316  // Prep work queue
318 
319  // The entry block may have already been marked reachable
320  // by the caller.
321  if (!Reachable[Start->getBlockID()]) {
322  ++count;
323  Reachable[Start->getBlockID()] = true;
324  }
325 
326  WL.push_back(Start);
327 
328  // Find the reachable blocks from 'Start'.
329  while (!WL.empty()) {
330  const CFGBlock *item = WL.pop_back_val();
331 
332  // There are cases where we want to treat all successors as reachable.
333  // The idea is that some "sometimes unreachable" code is not interesting,
334  // and that we should forge ahead and explore those branches anyway.
335  // This allows us to potentially uncover some "always unreachable" code
336  // within the "sometimes unreachable" code.
337  // Look at the successors and mark then reachable.
338  Optional<bool> TreatAllSuccessorsAsReachable;
339  if (!IncludeSometimesUnreachableEdges)
340  TreatAllSuccessorsAsReachable = false;
341 
342  for (CFGBlock::const_succ_iterator I = item->succ_begin(),
343  E = item->succ_end(); I != E; ++I) {
344  const CFGBlock *B = *I;
345  if (!B) do {
346  const CFGBlock *UB = I->getPossiblyUnreachableBlock();
347  if (!UB)
348  break;
349 
350  if (!TreatAllSuccessorsAsReachable.hasValue()) {
351  assert(PP);
352  TreatAllSuccessorsAsReachable =
354  }
355 
356  if (TreatAllSuccessorsAsReachable.getValue()) {
357  B = UB;
358  break;
359  }
360  }
361  while (false);
362 
363  if (B) {
364  unsigned blockID = B->getBlockID();
365  if (!Reachable[blockID]) {
366  Reachable.set(blockID);
367  WL.push_back(B);
368  ++count;
369  }
370  }
371  }
372  }
373  return count;
374 }
375 
376 static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start,
377  Preprocessor &PP,
378  llvm::BitVector &Reachable) {
379  return scanFromBlock(Start, Reachable, &PP, true);
380 }
381 
382 //===----------------------------------------------------------------------===//
383 // Dead Code Scanner.
384 //===----------------------------------------------------------------------===//
385 
386 namespace {
387  class DeadCodeScan {
388  llvm::BitVector Visited;
389  llvm::BitVector &Reachable;
391  Preprocessor &PP;
392  ASTContext &C;
393 
395  DeferredLocsTy;
396 
397  DeferredLocsTy DeferredLocs;
398 
399  public:
400  DeadCodeScan(llvm::BitVector &reachable, Preprocessor &PP, ASTContext &C)
401  : Visited(reachable.size()),
402  Reachable(reachable),
403  PP(PP), C(C) {}
404 
405  void enqueue(const CFGBlock *block);
406  unsigned scanBackwards(const CFGBlock *Start,
408 
409  bool isDeadCodeRoot(const CFGBlock *Block);
410 
411  const Stmt *findDeadCode(const CFGBlock *Block);
412 
413  void reportDeadCode(const CFGBlock *B,
414  const Stmt *S,
416  };
417 }
418 
419 void DeadCodeScan::enqueue(const CFGBlock *block) {
420  unsigned blockID = block->getBlockID();
421  if (Reachable[blockID] || Visited[blockID])
422  return;
423  Visited[blockID] = true;
424  WorkList.push_back(block);
425 }
426 
427 bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) {
428  bool isDeadRoot = true;
429 
430  for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
431  E = Block->pred_end(); I != E; ++I) {
432  if (const CFGBlock *PredBlock = *I) {
433  unsigned blockID = PredBlock->getBlockID();
434  if (Visited[blockID]) {
435  isDeadRoot = false;
436  continue;
437  }
438  if (!Reachable[blockID]) {
439  isDeadRoot = false;
440  Visited[blockID] = true;
441  WorkList.push_back(PredBlock);
442  continue;
443  }
444  }
445  }
446 
447  return isDeadRoot;
448 }
449 
450 static bool isValidDeadStmt(const Stmt *S) {
451  if (S->getBeginLoc().isInvalid())
452  return false;
453  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S))
454  return BO->getOpcode() != BO_Comma;
455  return true;
456 }
457 
458 const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) {
459  for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I)
460  if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
461  const Stmt *S = CS->getStmt();
462  if (isValidDeadStmt(S))
463  return S;
464  }
465 
466  CFGTerminator T = Block->getTerminator();
467  if (T.isStmtBranch()) {
468  const Stmt *S = T.getStmt();
469  if (S && isValidDeadStmt(S))
470  return S;
471  }
472 
473  return nullptr;
474 }
475 
476 static int SrcCmp(const std::pair<const CFGBlock *, const Stmt *> *p1,
477  const std::pair<const CFGBlock *, const Stmt *> *p2) {
478  if (p1->second->getBeginLoc() < p2->second->getBeginLoc())
479  return -1;
480  if (p2->second->getBeginLoc() < p1->second->getBeginLoc())
481  return 1;
482  return 0;
483 }
484 
485 unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start,
487 
488  unsigned count = 0;
489  enqueue(Start);
490 
491  while (!WorkList.empty()) {
492  const CFGBlock *Block = WorkList.pop_back_val();
493 
494  // It is possible that this block has been marked reachable after
495  // it was enqueued.
496  if (Reachable[Block->getBlockID()])
497  continue;
498 
499  // Look for any dead code within the block.
500  const Stmt *S = findDeadCode(Block);
501 
502  if (!S) {
503  // No dead code. Possibly an empty block. Look at dead predecessors.
504  for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
505  E = Block->pred_end(); I != E; ++I) {
506  if (const CFGBlock *predBlock = *I)
507  enqueue(predBlock);
508  }
509  continue;
510  }
511 
512  // Specially handle macro-expanded code.
513  if (S->getBeginLoc().isMacroID()) {
514  count += scanMaybeReachableFromBlock(Block, PP, Reachable);
515  continue;
516  }
517 
518  if (isDeadCodeRoot(Block)) {
519  reportDeadCode(Block, S, CB);
520  count += scanMaybeReachableFromBlock(Block, PP, Reachable);
521  }
522  else {
523  // Record this statement as the possibly best location in a
524  // strongly-connected component of dead code for emitting a
525  // warning.
526  DeferredLocs.push_back(std::make_pair(Block, S));
527  }
528  }
529 
530  // If we didn't find a dead root, then report the dead code with the
531  // earliest location.
532  if (!DeferredLocs.empty()) {
533  llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(), SrcCmp);
534  for (const auto &I : DeferredLocs) {
535  const CFGBlock *Block = I.first;
536  if (Reachable[Block->getBlockID()])
537  continue;
538  reportDeadCode(Block, I.second, CB);
539  count += scanMaybeReachableFromBlock(Block, PP, Reachable);
540  }
541  }
542 
543  return count;
544 }
545 
547  SourceRange &R1,
548  SourceRange &R2) {
549  R1 = R2 = SourceRange();
550 
551  if (const Expr *Ex = dyn_cast<Expr>(S))
552  S = Ex->IgnoreParenImpCasts();
553 
554  switch (S->getStmtClass()) {
555  case Expr::BinaryOperatorClass: {
556  const BinaryOperator *BO = cast<BinaryOperator>(S);
557  return BO->getOperatorLoc();
558  }
559  case Expr::UnaryOperatorClass: {
560  const UnaryOperator *UO = cast<UnaryOperator>(S);
561  R1 = UO->getSubExpr()->getSourceRange();
562  return UO->getOperatorLoc();
563  }
564  case Expr::CompoundAssignOperatorClass: {
565  const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
566  R1 = CAO->getLHS()->getSourceRange();
567  R2 = CAO->getRHS()->getSourceRange();
568  return CAO->getOperatorLoc();
569  }
570  case Expr::BinaryConditionalOperatorClass:
571  case Expr::ConditionalOperatorClass: {
572  const AbstractConditionalOperator *CO =
573  cast<AbstractConditionalOperator>(S);
574  return CO->getQuestionLoc();
575  }
576  case Expr::MemberExprClass: {
577  const MemberExpr *ME = cast<MemberExpr>(S);
578  R1 = ME->getSourceRange();
579  return ME->getMemberLoc();
580  }
581  case Expr::ArraySubscriptExprClass: {
582  const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
583  R1 = ASE->getLHS()->getSourceRange();
584  R2 = ASE->getRHS()->getSourceRange();
585  return ASE->getRBracketLoc();
586  }
587  case Expr::CStyleCastExprClass: {
588  const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
589  R1 = CSC->getSubExpr()->getSourceRange();
590  return CSC->getLParenLoc();
591  }
592  case Expr::CXXFunctionalCastExprClass: {
593  const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
594  R1 = CE->getSubExpr()->getSourceRange();
595  return CE->getBeginLoc();
596  }
597  case Stmt::CXXTryStmtClass: {
598  return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
599  }
600  case Expr::ObjCBridgedCastExprClass: {
601  const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
602  R1 = CSC->getSubExpr()->getSourceRange();
603  return CSC->getLParenLoc();
604  }
605  default: ;
606  }
607  R1 = S->getSourceRange();
608  return S->getBeginLoc();
609 }
610 
611 void DeadCodeScan::reportDeadCode(const CFGBlock *B,
612  const Stmt *S,
614  // Classify the unreachable code found, or suppress it in some cases.
616 
617  if (isa<BreakStmt>(S)) {
619  } else if (isTrivialDoWhile(B, S) || isBuiltinUnreachable(S) ||
620  isBuiltinAssumeFalse(B, S, C)) {
621  return;
622  }
623  else if (isDeadReturn(B, S)) {
625  }
626 
627  SourceRange SilenceableCondVal;
628 
629  if (UK == reachable_code::UK_Other) {
630  // Check if the dead code is part of the "loop target" of
631  // a for/for-range loop. This is the block that contains
632  // the increment code.
633  if (const Stmt *LoopTarget = B->getLoopTarget()) {
634  SourceLocation Loc = LoopTarget->getBeginLoc();
635  SourceRange R1(Loc, Loc), R2;
636 
637  if (const ForStmt *FS = dyn_cast<ForStmt>(LoopTarget)) {
638  const Expr *Inc = FS->getInc();
639  Loc = Inc->getBeginLoc();
640  R2 = Inc->getSourceRange();
641  }
642 
644  Loc, SourceRange(), SourceRange(Loc, Loc), R2);
645  return;
646  }
647 
648  // Check if the dead block has a predecessor whose branch has
649  // a configuration value that *could* be modified to
650  // silence the warning.
652  if (PI != B->pred_end()) {
653  if (const CFGBlock *PredBlock = PI->getPossiblyUnreachableBlock()) {
654  const Stmt *TermCond =
655  PredBlock->getTerminatorCondition(/* strip parens */ false);
656  isConfigurationValue(TermCond, PP, &SilenceableCondVal);
657  }
658  }
659  }
660 
661  SourceRange R1, R2;
662  SourceLocation Loc = GetUnreachableLoc(S, R1, R2);
663  CB.HandleUnreachable(UK, Loc, SilenceableCondVal, R1, R2);
664 }
665 
666 //===----------------------------------------------------------------------===//
667 // Reachability APIs.
668 //===----------------------------------------------------------------------===//
669 
670 namespace clang { namespace reachable_code {
671 
672 void Callback::anchor() { }
673 
674 unsigned ScanReachableFromBlock(const CFGBlock *Start,
675  llvm::BitVector &Reachable) {
676  return scanFromBlock(Start, Reachable, /* SourceManager* */ nullptr, false);
677 }
678 
680  Callback &CB) {
681 
682  CFG *cfg = AC.getCFG();
683  if (!cfg)
684  return;
685 
686  // Scan for reachable blocks from the entrance of the CFG.
687  // If there are no unreachable blocks, we're done.
688  llvm::BitVector reachable(cfg->getNumBlockIDs());
689  unsigned numReachable =
690  scanMaybeReachableFromBlock(&cfg->getEntry(), PP, reachable);
691  if (numReachable == cfg->getNumBlockIDs())
692  return;
693 
694  // If there aren't explicit EH edges, we should include the 'try' dispatch
695  // blocks as roots.
696  if (!AC.getCFGBuildOptions().AddEHEdges) {
697  for (const CFGBlock *B : cfg->try_blocks())
698  numReachable += scanMaybeReachableFromBlock(B, PP, reachable);
699  if (numReachable == cfg->getNumBlockIDs())
700  return;
701  }
702 
703  // There are some unreachable blocks. We need to find the root blocks that
704  // contain code that should be considered unreachable.
705  for (const CFGBlock *block : *cfg) {
706  // A block may have been marked reachable during this loop.
707  if (reachable[block->getBlockID()])
708  continue;
709 
710  DeadCodeScan DS(reachable, PP, AC.getASTContext());
711  numReachable += DS.scanBackwards(block, CB);
712 
713  if (numReachable == cfg->getNumBlockIDs())
714  return;
715  }
716 }
717 
718 }} // end namespace clang::reachable_code
clang::CFGTerminator::isStmtBranch
bool isStmtBranch() const
Definition: CFG.h:539
Builtins.h
clang::AnalysisDeclContext::getASTContext
ASTContext & getASTContext() const
Definition: AnalysisDeclContext.h:104
clang::reachable_code::FindUnreachableCode
void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, Callback &CB)
Definition: ReachableCode.cpp:679
clang::CFGBlock::getLoopTarget
const Stmt * getLoopTarget() const
Definition: CFG.h:1067
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:212
isExpandedFromConfigurationMacro
static bool isExpandedFromConfigurationMacro(const Stmt *S, Preprocessor &PP, bool IgnoreYES_NO=false)
Returns true if the statement is expanded from a configuration macro.
Definition: ReachableCode.cpp:149
clang::CFGBlock::empty
bool empty() const
Definition: CFG.h:918
shouldTreatSuccessorsAsReachable
static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B, Preprocessor &PP)
Returns true if we should always explore all successors of a block.
Definition: ReachableCode.cpp:295
clang::BinaryOperator::isComparisonOp
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3902
clang::CXXFunctionalCastExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.cpp:868
clang::CFG::getNumBlockIDs
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Definition: CFG.h:1411
clang::CFGBlock::succ_begin
succ_iterator succ_begin()
Definition: CFG.h:955
AnalysisDeclContext.h
llvm::SmallVector
Definition: LLVM.h:38
clang::CFG::BuildOptions::AddEHEdges
bool AddEHEdges
Definition: CFG.h:1240
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::AbstractConditionalOperator
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4103
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3524
clang::CFGBlock::getBlockID
unsigned getBlockID() const
Definition: CFG.h:1074
clang::reachable_code::UK_Loop_Increment
@ UK_Loop_Increment
Definition: ReachableCode.h:43
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:324
clang::ObjCBridgedCastExpr
An Objective-C "bridged" cast expression, which casts between Objective-C pointers and C pointers,...
Definition: ExprObjC.h:1625
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:54
clang::AnalysisDeclContext
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Definition: AnalysisDeclContext.h:72
llvm::Optional
Definition: LLVM.h:40
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2157
SourceManager.h
clang::CFGBlock::const_succ_iterator
AdjacentBlocks::const_iterator const_succ_iterator
Definition: CFG.h:931
clang::CFG
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition: CFG.h:1225
clang::reachable_code::UnreachableKind
UnreachableKind
Classifications of unreachable code.
Definition: ReachableCode.h:40
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
clang::CStyleCastExpr::getLParenLoc
SourceLocation getLParenLoc() const
Definition: Expr.h:3766
clang::Preprocessor::getLangOpts
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:960
Preprocessor.h
clang::Preprocessor::getImmediateMacroName
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
Definition: Preprocessor.h:1835
clang::CFGTerminator::getStmt
Stmt * getStmt()
Definition: CFG.h:535
clang::CFGBlock
Represents a single basic block in a source-level CFG.
Definition: CFG.h:576
scanFromBlock
static unsigned scanFromBlock(const CFGBlock *Start, llvm::BitVector &Reachable, Preprocessor *PP, bool IncludeSometimesUnreachableEdges)
Definition: ReachableCode.cpp:310
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3803
isValidDeadStmt
static bool isValidDeadStmt(const Stmt *S)
Definition: ReachableCode.cpp:450
SrcCmp
static int SrcCmp(const std::pair< const CFGBlock *, const Stmt * > *p1, const std::pair< const CFGBlock *, const Stmt * > *p2)
Definition: ReachableCode.cpp:476
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:212
ReachableCode.h
clang::ForStmt
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2534
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1289
clang::CFGBlock::const_iterator
ElementList::const_iterator const_iterator
Definition: CFG.h:866
Expr.h
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:876
clang::MemberExpr::getMemberLoc
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3351
clang::EnumConstantDecl
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3050
ExprObjC.h
ExprCXX.h
clang::CFGBlock::getTerminatorCondition
Stmt * getTerminatorCondition(bool StripParens=true)
Definition: CFG.cpp:6077
clang::CFGTerminator
Represents CFGBlock terminator statement.
Definition: CFG.h:503
clang::ArraySubscriptExpr::getLHS
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2668
clang::ArraySubscriptExpr::getRHS
Expr * getRHS()
Definition: Expr.h:2672
isBuiltinUnreachable
static bool isBuiltinUnreachable(const Stmt *S)
Definition: ReachableCode.cpp:61
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:964
clang::Expr::IgnoreParenCasts
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2924
clang::CStyleCastExpr
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3731
clang::ParentMap
Definition: ParentMap.h:20
clang::UnaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2208
clang::CFGBlock::back
CFGElement back() const
Definition: CFG.h:873
clang::CFGStmt
Definition: CFG.h:132
clang::AnalysisDeclContext::getCFGBuildOptions
CFG::BuildOptions & getCFGBuildOptions()
Definition: AnalysisDeclContext.h:110
isTrivialDoWhile
static bool isTrivialDoWhile(const CFGBlock *B, const Stmt *S)
Definition: ReachableCode.cpp:49
clang::CFGElement::getAs
Optional< T > getAs() const
Convert to the specified CFGElement type, returning None if this CFGElement is not of the desired typ...
Definition: CFG.h:109
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:676
clang::CFGBlock::succ_end
succ_iterator succ_end()
Definition: CFG.h:956
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3852
clang::ParenExpr
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2106
clang::reachable_code::Callback
Definition: ReachableCode.h:47
clang::CFGBlock::pred_begin
pred_iterator pred_begin()
Definition: CFG.h:937
clang::CXXFunctionalCastExpr
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition: ExprCXX.h:1726
clang::ArraySubscriptExpr
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2639
clang::DoStmt
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2478
clang::BinaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
Definition: Expr.h:3844
clang::CFG::getEntry
CFGBlock & getEntry()
Definition: CFG.h:1331
clang::ParentMap::getParent
Stmt * getParent(Stmt *) const
Definition: ParentMap.cpp:134
clang::CompoundAssignOperator
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4050
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:105
isTrivialExpression
static bool isTrivialExpression(const Expr *Ex)
Definition: ReachableCode.cpp:41
clang::CFGElement
Represents a top-level expression in a basic block.
Definition: CFG.h:55
clang::reachable_code::UK_Return
@ UK_Return
Definition: ReachableCode.h:41
isBuiltinAssumeFalse
static bool isBuiltinAssumeFalse(const CFGBlock *B, const Stmt *S, ASTContext &C)
Definition: ReachableCode.cpp:69
clang::BinaryOperator::isLogicalOp
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3935
ParentMap.h
clang::reachable_code::Callback::HandleUnreachable
virtual void HandleUnreachable(UnreachableKind UK, SourceLocation L, SourceRange ConditionVal, SourceRange R1, SourceRange R2)=0
clang::ArraySubscriptExpr::getRBracketLoc
SourceLocation getRBracketLoc() const
Definition: Expr.h:2687
isEnumConstant
static bool isEnumConstant(const Expr *Ex)
Definition: ReachableCode.cpp:34
clang::UnaryOperator::getSubExpr
Expr * getSubExpr() const
Definition: Expr.h:2204
clang
Definition: CalledOnceCheck.h:17
clang::reachable_code::UK_Other
@ UK_Other
Definition: ReachableCode.h:44
CFG.h
clang::DeclaratorContext::Block
@ Block
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:69
clang::ComparisonCategoryType::Last
@ Last
clang::UnaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:2199
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3854
clang::CFG::try_blocks
try_block_range try_blocks() const
Definition: CFG.h:1350
clang::CFGBlock::getTerminatorStmt
Stmt * getTerminatorStmt()
Definition: CFG.h:1050
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:336
clang::reachable_code::UK_Break
@ UK_Break
Definition: ReachableCode.h:42
scanMaybeReachableFromBlock
static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start, Preprocessor &PP, llvm::BitVector &Reachable)
Definition: ReachableCode.cpp:376
clang::MemberExpr
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3162
isConfigurationValue
static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP)
Definition: ReachableCode.cpp:273
clang::AbstractConditionalOperator::getQuestionLoc
SourceLocation getQuestionLoc() const
Definition: Expr.h:4130
clang::AnalysisDeclContext::getCFG
CFG * getCFG()
Definition: AnalysisDeclContext.cpp:213
clang::Expr::IgnoreCasts
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:2903
clang::Expr
This represents one expression.
Definition: Expr.h:109
isDeadReturn
static bool isDeadReturn(const CFGBlock *B, const Stmt *S)
Definition: ReachableCode.cpp:84
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:130
SM
#define SM(sm)
Definition: Cuda.cpp:78
clang::DeclRefExpr
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1217
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1856
clang::reachable_code::ScanReachableFromBlock
unsigned ScanReachableFromBlock(const CFGBlock *Start, llvm::BitVector &Reachable)
ScanReachableFromBlock - Mark all blocks reachable from Start.
Definition: ReachableCode.cpp:674
getTopMostMacro
static SourceLocation getTopMostMacro(SourceLocation Loc, SourceManager &SM)
Definition: ReachableCode.cpp:138
StmtCXX.h
GetUnreachableLoc
static SourceLocation GetUnreachableLoc(const Stmt *S, SourceRange &R1, SourceRange &R2)
Definition: ReachableCode.cpp:546
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2760
clang::CFGBlock::pred_end
pred_iterator pred_end()
Definition: CFG.h:938
clang::CFGBlock::const_pred_iterator
AdjacentBlocks::const_iterator const_pred_iterator
Definition: CFG.h:924
clang::ObjCBridgedCastExpr::getLParenLoc
SourceLocation getLParenLoc() const
Definition: ExprObjC.h:1649