ReachableCode.cpp 25 KB

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