1*09467b48Spatrick //===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==// 2*09467b48Spatrick // 3*09467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*09467b48Spatrick // See https://llvm.org/LICENSE.txt for license information. 5*09467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*09467b48Spatrick // 7*09467b48Spatrick //===----------------------------------------------------------------------===// 8*09467b48Spatrick // 9*09467b48Spatrick // This family of functions perform manipulations on basic blocks, and 10*09467b48Spatrick // instructions contained within basic blocks. 11*09467b48Spatrick // 12*09467b48Spatrick //===----------------------------------------------------------------------===// 13*09467b48Spatrick 14*09467b48Spatrick #include "llvm/Transforms/Utils/BasicBlockUtils.h" 15*09467b48Spatrick #include "llvm/ADT/ArrayRef.h" 16*09467b48Spatrick #include "llvm/ADT/SmallPtrSet.h" 17*09467b48Spatrick #include "llvm/ADT/SmallVector.h" 18*09467b48Spatrick #include "llvm/ADT/Twine.h" 19*09467b48Spatrick #include "llvm/Analysis/CFG.h" 20*09467b48Spatrick #include "llvm/Analysis/DomTreeUpdater.h" 21*09467b48Spatrick #include "llvm/Analysis/LoopInfo.h" 22*09467b48Spatrick #include "llvm/Analysis/MemoryDependenceAnalysis.h" 23*09467b48Spatrick #include "llvm/Analysis/MemorySSAUpdater.h" 24*09467b48Spatrick #include "llvm/Analysis/PostDominators.h" 25*09467b48Spatrick #include "llvm/IR/BasicBlock.h" 26*09467b48Spatrick #include "llvm/IR/CFG.h" 27*09467b48Spatrick #include "llvm/IR/Constants.h" 28*09467b48Spatrick #include "llvm/IR/DebugInfoMetadata.h" 29*09467b48Spatrick #include "llvm/IR/Dominators.h" 30*09467b48Spatrick #include "llvm/IR/Function.h" 31*09467b48Spatrick #include "llvm/IR/InstrTypes.h" 32*09467b48Spatrick #include "llvm/IR/Instruction.h" 33*09467b48Spatrick #include "llvm/IR/Instructions.h" 34*09467b48Spatrick #include "llvm/IR/IntrinsicInst.h" 35*09467b48Spatrick #include "llvm/IR/LLVMContext.h" 36*09467b48Spatrick #include "llvm/IR/Type.h" 37*09467b48Spatrick #include "llvm/IR/User.h" 38*09467b48Spatrick #include "llvm/IR/Value.h" 39*09467b48Spatrick #include "llvm/IR/ValueHandle.h" 40*09467b48Spatrick #include "llvm/Support/Casting.h" 41*09467b48Spatrick #include "llvm/Support/Debug.h" 42*09467b48Spatrick #include "llvm/Support/raw_ostream.h" 43*09467b48Spatrick #include "llvm/Transforms/Utils/Local.h" 44*09467b48Spatrick #include <cassert> 45*09467b48Spatrick #include <cstdint> 46*09467b48Spatrick #include <string> 47*09467b48Spatrick #include <utility> 48*09467b48Spatrick #include <vector> 49*09467b48Spatrick 50*09467b48Spatrick using namespace llvm; 51*09467b48Spatrick 52*09467b48Spatrick #define DEBUG_TYPE "basicblock-utils" 53*09467b48Spatrick 54*09467b48Spatrick void llvm::DetatchDeadBlocks( 55*09467b48Spatrick ArrayRef<BasicBlock *> BBs, 56*09467b48Spatrick SmallVectorImpl<DominatorTree::UpdateType> *Updates, 57*09467b48Spatrick bool KeepOneInputPHIs) { 58*09467b48Spatrick for (auto *BB : BBs) { 59*09467b48Spatrick // Loop through all of our successors and make sure they know that one 60*09467b48Spatrick // of their predecessors is going away. 61*09467b48Spatrick SmallPtrSet<BasicBlock *, 4> UniqueSuccessors; 62*09467b48Spatrick for (BasicBlock *Succ : successors(BB)) { 63*09467b48Spatrick Succ->removePredecessor(BB, KeepOneInputPHIs); 64*09467b48Spatrick if (Updates && UniqueSuccessors.insert(Succ).second) 65*09467b48Spatrick Updates->push_back({DominatorTree::Delete, BB, Succ}); 66*09467b48Spatrick } 67*09467b48Spatrick 68*09467b48Spatrick // Zap all the instructions in the block. 69*09467b48Spatrick while (!BB->empty()) { 70*09467b48Spatrick Instruction &I = BB->back(); 71*09467b48Spatrick // If this instruction is used, replace uses with an arbitrary value. 72*09467b48Spatrick // Because control flow can't get here, we don't care what we replace the 73*09467b48Spatrick // value with. Note that since this block is unreachable, and all values 74*09467b48Spatrick // contained within it must dominate their uses, that all uses will 75*09467b48Spatrick // eventually be removed (they are themselves dead). 76*09467b48Spatrick if (!I.use_empty()) 77*09467b48Spatrick I.replaceAllUsesWith(UndefValue::get(I.getType())); 78*09467b48Spatrick BB->getInstList().pop_back(); 79*09467b48Spatrick } 80*09467b48Spatrick new UnreachableInst(BB->getContext(), BB); 81*09467b48Spatrick assert(BB->getInstList().size() == 1 && 82*09467b48Spatrick isa<UnreachableInst>(BB->getTerminator()) && 83*09467b48Spatrick "The successor list of BB isn't empty before " 84*09467b48Spatrick "applying corresponding DTU updates."); 85*09467b48Spatrick } 86*09467b48Spatrick } 87*09467b48Spatrick 88*09467b48Spatrick void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU, 89*09467b48Spatrick bool KeepOneInputPHIs) { 90*09467b48Spatrick DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs); 91*09467b48Spatrick } 92*09467b48Spatrick 93*09467b48Spatrick void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU, 94*09467b48Spatrick bool KeepOneInputPHIs) { 95*09467b48Spatrick #ifndef NDEBUG 96*09467b48Spatrick // Make sure that all predecessors of each dead block is also dead. 97*09467b48Spatrick SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end()); 98*09467b48Spatrick assert(Dead.size() == BBs.size() && "Duplicating blocks?"); 99*09467b48Spatrick for (auto *BB : Dead) 100*09467b48Spatrick for (BasicBlock *Pred : predecessors(BB)) 101*09467b48Spatrick assert(Dead.count(Pred) && "All predecessors must be dead!"); 102*09467b48Spatrick #endif 103*09467b48Spatrick 104*09467b48Spatrick SmallVector<DominatorTree::UpdateType, 4> Updates; 105*09467b48Spatrick DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs); 106*09467b48Spatrick 107*09467b48Spatrick if (DTU) 108*09467b48Spatrick DTU->applyUpdatesPermissive(Updates); 109*09467b48Spatrick 110*09467b48Spatrick for (BasicBlock *BB : BBs) 111*09467b48Spatrick if (DTU) 112*09467b48Spatrick DTU->deleteBB(BB); 113*09467b48Spatrick else 114*09467b48Spatrick BB->eraseFromParent(); 115*09467b48Spatrick } 116*09467b48Spatrick 117*09467b48Spatrick bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU, 118*09467b48Spatrick bool KeepOneInputPHIs) { 119*09467b48Spatrick df_iterator_default_set<BasicBlock*> Reachable; 120*09467b48Spatrick 121*09467b48Spatrick // Mark all reachable blocks. 122*09467b48Spatrick for (BasicBlock *BB : depth_first_ext(&F, Reachable)) 123*09467b48Spatrick (void)BB/* Mark all reachable blocks */; 124*09467b48Spatrick 125*09467b48Spatrick // Collect all dead blocks. 126*09467b48Spatrick std::vector<BasicBlock*> DeadBlocks; 127*09467b48Spatrick for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) 128*09467b48Spatrick if (!Reachable.count(&*I)) { 129*09467b48Spatrick BasicBlock *BB = &*I; 130*09467b48Spatrick DeadBlocks.push_back(BB); 131*09467b48Spatrick } 132*09467b48Spatrick 133*09467b48Spatrick // Delete the dead blocks. 134*09467b48Spatrick DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs); 135*09467b48Spatrick 136*09467b48Spatrick return !DeadBlocks.empty(); 137*09467b48Spatrick } 138*09467b48Spatrick 139*09467b48Spatrick void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, 140*09467b48Spatrick MemoryDependenceResults *MemDep) { 141*09467b48Spatrick if (!isa<PHINode>(BB->begin())) return; 142*09467b48Spatrick 143*09467b48Spatrick while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 144*09467b48Spatrick if (PN->getIncomingValue(0) != PN) 145*09467b48Spatrick PN->replaceAllUsesWith(PN->getIncomingValue(0)); 146*09467b48Spatrick else 147*09467b48Spatrick PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 148*09467b48Spatrick 149*09467b48Spatrick if (MemDep) 150*09467b48Spatrick MemDep->removeInstruction(PN); // Memdep updates AA itself. 151*09467b48Spatrick 152*09467b48Spatrick PN->eraseFromParent(); 153*09467b48Spatrick } 154*09467b48Spatrick } 155*09467b48Spatrick 156*09467b48Spatrick bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) { 157*09467b48Spatrick // Recursively deleting a PHI may cause multiple PHIs to be deleted 158*09467b48Spatrick // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete. 159*09467b48Spatrick SmallVector<WeakTrackingVH, 8> PHIs; 160*09467b48Spatrick for (PHINode &PN : BB->phis()) 161*09467b48Spatrick PHIs.push_back(&PN); 162*09467b48Spatrick 163*09467b48Spatrick bool Changed = false; 164*09467b48Spatrick for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 165*09467b48Spatrick if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*())) 166*09467b48Spatrick Changed |= RecursivelyDeleteDeadPHINode(PN, TLI); 167*09467b48Spatrick 168*09467b48Spatrick return Changed; 169*09467b48Spatrick } 170*09467b48Spatrick 171*09467b48Spatrick bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU, 172*09467b48Spatrick LoopInfo *LI, MemorySSAUpdater *MSSAU, 173*09467b48Spatrick MemoryDependenceResults *MemDep, 174*09467b48Spatrick bool PredecessorWithTwoSuccessors) { 175*09467b48Spatrick if (BB->hasAddressTaken()) 176*09467b48Spatrick return false; 177*09467b48Spatrick 178*09467b48Spatrick // Can't merge if there are multiple predecessors, or no predecessors. 179*09467b48Spatrick BasicBlock *PredBB = BB->getUniquePredecessor(); 180*09467b48Spatrick if (!PredBB) return false; 181*09467b48Spatrick 182*09467b48Spatrick // Don't break self-loops. 183*09467b48Spatrick if (PredBB == BB) return false; 184*09467b48Spatrick // Don't break unwinding instructions. 185*09467b48Spatrick if (PredBB->getTerminator()->isExceptionalTerminator()) 186*09467b48Spatrick return false; 187*09467b48Spatrick 188*09467b48Spatrick // Can't merge if there are multiple distinct successors. 189*09467b48Spatrick if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB) 190*09467b48Spatrick return false; 191*09467b48Spatrick 192*09467b48Spatrick // Currently only allow PredBB to have two predecessors, one being BB. 193*09467b48Spatrick // Update BI to branch to BB's only successor instead of BB. 194*09467b48Spatrick BranchInst *PredBB_BI; 195*09467b48Spatrick BasicBlock *NewSucc = nullptr; 196*09467b48Spatrick unsigned FallThruPath; 197*09467b48Spatrick if (PredecessorWithTwoSuccessors) { 198*09467b48Spatrick if (!(PredBB_BI = dyn_cast<BranchInst>(PredBB->getTerminator()))) 199*09467b48Spatrick return false; 200*09467b48Spatrick BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator()); 201*09467b48Spatrick if (!BB_JmpI || !BB_JmpI->isUnconditional()) 202*09467b48Spatrick return false; 203*09467b48Spatrick NewSucc = BB_JmpI->getSuccessor(0); 204*09467b48Spatrick FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1; 205*09467b48Spatrick } 206*09467b48Spatrick 207*09467b48Spatrick // Can't merge if there is PHI loop. 208*09467b48Spatrick for (PHINode &PN : BB->phis()) 209*09467b48Spatrick for (Value *IncValue : PN.incoming_values()) 210*09467b48Spatrick if (IncValue == &PN) 211*09467b48Spatrick return false; 212*09467b48Spatrick 213*09467b48Spatrick LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into " 214*09467b48Spatrick << PredBB->getName() << "\n"); 215*09467b48Spatrick 216*09467b48Spatrick // Begin by getting rid of unneeded PHIs. 217*09467b48Spatrick SmallVector<AssertingVH<Value>, 4> IncomingValues; 218*09467b48Spatrick if (isa<PHINode>(BB->front())) { 219*09467b48Spatrick for (PHINode &PN : BB->phis()) 220*09467b48Spatrick if (!isa<PHINode>(PN.getIncomingValue(0)) || 221*09467b48Spatrick cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB) 222*09467b48Spatrick IncomingValues.push_back(PN.getIncomingValue(0)); 223*09467b48Spatrick FoldSingleEntryPHINodes(BB, MemDep); 224*09467b48Spatrick } 225*09467b48Spatrick 226*09467b48Spatrick // DTU update: Collect all the edges that exit BB. 227*09467b48Spatrick // These dominator edges will be redirected from Pred. 228*09467b48Spatrick std::vector<DominatorTree::UpdateType> Updates; 229*09467b48Spatrick if (DTU) { 230*09467b48Spatrick Updates.reserve(1 + (2 * succ_size(BB))); 231*09467b48Spatrick // Add insert edges first. Experimentally, for the particular case of two 232*09467b48Spatrick // blocks that can be merged, with a single successor and single predecessor 233*09467b48Spatrick // respectively, it is beneficial to have all insert updates first. Deleting 234*09467b48Spatrick // edges first may lead to unreachable blocks, followed by inserting edges 235*09467b48Spatrick // making the blocks reachable again. Such DT updates lead to high compile 236*09467b48Spatrick // times. We add inserts before deletes here to reduce compile time. 237*09467b48Spatrick for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) 238*09467b48Spatrick // This successor of BB may already have PredBB as a predecessor. 239*09467b48Spatrick if (llvm::find(successors(PredBB), *I) == succ_end(PredBB)) 240*09467b48Spatrick Updates.push_back({DominatorTree::Insert, PredBB, *I}); 241*09467b48Spatrick for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) 242*09467b48Spatrick Updates.push_back({DominatorTree::Delete, BB, *I}); 243*09467b48Spatrick Updates.push_back({DominatorTree::Delete, PredBB, BB}); 244*09467b48Spatrick } 245*09467b48Spatrick 246*09467b48Spatrick Instruction *PTI = PredBB->getTerminator(); 247*09467b48Spatrick Instruction *STI = BB->getTerminator(); 248*09467b48Spatrick Instruction *Start = &*BB->begin(); 249*09467b48Spatrick // If there's nothing to move, mark the starting instruction as the last 250*09467b48Spatrick // instruction in the block. Terminator instruction is handled separately. 251*09467b48Spatrick if (Start == STI) 252*09467b48Spatrick Start = PTI; 253*09467b48Spatrick 254*09467b48Spatrick // Move all definitions in the successor to the predecessor... 255*09467b48Spatrick PredBB->getInstList().splice(PTI->getIterator(), BB->getInstList(), 256*09467b48Spatrick BB->begin(), STI->getIterator()); 257*09467b48Spatrick 258*09467b48Spatrick if (MSSAU) 259*09467b48Spatrick MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start); 260*09467b48Spatrick 261*09467b48Spatrick // Make all PHI nodes that referred to BB now refer to Pred as their 262*09467b48Spatrick // source... 263*09467b48Spatrick BB->replaceAllUsesWith(PredBB); 264*09467b48Spatrick 265*09467b48Spatrick if (PredecessorWithTwoSuccessors) { 266*09467b48Spatrick // Delete the unconditional branch from BB. 267*09467b48Spatrick BB->getInstList().pop_back(); 268*09467b48Spatrick 269*09467b48Spatrick // Update branch in the predecessor. 270*09467b48Spatrick PredBB_BI->setSuccessor(FallThruPath, NewSucc); 271*09467b48Spatrick } else { 272*09467b48Spatrick // Delete the unconditional branch from the predecessor. 273*09467b48Spatrick PredBB->getInstList().pop_back(); 274*09467b48Spatrick 275*09467b48Spatrick // Move terminator instruction. 276*09467b48Spatrick PredBB->getInstList().splice(PredBB->end(), BB->getInstList()); 277*09467b48Spatrick 278*09467b48Spatrick // Terminator may be a memory accessing instruction too. 279*09467b48Spatrick if (MSSAU) 280*09467b48Spatrick if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>( 281*09467b48Spatrick MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator()))) 282*09467b48Spatrick MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End); 283*09467b48Spatrick } 284*09467b48Spatrick // Add unreachable to now empty BB. 285*09467b48Spatrick new UnreachableInst(BB->getContext(), BB); 286*09467b48Spatrick 287*09467b48Spatrick // Eliminate duplicate/redundant dbg.values. This seems to be a good place to 288*09467b48Spatrick // do that since we might end up with redundant dbg.values describing the 289*09467b48Spatrick // entry PHI node post-splice. 290*09467b48Spatrick RemoveRedundantDbgInstrs(PredBB); 291*09467b48Spatrick 292*09467b48Spatrick // Inherit predecessors name if it exists. 293*09467b48Spatrick if (!PredBB->hasName()) 294*09467b48Spatrick PredBB->takeName(BB); 295*09467b48Spatrick 296*09467b48Spatrick if (LI) 297*09467b48Spatrick LI->removeBlock(BB); 298*09467b48Spatrick 299*09467b48Spatrick if (MemDep) 300*09467b48Spatrick MemDep->invalidateCachedPredecessors(); 301*09467b48Spatrick 302*09467b48Spatrick // Finally, erase the old block and update dominator info. 303*09467b48Spatrick if (DTU) { 304*09467b48Spatrick assert(BB->getInstList().size() == 1 && 305*09467b48Spatrick isa<UnreachableInst>(BB->getTerminator()) && 306*09467b48Spatrick "The successor list of BB isn't empty before " 307*09467b48Spatrick "applying corresponding DTU updates."); 308*09467b48Spatrick DTU->applyUpdatesPermissive(Updates); 309*09467b48Spatrick DTU->deleteBB(BB); 310*09467b48Spatrick } else { 311*09467b48Spatrick BB->eraseFromParent(); // Nuke BB if DTU is nullptr. 312*09467b48Spatrick } 313*09467b48Spatrick 314*09467b48Spatrick return true; 315*09467b48Spatrick } 316*09467b48Spatrick 317*09467b48Spatrick /// Remove redundant instructions within sequences of consecutive dbg.value 318*09467b48Spatrick /// instructions. This is done using a backward scan to keep the last dbg.value 319*09467b48Spatrick /// describing a specific variable/fragment. 320*09467b48Spatrick /// 321*09467b48Spatrick /// BackwardScan strategy: 322*09467b48Spatrick /// ---------------------- 323*09467b48Spatrick /// Given a sequence of consecutive DbgValueInst like this 324*09467b48Spatrick /// 325*09467b48Spatrick /// dbg.value ..., "x", FragmentX1 (*) 326*09467b48Spatrick /// dbg.value ..., "y", FragmentY1 327*09467b48Spatrick /// dbg.value ..., "x", FragmentX2 328*09467b48Spatrick /// dbg.value ..., "x", FragmentX1 (**) 329*09467b48Spatrick /// 330*09467b48Spatrick /// then the instruction marked with (*) can be removed (it is guaranteed to be 331*09467b48Spatrick /// obsoleted by the instruction marked with (**) as the latter instruction is 332*09467b48Spatrick /// describing the same variable using the same fragment info). 333*09467b48Spatrick /// 334*09467b48Spatrick /// Possible improvements: 335*09467b48Spatrick /// - Check fully overlapping fragments and not only identical fragments. 336*09467b48Spatrick /// - Support dbg.addr, dbg.declare. dbg.label, and possibly other meta 337*09467b48Spatrick /// instructions being part of the sequence of consecutive instructions. 338*09467b48Spatrick static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) { 339*09467b48Spatrick SmallVector<DbgValueInst *, 8> ToBeRemoved; 340*09467b48Spatrick SmallDenseSet<DebugVariable> VariableSet; 341*09467b48Spatrick for (auto &I : reverse(*BB)) { 342*09467b48Spatrick if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 343*09467b48Spatrick DebugVariable Key(DVI->getVariable(), 344*09467b48Spatrick DVI->getExpression(), 345*09467b48Spatrick DVI->getDebugLoc()->getInlinedAt()); 346*09467b48Spatrick auto R = VariableSet.insert(Key); 347*09467b48Spatrick // If the same variable fragment is described more than once it is enough 348*09467b48Spatrick // to keep the last one (i.e. the first found since we for reverse 349*09467b48Spatrick // iteration). 350*09467b48Spatrick if (!R.second) 351*09467b48Spatrick ToBeRemoved.push_back(DVI); 352*09467b48Spatrick continue; 353*09467b48Spatrick } 354*09467b48Spatrick // Sequence with consecutive dbg.value instrs ended. Clear the map to 355*09467b48Spatrick // restart identifying redundant instructions if case we find another 356*09467b48Spatrick // dbg.value sequence. 357*09467b48Spatrick VariableSet.clear(); 358*09467b48Spatrick } 359*09467b48Spatrick 360*09467b48Spatrick for (auto &Instr : ToBeRemoved) 361*09467b48Spatrick Instr->eraseFromParent(); 362*09467b48Spatrick 363*09467b48Spatrick return !ToBeRemoved.empty(); 364*09467b48Spatrick } 365*09467b48Spatrick 366*09467b48Spatrick /// Remove redundant dbg.value instructions using a forward scan. This can 367*09467b48Spatrick /// remove a dbg.value instruction that is redundant due to indicating that a 368*09467b48Spatrick /// variable has the same value as already being indicated by an earlier 369*09467b48Spatrick /// dbg.value. 370*09467b48Spatrick /// 371*09467b48Spatrick /// ForwardScan strategy: 372*09467b48Spatrick /// --------------------- 373*09467b48Spatrick /// Given two identical dbg.value instructions, separated by a block of 374*09467b48Spatrick /// instructions that isn't describing the same variable, like this 375*09467b48Spatrick /// 376*09467b48Spatrick /// dbg.value X1, "x", FragmentX1 (**) 377*09467b48Spatrick /// <block of instructions, none being "dbg.value ..., "x", ..."> 378*09467b48Spatrick /// dbg.value X1, "x", FragmentX1 (*) 379*09467b48Spatrick /// 380*09467b48Spatrick /// then the instruction marked with (*) can be removed. Variable "x" is already 381*09467b48Spatrick /// described as being mapped to the SSA value X1. 382*09467b48Spatrick /// 383*09467b48Spatrick /// Possible improvements: 384*09467b48Spatrick /// - Keep track of non-overlapping fragments. 385*09467b48Spatrick static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) { 386*09467b48Spatrick SmallVector<DbgValueInst *, 8> ToBeRemoved; 387*09467b48Spatrick DenseMap<DebugVariable, std::pair<Value *, DIExpression *> > VariableMap; 388*09467b48Spatrick for (auto &I : *BB) { 389*09467b48Spatrick if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 390*09467b48Spatrick DebugVariable Key(DVI->getVariable(), 391*09467b48Spatrick NoneType(), 392*09467b48Spatrick DVI->getDebugLoc()->getInlinedAt()); 393*09467b48Spatrick auto VMI = VariableMap.find(Key); 394*09467b48Spatrick // Update the map if we found a new value/expression describing the 395*09467b48Spatrick // variable, or if the variable wasn't mapped already. 396*09467b48Spatrick if (VMI == VariableMap.end() || 397*09467b48Spatrick VMI->second.first != DVI->getValue() || 398*09467b48Spatrick VMI->second.second != DVI->getExpression()) { 399*09467b48Spatrick VariableMap[Key] = { DVI->getValue(), DVI->getExpression() }; 400*09467b48Spatrick continue; 401*09467b48Spatrick } 402*09467b48Spatrick // Found an identical mapping. Remember the instruction for later removal. 403*09467b48Spatrick ToBeRemoved.push_back(DVI); 404*09467b48Spatrick } 405*09467b48Spatrick } 406*09467b48Spatrick 407*09467b48Spatrick for (auto &Instr : ToBeRemoved) 408*09467b48Spatrick Instr->eraseFromParent(); 409*09467b48Spatrick 410*09467b48Spatrick return !ToBeRemoved.empty(); 411*09467b48Spatrick } 412*09467b48Spatrick 413*09467b48Spatrick bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) { 414*09467b48Spatrick bool MadeChanges = false; 415*09467b48Spatrick // By using the "backward scan" strategy before the "forward scan" strategy we 416*09467b48Spatrick // can remove both dbg.value (2) and (3) in a situation like this: 417*09467b48Spatrick // 418*09467b48Spatrick // (1) dbg.value V1, "x", DIExpression() 419*09467b48Spatrick // ... 420*09467b48Spatrick // (2) dbg.value V2, "x", DIExpression() 421*09467b48Spatrick // (3) dbg.value V1, "x", DIExpression() 422*09467b48Spatrick // 423*09467b48Spatrick // The backward scan will remove (2), it is made obsolete by (3). After 424*09467b48Spatrick // getting (2) out of the way, the foward scan will remove (3) since "x" 425*09467b48Spatrick // already is described as having the value V1 at (1). 426*09467b48Spatrick MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB); 427*09467b48Spatrick MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB); 428*09467b48Spatrick 429*09467b48Spatrick if (MadeChanges) 430*09467b48Spatrick LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: " 431*09467b48Spatrick << BB->getName() << "\n"); 432*09467b48Spatrick return MadeChanges; 433*09467b48Spatrick } 434*09467b48Spatrick 435*09467b48Spatrick void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL, 436*09467b48Spatrick BasicBlock::iterator &BI, Value *V) { 437*09467b48Spatrick Instruction &I = *BI; 438*09467b48Spatrick // Replaces all of the uses of the instruction with uses of the value 439*09467b48Spatrick I.replaceAllUsesWith(V); 440*09467b48Spatrick 441*09467b48Spatrick // Make sure to propagate a name if there is one already. 442*09467b48Spatrick if (I.hasName() && !V->hasName()) 443*09467b48Spatrick V->takeName(&I); 444*09467b48Spatrick 445*09467b48Spatrick // Delete the unnecessary instruction now... 446*09467b48Spatrick BI = BIL.erase(BI); 447*09467b48Spatrick } 448*09467b48Spatrick 449*09467b48Spatrick void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 450*09467b48Spatrick BasicBlock::iterator &BI, Instruction *I) { 451*09467b48Spatrick assert(I->getParent() == nullptr && 452*09467b48Spatrick "ReplaceInstWithInst: Instruction already inserted into basic block!"); 453*09467b48Spatrick 454*09467b48Spatrick // Copy debug location to newly added instruction, if it wasn't already set 455*09467b48Spatrick // by the caller. 456*09467b48Spatrick if (!I->getDebugLoc()) 457*09467b48Spatrick I->setDebugLoc(BI->getDebugLoc()); 458*09467b48Spatrick 459*09467b48Spatrick // Insert the new instruction into the basic block... 460*09467b48Spatrick BasicBlock::iterator New = BIL.insert(BI, I); 461*09467b48Spatrick 462*09467b48Spatrick // Replace all uses of the old instruction, and delete it. 463*09467b48Spatrick ReplaceInstWithValue(BIL, BI, I); 464*09467b48Spatrick 465*09467b48Spatrick // Move BI back to point to the newly inserted instruction 466*09467b48Spatrick BI = New; 467*09467b48Spatrick } 468*09467b48Spatrick 469*09467b48Spatrick void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 470*09467b48Spatrick BasicBlock::iterator BI(From); 471*09467b48Spatrick ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 472*09467b48Spatrick } 473*09467b48Spatrick 474*09467b48Spatrick BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT, 475*09467b48Spatrick LoopInfo *LI, MemorySSAUpdater *MSSAU) { 476*09467b48Spatrick unsigned SuccNum = GetSuccessorNumber(BB, Succ); 477*09467b48Spatrick 478*09467b48Spatrick // If this is a critical edge, let SplitCriticalEdge do it. 479*09467b48Spatrick Instruction *LatchTerm = BB->getTerminator(); 480*09467b48Spatrick if (SplitCriticalEdge( 481*09467b48Spatrick LatchTerm, SuccNum, 482*09467b48Spatrick CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA())) 483*09467b48Spatrick return LatchTerm->getSuccessor(SuccNum); 484*09467b48Spatrick 485*09467b48Spatrick // If the edge isn't critical, then BB has a single successor or Succ has a 486*09467b48Spatrick // single pred. Split the block. 487*09467b48Spatrick if (BasicBlock *SP = Succ->getSinglePredecessor()) { 488*09467b48Spatrick // If the successor only has a single pred, split the top of the successor 489*09467b48Spatrick // block. 490*09467b48Spatrick assert(SP == BB && "CFG broken"); 491*09467b48Spatrick SP = nullptr; 492*09467b48Spatrick return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU); 493*09467b48Spatrick } 494*09467b48Spatrick 495*09467b48Spatrick // Otherwise, if BB has a single successor, split it at the bottom of the 496*09467b48Spatrick // block. 497*09467b48Spatrick assert(BB->getTerminator()->getNumSuccessors() == 1 && 498*09467b48Spatrick "Should have a single succ!"); 499*09467b48Spatrick return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU); 500*09467b48Spatrick } 501*09467b48Spatrick 502*09467b48Spatrick unsigned 503*09467b48Spatrick llvm::SplitAllCriticalEdges(Function &F, 504*09467b48Spatrick const CriticalEdgeSplittingOptions &Options) { 505*09467b48Spatrick unsigned NumBroken = 0; 506*09467b48Spatrick for (BasicBlock &BB : F) { 507*09467b48Spatrick Instruction *TI = BB.getTerminator(); 508*09467b48Spatrick if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI) && 509*09467b48Spatrick !isa<CallBrInst>(TI)) 510*09467b48Spatrick for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 511*09467b48Spatrick if (SplitCriticalEdge(TI, i, Options)) 512*09467b48Spatrick ++NumBroken; 513*09467b48Spatrick } 514*09467b48Spatrick return NumBroken; 515*09467b48Spatrick } 516*09467b48Spatrick 517*09467b48Spatrick BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 518*09467b48Spatrick DominatorTree *DT, LoopInfo *LI, 519*09467b48Spatrick MemorySSAUpdater *MSSAU, const Twine &BBName) { 520*09467b48Spatrick BasicBlock::iterator SplitIt = SplitPt->getIterator(); 521*09467b48Spatrick while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 522*09467b48Spatrick ++SplitIt; 523*09467b48Spatrick std::string Name = BBName.str(); 524*09467b48Spatrick BasicBlock *New = Old->splitBasicBlock( 525*09467b48Spatrick SplitIt, Name.empty() ? Old->getName() + ".split" : Name); 526*09467b48Spatrick 527*09467b48Spatrick // The new block lives in whichever loop the old one did. This preserves 528*09467b48Spatrick // LCSSA as well, because we force the split point to be after any PHI nodes. 529*09467b48Spatrick if (LI) 530*09467b48Spatrick if (Loop *L = LI->getLoopFor(Old)) 531*09467b48Spatrick L->addBasicBlockToLoop(New, *LI); 532*09467b48Spatrick 533*09467b48Spatrick if (DT) 534*09467b48Spatrick // Old dominates New. New node dominates all other nodes dominated by Old. 535*09467b48Spatrick if (DomTreeNode *OldNode = DT->getNode(Old)) { 536*09467b48Spatrick std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 537*09467b48Spatrick 538*09467b48Spatrick DomTreeNode *NewNode = DT->addNewBlock(New, Old); 539*09467b48Spatrick for (DomTreeNode *I : Children) 540*09467b48Spatrick DT->changeImmediateDominator(I, NewNode); 541*09467b48Spatrick } 542*09467b48Spatrick 543*09467b48Spatrick // Move MemoryAccesses still tracked in Old, but part of New now. 544*09467b48Spatrick // Update accesses in successor blocks accordingly. 545*09467b48Spatrick if (MSSAU) 546*09467b48Spatrick MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin())); 547*09467b48Spatrick 548*09467b48Spatrick return New; 549*09467b48Spatrick } 550*09467b48Spatrick 551*09467b48Spatrick /// Update DominatorTree, LoopInfo, and LCCSA analysis information. 552*09467b48Spatrick static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, 553*09467b48Spatrick ArrayRef<BasicBlock *> Preds, 554*09467b48Spatrick DominatorTree *DT, LoopInfo *LI, 555*09467b48Spatrick MemorySSAUpdater *MSSAU, 556*09467b48Spatrick bool PreserveLCSSA, bool &HasLoopExit) { 557*09467b48Spatrick // Update dominator tree if available. 558*09467b48Spatrick if (DT) { 559*09467b48Spatrick if (OldBB == DT->getRootNode()->getBlock()) { 560*09467b48Spatrick assert(NewBB == &NewBB->getParent()->getEntryBlock()); 561*09467b48Spatrick DT->setNewRoot(NewBB); 562*09467b48Spatrick } else { 563*09467b48Spatrick // Split block expects NewBB to have a non-empty set of predecessors. 564*09467b48Spatrick DT->splitBlock(NewBB); 565*09467b48Spatrick } 566*09467b48Spatrick } 567*09467b48Spatrick 568*09467b48Spatrick // Update MemoryPhis after split if MemorySSA is available 569*09467b48Spatrick if (MSSAU) 570*09467b48Spatrick MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds); 571*09467b48Spatrick 572*09467b48Spatrick // The rest of the logic is only relevant for updating the loop structures. 573*09467b48Spatrick if (!LI) 574*09467b48Spatrick return; 575*09467b48Spatrick 576*09467b48Spatrick assert(DT && "DT should be available to update LoopInfo!"); 577*09467b48Spatrick Loop *L = LI->getLoopFor(OldBB); 578*09467b48Spatrick 579*09467b48Spatrick // If we need to preserve loop analyses, collect some information about how 580*09467b48Spatrick // this split will affect loops. 581*09467b48Spatrick bool IsLoopEntry = !!L; 582*09467b48Spatrick bool SplitMakesNewLoopHeader = false; 583*09467b48Spatrick for (BasicBlock *Pred : Preds) { 584*09467b48Spatrick // Preds that are not reachable from entry should not be used to identify if 585*09467b48Spatrick // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks 586*09467b48Spatrick // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader 587*09467b48Spatrick // as true and make the NewBB the header of some loop. This breaks LI. 588*09467b48Spatrick if (!DT->isReachableFromEntry(Pred)) 589*09467b48Spatrick continue; 590*09467b48Spatrick // If we need to preserve LCSSA, determine if any of the preds is a loop 591*09467b48Spatrick // exit. 592*09467b48Spatrick if (PreserveLCSSA) 593*09467b48Spatrick if (Loop *PL = LI->getLoopFor(Pred)) 594*09467b48Spatrick if (!PL->contains(OldBB)) 595*09467b48Spatrick HasLoopExit = true; 596*09467b48Spatrick 597*09467b48Spatrick // If we need to preserve LoopInfo, note whether any of the preds crosses 598*09467b48Spatrick // an interesting loop boundary. 599*09467b48Spatrick if (!L) 600*09467b48Spatrick continue; 601*09467b48Spatrick if (L->contains(Pred)) 602*09467b48Spatrick IsLoopEntry = false; 603*09467b48Spatrick else 604*09467b48Spatrick SplitMakesNewLoopHeader = true; 605*09467b48Spatrick } 606*09467b48Spatrick 607*09467b48Spatrick // Unless we have a loop for OldBB, nothing else to do here. 608*09467b48Spatrick if (!L) 609*09467b48Spatrick return; 610*09467b48Spatrick 611*09467b48Spatrick if (IsLoopEntry) { 612*09467b48Spatrick // Add the new block to the nearest enclosing loop (and not an adjacent 613*09467b48Spatrick // loop). To find this, examine each of the predecessors and determine which 614*09467b48Spatrick // loops enclose them, and select the most-nested loop which contains the 615*09467b48Spatrick // loop containing the block being split. 616*09467b48Spatrick Loop *InnermostPredLoop = nullptr; 617*09467b48Spatrick for (BasicBlock *Pred : Preds) { 618*09467b48Spatrick if (Loop *PredLoop = LI->getLoopFor(Pred)) { 619*09467b48Spatrick // Seek a loop which actually contains the block being split (to avoid 620*09467b48Spatrick // adjacent loops). 621*09467b48Spatrick while (PredLoop && !PredLoop->contains(OldBB)) 622*09467b48Spatrick PredLoop = PredLoop->getParentLoop(); 623*09467b48Spatrick 624*09467b48Spatrick // Select the most-nested of these loops which contains the block. 625*09467b48Spatrick if (PredLoop && PredLoop->contains(OldBB) && 626*09467b48Spatrick (!InnermostPredLoop || 627*09467b48Spatrick InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 628*09467b48Spatrick InnermostPredLoop = PredLoop; 629*09467b48Spatrick } 630*09467b48Spatrick } 631*09467b48Spatrick 632*09467b48Spatrick if (InnermostPredLoop) 633*09467b48Spatrick InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI); 634*09467b48Spatrick } else { 635*09467b48Spatrick L->addBasicBlockToLoop(NewBB, *LI); 636*09467b48Spatrick if (SplitMakesNewLoopHeader) 637*09467b48Spatrick L->moveToHeader(NewBB); 638*09467b48Spatrick } 639*09467b48Spatrick } 640*09467b48Spatrick 641*09467b48Spatrick /// Update the PHI nodes in OrigBB to include the values coming from NewBB. 642*09467b48Spatrick /// This also updates AliasAnalysis, if available. 643*09467b48Spatrick static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, 644*09467b48Spatrick ArrayRef<BasicBlock *> Preds, BranchInst *BI, 645*09467b48Spatrick bool HasLoopExit) { 646*09467b48Spatrick // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB. 647*09467b48Spatrick SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end()); 648*09467b48Spatrick for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) { 649*09467b48Spatrick PHINode *PN = cast<PHINode>(I++); 650*09467b48Spatrick 651*09467b48Spatrick // Check to see if all of the values coming in are the same. If so, we 652*09467b48Spatrick // don't need to create a new PHI node, unless it's needed for LCSSA. 653*09467b48Spatrick Value *InVal = nullptr; 654*09467b48Spatrick if (!HasLoopExit) { 655*09467b48Spatrick InVal = PN->getIncomingValueForBlock(Preds[0]); 656*09467b48Spatrick for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 657*09467b48Spatrick if (!PredSet.count(PN->getIncomingBlock(i))) 658*09467b48Spatrick continue; 659*09467b48Spatrick if (!InVal) 660*09467b48Spatrick InVal = PN->getIncomingValue(i); 661*09467b48Spatrick else if (InVal != PN->getIncomingValue(i)) { 662*09467b48Spatrick InVal = nullptr; 663*09467b48Spatrick break; 664*09467b48Spatrick } 665*09467b48Spatrick } 666*09467b48Spatrick } 667*09467b48Spatrick 668*09467b48Spatrick if (InVal) { 669*09467b48Spatrick // If all incoming values for the new PHI would be the same, just don't 670*09467b48Spatrick // make a new PHI. Instead, just remove the incoming values from the old 671*09467b48Spatrick // PHI. 672*09467b48Spatrick 673*09467b48Spatrick // NOTE! This loop walks backwards for a reason! First off, this minimizes 674*09467b48Spatrick // the cost of removal if we end up removing a large number of values, and 675*09467b48Spatrick // second off, this ensures that the indices for the incoming values 676*09467b48Spatrick // aren't invalidated when we remove one. 677*09467b48Spatrick for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) 678*09467b48Spatrick if (PredSet.count(PN->getIncomingBlock(i))) 679*09467b48Spatrick PN->removeIncomingValue(i, false); 680*09467b48Spatrick 681*09467b48Spatrick // Add an incoming value to the PHI node in the loop for the preheader 682*09467b48Spatrick // edge. 683*09467b48Spatrick PN->addIncoming(InVal, NewBB); 684*09467b48Spatrick continue; 685*09467b48Spatrick } 686*09467b48Spatrick 687*09467b48Spatrick // If the values coming into the block are not the same, we need a new 688*09467b48Spatrick // PHI. 689*09467b48Spatrick // Create the new PHI node, insert it into NewBB at the end of the block 690*09467b48Spatrick PHINode *NewPHI = 691*09467b48Spatrick PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI); 692*09467b48Spatrick 693*09467b48Spatrick // NOTE! This loop walks backwards for a reason! First off, this minimizes 694*09467b48Spatrick // the cost of removal if we end up removing a large number of values, and 695*09467b48Spatrick // second off, this ensures that the indices for the incoming values aren't 696*09467b48Spatrick // invalidated when we remove one. 697*09467b48Spatrick for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 698*09467b48Spatrick BasicBlock *IncomingBB = PN->getIncomingBlock(i); 699*09467b48Spatrick if (PredSet.count(IncomingBB)) { 700*09467b48Spatrick Value *V = PN->removeIncomingValue(i, false); 701*09467b48Spatrick NewPHI->addIncoming(V, IncomingBB); 702*09467b48Spatrick } 703*09467b48Spatrick } 704*09467b48Spatrick 705*09467b48Spatrick PN->addIncoming(NewPHI, NewBB); 706*09467b48Spatrick } 707*09467b48Spatrick } 708*09467b48Spatrick 709*09467b48Spatrick BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 710*09467b48Spatrick ArrayRef<BasicBlock *> Preds, 711*09467b48Spatrick const char *Suffix, DominatorTree *DT, 712*09467b48Spatrick LoopInfo *LI, MemorySSAUpdater *MSSAU, 713*09467b48Spatrick bool PreserveLCSSA) { 714*09467b48Spatrick // Do not attempt to split that which cannot be split. 715*09467b48Spatrick if (!BB->canSplitPredecessors()) 716*09467b48Spatrick return nullptr; 717*09467b48Spatrick 718*09467b48Spatrick // For the landingpads we need to act a bit differently. 719*09467b48Spatrick // Delegate this work to the SplitLandingPadPredecessors. 720*09467b48Spatrick if (BB->isLandingPad()) { 721*09467b48Spatrick SmallVector<BasicBlock*, 2> NewBBs; 722*09467b48Spatrick std::string NewName = std::string(Suffix) + ".split-lp"; 723*09467b48Spatrick 724*09467b48Spatrick SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT, 725*09467b48Spatrick LI, MSSAU, PreserveLCSSA); 726*09467b48Spatrick return NewBBs[0]; 727*09467b48Spatrick } 728*09467b48Spatrick 729*09467b48Spatrick // Create new basic block, insert right before the original block. 730*09467b48Spatrick BasicBlock *NewBB = BasicBlock::Create( 731*09467b48Spatrick BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB); 732*09467b48Spatrick 733*09467b48Spatrick // The new block unconditionally branches to the old block. 734*09467b48Spatrick BranchInst *BI = BranchInst::Create(BB, NewBB); 735*09467b48Spatrick // Splitting the predecessors of a loop header creates a preheader block. 736*09467b48Spatrick if (LI && LI->isLoopHeader(BB)) 737*09467b48Spatrick // Using the loop start line number prevents debuggers stepping into the 738*09467b48Spatrick // loop body for this instruction. 739*09467b48Spatrick BI->setDebugLoc(LI->getLoopFor(BB)->getStartLoc()); 740*09467b48Spatrick else 741*09467b48Spatrick BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc()); 742*09467b48Spatrick 743*09467b48Spatrick // Move the edges from Preds to point to NewBB instead of BB. 744*09467b48Spatrick for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 745*09467b48Spatrick // This is slightly more strict than necessary; the minimum requirement 746*09467b48Spatrick // is that there be no more than one indirectbr branching to BB. And 747*09467b48Spatrick // all BlockAddress uses would need to be updated. 748*09467b48Spatrick assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 749*09467b48Spatrick "Cannot split an edge from an IndirectBrInst"); 750*09467b48Spatrick assert(!isa<CallBrInst>(Preds[i]->getTerminator()) && 751*09467b48Spatrick "Cannot split an edge from a CallBrInst"); 752*09467b48Spatrick Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 753*09467b48Spatrick } 754*09467b48Spatrick 755*09467b48Spatrick // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 756*09467b48Spatrick // node becomes an incoming value for BB's phi node. However, if the Preds 757*09467b48Spatrick // list is empty, we need to insert dummy entries into the PHI nodes in BB to 758*09467b48Spatrick // account for the newly created predecessor. 759*09467b48Spatrick if (Preds.empty()) { 760*09467b48Spatrick // Insert dummy values as the incoming value. 761*09467b48Spatrick for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 762*09467b48Spatrick cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 763*09467b48Spatrick } 764*09467b48Spatrick 765*09467b48Spatrick // Update DominatorTree, LoopInfo, and LCCSA analysis information. 766*09467b48Spatrick bool HasLoopExit = false; 767*09467b48Spatrick UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA, 768*09467b48Spatrick HasLoopExit); 769*09467b48Spatrick 770*09467b48Spatrick if (!Preds.empty()) { 771*09467b48Spatrick // Update the PHI nodes in BB with the values coming from NewBB. 772*09467b48Spatrick UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit); 773*09467b48Spatrick } 774*09467b48Spatrick 775*09467b48Spatrick return NewBB; 776*09467b48Spatrick } 777*09467b48Spatrick 778*09467b48Spatrick void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 779*09467b48Spatrick ArrayRef<BasicBlock *> Preds, 780*09467b48Spatrick const char *Suffix1, const char *Suffix2, 781*09467b48Spatrick SmallVectorImpl<BasicBlock *> &NewBBs, 782*09467b48Spatrick DominatorTree *DT, LoopInfo *LI, 783*09467b48Spatrick MemorySSAUpdater *MSSAU, 784*09467b48Spatrick bool PreserveLCSSA) { 785*09467b48Spatrick assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!"); 786*09467b48Spatrick 787*09467b48Spatrick // Create a new basic block for OrigBB's predecessors listed in Preds. Insert 788*09467b48Spatrick // it right before the original block. 789*09467b48Spatrick BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(), 790*09467b48Spatrick OrigBB->getName() + Suffix1, 791*09467b48Spatrick OrigBB->getParent(), OrigBB); 792*09467b48Spatrick NewBBs.push_back(NewBB1); 793*09467b48Spatrick 794*09467b48Spatrick // The new block unconditionally branches to the old block. 795*09467b48Spatrick BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1); 796*09467b48Spatrick BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 797*09467b48Spatrick 798*09467b48Spatrick // Move the edges from Preds to point to NewBB1 instead of OrigBB. 799*09467b48Spatrick for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 800*09467b48Spatrick // This is slightly more strict than necessary; the minimum requirement 801*09467b48Spatrick // is that there be no more than one indirectbr branching to BB. And 802*09467b48Spatrick // all BlockAddress uses would need to be updated. 803*09467b48Spatrick assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 804*09467b48Spatrick "Cannot split an edge from an IndirectBrInst"); 805*09467b48Spatrick Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1); 806*09467b48Spatrick } 807*09467b48Spatrick 808*09467b48Spatrick bool HasLoopExit = false; 809*09467b48Spatrick UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA, 810*09467b48Spatrick HasLoopExit); 811*09467b48Spatrick 812*09467b48Spatrick // Update the PHI nodes in OrigBB with the values coming from NewBB1. 813*09467b48Spatrick UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit); 814*09467b48Spatrick 815*09467b48Spatrick // Move the remaining edges from OrigBB to point to NewBB2. 816*09467b48Spatrick SmallVector<BasicBlock*, 8> NewBB2Preds; 817*09467b48Spatrick for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB); 818*09467b48Spatrick i != e; ) { 819*09467b48Spatrick BasicBlock *Pred = *i++; 820*09467b48Spatrick if (Pred == NewBB1) continue; 821*09467b48Spatrick assert(!isa<IndirectBrInst>(Pred->getTerminator()) && 822*09467b48Spatrick "Cannot split an edge from an IndirectBrInst"); 823*09467b48Spatrick NewBB2Preds.push_back(Pred); 824*09467b48Spatrick e = pred_end(OrigBB); 825*09467b48Spatrick } 826*09467b48Spatrick 827*09467b48Spatrick BasicBlock *NewBB2 = nullptr; 828*09467b48Spatrick if (!NewBB2Preds.empty()) { 829*09467b48Spatrick // Create another basic block for the rest of OrigBB's predecessors. 830*09467b48Spatrick NewBB2 = BasicBlock::Create(OrigBB->getContext(), 831*09467b48Spatrick OrigBB->getName() + Suffix2, 832*09467b48Spatrick OrigBB->getParent(), OrigBB); 833*09467b48Spatrick NewBBs.push_back(NewBB2); 834*09467b48Spatrick 835*09467b48Spatrick // The new block unconditionally branches to the old block. 836*09467b48Spatrick BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2); 837*09467b48Spatrick BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 838*09467b48Spatrick 839*09467b48Spatrick // Move the remaining edges from OrigBB to point to NewBB2. 840*09467b48Spatrick for (BasicBlock *NewBB2Pred : NewBB2Preds) 841*09467b48Spatrick NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2); 842*09467b48Spatrick 843*09467b48Spatrick // Update DominatorTree, LoopInfo, and LCCSA analysis information. 844*09467b48Spatrick HasLoopExit = false; 845*09467b48Spatrick UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU, 846*09467b48Spatrick PreserveLCSSA, HasLoopExit); 847*09467b48Spatrick 848*09467b48Spatrick // Update the PHI nodes in OrigBB with the values coming from NewBB2. 849*09467b48Spatrick UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit); 850*09467b48Spatrick } 851*09467b48Spatrick 852*09467b48Spatrick LandingPadInst *LPad = OrigBB->getLandingPadInst(); 853*09467b48Spatrick Instruction *Clone1 = LPad->clone(); 854*09467b48Spatrick Clone1->setName(Twine("lpad") + Suffix1); 855*09467b48Spatrick NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1); 856*09467b48Spatrick 857*09467b48Spatrick if (NewBB2) { 858*09467b48Spatrick Instruction *Clone2 = LPad->clone(); 859*09467b48Spatrick Clone2->setName(Twine("lpad") + Suffix2); 860*09467b48Spatrick NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2); 861*09467b48Spatrick 862*09467b48Spatrick // Create a PHI node for the two cloned landingpad instructions only 863*09467b48Spatrick // if the original landingpad instruction has some uses. 864*09467b48Spatrick if (!LPad->use_empty()) { 865*09467b48Spatrick assert(!LPad->getType()->isTokenTy() && 866*09467b48Spatrick "Split cannot be applied if LPad is token type. Otherwise an " 867*09467b48Spatrick "invalid PHINode of token type would be created."); 868*09467b48Spatrick PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad); 869*09467b48Spatrick PN->addIncoming(Clone1, NewBB1); 870*09467b48Spatrick PN->addIncoming(Clone2, NewBB2); 871*09467b48Spatrick LPad->replaceAllUsesWith(PN); 872*09467b48Spatrick } 873*09467b48Spatrick LPad->eraseFromParent(); 874*09467b48Spatrick } else { 875*09467b48Spatrick // There is no second clone. Just replace the landing pad with the first 876*09467b48Spatrick // clone. 877*09467b48Spatrick LPad->replaceAllUsesWith(Clone1); 878*09467b48Spatrick LPad->eraseFromParent(); 879*09467b48Spatrick } 880*09467b48Spatrick } 881*09467b48Spatrick 882*09467b48Spatrick ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, 883*09467b48Spatrick BasicBlock *Pred, 884*09467b48Spatrick DomTreeUpdater *DTU) { 885*09467b48Spatrick Instruction *UncondBranch = Pred->getTerminator(); 886*09467b48Spatrick // Clone the return and add it to the end of the predecessor. 887*09467b48Spatrick Instruction *NewRet = RI->clone(); 888*09467b48Spatrick Pred->getInstList().push_back(NewRet); 889*09467b48Spatrick 890*09467b48Spatrick // If the return instruction returns a value, and if the value was a 891*09467b48Spatrick // PHI node in "BB", propagate the right value into the return. 892*09467b48Spatrick for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end(); 893*09467b48Spatrick i != e; ++i) { 894*09467b48Spatrick Value *V = *i; 895*09467b48Spatrick Instruction *NewBC = nullptr; 896*09467b48Spatrick if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) { 897*09467b48Spatrick // Return value might be bitcasted. Clone and insert it before the 898*09467b48Spatrick // return instruction. 899*09467b48Spatrick V = BCI->getOperand(0); 900*09467b48Spatrick NewBC = BCI->clone(); 901*09467b48Spatrick Pred->getInstList().insert(NewRet->getIterator(), NewBC); 902*09467b48Spatrick *i = NewBC; 903*09467b48Spatrick } 904*09467b48Spatrick if (PHINode *PN = dyn_cast<PHINode>(V)) { 905*09467b48Spatrick if (PN->getParent() == BB) { 906*09467b48Spatrick if (NewBC) 907*09467b48Spatrick NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred)); 908*09467b48Spatrick else 909*09467b48Spatrick *i = PN->getIncomingValueForBlock(Pred); 910*09467b48Spatrick } 911*09467b48Spatrick } 912*09467b48Spatrick } 913*09467b48Spatrick 914*09467b48Spatrick // Update any PHI nodes in the returning block to realize that we no 915*09467b48Spatrick // longer branch to them. 916*09467b48Spatrick BB->removePredecessor(Pred); 917*09467b48Spatrick UncondBranch->eraseFromParent(); 918*09467b48Spatrick 919*09467b48Spatrick if (DTU) 920*09467b48Spatrick DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}}); 921*09467b48Spatrick 922*09467b48Spatrick return cast<ReturnInst>(NewRet); 923*09467b48Spatrick } 924*09467b48Spatrick 925*09467b48Spatrick Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond, 926*09467b48Spatrick Instruction *SplitBefore, 927*09467b48Spatrick bool Unreachable, 928*09467b48Spatrick MDNode *BranchWeights, 929*09467b48Spatrick DominatorTree *DT, LoopInfo *LI, 930*09467b48Spatrick BasicBlock *ThenBlock) { 931*09467b48Spatrick BasicBlock *Head = SplitBefore->getParent(); 932*09467b48Spatrick BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 933*09467b48Spatrick Instruction *HeadOldTerm = Head->getTerminator(); 934*09467b48Spatrick LLVMContext &C = Head->getContext(); 935*09467b48Spatrick Instruction *CheckTerm; 936*09467b48Spatrick bool CreateThenBlock = (ThenBlock == nullptr); 937*09467b48Spatrick if (CreateThenBlock) { 938*09467b48Spatrick ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 939*09467b48Spatrick if (Unreachable) 940*09467b48Spatrick CheckTerm = new UnreachableInst(C, ThenBlock); 941*09467b48Spatrick else 942*09467b48Spatrick CheckTerm = BranchInst::Create(Tail, ThenBlock); 943*09467b48Spatrick CheckTerm->setDebugLoc(SplitBefore->getDebugLoc()); 944*09467b48Spatrick } else 945*09467b48Spatrick CheckTerm = ThenBlock->getTerminator(); 946*09467b48Spatrick BranchInst *HeadNewTerm = 947*09467b48Spatrick BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond); 948*09467b48Spatrick HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 949*09467b48Spatrick ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 950*09467b48Spatrick 951*09467b48Spatrick if (DT) { 952*09467b48Spatrick if (DomTreeNode *OldNode = DT->getNode(Head)) { 953*09467b48Spatrick std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 954*09467b48Spatrick 955*09467b48Spatrick DomTreeNode *NewNode = DT->addNewBlock(Tail, Head); 956*09467b48Spatrick for (DomTreeNode *Child : Children) 957*09467b48Spatrick DT->changeImmediateDominator(Child, NewNode); 958*09467b48Spatrick 959*09467b48Spatrick // Head dominates ThenBlock. 960*09467b48Spatrick if (CreateThenBlock) 961*09467b48Spatrick DT->addNewBlock(ThenBlock, Head); 962*09467b48Spatrick else 963*09467b48Spatrick DT->changeImmediateDominator(ThenBlock, Head); 964*09467b48Spatrick } 965*09467b48Spatrick } 966*09467b48Spatrick 967*09467b48Spatrick if (LI) { 968*09467b48Spatrick if (Loop *L = LI->getLoopFor(Head)) { 969*09467b48Spatrick L->addBasicBlockToLoop(ThenBlock, *LI); 970*09467b48Spatrick L->addBasicBlockToLoop(Tail, *LI); 971*09467b48Spatrick } 972*09467b48Spatrick } 973*09467b48Spatrick 974*09467b48Spatrick return CheckTerm; 975*09467b48Spatrick } 976*09467b48Spatrick 977*09467b48Spatrick void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, 978*09467b48Spatrick Instruction **ThenTerm, 979*09467b48Spatrick Instruction **ElseTerm, 980*09467b48Spatrick MDNode *BranchWeights) { 981*09467b48Spatrick BasicBlock *Head = SplitBefore->getParent(); 982*09467b48Spatrick BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 983*09467b48Spatrick Instruction *HeadOldTerm = Head->getTerminator(); 984*09467b48Spatrick LLVMContext &C = Head->getContext(); 985*09467b48Spatrick BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 986*09467b48Spatrick BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 987*09467b48Spatrick *ThenTerm = BranchInst::Create(Tail, ThenBlock); 988*09467b48Spatrick (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 989*09467b48Spatrick *ElseTerm = BranchInst::Create(Tail, ElseBlock); 990*09467b48Spatrick (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 991*09467b48Spatrick BranchInst *HeadNewTerm = 992*09467b48Spatrick BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond); 993*09467b48Spatrick HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 994*09467b48Spatrick ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 995*09467b48Spatrick } 996*09467b48Spatrick 997*09467b48Spatrick Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 998*09467b48Spatrick BasicBlock *&IfFalse) { 999*09467b48Spatrick PHINode *SomePHI = dyn_cast<PHINode>(BB->begin()); 1000*09467b48Spatrick BasicBlock *Pred1 = nullptr; 1001*09467b48Spatrick BasicBlock *Pred2 = nullptr; 1002*09467b48Spatrick 1003*09467b48Spatrick if (SomePHI) { 1004*09467b48Spatrick if (SomePHI->getNumIncomingValues() != 2) 1005*09467b48Spatrick return nullptr; 1006*09467b48Spatrick Pred1 = SomePHI->getIncomingBlock(0); 1007*09467b48Spatrick Pred2 = SomePHI->getIncomingBlock(1); 1008*09467b48Spatrick } else { 1009*09467b48Spatrick pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1010*09467b48Spatrick if (PI == PE) // No predecessor 1011*09467b48Spatrick return nullptr; 1012*09467b48Spatrick Pred1 = *PI++; 1013*09467b48Spatrick if (PI == PE) // Only one predecessor 1014*09467b48Spatrick return nullptr; 1015*09467b48Spatrick Pred2 = *PI++; 1016*09467b48Spatrick if (PI != PE) // More than two predecessors 1017*09467b48Spatrick return nullptr; 1018*09467b48Spatrick } 1019*09467b48Spatrick 1020*09467b48Spatrick // We can only handle branches. Other control flow will be lowered to 1021*09467b48Spatrick // branches if possible anyway. 1022*09467b48Spatrick BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 1023*09467b48Spatrick BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 1024*09467b48Spatrick if (!Pred1Br || !Pred2Br) 1025*09467b48Spatrick return nullptr; 1026*09467b48Spatrick 1027*09467b48Spatrick // Eliminate code duplication by ensuring that Pred1Br is conditional if 1028*09467b48Spatrick // either are. 1029*09467b48Spatrick if (Pred2Br->isConditional()) { 1030*09467b48Spatrick // If both branches are conditional, we don't have an "if statement". In 1031*09467b48Spatrick // reality, we could transform this case, but since the condition will be 1032*09467b48Spatrick // required anyway, we stand no chance of eliminating it, so the xform is 1033*09467b48Spatrick // probably not profitable. 1034*09467b48Spatrick if (Pred1Br->isConditional()) 1035*09467b48Spatrick return nullptr; 1036*09467b48Spatrick 1037*09467b48Spatrick std::swap(Pred1, Pred2); 1038*09467b48Spatrick std::swap(Pred1Br, Pred2Br); 1039*09467b48Spatrick } 1040*09467b48Spatrick 1041*09467b48Spatrick if (Pred1Br->isConditional()) { 1042*09467b48Spatrick // The only thing we have to watch out for here is to make sure that Pred2 1043*09467b48Spatrick // doesn't have incoming edges from other blocks. If it does, the condition 1044*09467b48Spatrick // doesn't dominate BB. 1045*09467b48Spatrick if (!Pred2->getSinglePredecessor()) 1046*09467b48Spatrick return nullptr; 1047*09467b48Spatrick 1048*09467b48Spatrick // If we found a conditional branch predecessor, make sure that it branches 1049*09467b48Spatrick // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 1050*09467b48Spatrick if (Pred1Br->getSuccessor(0) == BB && 1051*09467b48Spatrick Pred1Br->getSuccessor(1) == Pred2) { 1052*09467b48Spatrick IfTrue = Pred1; 1053*09467b48Spatrick IfFalse = Pred2; 1054*09467b48Spatrick } else if (Pred1Br->getSuccessor(0) == Pred2 && 1055*09467b48Spatrick Pred1Br->getSuccessor(1) == BB) { 1056*09467b48Spatrick IfTrue = Pred2; 1057*09467b48Spatrick IfFalse = Pred1; 1058*09467b48Spatrick } else { 1059*09467b48Spatrick // We know that one arm of the conditional goes to BB, so the other must 1060*09467b48Spatrick // go somewhere unrelated, and this must not be an "if statement". 1061*09467b48Spatrick return nullptr; 1062*09467b48Spatrick } 1063*09467b48Spatrick 1064*09467b48Spatrick return Pred1Br->getCondition(); 1065*09467b48Spatrick } 1066*09467b48Spatrick 1067*09467b48Spatrick // Ok, if we got here, both predecessors end with an unconditional branch to 1068*09467b48Spatrick // BB. Don't panic! If both blocks only have a single (identical) 1069*09467b48Spatrick // predecessor, and THAT is a conditional branch, then we're all ok! 1070*09467b48Spatrick BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 1071*09467b48Spatrick if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor()) 1072*09467b48Spatrick return nullptr; 1073*09467b48Spatrick 1074*09467b48Spatrick // Otherwise, if this is a conditional branch, then we can use it! 1075*09467b48Spatrick BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 1076*09467b48Spatrick if (!BI) return nullptr; 1077*09467b48Spatrick 1078*09467b48Spatrick assert(BI->isConditional() && "Two successors but not conditional?"); 1079*09467b48Spatrick if (BI->getSuccessor(0) == Pred1) { 1080*09467b48Spatrick IfTrue = Pred1; 1081*09467b48Spatrick IfFalse = Pred2; 1082*09467b48Spatrick } else { 1083*09467b48Spatrick IfTrue = Pred2; 1084*09467b48Spatrick IfFalse = Pred1; 1085*09467b48Spatrick } 1086*09467b48Spatrick return BI->getCondition(); 1087*09467b48Spatrick } 1088