ReachableCode.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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. #include "clang/Analysis/Analyses/ReachableCode.h"
  14. #include "clang/AST/Expr.h"
  15. #include "clang/AST/ExprCXX.h"
  16. #include "clang/AST/ExprObjC.h"
  17. #include "clang/AST/ParentMap.h"
  18. #include "clang/AST/StmtCXX.h"
  19. #include "clang/Analysis/AnalysisDeclContext.h"
  20. #include "clang/Analysis/CFG.h"
  21. #include "clang/Basic/Builtins.h"
  22. #include "clang/Basic/SourceManager.h"
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "llvm/ADT/BitVector.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. using namespace clang;
  27. //===----------------------------------------------------------------------===//
  28. // Core Reachability Analysis routines.
  29. //===----------------------------------------------------------------------===//
  30. static bool isEnumConstant(const Expr *Ex) {
  31. const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex);
  32. if (!DR)
  33. return false;
  34. return isa<EnumConstantDecl>(DR->getDecl());
  35. }
  36. static bool isTrivialExpression(const Expr *Ex) {
  37. Ex = Ex->IgnoreParenCasts();
  38. return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
  39. isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
  40. isa<CharacterLiteral>(Ex) ||
  41. isEnumConstant(Ex);
  42. }
  43. static bool isTrivialDoWhile(const CFGBlock *B, const Stmt *S) {
  44. // Check if the block ends with a do...while() and see if 'S' is the
  45. // condition.
  46. if (const Stmt *Term = B->getTerminatorStmt()) {
  47. if (const DoStmt *DS = dyn_cast<DoStmt>(Term)) {
  48. const Expr *Cond = DS->getCond()->IgnoreParenCasts();
  49. return Cond == S && isTrivialExpression(Cond);
  50. }
  51. }
  52. return false;
  53. }
  54. static bool isBuiltinUnreachable(const Stmt *S) {
  55. if (const auto *DRE = dyn_cast<DeclRefExpr>(S))
  56. if (const auto *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()))
  57. return FDecl->getIdentifier() &&
  58. FDecl->getBuiltinID() == Builtin::BI__builtin_unreachable;
  59. return false;
  60. }
  61. static bool isBuiltinAssumeFalse(const CFGBlock *B, const Stmt *S,
  62. ASTContext &C) {
  63. if (B->empty()) {
  64. // Happens if S is B's terminator and B contains nothing else
  65. // (e.g. a CFGBlock containing only a goto).
  66. return false;
  67. }
  68. if (Optional<CFGStmt> CS = B->back().getAs<CFGStmt>()) {
  69. if (const auto *CE = dyn_cast<CallExpr>(CS->getStmt())) {
  70. return CE->getCallee()->IgnoreCasts() == S && CE->isBuiltinAssumeFalse(C);
  71. }
  72. }
  73. return false;
  74. }
  75. static bool isDeadReturn(const CFGBlock *B, const Stmt *S) {
  76. // Look to see if the current control flow ends with a 'return', and see if
  77. // 'S' is a substatement. The 'return' may not be the last element in the
  78. // block, or may be in a subsequent block because of destructors.
  79. const CFGBlock *Current = B;
  80. while (true) {
  81. for (const CFGElement &CE : llvm::reverse(*Current)) {
  82. if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
  83. if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
  84. if (RS == S)
  85. return true;
  86. if (const Expr *RE = RS->getRetValue()) {
  87. RE = RE->IgnoreParenCasts();
  88. if (RE == S)
  89. return true;
  90. ParentMap PM(const_cast<Expr *>(RE));
  91. // If 'S' is in the ParentMap, it is a subexpression of
  92. // the return statement.
  93. return PM.getParent(S);
  94. }
  95. }
  96. break;
  97. }
  98. }
  99. // Note also that we are restricting the search for the return statement
  100. // to stop at control-flow; only part of a return statement may be dead,
  101. // without the whole return statement being dead.
  102. if (Current->getTerminator().isTemporaryDtorsBranch()) {
  103. // Temporary destructors have a predictable control flow, thus we want to
  104. // look into the next block for the return statement.
  105. // We look into the false branch, as we know the true branch only contains
  106. // the call to the destructor.
  107. assert(Current->succ_size() == 2);
  108. Current = *(Current->succ_begin() + 1);
  109. } else if (!Current->getTerminatorStmt() && Current->succ_size() == 1) {
  110. // If there is only one successor, we're not dealing with outgoing control
  111. // flow. Thus, look into the next block.
  112. Current = *Current->succ_begin();
  113. if (Current->pred_size() > 1) {
  114. // If there is more than one predecessor, we're dealing with incoming
  115. // control flow - if the return statement is in that block, it might
  116. // well be reachable via a different control flow, thus it's not dead.
  117. return false;
  118. }
  119. } else {
  120. // We hit control flow or a dead end. Stop searching.
  121. return false;
  122. }
  123. }
  124. llvm_unreachable("Broke out of infinite loop.");
  125. }
  126. static SourceLocation getTopMostMacro(SourceLocation Loc, SourceManager &SM) {
  127. assert(Loc.isMacroID());
  128. SourceLocation Last;
  129. do {
  130. Last = Loc;
  131. Loc = SM.getImmediateMacroCallerLoc(Loc);
  132. } while (Loc.isMacroID());
  133. return Last;
  134. }
  135. /// Returns true if the statement is expanded from a configuration macro.
  136. static bool isExpandedFromConfigurationMacro(const Stmt *S,
  137. Preprocessor &PP,
  138. bool IgnoreYES_NO = false) {
  139. // FIXME: This is not very precise. Here we just check to see if the
  140. // value comes from a macro, but we can do much better. This is likely
  141. // to be over conservative. This logic is factored into a separate function
  142. // so that we can refine it later.
  143. SourceLocation L = S->getBeginLoc();
  144. if (L.isMacroID()) {
  145. SourceManager &SM = PP.getSourceManager();
  146. if (IgnoreYES_NO) {
  147. // The Objective-C constant 'YES' and 'NO'
  148. // are defined as macros. Do not treat them
  149. // as configuration values.
  150. SourceLocation TopL = getTopMostMacro(L, SM);
  151. StringRef MacroName = PP.getImmediateMacroName(TopL);
  152. if (MacroName == "YES" || MacroName == "NO")
  153. return false;
  154. } else if (!PP.getLangOpts().CPlusPlus) {
  155. // Do not treat C 'false' and 'true' macros as configuration values.
  156. SourceLocation TopL = getTopMostMacro(L, SM);
  157. StringRef MacroName = PP.getImmediateMacroName(TopL);
  158. if (MacroName == "false" || MacroName == "true")
  159. return false;
  160. }
  161. return true;
  162. }
  163. return false;
  164. }
  165. static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP);
  166. /// Returns true if the statement represents a configuration value.
  167. ///
  168. /// A configuration value is something usually determined at compile-time
  169. /// to conditionally always execute some branch. Such guards are for
  170. /// "sometimes unreachable" code. Such code is usually not interesting
  171. /// to report as unreachable, and may mask truly unreachable code within
  172. /// those blocks.
  173. static bool isConfigurationValue(const Stmt *S,
  174. Preprocessor &PP,
  175. SourceRange *SilenceableCondVal = nullptr,
  176. bool IncludeIntegers = true,
  177. bool WrappedInParens = false) {
  178. if (!S)
  179. return false;
  180. if (const auto *Ex = dyn_cast<Expr>(S))
  181. S = Ex->IgnoreImplicit();
  182. if (const auto *Ex = dyn_cast<Expr>(S))
  183. S = Ex->IgnoreCasts();
  184. // Special case looking for the sigil '()' around an integer literal.
  185. if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
  186. if (!PE->getBeginLoc().isMacroID())
  187. return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal,
  188. IncludeIntegers, true);
  189. if (const Expr *Ex = dyn_cast<Expr>(S))
  190. S = Ex->IgnoreCasts();
  191. bool IgnoreYES_NO = false;
  192. switch (S->getStmtClass()) {
  193. case Stmt::CallExprClass: {
  194. const FunctionDecl *Callee =
  195. dyn_cast_or_null<FunctionDecl>(cast<CallExpr>(S)->getCalleeDecl());
  196. return Callee ? Callee->isConstexpr() : false;
  197. }
  198. case Stmt::DeclRefExprClass:
  199. return isConfigurationValue(cast<DeclRefExpr>(S)->getDecl(), PP);
  200. case Stmt::ObjCBoolLiteralExprClass:
  201. IgnoreYES_NO = true;
  202. LLVM_FALLTHROUGH;
  203. case Stmt::CXXBoolLiteralExprClass:
  204. case Stmt::IntegerLiteralClass: {
  205. const Expr *E = cast<Expr>(S);
  206. if (IncludeIntegers) {
  207. if (SilenceableCondVal && !SilenceableCondVal->getBegin().isValid())
  208. *SilenceableCondVal = E->getSourceRange();
  209. return WrappedInParens ||
  210. isExpandedFromConfigurationMacro(E, PP, IgnoreYES_NO);
  211. }
  212. return false;
  213. }
  214. case Stmt::MemberExprClass:
  215. return isConfigurationValue(cast<MemberExpr>(S)->getMemberDecl(), PP);
  216. case Stmt::UnaryExprOrTypeTraitExprClass:
  217. return true;
  218. case Stmt::BinaryOperatorClass: {
  219. const BinaryOperator *B = cast<BinaryOperator>(S);
  220. // Only include raw integers (not enums) as configuration
  221. // values if they are used in a logical or comparison operator
  222. // (not arithmetic).
  223. IncludeIntegers &= (B->isLogicalOp() || B->isComparisonOp());
  224. return isConfigurationValue(B->getLHS(), PP, SilenceableCondVal,
  225. IncludeIntegers) ||
  226. isConfigurationValue(B->getRHS(), PP, SilenceableCondVal,
  227. IncludeIntegers);
  228. }
  229. case Stmt::UnaryOperatorClass: {
  230. const UnaryOperator *UO = cast<UnaryOperator>(S);
  231. if (UO->getOpcode() != UO_LNot && UO->getOpcode() != UO_Minus)
  232. return false;
  233. bool SilenceableCondValNotSet =
  234. SilenceableCondVal && SilenceableCondVal->getBegin().isInvalid();
  235. bool IsSubExprConfigValue =
  236. isConfigurationValue(UO->getSubExpr(), PP, SilenceableCondVal,
  237. IncludeIntegers, WrappedInParens);
  238. // Update the silenceable condition value source range only if the range
  239. // was set directly by the child expression.
  240. if (SilenceableCondValNotSet &&
  241. SilenceableCondVal->getBegin().isValid() &&
  242. *SilenceableCondVal ==
  243. UO->getSubExpr()->IgnoreCasts()->getSourceRange())
  244. *SilenceableCondVal = UO->getSourceRange();
  245. return IsSubExprConfigValue;
  246. }
  247. default:
  248. return false;
  249. }
  250. }
  251. static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP) {
  252. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D))
  253. return isConfigurationValue(ED->getInitExpr(), PP);
  254. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  255. // As a heuristic, treat globals as configuration values. Note
  256. // that we only will get here if Sema evaluated this
  257. // condition to a constant expression, which means the global
  258. // had to be declared in a way to be a truly constant value.
  259. // We could generalize this to local variables, but it isn't
  260. // clear if those truly represent configuration values that
  261. // gate unreachable code.
  262. if (!VD->hasLocalStorage())
  263. return true;
  264. // As a heuristic, locals that have been marked 'const' explicitly
  265. // can be treated as configuration values as well.
  266. return VD->getType().isLocalConstQualified();
  267. }
  268. return false;
  269. }
  270. /// Returns true if we should always explore all successors of a block.
  271. static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B,
  272. Preprocessor &PP) {
  273. if (const Stmt *Term = B->getTerminatorStmt()) {
  274. if (isa<SwitchStmt>(Term))
  275. return true;
  276. // Specially handle '||' and '&&'.
  277. if (isa<BinaryOperator>(Term)) {
  278. return isConfigurationValue(Term, PP);
  279. }
  280. }
  281. const Stmt *Cond = B->getTerminatorCondition(/* stripParens */ false);
  282. return isConfigurationValue(Cond, PP);
  283. }
  284. static unsigned scanFromBlock(const CFGBlock *Start,
  285. llvm::BitVector &Reachable,
  286. Preprocessor *PP,
  287. bool IncludeSometimesUnreachableEdges) {
  288. unsigned count = 0;
  289. // Prep work queue
  290. SmallVector<const CFGBlock*, 32> WL;
  291. // The entry block may have already been marked reachable
  292. // by the caller.
  293. if (!Reachable[Start->getBlockID()]) {
  294. ++count;
  295. Reachable[Start->getBlockID()] = true;
  296. }
  297. WL.push_back(Start);
  298. // Find the reachable blocks from 'Start'.
  299. while (!WL.empty()) {
  300. const CFGBlock *item = WL.pop_back_val();
  301. // There are cases where we want to treat all successors as reachable.
  302. // The idea is that some "sometimes unreachable" code is not interesting,
  303. // and that we should forge ahead and explore those branches anyway.
  304. // This allows us to potentially uncover some "always unreachable" code
  305. // within the "sometimes unreachable" code.
  306. // Look at the successors and mark then reachable.
  307. Optional<bool> TreatAllSuccessorsAsReachable;
  308. if (!IncludeSometimesUnreachableEdges)
  309. TreatAllSuccessorsAsReachable = false;
  310. for (CFGBlock::const_succ_iterator I = item->succ_begin(),
  311. E = item->succ_end(); I != E; ++I) {
  312. const CFGBlock *B = *I;
  313. if (!B) do {
  314. const CFGBlock *UB = I->getPossiblyUnreachableBlock();
  315. if (!UB)
  316. break;
  317. if (!TreatAllSuccessorsAsReachable.hasValue()) {
  318. assert(PP);
  319. TreatAllSuccessorsAsReachable =
  320. shouldTreatSuccessorsAsReachable(item, *PP);
  321. }
  322. if (TreatAllSuccessorsAsReachable.getValue()) {
  323. B = UB;
  324. break;
  325. }
  326. }
  327. while (false);
  328. if (B) {
  329. unsigned blockID = B->getBlockID();
  330. if (!Reachable[blockID]) {
  331. Reachable.set(blockID);
  332. WL.push_back(B);
  333. ++count;
  334. }
  335. }
  336. }
  337. }
  338. return count;
  339. }
  340. static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start,
  341. Preprocessor &PP,
  342. llvm::BitVector &Reachable) {
  343. return scanFromBlock(Start, Reachable, &PP, true);
  344. }
  345. //===----------------------------------------------------------------------===//
  346. // Dead Code Scanner.
  347. //===----------------------------------------------------------------------===//
  348. namespace {
  349. class DeadCodeScan {
  350. llvm::BitVector Visited;
  351. llvm::BitVector &Reachable;
  352. SmallVector<const CFGBlock *, 10> WorkList;
  353. Preprocessor &PP;
  354. ASTContext &C;
  355. typedef SmallVector<std::pair<const CFGBlock *, const Stmt *>, 12>
  356. DeferredLocsTy;
  357. DeferredLocsTy DeferredLocs;
  358. public:
  359. DeadCodeScan(llvm::BitVector &reachable, Preprocessor &PP, ASTContext &C)
  360. : Visited(reachable.size()),
  361. Reachable(reachable),
  362. PP(PP), C(C) {}
  363. void enqueue(const CFGBlock *block);
  364. unsigned scanBackwards(const CFGBlock *Start,
  365. clang::reachable_code::Callback &CB);
  366. bool isDeadCodeRoot(const CFGBlock *Block);
  367. const Stmt *findDeadCode(const CFGBlock *Block);
  368. void reportDeadCode(const CFGBlock *B,
  369. const Stmt *S,
  370. clang::reachable_code::Callback &CB);
  371. };
  372. }
  373. void DeadCodeScan::enqueue(const CFGBlock *block) {
  374. unsigned blockID = block->getBlockID();
  375. if (Reachable[blockID] || Visited[blockID])
  376. return;
  377. Visited[blockID] = true;
  378. WorkList.push_back(block);
  379. }
  380. bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) {
  381. bool isDeadRoot = true;
  382. for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
  383. E = Block->pred_end(); I != E; ++I) {
  384. if (const CFGBlock *PredBlock = *I) {
  385. unsigned blockID = PredBlock->getBlockID();
  386. if (Visited[blockID]) {
  387. isDeadRoot = false;
  388. continue;
  389. }
  390. if (!Reachable[blockID]) {
  391. isDeadRoot = false;
  392. Visited[blockID] = true;
  393. WorkList.push_back(PredBlock);
  394. continue;
  395. }
  396. }
  397. }
  398. return isDeadRoot;
  399. }
  400. static bool isValidDeadStmt(const Stmt *S) {
  401. if (S->getBeginLoc().isInvalid())
  402. return false;
  403. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S))
  404. return BO->getOpcode() != BO_Comma;
  405. return true;
  406. }
  407. const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) {
  408. for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I)
  409. if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
  410. const Stmt *S = CS->getStmt();
  411. if (isValidDeadStmt(S))
  412. return S;
  413. }
  414. CFGTerminator T = Block->getTerminator();
  415. if (T.isStmtBranch()) {
  416. const Stmt *S = T.getStmt();
  417. if (S && isValidDeadStmt(S))
  418. return S;
  419. }
  420. return nullptr;
  421. }
  422. static int SrcCmp(const std::pair<const CFGBlock *, const Stmt *> *p1,
  423. const std::pair<const CFGBlock *, const Stmt *> *p2) {
  424. if (p1->second->getBeginLoc() < p2->second->getBeginLoc())
  425. return -1;
  426. if (p2->second->getBeginLoc() < p1->second->getBeginLoc())
  427. return 1;
  428. return 0;
  429. }
  430. unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start,
  431. clang::reachable_code::Callback &CB) {
  432. unsigned count = 0;
  433. enqueue(Start);
  434. while (!WorkList.empty()) {
  435. const CFGBlock *Block = WorkList.pop_back_val();
  436. // It is possible that this block has been marked reachable after
  437. // it was enqueued.
  438. if (Reachable[Block->getBlockID()])
  439. continue;
  440. // Look for any dead code within the block.
  441. const Stmt *S = findDeadCode(Block);
  442. if (!S) {
  443. // No dead code. Possibly an empty block. Look at dead predecessors.
  444. for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
  445. E = Block->pred_end(); I != E; ++I) {
  446. if (const CFGBlock *predBlock = *I)
  447. enqueue(predBlock);
  448. }
  449. continue;
  450. }
  451. // Specially handle macro-expanded code.
  452. if (S->getBeginLoc().isMacroID()) {
  453. count += scanMaybeReachableFromBlock(Block, PP, Reachable);
  454. continue;
  455. }
  456. if (isDeadCodeRoot(Block)) {
  457. reportDeadCode(Block, S, CB);
  458. count += scanMaybeReachableFromBlock(Block, PP, Reachable);
  459. }
  460. else {
  461. // Record this statement as the possibly best location in a
  462. // strongly-connected component of dead code for emitting a
  463. // warning.
  464. DeferredLocs.push_back(std::make_pair(Block, S));
  465. }
  466. }
  467. // If we didn't find a dead root, then report the dead code with the
  468. // earliest location.
  469. if (!DeferredLocs.empty()) {
  470. llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(), SrcCmp);
  471. for (const auto &I : DeferredLocs) {
  472. const CFGBlock *Block = I.first;
  473. if (Reachable[Block->getBlockID()])
  474. continue;
  475. reportDeadCode(Block, I.second, CB);
  476. count += scanMaybeReachableFromBlock(Block, PP, Reachable);
  477. }
  478. }
  479. return count;
  480. }
  481. static SourceLocation GetUnreachableLoc(const Stmt *S,
  482. SourceRange &R1,
  483. SourceRange &R2) {
  484. R1 = R2 = SourceRange();
  485. if (const Expr *Ex = dyn_cast<Expr>(S))
  486. S = Ex->IgnoreParenImpCasts();
  487. switch (S->getStmtClass()) {
  488. case Expr::BinaryOperatorClass: {
  489. const BinaryOperator *BO = cast<BinaryOperator>(S);
  490. return BO->getOperatorLoc();
  491. }
  492. case Expr::UnaryOperatorClass: {
  493. const UnaryOperator *UO = cast<UnaryOperator>(S);
  494. R1 = UO->getSubExpr()->getSourceRange();
  495. return UO->getOperatorLoc();
  496. }
  497. case Expr::CompoundAssignOperatorClass: {
  498. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
  499. R1 = CAO->getLHS()->getSourceRange();
  500. R2 = CAO->getRHS()->getSourceRange();
  501. return CAO->getOperatorLoc();
  502. }
  503. case Expr::BinaryConditionalOperatorClass:
  504. case Expr::ConditionalOperatorClass: {
  505. const AbstractConditionalOperator *CO =
  506. cast<AbstractConditionalOperator>(S);
  507. return CO->getQuestionLoc();
  508. }
  509. case Expr::MemberExprClass: {
  510. const MemberExpr *ME = cast<MemberExpr>(S);
  511. R1 = ME->getSourceRange();
  512. return ME->getMemberLoc();
  513. }
  514. case Expr::ArraySubscriptExprClass: {
  515. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
  516. R1 = ASE->getLHS()->getSourceRange();
  517. R2 = ASE->getRHS()->getSourceRange();
  518. return ASE->getRBracketLoc();
  519. }
  520. case Expr::CStyleCastExprClass: {
  521. const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
  522. R1 = CSC->getSubExpr()->getSourceRange();
  523. return CSC->getLParenLoc();
  524. }
  525. case Expr::CXXFunctionalCastExprClass: {
  526. const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
  527. R1 = CE->getSubExpr()->getSourceRange();
  528. return CE->getBeginLoc();
  529. }
  530. case Stmt::CXXTryStmtClass: {
  531. return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
  532. }
  533. case Expr::ObjCBridgedCastExprClass: {
  534. const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
  535. R1 = CSC->getSubExpr()->getSourceRange();
  536. return CSC->getLParenLoc();
  537. }
  538. default: ;
  539. }
  540. R1 = S->getSourceRange();
  541. return S->getBeginLoc();
  542. }
  543. void DeadCodeScan::reportDeadCode(const CFGBlock *B,
  544. const Stmt *S,
  545. clang::reachable_code::Callback &CB) {
  546. // Classify the unreachable code found, or suppress it in some cases.
  547. reachable_code::UnreachableKind UK = reachable_code::UK_Other;
  548. if (isa<BreakStmt>(S)) {
  549. UK = reachable_code::UK_Break;
  550. } else if (isTrivialDoWhile(B, S) || isBuiltinUnreachable(S) ||
  551. isBuiltinAssumeFalse(B, S, C)) {
  552. return;
  553. }
  554. else if (isDeadReturn(B, S)) {
  555. UK = reachable_code::UK_Return;
  556. }
  557. SourceRange SilenceableCondVal;
  558. if (UK == reachable_code::UK_Other) {
  559. // Check if the dead code is part of the "loop target" of
  560. // a for/for-range loop. This is the block that contains
  561. // the increment code.
  562. if (const Stmt *LoopTarget = B->getLoopTarget()) {
  563. SourceLocation Loc = LoopTarget->getBeginLoc();
  564. SourceRange R1(Loc, Loc), R2;
  565. if (const ForStmt *FS = dyn_cast<ForStmt>(LoopTarget)) {
  566. const Expr *Inc = FS->getInc();
  567. Loc = Inc->getBeginLoc();
  568. R2 = Inc->getSourceRange();
  569. }
  570. CB.HandleUnreachable(reachable_code::UK_Loop_Increment,
  571. Loc, SourceRange(), SourceRange(Loc, Loc), R2);
  572. return;
  573. }
  574. // Check if the dead block has a predecessor whose branch has
  575. // a configuration value that *could* be modified to
  576. // silence the warning.
  577. CFGBlock::const_pred_iterator PI = B->pred_begin();
  578. if (PI != B->pred_end()) {
  579. if (const CFGBlock *PredBlock = PI->getPossiblyUnreachableBlock()) {
  580. const Stmt *TermCond =
  581. PredBlock->getTerminatorCondition(/* strip parens */ false);
  582. isConfigurationValue(TermCond, PP, &SilenceableCondVal);
  583. }
  584. }
  585. }
  586. SourceRange R1, R2;
  587. SourceLocation Loc = GetUnreachableLoc(S, R1, R2);
  588. CB.HandleUnreachable(UK, Loc, SilenceableCondVal, R1, R2);
  589. }
  590. //===----------------------------------------------------------------------===//
  591. // Reachability APIs.
  592. //===----------------------------------------------------------------------===//
  593. namespace clang { namespace reachable_code {
  594. void Callback::anchor() { }
  595. unsigned ScanReachableFromBlock(const CFGBlock *Start,
  596. llvm::BitVector &Reachable) {
  597. return scanFromBlock(Start, Reachable, /* SourceManager* */ nullptr, false);
  598. }
  599. void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP,
  600. Callback &CB) {
  601. CFG *cfg = AC.getCFG();
  602. if (!cfg)
  603. return;
  604. // Scan for reachable blocks from the entrance of the CFG.
  605. // If there are no unreachable blocks, we're done.
  606. llvm::BitVector reachable(cfg->getNumBlockIDs());
  607. unsigned numReachable =
  608. scanMaybeReachableFromBlock(&cfg->getEntry(), PP, reachable);
  609. if (numReachable == cfg->getNumBlockIDs())
  610. return;
  611. // If there aren't explicit EH edges, we should include the 'try' dispatch
  612. // blocks as roots.
  613. if (!AC.getCFGBuildOptions().AddEHEdges) {
  614. for (const CFGBlock *B : cfg->try_blocks())
  615. numReachable += scanMaybeReachableFromBlock(B, PP, reachable);
  616. if (numReachable == cfg->getNumBlockIDs())
  617. return;
  618. }
  619. // There are some unreachable blocks. We need to find the root blocks that
  620. // contain code that should be considered unreachable.
  621. for (const CFGBlock *block : *cfg) {
  622. // A block may have been marked reachable during this loop.
  623. if (reachable[block->getBlockID()])
  624. continue;
  625. DeadCodeScan DS(reachable, PP, AC.getASTContext());
  626. numReachable += DS.scanBackwards(block, CB);
  627. if (numReachable == cfg->getNumBlockIDs())
  628. return;
  629. }
  630. }
  631. }} // end namespace clang::reachable_code