ReachableCode.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //=- 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. #include "llvm/ADT/BitVector.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/ExprObjC.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/Analysis/Analyses/ReachableCode.h"
  21. #include "clang/Analysis/CFG.h"
  22. #include "clang/Analysis/AnalysisContext.h"
  23. #include "clang/Basic/SourceManager.h"
  24. using namespace clang;
  25. static SourceLocation GetUnreachableLoc(const CFGBlock &b, SourceRange &R1,
  26. SourceRange &R2) {
  27. const Stmt *S = 0;
  28. unsigned sn = 0;
  29. R1 = R2 = SourceRange();
  30. if (sn < b.size()) {
  31. const CFGStmt *CS = b[sn].getAs<CFGStmt>();
  32. if (!CS)
  33. return SourceLocation();
  34. S = CS->getStmt();
  35. } else if (b.getTerminator())
  36. S = b.getTerminator();
  37. else
  38. return SourceLocation();
  39. if (const Expr *Ex = dyn_cast<Expr>(S))
  40. S = Ex->IgnoreParenImpCasts();
  41. switch (S->getStmtClass()) {
  42. case Expr::BinaryOperatorClass: {
  43. const BinaryOperator *BO = cast<BinaryOperator>(S);
  44. if (BO->getOpcode() == BO_Comma) {
  45. if (sn+1 < b.size())
  46. return b[sn+1].getAs<CFGStmt>()->getStmt()->getLocStart();
  47. const CFGBlock *n = &b;
  48. while (1) {
  49. if (n->getTerminator())
  50. return n->getTerminator()->getLocStart();
  51. if (n->succ_size() != 1)
  52. return SourceLocation();
  53. n = n[0].succ_begin()[0];
  54. if (n->pred_size() != 1)
  55. return SourceLocation();
  56. if (!n->empty())
  57. return n[0][0].getAs<CFGStmt>()->getStmt()->getLocStart();
  58. }
  59. }
  60. R1 = BO->getLHS()->getSourceRange();
  61. R2 = BO->getRHS()->getSourceRange();
  62. return BO->getOperatorLoc();
  63. }
  64. case Expr::UnaryOperatorClass: {
  65. const UnaryOperator *UO = cast<UnaryOperator>(S);
  66. R1 = UO->getSubExpr()->getSourceRange();
  67. return UO->getOperatorLoc();
  68. }
  69. case Expr::CompoundAssignOperatorClass: {
  70. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
  71. R1 = CAO->getLHS()->getSourceRange();
  72. R2 = CAO->getRHS()->getSourceRange();
  73. return CAO->getOperatorLoc();
  74. }
  75. case Expr::BinaryConditionalOperatorClass:
  76. case Expr::ConditionalOperatorClass: {
  77. const AbstractConditionalOperator *CO =
  78. cast<AbstractConditionalOperator>(S);
  79. return CO->getQuestionLoc();
  80. }
  81. case Expr::MemberExprClass: {
  82. const MemberExpr *ME = cast<MemberExpr>(S);
  83. R1 = ME->getSourceRange();
  84. return ME->getMemberLoc();
  85. }
  86. case Expr::ArraySubscriptExprClass: {
  87. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
  88. R1 = ASE->getLHS()->getSourceRange();
  89. R2 = ASE->getRHS()->getSourceRange();
  90. return ASE->getRBracketLoc();
  91. }
  92. case Expr::CStyleCastExprClass: {
  93. const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
  94. R1 = CSC->getSubExpr()->getSourceRange();
  95. return CSC->getLParenLoc();
  96. }
  97. case Expr::CXXFunctionalCastExprClass: {
  98. const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
  99. R1 = CE->getSubExpr()->getSourceRange();
  100. return CE->getTypeBeginLoc();
  101. }
  102. case Stmt::CXXTryStmtClass: {
  103. return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
  104. }
  105. case Expr::ObjCBridgedCastExprClass: {
  106. const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
  107. R1 = CSC->getSubExpr()->getSourceRange();
  108. return CSC->getLParenLoc();
  109. }
  110. default: ;
  111. }
  112. R1 = S->getSourceRange();
  113. return S->getLocStart();
  114. }
  115. static SourceLocation MarkLiveTop(const CFGBlock *Start,
  116. llvm::BitVector &reachable,
  117. SourceManager &SM) {
  118. // Prep work worklist.
  119. llvm::SmallVector<const CFGBlock*, 32> WL;
  120. WL.push_back(Start);
  121. SourceRange R1, R2;
  122. SourceLocation top = GetUnreachableLoc(*Start, R1, R2);
  123. bool FromMainFile = false;
  124. bool FromSystemHeader = false;
  125. bool TopValid = false;
  126. if (top.isValid()) {
  127. FromMainFile = SM.isFromMainFile(top);
  128. FromSystemHeader = SM.isInSystemHeader(top);
  129. TopValid = true;
  130. }
  131. // Solve
  132. CFGBlock::FilterOptions FO;
  133. FO.IgnoreDefaultsWithCoveredEnums = 1;
  134. while (!WL.empty()) {
  135. const CFGBlock *item = WL.back();
  136. WL.pop_back();
  137. SourceLocation c = GetUnreachableLoc(*item, R1, R2);
  138. if (c.isValid()
  139. && (!TopValid
  140. || (SM.isFromMainFile(c) && !FromMainFile)
  141. || (FromSystemHeader && !SM.isInSystemHeader(c))
  142. || SM.isBeforeInTranslationUnit(c, top))) {
  143. top = c;
  144. FromMainFile = SM.isFromMainFile(top);
  145. FromSystemHeader = SM.isInSystemHeader(top);
  146. }
  147. reachable.set(item->getBlockID());
  148. for (CFGBlock::filtered_succ_iterator I =
  149. item->filtered_succ_start_end(FO); I.hasMore(); ++I)
  150. if (const CFGBlock *B = *I) {
  151. unsigned blockID = B->getBlockID();
  152. if (!reachable[blockID]) {
  153. reachable.set(blockID);
  154. WL.push_back(B);
  155. }
  156. }
  157. }
  158. return top;
  159. }
  160. static int LineCmp(const void *p1, const void *p2) {
  161. SourceLocation *Line1 = (SourceLocation *)p1;
  162. SourceLocation *Line2 = (SourceLocation *)p2;
  163. return !(*Line1 < *Line2);
  164. }
  165. namespace {
  166. struct ErrLoc {
  167. SourceLocation Loc;
  168. SourceRange R1;
  169. SourceRange R2;
  170. ErrLoc(SourceLocation l, SourceRange r1, SourceRange r2)
  171. : Loc(l), R1(r1), R2(r2) { }
  172. };
  173. }
  174. namespace clang { namespace reachable_code {
  175. /// ScanReachableFromBlock - Mark all blocks reachable from Start.
  176. /// Returns the total number of blocks that were marked reachable.
  177. unsigned ScanReachableFromBlock(const CFGBlock &Start,
  178. llvm::BitVector &Reachable) {
  179. unsigned count = 0;
  180. llvm::SmallVector<const CFGBlock*, 32> WL;
  181. // Prep work queue
  182. Reachable.set(Start.getBlockID());
  183. ++count;
  184. WL.push_back(&Start);
  185. // Find the reachable blocks from 'Start'.
  186. CFGBlock::FilterOptions FO;
  187. FO.IgnoreDefaultsWithCoveredEnums = 1;
  188. while (!WL.empty()) {
  189. const CFGBlock *item = WL.back();
  190. WL.pop_back();
  191. // Look at the successors and mark then reachable.
  192. for (CFGBlock::filtered_succ_iterator I= item->filtered_succ_start_end(FO);
  193. I.hasMore(); ++I)
  194. if (const CFGBlock *B = *I) {
  195. unsigned blockID = B->getBlockID();
  196. if (!Reachable[blockID]) {
  197. Reachable.set(blockID);
  198. ++count;
  199. WL.push_back(B);
  200. }
  201. }
  202. }
  203. return count;
  204. }
  205. void FindUnreachableCode(AnalysisContext &AC, Callback &CB) {
  206. CFG *cfg = AC.getCFG();
  207. if (!cfg)
  208. return;
  209. // Scan for reachable blocks.
  210. llvm::BitVector reachable(cfg->getNumBlockIDs());
  211. unsigned numReachable = ScanReachableFromBlock(cfg->getEntry(), reachable);
  212. // If there are no unreachable blocks, we're done.
  213. if (numReachable == cfg->getNumBlockIDs())
  214. return;
  215. SourceRange R1, R2;
  216. llvm::SmallVector<ErrLoc, 24> lines;
  217. bool AddEHEdges = AC.getAddEHEdges();
  218. // First, give warnings for blocks with no predecessors, as they
  219. // can't be part of a loop.
  220. for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
  221. CFGBlock &b = **I;
  222. if (!reachable[b.getBlockID()]) {
  223. if (b.pred_empty()) {
  224. if (!AddEHEdges
  225. && dyn_cast_or_null<CXXTryStmt>(b.getTerminator().getStmt())) {
  226. // When not adding EH edges from calls, catch clauses
  227. // can otherwise seem dead. Avoid noting them as dead.
  228. numReachable += ScanReachableFromBlock(b, reachable);
  229. continue;
  230. }
  231. SourceLocation c = GetUnreachableLoc(b, R1, R2);
  232. if (!c.isValid()) {
  233. // Blocks without a location can't produce a warning, so don't mark
  234. // reachable blocks from here as live.
  235. reachable.set(b.getBlockID());
  236. ++numReachable;
  237. continue;
  238. }
  239. lines.push_back(ErrLoc(c, R1, R2));
  240. // Avoid excessive errors by marking everything reachable from here
  241. numReachable += ScanReachableFromBlock(b, reachable);
  242. }
  243. }
  244. }
  245. if (numReachable < cfg->getNumBlockIDs()) {
  246. // And then give warnings for the tops of loops.
  247. for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
  248. CFGBlock &b = **I;
  249. if (!reachable[b.getBlockID()])
  250. // Avoid excessive errors by marking everything reachable from here
  251. lines.push_back(ErrLoc(MarkLiveTop(&b, reachable,
  252. AC.getASTContext().getSourceManager()),
  253. SourceRange(), SourceRange()));
  254. }
  255. }
  256. llvm::array_pod_sort(lines.begin(), lines.end(), LineCmp);
  257. for (llvm::SmallVectorImpl<ErrLoc>::iterator I=lines.begin(), E=lines.end();
  258. I != E; ++I)
  259. if (I->Loc.isValid())
  260. CB.HandleUnreachable(I->Loc, I->R1, I->R2);
  261. }
  262. }} // end namespace clang::reachable_code