clang API Documentation

ReachableCode.cpp
Go to the documentation of this file.
00001 //=- ReachableCodePathInsensitive.cpp ---------------------------*- C++ --*-==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a flow-sensitive, path-insensitive analysis of
00011 // determining reachable blocks within a CFG.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Analysis/Analyses/ReachableCode.h"
00016 #include "clang/Lex/Preprocessor.h"
00017 #include "clang/AST/Expr.h"
00018 #include "clang/AST/ExprCXX.h"
00019 #include "clang/AST/ExprObjC.h"
00020 #include "clang/AST/StmtCXX.h"
00021 #include "clang/AST/ParentMap.h"
00022 #include "clang/Analysis/AnalysisContext.h"
00023 #include "clang/Analysis/CFG.h"
00024 #include "clang/Basic/SourceManager.h"
00025 #include "llvm/ADT/BitVector.h"
00026 #include "llvm/ADT/SmallVector.h"
00027 
00028 using namespace clang;
00029 
00030 //===----------------------------------------------------------------------===//
00031 // Core Reachability Analysis routines.
00032 //===----------------------------------------------------------------------===//
00033 
00034 static bool isEnumConstant(const Expr *Ex) {
00035   const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex);
00036   if (!DR)
00037     return false;
00038   return isa<EnumConstantDecl>(DR->getDecl());
00039 }
00040 
00041 static bool isTrivialExpression(const Expr *Ex) {
00042   Ex = Ex->IgnoreParenCasts();
00043   return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
00044          isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
00045          isa<CharacterLiteral>(Ex) ||
00046          isEnumConstant(Ex);
00047 }
00048 
00049 static bool isTrivialDoWhile(const CFGBlock *B, const Stmt *S) {
00050   // Check if the block ends with a do...while() and see if 'S' is the
00051   // condition.
00052   if (const Stmt *Term = B->getTerminator()) {
00053     if (const DoStmt *DS = dyn_cast<DoStmt>(Term)) {
00054       const Expr *Cond = DS->getCond()->IgnoreParenCasts();
00055       return Cond == S && isTrivialExpression(Cond);
00056     }
00057   }
00058   return false;
00059 }
00060 
00061 static bool isDeadReturn(const CFGBlock *B, const Stmt *S) {
00062   // Look to see if the current control flow ends with a 'return', and see if
00063   // 'S' is a substatement. The 'return' may not be the last element in the
00064   // block, or may be in a subsequent block because of destructors.
00065   const CFGBlock *Current = B;
00066   while (true) {
00067     for (CFGBlock::const_reverse_iterator I = Current->rbegin(),
00068                                           E = Current->rend();
00069          I != E; ++I) {
00070       if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
00071         if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
00072           if (RS == S)
00073             return true;
00074           if (const Expr *RE = RS->getRetValue()) {
00075             RE = RE->IgnoreParenCasts();
00076             if (RE == S)
00077               return true;
00078             ParentMap PM(const_cast<Expr *>(RE));
00079             // If 'S' is in the ParentMap, it is a subexpression of
00080             // the return statement.
00081             return PM.getParent(S);
00082           }
00083         }
00084         break;
00085       }
00086     }
00087     // Note also that we are restricting the search for the return statement
00088     // to stop at control-flow; only part of a return statement may be dead,
00089     // without the whole return statement being dead.
00090     if (Current->getTerminator().isTemporaryDtorsBranch()) {
00091       // Temporary destructors have a predictable control flow, thus we want to
00092       // look into the next block for the return statement.
00093       // We look into the false branch, as we know the true branch only contains
00094       // the call to the destructor.
00095       assert(Current->succ_size() == 2);
00096       Current = *(Current->succ_begin() + 1);
00097     } else if (!Current->getTerminator() && Current->succ_size() == 1) {
00098       // If there is only one successor, we're not dealing with outgoing control
00099       // flow. Thus, look into the next block.
00100       Current = *Current->succ_begin();
00101       if (Current->pred_size() > 1) {
00102         // If there is more than one predecessor, we're dealing with incoming
00103         // control flow - if the return statement is in that block, it might
00104         // well be reachable via a different control flow, thus it's not dead.
00105         return false;
00106       }
00107     } else {
00108       // We hit control flow or a dead end. Stop searching.
00109       return false;
00110     }
00111   }
00112   llvm_unreachable("Broke out of infinite loop.");
00113 }
00114 
00115 static SourceLocation getTopMostMacro(SourceLocation Loc, SourceManager &SM) {
00116   assert(Loc.isMacroID());
00117   SourceLocation Last;
00118   while (Loc.isMacroID()) {
00119     Last = Loc;
00120     Loc = SM.getImmediateMacroCallerLoc(Loc);
00121   }
00122   return Last;
00123 }
00124 
00125 /// Returns true if the statement is expanded from a configuration macro.
00126 static bool isExpandedFromConfigurationMacro(const Stmt *S,
00127                                              Preprocessor &PP,
00128                                              bool IgnoreYES_NO = false) {
00129   // FIXME: This is not very precise.  Here we just check to see if the
00130   // value comes from a macro, but we can do much better.  This is likely
00131   // to be over conservative.  This logic is factored into a separate function
00132   // so that we can refine it later.
00133   SourceLocation L = S->getLocStart();
00134   if (L.isMacroID()) {
00135     if (IgnoreYES_NO) {
00136       // The Objective-C constant 'YES' and 'NO'
00137       // are defined as macros.  Do not treat them
00138       // as configuration values.
00139       SourceManager &SM = PP.getSourceManager();
00140       SourceLocation TopL = getTopMostMacro(L, SM);
00141       StringRef MacroName = PP.getImmediateMacroName(TopL);
00142       if (MacroName == "YES" || MacroName == "NO")
00143         return false;
00144     }
00145     return true;
00146   }
00147   return false;
00148 }
00149 
00150 static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP);
00151 
00152 /// Returns true if the statement represents a configuration value.
00153 ///
00154 /// A configuration value is something usually determined at compile-time
00155 /// to conditionally always execute some branch.  Such guards are for
00156 /// "sometimes unreachable" code.  Such code is usually not interesting
00157 /// to report as unreachable, and may mask truly unreachable code within
00158 /// those blocks.
00159 static bool isConfigurationValue(const Stmt *S,
00160                                  Preprocessor &PP,
00161                                  SourceRange *SilenceableCondVal = nullptr,
00162                                  bool IncludeIntegers = true,
00163                                  bool WrappedInParens = false) {
00164   if (!S)
00165     return false;
00166 
00167   if (const Expr *Ex = dyn_cast<Expr>(S))
00168     S = Ex->IgnoreCasts();
00169 
00170   // Special case looking for the sigil '()' around an integer literal.
00171   if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
00172     if (!PE->getLocStart().isMacroID())
00173       return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal, 
00174                                   IncludeIntegers, true);
00175 
00176   if (const Expr *Ex = dyn_cast<Expr>(S))
00177     S = Ex->IgnoreCasts();
00178 
00179   bool IgnoreYES_NO = false;
00180 
00181   switch (S->getStmtClass()) {
00182     case Stmt::CallExprClass: {
00183       const FunctionDecl *Callee =
00184         dyn_cast_or_null<FunctionDecl>(cast<CallExpr>(S)->getCalleeDecl());
00185       return Callee ? Callee->isConstexpr() : false;
00186     }
00187     case Stmt::DeclRefExprClass:
00188       return isConfigurationValue(cast<DeclRefExpr>(S)->getDecl(), PP);
00189     case Stmt::ObjCBoolLiteralExprClass:
00190       IgnoreYES_NO = true;
00191       // Fallthrough.
00192     case Stmt::CXXBoolLiteralExprClass:
00193     case Stmt::IntegerLiteralClass: {
00194       const Expr *E = cast<Expr>(S);
00195       if (IncludeIntegers) {
00196         if (SilenceableCondVal && !SilenceableCondVal->getBegin().isValid())
00197           *SilenceableCondVal = E->getSourceRange();
00198         return WrappedInParens || isExpandedFromConfigurationMacro(E, PP, IgnoreYES_NO);
00199       }
00200       return false;
00201     }
00202     case Stmt::MemberExprClass:
00203       return isConfigurationValue(cast<MemberExpr>(S)->getMemberDecl(), PP);
00204     case Stmt::UnaryExprOrTypeTraitExprClass:
00205       return true;
00206     case Stmt::BinaryOperatorClass: {
00207       const BinaryOperator *B = cast<BinaryOperator>(S);
00208       // Only include raw integers (not enums) as configuration
00209       // values if they are used in a logical or comparison operator
00210       // (not arithmetic).
00211       IncludeIntegers &= (B->isLogicalOp() || B->isComparisonOp());
00212       return isConfigurationValue(B->getLHS(), PP, SilenceableCondVal,
00213                                   IncludeIntegers) ||
00214              isConfigurationValue(B->getRHS(), PP, SilenceableCondVal,
00215                                   IncludeIntegers);
00216     }
00217     case Stmt::UnaryOperatorClass: {
00218       const UnaryOperator *UO = cast<UnaryOperator>(S);
00219       if (SilenceableCondVal) 
00220         *SilenceableCondVal = UO->getSourceRange();      
00221       return UO->getOpcode() == UO_LNot &&
00222              isConfigurationValue(UO->getSubExpr(), PP, SilenceableCondVal,
00223                                   IncludeIntegers, WrappedInParens);
00224     }
00225     default:
00226       return false;
00227   }
00228 }
00229 
00230 static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP) {
00231   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D))
00232     return isConfigurationValue(ED->getInitExpr(), PP);
00233   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00234     // As a heuristic, treat globals as configuration values.  Note
00235     // that we only will get here if Sema evaluated this
00236     // condition to a constant expression, which means the global
00237     // had to be declared in a way to be a truly constant value.
00238     // We could generalize this to local variables, but it isn't
00239     // clear if those truly represent configuration values that
00240     // gate unreachable code.
00241     if (!VD->hasLocalStorage())
00242       return true;
00243 
00244     // As a heuristic, locals that have been marked 'const' explicitly
00245     // can be treated as configuration values as well.
00246     return VD->getType().isLocalConstQualified();
00247   }
00248   return false;
00249 }
00250 
00251 /// Returns true if we should always explore all successors of a block.
00252 static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B,
00253                                              Preprocessor &PP) {
00254   if (const Stmt *Term = B->getTerminator()) {
00255     if (isa<SwitchStmt>(Term))
00256       return true;
00257     // Specially handle '||' and '&&'.
00258     if (isa<BinaryOperator>(Term)) {
00259       return isConfigurationValue(Term, PP);
00260     }
00261   }
00262 
00263   const Stmt *Cond = B->getTerminatorCondition(/* stripParens */ false);
00264   return isConfigurationValue(Cond, PP);
00265 }
00266 
00267 static unsigned scanFromBlock(const CFGBlock *Start,
00268                               llvm::BitVector &Reachable,
00269                               Preprocessor *PP,
00270                               bool IncludeSometimesUnreachableEdges) {
00271   unsigned count = 0;
00272   
00273   // Prep work queue
00274   SmallVector<const CFGBlock*, 32> WL;
00275   
00276   // The entry block may have already been marked reachable
00277   // by the caller.
00278   if (!Reachable[Start->getBlockID()]) {
00279     ++count;
00280     Reachable[Start->getBlockID()] = true;
00281   }
00282   
00283   WL.push_back(Start);
00284   
00285   // Find the reachable blocks from 'Start'.
00286   while (!WL.empty()) {
00287     const CFGBlock *item = WL.pop_back_val();
00288 
00289     // There are cases where we want to treat all successors as reachable.
00290     // The idea is that some "sometimes unreachable" code is not interesting,
00291     // and that we should forge ahead and explore those branches anyway.
00292     // This allows us to potentially uncover some "always unreachable" code
00293     // within the "sometimes unreachable" code.
00294     // Look at the successors and mark then reachable.
00295     Optional<bool> TreatAllSuccessorsAsReachable;
00296     if (!IncludeSometimesUnreachableEdges)
00297       TreatAllSuccessorsAsReachable = false;
00298 
00299     for (CFGBlock::const_succ_iterator I = item->succ_begin(), 
00300          E = item->succ_end(); I != E; ++I) {
00301       const CFGBlock *B = *I;
00302       if (!B) do {
00303         const CFGBlock *UB = I->getPossiblyUnreachableBlock();
00304         if (!UB)
00305           break;
00306 
00307         if (!TreatAllSuccessorsAsReachable.hasValue()) {
00308           assert(PP);
00309           TreatAllSuccessorsAsReachable =
00310             shouldTreatSuccessorsAsReachable(item, *PP);
00311         }
00312 
00313         if (TreatAllSuccessorsAsReachable.getValue()) {
00314           B = UB;
00315           break;
00316         }
00317       }
00318       while (false);
00319 
00320       if (B) {
00321         unsigned blockID = B->getBlockID();
00322         if (!Reachable[blockID]) {
00323           Reachable.set(blockID);
00324           WL.push_back(B);
00325           ++count;
00326         }
00327       }
00328     }
00329   }
00330   return count;
00331 }
00332 
00333 static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start,
00334                                             Preprocessor &PP,
00335                                             llvm::BitVector &Reachable) {
00336   return scanFromBlock(Start, Reachable, &PP, true);
00337 }
00338 
00339 //===----------------------------------------------------------------------===//
00340 // Dead Code Scanner.
00341 //===----------------------------------------------------------------------===//
00342 
00343 namespace {
00344   class DeadCodeScan {
00345     llvm::BitVector Visited;
00346     llvm::BitVector &Reachable;
00347     SmallVector<const CFGBlock *, 10> WorkList;
00348     Preprocessor &PP;
00349 
00350     typedef SmallVector<std::pair<const CFGBlock *, const Stmt *>, 12>
00351     DeferredLocsTy;
00352 
00353     DeferredLocsTy DeferredLocs;
00354 
00355   public:
00356     DeadCodeScan(llvm::BitVector &reachable, Preprocessor &PP)
00357     : Visited(reachable.size()),
00358       Reachable(reachable),
00359       PP(PP) {}
00360 
00361     void enqueue(const CFGBlock *block);
00362     unsigned scanBackwards(const CFGBlock *Start,
00363     clang::reachable_code::Callback &CB);
00364 
00365     bool isDeadCodeRoot(const CFGBlock *Block);
00366 
00367     const Stmt *findDeadCode(const CFGBlock *Block);
00368 
00369     void reportDeadCode(const CFGBlock *B,
00370                         const Stmt *S,
00371                         clang::reachable_code::Callback &CB);
00372   };
00373 }
00374 
00375 void DeadCodeScan::enqueue(const CFGBlock *block) {
00376   unsigned blockID = block->getBlockID();
00377   if (Reachable[blockID] || Visited[blockID])
00378     return;
00379   Visited[blockID] = true;
00380   WorkList.push_back(block);
00381 }
00382 
00383 bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) {
00384   bool isDeadRoot = true;
00385 
00386   for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
00387        E = Block->pred_end(); I != E; ++I) {
00388     if (const CFGBlock *PredBlock = *I) {
00389       unsigned blockID = PredBlock->getBlockID();
00390       if (Visited[blockID]) {
00391         isDeadRoot = false;
00392         continue;
00393       }
00394       if (!Reachable[blockID]) {
00395         isDeadRoot = false;
00396         Visited[blockID] = true;
00397         WorkList.push_back(PredBlock);
00398         continue;
00399       }
00400     }
00401   }
00402 
00403   return isDeadRoot;
00404 }
00405 
00406 static bool isValidDeadStmt(const Stmt *S) {
00407   if (S->getLocStart().isInvalid())
00408     return false;
00409   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S))
00410     return BO->getOpcode() != BO_Comma;
00411   return true;
00412 }
00413 
00414 const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) {
00415   for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I)
00416     if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
00417       const Stmt *S = CS->getStmt();
00418       if (isValidDeadStmt(S))
00419         return S;
00420     }
00421 
00422   if (CFGTerminator T = Block->getTerminator()) {
00423     if (!T.isTemporaryDtorsBranch()) {
00424       const Stmt *S = T.getStmt();
00425       if (isValidDeadStmt(S))
00426         return S;
00427     }
00428   }
00429 
00430   return nullptr;
00431 }
00432 
00433 static int SrcCmp(const std::pair<const CFGBlock *, const Stmt *> *p1,
00434                   const std::pair<const CFGBlock *, const Stmt *> *p2) {
00435   if (p1->second->getLocStart() < p2->second->getLocStart())
00436     return -1;
00437   if (p2->second->getLocStart() < p1->second->getLocStart())
00438     return 1;
00439   return 0;
00440 }
00441 
00442 unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start,
00443                                      clang::reachable_code::Callback &CB) {
00444 
00445   unsigned count = 0;
00446   enqueue(Start);
00447 
00448   while (!WorkList.empty()) {
00449     const CFGBlock *Block = WorkList.pop_back_val();
00450 
00451     // It is possible that this block has been marked reachable after
00452     // it was enqueued.
00453     if (Reachable[Block->getBlockID()])
00454       continue;
00455 
00456     // Look for any dead code within the block.
00457     const Stmt *S = findDeadCode(Block);
00458 
00459     if (!S) {
00460       // No dead code.  Possibly an empty block.  Look at dead predecessors.
00461       for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
00462            E = Block->pred_end(); I != E; ++I) {
00463         if (const CFGBlock *predBlock = *I)
00464           enqueue(predBlock);
00465       }
00466       continue;
00467     }
00468 
00469     // Specially handle macro-expanded code.
00470     if (S->getLocStart().isMacroID()) {
00471       count += scanMaybeReachableFromBlock(Block, PP, Reachable);
00472       continue;
00473     }
00474 
00475     if (isDeadCodeRoot(Block)) {
00476       reportDeadCode(Block, S, CB);
00477       count += scanMaybeReachableFromBlock(Block, PP, Reachable);
00478     }
00479     else {
00480       // Record this statement as the possibly best location in a
00481       // strongly-connected component of dead code for emitting a
00482       // warning.
00483       DeferredLocs.push_back(std::make_pair(Block, S));
00484     }
00485   }
00486 
00487   // If we didn't find a dead root, then report the dead code with the
00488   // earliest location.
00489   if (!DeferredLocs.empty()) {
00490     llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(), SrcCmp);
00491     for (DeferredLocsTy::iterator I = DeferredLocs.begin(),
00492          E = DeferredLocs.end(); I != E; ++I) {
00493       const CFGBlock *Block = I->first;
00494       if (Reachable[Block->getBlockID()])
00495         continue;
00496       reportDeadCode(Block, I->second, CB);
00497       count += scanMaybeReachableFromBlock(Block, PP, Reachable);
00498     }
00499   }
00500 
00501   return count;
00502 }
00503 
00504 static SourceLocation GetUnreachableLoc(const Stmt *S,
00505                                         SourceRange &R1,
00506                                         SourceRange &R2) {
00507   R1 = R2 = SourceRange();
00508 
00509   if (const Expr *Ex = dyn_cast<Expr>(S))
00510     S = Ex->IgnoreParenImpCasts();
00511 
00512   switch (S->getStmtClass()) {
00513     case Expr::BinaryOperatorClass: {
00514       const BinaryOperator *BO = cast<BinaryOperator>(S);
00515       return BO->getOperatorLoc();
00516     }
00517     case Expr::UnaryOperatorClass: {
00518       const UnaryOperator *UO = cast<UnaryOperator>(S);
00519       R1 = UO->getSubExpr()->getSourceRange();
00520       return UO->getOperatorLoc();
00521     }
00522     case Expr::CompoundAssignOperatorClass: {
00523       const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
00524       R1 = CAO->getLHS()->getSourceRange();
00525       R2 = CAO->getRHS()->getSourceRange();
00526       return CAO->getOperatorLoc();
00527     }
00528     case Expr::BinaryConditionalOperatorClass:
00529     case Expr::ConditionalOperatorClass: {
00530       const AbstractConditionalOperator *CO =
00531       cast<AbstractConditionalOperator>(S);
00532       return CO->getQuestionLoc();
00533     }
00534     case Expr::MemberExprClass: {
00535       const MemberExpr *ME = cast<MemberExpr>(S);
00536       R1 = ME->getSourceRange();
00537       return ME->getMemberLoc();
00538     }
00539     case Expr::ArraySubscriptExprClass: {
00540       const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
00541       R1 = ASE->getLHS()->getSourceRange();
00542       R2 = ASE->getRHS()->getSourceRange();
00543       return ASE->getRBracketLoc();
00544     }
00545     case Expr::CStyleCastExprClass: {
00546       const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
00547       R1 = CSC->getSubExpr()->getSourceRange();
00548       return CSC->getLParenLoc();
00549     }
00550     case Expr::CXXFunctionalCastExprClass: {
00551       const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
00552       R1 = CE->getSubExpr()->getSourceRange();
00553       return CE->getLocStart();
00554     }
00555     case Stmt::CXXTryStmtClass: {
00556       return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
00557     }
00558     case Expr::ObjCBridgedCastExprClass: {
00559       const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
00560       R1 = CSC->getSubExpr()->getSourceRange();
00561       return CSC->getLParenLoc();
00562     }
00563     default: ;
00564   }
00565   R1 = S->getSourceRange();
00566   return S->getLocStart();
00567 }
00568 
00569 void DeadCodeScan::reportDeadCode(const CFGBlock *B,
00570                                   const Stmt *S,
00571                                   clang::reachable_code::Callback &CB) {
00572   // Classify the unreachable code found, or suppress it in some cases.
00573   reachable_code::UnreachableKind UK = reachable_code::UK_Other;
00574 
00575   if (isa<BreakStmt>(S)) {
00576     UK = reachable_code::UK_Break;
00577   }
00578   else if (isTrivialDoWhile(B, S)) {
00579     return;
00580   }
00581   else if (isDeadReturn(B, S)) {
00582     UK = reachable_code::UK_Return;
00583   }
00584 
00585   SourceRange SilenceableCondVal;
00586 
00587   if (UK == reachable_code::UK_Other) {
00588     // Check if the dead code is part of the "loop target" of
00589     // a for/for-range loop.  This is the block that contains
00590     // the increment code.
00591     if (const Stmt *LoopTarget = B->getLoopTarget()) {
00592       SourceLocation Loc = LoopTarget->getLocStart();
00593       SourceRange R1(Loc, Loc), R2;
00594 
00595       if (const ForStmt *FS = dyn_cast<ForStmt>(LoopTarget)) {
00596         const Expr *Inc = FS->getInc();
00597         Loc = Inc->getLocStart();
00598         R2 = Inc->getSourceRange();
00599       }
00600 
00601       CB.HandleUnreachable(reachable_code::UK_Loop_Increment,
00602                            Loc, SourceRange(), SourceRange(Loc, Loc), R2);
00603       return;
00604     }
00605     
00606     // Check if the dead block has a predecessor whose branch has
00607     // a configuration value that *could* be modified to
00608     // silence the warning.
00609     CFGBlock::const_pred_iterator PI = B->pred_begin();
00610     if (PI != B->pred_end()) {
00611       if (const CFGBlock *PredBlock = PI->getPossiblyUnreachableBlock()) {
00612         const Stmt *TermCond =
00613             PredBlock->getTerminatorCondition(/* strip parens */ false);
00614         isConfigurationValue(TermCond, PP, &SilenceableCondVal);
00615       }
00616     }
00617   }
00618 
00619   SourceRange R1, R2;
00620   SourceLocation Loc = GetUnreachableLoc(S, R1, R2);
00621   CB.HandleUnreachable(UK, Loc, SilenceableCondVal, R1, R2);
00622 }
00623 
00624 //===----------------------------------------------------------------------===//
00625 // Reachability APIs.
00626 //===----------------------------------------------------------------------===//
00627 
00628 namespace clang { namespace reachable_code {
00629 
00630 void Callback::anchor() { }
00631 
00632 unsigned ScanReachableFromBlock(const CFGBlock *Start,
00633                                 llvm::BitVector &Reachable) {
00634   return scanFromBlock(Start, Reachable, /* SourceManager* */ nullptr, false);
00635 }
00636 
00637 void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP,
00638                          Callback &CB) {
00639 
00640   CFG *cfg = AC.getCFG();
00641   if (!cfg)
00642     return;
00643 
00644   // Scan for reachable blocks from the entrance of the CFG.
00645   // If there are no unreachable blocks, we're done.
00646   llvm::BitVector reachable(cfg->getNumBlockIDs());
00647   unsigned numReachable =
00648     scanMaybeReachableFromBlock(&cfg->getEntry(), PP, reachable);
00649   if (numReachable == cfg->getNumBlockIDs())
00650     return;
00651   
00652   // If there aren't explicit EH edges, we should include the 'try' dispatch
00653   // blocks as roots.
00654   if (!AC.getCFGBuildOptions().AddEHEdges) {
00655     for (CFG::try_block_iterator I = cfg->try_blocks_begin(),
00656          E = cfg->try_blocks_end() ; I != E; ++I) {
00657       numReachable += scanMaybeReachableFromBlock(*I, PP, reachable);
00658     }
00659     if (numReachable == cfg->getNumBlockIDs())
00660       return;
00661   }
00662 
00663   // There are some unreachable blocks.  We need to find the root blocks that
00664   // contain code that should be considered unreachable.  
00665   for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
00666     const CFGBlock *block = *I;
00667     // A block may have been marked reachable during this loop.
00668     if (reachable[block->getBlockID()])
00669       continue;
00670     
00671     DeadCodeScan DS(reachable, PP);
00672     numReachable += DS.scanBackwards(block, CB);
00673     
00674     if (numReachable == cfg->getNumBlockIDs())
00675       return;
00676   }
00677 }
00678 
00679 }} // end namespace clang::reachable_code