bool CfgNaive::runOnFunction(Function &F) { errs() << F.getName() << "\n"; SmallPtrSet<BasicBlock*, 8> visitedBlocks; // Mark all reachable blocks. for (df_ext_iterator<Function*, SmallPtrSet<BasicBlock*, 8>> currentBlock = df_ext_begin(&F, visitedBlocks), endBlock = df_ext_end(&F, visitedBlocks); currentBlock != endBlock; currentBlock++) { //do nothing, iterator marks visited nodes automatically } // Build set of unreachable blocks std::vector<BasicBlock*> unreachableBlocks; for (Function::iterator currentBlock = F.begin(), endBlock = F.end(); currentBlock != endBlock; currentBlock++) { if (visitedBlocks.count(currentBlock) == 0) { unreachableBlocks.push_back(currentBlock); } } // Remove unreachable blocks for (int i = 0, e = unreachableBlocks.size(); i != e; i++) { errs() << unreachableBlocks[i]->getName() << " is unreachable\n"; unreachableBlocks[i]->eraseFromParent(); } bool hasModifiedBlocks = (unreachableBlocks.size() > 0); return hasModifiedBlocks; }
bool DeadBlocks::runOnFunction(Function& F) { BasicBlock* entry = F.begin(); bool changed = false; std::set<BasicBlock*> visitedSet; std::set<BasicBlock*> unvisitedSet; //Perform DFS from entry block for (df_ext_iterator<BasicBlock*> dfi = df_ext_begin(entry,visitedSet), endi = df_ext_end(entry, visitedSet); dfi != endi; ++dfi) { } // Store unvisited blocks for(auto& BB : F) { auto search = visitedSet.find(&BB); if(search == visitedSet.end()) // if not in visited set { unvisitedSet.insert(&BB); // blocks to be removed... } } if(unvisitedSet.size() > 0) { changed = true; for(auto& BB : unvisitedSet) { for(succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++) { SI->removePredecessor(BB); } BB->eraseFromParent(); } } return changed; }