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 15 #include "clang/Analysis/Analyses/ReachableCode.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/AnalysisContext.h" 21 #include "clang/Analysis/CFG.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "llvm/ADT/BitVector.h" 24 #include "llvm/ADT/SmallVector.h" 25 26 using namespace clang; 27 28 //===----------------------------------------------------------------------===// 29 // Core Reachability Analysis routines. 30 //===----------------------------------------------------------------------===// 31 32 static bool bodyEndsWithNoReturn(const CFGBlock *B) { 33 for (CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 34 I != E; ++I) { 35 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) { 36 const Stmt *S = CS->getStmt(); 37 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) 38 S = EWC->getSubExpr(); 39 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 40 QualType CalleeType = CE->getCallee()->getType(); 41 if (getFunctionExtInfo(*CalleeType).getNoReturn()) 42 return true; 43 } 44 break; 45 } 46 } 47 return false; 48 } 49 50 static bool bodyEndsWithNoReturn(const CFGBlock::AdjacentBlock &AB) { 51 // If the predecessor is a normal CFG edge, then by definition 52 // the predecessor did not end with a 'noreturn'. 53 if (AB.getReachableBlock()) 54 return false; 55 56 const CFGBlock *Pred = AB.getPossiblyUnreachableBlock(); 57 assert(!AB.isReachable() && Pred); 58 return bodyEndsWithNoReturn(Pred); 59 } 60 61 static bool isBreakPrecededByNoReturn(const CFGBlock *B, 62 const Stmt *S) { 63 if (!isa<BreakStmt>(S) || B->pred_empty()) 64 return false; 65 66 assert(B->empty()); 67 assert(B->pred_size() == 1); 68 return bodyEndsWithNoReturn(*B->pred_begin()); 69 } 70 71 static bool isEnumConstant(const Expr *Ex) { 72 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex); 73 if (!DR) 74 return false; 75 return isa<EnumConstantDecl>(DR->getDecl()); 76 } 77 78 static const Expr *stripStdStringCtor(const Expr *Ex) { 79 // Go crazy pattern matching an implicit construction of std::string(""). 80 const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex); 81 if (!EWC) 82 return 0; 83 const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(EWC->getSubExpr()); 84 if (!CCE) 85 return 0; 86 QualType Ty = CCE->getType(); 87 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) 88 Ty = ET->getNamedType(); 89 const TypedefType *TT = dyn_cast<TypedefType>(Ty); 90 StringRef Name = TT->getDecl()->getName(); 91 if (Name != "string") 92 return 0; 93 if (CCE->getNumArgs() != 1) 94 return 0; 95 const MaterializeTemporaryExpr *MTE = 96 dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0)); 97 if (!MTE) 98 return 0; 99 CXXBindTemporaryExpr *CBT = 100 dyn_cast<CXXBindTemporaryExpr>(MTE->GetTemporaryExpr()->IgnoreParenCasts()); 101 if (!CBT) 102 return 0; 103 Ex = CBT->getSubExpr()->IgnoreParenCasts(); 104 CCE = dyn_cast<CXXConstructExpr>(Ex); 105 if (!CCE) 106 return 0; 107 if (CCE->getNumArgs() != 1) 108 return 0; 109 return dyn_cast<StringLiteral>(CCE->getArg(0)->IgnoreParenCasts()); 110 } 111 112 /// Strip away "sugar" around trivial expressions that are for the 113 /// purpose of this analysis considered uninteresting for dead code warnings. 114 static const Expr *stripExprSugar(const Expr *Ex) { 115 Ex = Ex->IgnoreParenCasts(); 116 // If 'Ex' is a constructor for a std::string, strip that 117 // away. We can only get here if the trivial expression was 118 // something like a C string literal, with the std::string 119 // just wrapping that value. 120 if (const Expr *StdStringVal = stripStdStringCtor(Ex)) 121 return StdStringVal; 122 return Ex; 123 } 124 125 static bool isTrivialExpression(const Expr *Ex) { 126 Ex = Ex->IgnoreParenCasts(); 127 return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) || 128 isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) || 129 isa<CharacterLiteral>(Ex) || 130 isEnumConstant(Ex); 131 } 132 133 static bool isTrivialReturnOrDoWhile(const CFGBlock *B, const Stmt *S) { 134 const Expr *Ex = dyn_cast<Expr>(S); 135 if (!Ex) 136 return false; 137 138 if (!isTrivialExpression(Ex)) 139 return false; 140 141 // Check if the block ends with a do...while() and see if 'S' is the 142 // condition. 143 if (const Stmt *Term = B->getTerminator()) { 144 if (const DoStmt *DS = dyn_cast<DoStmt>(Term)) 145 if (DS->getCond() == S) 146 return true; 147 } 148 149 if (B->pred_size() != 1) 150 return false; 151 152 // Look to see if the block ends with a 'return', and see if 'S' 153 // is a substatement. The 'return' may not be the last element in 154 // the block because of destructors. 155 assert(!B->empty()); 156 for (CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 157 I != E; ++I) { 158 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) { 159 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) { 160 const Expr *RE = RS->getRetValue(); 161 if (RE && stripExprSugar(RE->IgnoreParenCasts()) == Ex) 162 return bodyEndsWithNoReturn(*B->pred_begin()); 163 } 164 break; 165 } 166 } 167 return false; 168 } 169 170 /// Returns true if the statement is expanded from a configuration macro. 171 static bool isExpandedFromConfigurationMacro(const Stmt *S) { 172 // FIXME: This is not very precise. Here we just check to see if the 173 // value comes from a macro, but we can do much better. This is likely 174 // to be over conservative. This logic is factored into a separate function 175 // so that we can refine it later. 176 SourceLocation L = S->getLocStart(); 177 return L.isMacroID(); 178 } 179 180 /// Returns true if the statement represents a configuration value. 181 /// 182 /// A configuration value is something usually determined at compile-time 183 /// to conditionally always execute some branch. Such guards are for 184 /// "sometimes unreachable" code. Such code is usually not interesting 185 /// to report as unreachable, and may mask truly unreachable code within 186 /// those blocks. 187 static bool isConfigurationValue(const Stmt *S) { 188 if (!S) 189 return false; 190 191 if (const Expr *Ex = dyn_cast<Expr>(S)) 192 S = Ex->IgnoreParenCasts(); 193 194 switch (S->getStmtClass()) { 195 case Stmt::DeclRefExprClass: { 196 const DeclRefExpr *DR = cast<DeclRefExpr>(S); 197 const ValueDecl *D = DR->getDecl(); 198 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) 199 return ED ? isConfigurationValue(ED->getInitExpr()) : false; 200 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 201 // As a heuristic, treat globals as configuration values. Note 202 // that we only will get here if Sema evaluated this 203 // condition to a constant expression, which means the global 204 // had to be declared in a way to be a truly constant value. 205 // We could generalize this to local variables, but it isn't 206 // clear if those truly represent configuration values that 207 // gate unreachable code. 208 return !VD->hasLocalStorage(); 209 } 210 return false; 211 } 212 case Stmt::IntegerLiteralClass: 213 return isExpandedFromConfigurationMacro(S); 214 case Stmt::UnaryExprOrTypeTraitExprClass: 215 return true; 216 case Stmt::BinaryOperatorClass: { 217 const BinaryOperator *B = cast<BinaryOperator>(S); 218 return (B->isLogicalOp() || B->isComparisonOp()) && 219 (isConfigurationValue(B->getLHS()) || 220 isConfigurationValue(B->getRHS())); 221 } 222 case Stmt::UnaryOperatorClass: { 223 const UnaryOperator *UO = cast<UnaryOperator>(S); 224 return UO->getOpcode() == UO_LNot && 225 isConfigurationValue(UO->getSubExpr()); 226 } 227 default: 228 return false; 229 } 230 } 231 232 /// Returns true if we should always explore all successors of a block. 233 static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B) { 234 if (const Stmt *Term = B->getTerminator()) { 235 if (isa<SwitchStmt>(Term)) 236 return true; 237 // Specially handle '||' and '&&'. 238 if (isa<BinaryOperator>(Term)) 239 return isConfigurationValue(Term); 240 } 241 242 return isConfigurationValue(B->getTerminatorCondition()); 243 } 244 245 static unsigned scanFromBlock(const CFGBlock *Start, 246 llvm::BitVector &Reachable, 247 bool IncludeSometimesUnreachableEdges) { 248 unsigned count = 0; 249 250 // Prep work queue 251 SmallVector<const CFGBlock*, 32> WL; 252 253 // The entry block may have already been marked reachable 254 // by the caller. 255 if (!Reachable[Start->getBlockID()]) { 256 ++count; 257 Reachable[Start->getBlockID()] = true; 258 } 259 260 WL.push_back(Start); 261 262 // Find the reachable blocks from 'Start'. 263 while (!WL.empty()) { 264 const CFGBlock *item = WL.pop_back_val(); 265 266 // There are cases where we want to treat all successors as reachable. 267 // The idea is that some "sometimes unreachable" code is not interesting, 268 // and that we should forge ahead and explore those branches anyway. 269 // This allows us to potentially uncover some "always unreachable" code 270 // within the "sometimes unreachable" code. 271 // Look at the successors and mark then reachable. 272 Optional<bool> TreatAllSuccessorsAsReachable; 273 if (!IncludeSometimesUnreachableEdges) 274 TreatAllSuccessorsAsReachable = false; 275 276 for (CFGBlock::const_succ_iterator I = item->succ_begin(), 277 E = item->succ_end(); I != E; ++I) { 278 const CFGBlock *B = *I; 279 if (!B) do { 280 const CFGBlock *UB = I->getPossiblyUnreachableBlock(); 281 if (!UB) 282 break; 283 284 if (!TreatAllSuccessorsAsReachable.hasValue()) 285 TreatAllSuccessorsAsReachable = 286 shouldTreatSuccessorsAsReachable(item); 287 288 if (TreatAllSuccessorsAsReachable.getValue()) { 289 B = UB; 290 break; 291 } 292 } 293 while (false); 294 295 if (B) { 296 unsigned blockID = B->getBlockID(); 297 if (!Reachable[blockID]) { 298 Reachable.set(blockID); 299 WL.push_back(B); 300 ++count; 301 } 302 } 303 } 304 } 305 return count; 306 } 307 308 static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start, 309 llvm::BitVector &Reachable) { 310 return scanFromBlock(Start, Reachable, true); 311 } 312 313 //===----------------------------------------------------------------------===// 314 // Dead Code Scanner. 315 //===----------------------------------------------------------------------===// 316 317 namespace { 318 class DeadCodeScan { 319 llvm::BitVector Visited; 320 llvm::BitVector &Reachable; 321 SmallVector<const CFGBlock *, 10> WorkList; 322 323 typedef SmallVector<std::pair<const CFGBlock *, const Stmt *>, 12> 324 DeferredLocsTy; 325 326 DeferredLocsTy DeferredLocs; 327 328 public: 329 DeadCodeScan(llvm::BitVector &reachable) 330 : Visited(reachable.size()), 331 Reachable(reachable) {} 332 333 void enqueue(const CFGBlock *block); 334 unsigned scanBackwards(const CFGBlock *Start, 335 clang::reachable_code::Callback &CB); 336 337 bool isDeadCodeRoot(const CFGBlock *Block); 338 339 const Stmt *findDeadCode(const CFGBlock *Block); 340 341 void reportDeadCode(const CFGBlock *B, 342 const Stmt *S, 343 clang::reachable_code::Callback &CB); 344 }; 345 } 346 347 void DeadCodeScan::enqueue(const CFGBlock *block) { 348 unsigned blockID = block->getBlockID(); 349 if (Reachable[blockID] || Visited[blockID]) 350 return; 351 Visited[blockID] = true; 352 WorkList.push_back(block); 353 } 354 355 bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) { 356 bool isDeadRoot = true; 357 358 for (CFGBlock::const_pred_iterator I = Block->pred_begin(), 359 E = Block->pred_end(); I != E; ++I) { 360 if (const CFGBlock *PredBlock = *I) { 361 unsigned blockID = PredBlock->getBlockID(); 362 if (Visited[blockID]) { 363 isDeadRoot = false; 364 continue; 365 } 366 if (!Reachable[blockID]) { 367 isDeadRoot = false; 368 Visited[blockID] = true; 369 WorkList.push_back(PredBlock); 370 continue; 371 } 372 } 373 } 374 375 return isDeadRoot; 376 } 377 378 static bool isValidDeadStmt(const Stmt *S) { 379 if (S->getLocStart().isInvalid()) 380 return false; 381 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) 382 return BO->getOpcode() != BO_Comma; 383 return true; 384 } 385 386 const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) { 387 for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I) 388 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) { 389 const Stmt *S = CS->getStmt(); 390 if (isValidDeadStmt(S)) 391 return S; 392 } 393 394 if (CFGTerminator T = Block->getTerminator()) { 395 const Stmt *S = T.getStmt(); 396 if (isValidDeadStmt(S)) 397 return S; 398 } 399 400 return 0; 401 } 402 403 static int SrcCmp(const std::pair<const CFGBlock *, const Stmt *> *p1, 404 const std::pair<const CFGBlock *, const Stmt *> *p2) { 405 if (p1->second->getLocStart() < p2->second->getLocStart()) 406 return -1; 407 if (p2->second->getLocStart() < p1->second->getLocStart()) 408 return 1; 409 return 0; 410 } 411 412 unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start, 413 clang::reachable_code::Callback &CB) { 414 415 unsigned count = 0; 416 enqueue(Start); 417 418 while (!WorkList.empty()) { 419 const CFGBlock *Block = WorkList.pop_back_val(); 420 421 // It is possible that this block has been marked reachable after 422 // it was enqueued. 423 if (Reachable[Block->getBlockID()]) 424 continue; 425 426 // Look for any dead code within the block. 427 const Stmt *S = findDeadCode(Block); 428 429 if (!S) { 430 // No dead code. Possibly an empty block. Look at dead predecessors. 431 for (CFGBlock::const_pred_iterator I = Block->pred_begin(), 432 E = Block->pred_end(); I != E; ++I) { 433 if (const CFGBlock *predBlock = *I) 434 enqueue(predBlock); 435 } 436 continue; 437 } 438 439 // Specially handle macro-expanded code. 440 if (S->getLocStart().isMacroID()) { 441 count += scanMaybeReachableFromBlock(Block, Reachable); 442 continue; 443 } 444 445 if (isDeadCodeRoot(Block)) { 446 reportDeadCode(Block, S, CB); 447 count += scanMaybeReachableFromBlock(Block, Reachable); 448 } 449 else { 450 // Record this statement as the possibly best location in a 451 // strongly-connected component of dead code for emitting a 452 // warning. 453 DeferredLocs.push_back(std::make_pair(Block, S)); 454 } 455 } 456 457 // If we didn't find a dead root, then report the dead code with the 458 // earliest location. 459 if (!DeferredLocs.empty()) { 460 llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(), SrcCmp); 461 for (DeferredLocsTy::iterator I = DeferredLocs.begin(), 462 E = DeferredLocs.end(); I != E; ++I) { 463 const CFGBlock *Block = I->first; 464 if (Reachable[Block->getBlockID()]) 465 continue; 466 reportDeadCode(Block, I->second, CB); 467 count += scanMaybeReachableFromBlock(Block, Reachable); 468 } 469 } 470 471 return count; 472 } 473 474 static SourceLocation GetUnreachableLoc(const Stmt *S, 475 SourceRange &R1, 476 SourceRange &R2) { 477 R1 = R2 = SourceRange(); 478 479 if (const Expr *Ex = dyn_cast<Expr>(S)) 480 S = Ex->IgnoreParenImpCasts(); 481 482 switch (S->getStmtClass()) { 483 case Expr::BinaryOperatorClass: { 484 const BinaryOperator *BO = cast<BinaryOperator>(S); 485 return BO->getOperatorLoc(); 486 } 487 case Expr::UnaryOperatorClass: { 488 const UnaryOperator *UO = cast<UnaryOperator>(S); 489 R1 = UO->getSubExpr()->getSourceRange(); 490 return UO->getOperatorLoc(); 491 } 492 case Expr::CompoundAssignOperatorClass: { 493 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S); 494 R1 = CAO->getLHS()->getSourceRange(); 495 R2 = CAO->getRHS()->getSourceRange(); 496 return CAO->getOperatorLoc(); 497 } 498 case Expr::BinaryConditionalOperatorClass: 499 case Expr::ConditionalOperatorClass: { 500 const AbstractConditionalOperator *CO = 501 cast<AbstractConditionalOperator>(S); 502 return CO->getQuestionLoc(); 503 } 504 case Expr::MemberExprClass: { 505 const MemberExpr *ME = cast<MemberExpr>(S); 506 R1 = ME->getSourceRange(); 507 return ME->getMemberLoc(); 508 } 509 case Expr::ArraySubscriptExprClass: { 510 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S); 511 R1 = ASE->getLHS()->getSourceRange(); 512 R2 = ASE->getRHS()->getSourceRange(); 513 return ASE->getRBracketLoc(); 514 } 515 case Expr::CStyleCastExprClass: { 516 const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S); 517 R1 = CSC->getSubExpr()->getSourceRange(); 518 return CSC->getLParenLoc(); 519 } 520 case Expr::CXXFunctionalCastExprClass: { 521 const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S); 522 R1 = CE->getSubExpr()->getSourceRange(); 523 return CE->getLocStart(); 524 } 525 case Stmt::CXXTryStmtClass: { 526 return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc(); 527 } 528 case Expr::ObjCBridgedCastExprClass: { 529 const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S); 530 R1 = CSC->getSubExpr()->getSourceRange(); 531 return CSC->getLParenLoc(); 532 } 533 default: ; 534 } 535 R1 = S->getSourceRange(); 536 return S->getLocStart(); 537 } 538 539 void DeadCodeScan::reportDeadCode(const CFGBlock *B, 540 const Stmt *S, 541 clang::reachable_code::Callback &CB) { 542 // Suppress idiomatic cases of calling a noreturn function just 543 // before executing a 'break'. If there is other code after the 'break' 544 // in the block then don't suppress the warning. 545 if (isBreakPrecededByNoReturn(B, S)) 546 return; 547 548 // Suppress trivial 'return' statements that are dead. 549 if (isTrivialReturnOrDoWhile(B, S)) 550 return; 551 552 SourceRange R1, R2; 553 SourceLocation Loc = GetUnreachableLoc(S, R1, R2); 554 CB.HandleUnreachable(Loc, R1, R2); 555 } 556 557 //===----------------------------------------------------------------------===// 558 // Reachability APIs. 559 //===----------------------------------------------------------------------===// 560 561 namespace clang { namespace reachable_code { 562 563 void Callback::anchor() { } 564 565 unsigned ScanReachableFromBlock(const CFGBlock *Start, 566 llvm::BitVector &Reachable) { 567 return scanFromBlock(Start, Reachable, false); 568 } 569 570 void FindUnreachableCode(AnalysisDeclContext &AC, Callback &CB) { 571 CFG *cfg = AC.getCFG(); 572 if (!cfg) 573 return; 574 575 // Scan for reachable blocks from the entrance of the CFG. 576 // If there are no unreachable blocks, we're done. 577 llvm::BitVector reachable(cfg->getNumBlockIDs()); 578 unsigned numReachable = 579 scanMaybeReachableFromBlock(&cfg->getEntry(), reachable); 580 if (numReachable == cfg->getNumBlockIDs()) 581 return; 582 583 // If there aren't explicit EH edges, we should include the 'try' dispatch 584 // blocks as roots. 585 if (!AC.getCFGBuildOptions().AddEHEdges) { 586 for (CFG::try_block_iterator I = cfg->try_blocks_begin(), 587 E = cfg->try_blocks_end() ; I != E; ++I) { 588 numReachable += scanMaybeReachableFromBlock(*I, reachable); 589 } 590 if (numReachable == cfg->getNumBlockIDs()) 591 return; 592 } 593 594 // There are some unreachable blocks. We need to find the root blocks that 595 // contain code that should be considered unreachable. 596 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) { 597 const CFGBlock *block = *I; 598 // A block may have been marked reachable during this loop. 599 if (reachable[block->getBlockID()]) 600 continue; 601 602 DeadCodeScan DS(reachable); 603 numReachable += DS.scanBackwards(block, CB); 604 605 if (numReachable == cfg->getNumBlockIDs()) 606 return; 607 } 608 } 609 610 }} // end namespace clang::reachable_code 611