10b57cec5SDimitry Andric //===-- Sink.cpp - Code Sinking -------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This pass moves instructions into successor blocks, when possible, so that 100b57cec5SDimitry Andric // they aren't executed on paths where their results aren't needed. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 130b57cec5SDimitry Andric 140b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/Sink.h" 150b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 160b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 170b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 180b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 19480093f4SDimitry Andric #include "llvm/InitializePasses.h" 200b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 210b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 220b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h" 230b57cec5SDimitry Andric using namespace llvm; 240b57cec5SDimitry Andric 250b57cec5SDimitry Andric #define DEBUG_TYPE "sink" 260b57cec5SDimitry Andric 270b57cec5SDimitry Andric STATISTIC(NumSunk, "Number of instructions sunk"); 280b57cec5SDimitry Andric STATISTIC(NumSinkIter, "Number of sinking iterations"); 290b57cec5SDimitry Andric 300b57cec5SDimitry Andric static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA, 310b57cec5SDimitry Andric SmallPtrSetImpl<Instruction *> &Stores) { 320b57cec5SDimitry Andric 330b57cec5SDimitry Andric if (Inst->mayWriteToMemory()) { 340b57cec5SDimitry Andric Stores.insert(Inst); 350b57cec5SDimitry Andric return false; 360b57cec5SDimitry Andric } 370b57cec5SDimitry Andric 380b57cec5SDimitry Andric if (LoadInst *L = dyn_cast<LoadInst>(Inst)) { 390b57cec5SDimitry Andric MemoryLocation Loc = MemoryLocation::get(L); 400b57cec5SDimitry Andric for (Instruction *S : Stores) 410b57cec5SDimitry Andric if (isModSet(AA.getModRefInfo(S, Loc))) 420b57cec5SDimitry Andric return false; 430b57cec5SDimitry Andric } 440b57cec5SDimitry Andric 450b57cec5SDimitry Andric if (Inst->isTerminator() || isa<PHINode>(Inst) || Inst->isEHPad() || 4681ad6265SDimitry Andric Inst->mayThrow() || !Inst->willReturn()) 470b57cec5SDimitry Andric return false; 480b57cec5SDimitry Andric 490b57cec5SDimitry Andric if (auto *Call = dyn_cast<CallBase>(Inst)) { 500b57cec5SDimitry Andric // Convergent operations cannot be made control-dependent on additional 510b57cec5SDimitry Andric // values. 52480093f4SDimitry Andric if (Call->isConvergent()) 530b57cec5SDimitry Andric return false; 540b57cec5SDimitry Andric 550b57cec5SDimitry Andric for (Instruction *S : Stores) 560b57cec5SDimitry Andric if (isModSet(AA.getModRefInfo(S, Call))) 570b57cec5SDimitry Andric return false; 580b57cec5SDimitry Andric } 590b57cec5SDimitry Andric 600b57cec5SDimitry Andric return true; 610b57cec5SDimitry Andric } 620b57cec5SDimitry Andric 630b57cec5SDimitry Andric /// IsAcceptableTarget - Return true if it is possible to sink the instruction 640b57cec5SDimitry Andric /// in the specified basic block. 650b57cec5SDimitry Andric static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo, 660b57cec5SDimitry Andric DominatorTree &DT, LoopInfo &LI) { 670b57cec5SDimitry Andric assert(Inst && "Instruction to be sunk is null"); 680b57cec5SDimitry Andric assert(SuccToSinkTo && "Candidate sink target is null"); 690b57cec5SDimitry Andric 70*5f757f3fSDimitry Andric // It's never legal to sink an instruction into an EH-pad block. 71*5f757f3fSDimitry Andric if (SuccToSinkTo->isEHPad()) 720b57cec5SDimitry Andric return false; 730b57cec5SDimitry Andric 740b57cec5SDimitry Andric // If the block has multiple predecessors, this would introduce computation 750b57cec5SDimitry Andric // on different code paths. We could split the critical edge, but for now we 760b57cec5SDimitry Andric // just punt. 770b57cec5SDimitry Andric // FIXME: Split critical edges if not backedges. 780b57cec5SDimitry Andric if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) { 790b57cec5SDimitry Andric // We cannot sink a load across a critical edge - there may be stores in 800b57cec5SDimitry Andric // other code paths. 81bdd1243dSDimitry Andric if (Inst->mayReadFromMemory() && 82bdd1243dSDimitry Andric !Inst->hasMetadata(LLVMContext::MD_invariant_load)) 830b57cec5SDimitry Andric return false; 840b57cec5SDimitry Andric 850b57cec5SDimitry Andric // We don't want to sink across a critical edge if we don't dominate the 860b57cec5SDimitry Andric // successor. We could be introducing calculations to new code paths. 870b57cec5SDimitry Andric if (!DT.dominates(Inst->getParent(), SuccToSinkTo)) 880b57cec5SDimitry Andric return false; 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric // Don't sink instructions into a loop. 910b57cec5SDimitry Andric Loop *succ = LI.getLoopFor(SuccToSinkTo); 920b57cec5SDimitry Andric Loop *cur = LI.getLoopFor(Inst->getParent()); 930b57cec5SDimitry Andric if (succ != nullptr && succ != cur) 940b57cec5SDimitry Andric return false; 950b57cec5SDimitry Andric } 960b57cec5SDimitry Andric 97e8d8bef9SDimitry Andric return true; 980b57cec5SDimitry Andric } 990b57cec5SDimitry Andric 1000b57cec5SDimitry Andric /// SinkInstruction - Determine whether it is safe to sink the specified machine 1010b57cec5SDimitry Andric /// instruction out of its current block into a successor. 1020b57cec5SDimitry Andric static bool SinkInstruction(Instruction *Inst, 1030b57cec5SDimitry Andric SmallPtrSetImpl<Instruction *> &Stores, 1040b57cec5SDimitry Andric DominatorTree &DT, LoopInfo &LI, AAResults &AA) { 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric // Don't sink static alloca instructions. CodeGen assumes allocas outside the 1070b57cec5SDimitry Andric // entry block are dynamically sized stack objects. 1080b57cec5SDimitry Andric if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst)) 1090b57cec5SDimitry Andric if (AI->isStaticAlloca()) 1100b57cec5SDimitry Andric return false; 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric // Check if it's safe to move the instruction. 1130b57cec5SDimitry Andric if (!isSafeToMove(Inst, AA, Stores)) 1140b57cec5SDimitry Andric return false; 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric // FIXME: This should include support for sinking instructions within the 1170b57cec5SDimitry Andric // block they are currently in to shorten the live ranges. We often get 1180b57cec5SDimitry Andric // instructions sunk into the top of a large block, but it would be better to 1190b57cec5SDimitry Andric // also sink them down before their first use in the block. This xform has to 1200b57cec5SDimitry Andric // be careful not to *increase* register pressure though, e.g. sinking 1210b57cec5SDimitry Andric // "x = y + z" down if it kills y and z would increase the live ranges of y 1220b57cec5SDimitry Andric // and z and only shrink the live range of x. 1230b57cec5SDimitry Andric 1240b57cec5SDimitry Andric // SuccToSinkTo - This is the successor to sink this instruction to, once we 1250b57cec5SDimitry Andric // decide. 1260b57cec5SDimitry Andric BasicBlock *SuccToSinkTo = nullptr; 1270b57cec5SDimitry Andric 128e8d8bef9SDimitry Andric // Find the nearest common dominator of all users as the candidate. 129e8d8bef9SDimitry Andric BasicBlock *BB = Inst->getParent(); 130e8d8bef9SDimitry Andric for (Use &U : Inst->uses()) { 131e8d8bef9SDimitry Andric Instruction *UseInst = cast<Instruction>(U.getUser()); 132e8d8bef9SDimitry Andric BasicBlock *UseBlock = UseInst->getParent(); 133e8d8bef9SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(UseInst)) { 134e8d8bef9SDimitry Andric // PHI nodes use the operand in the predecessor block, not the block with 135e8d8bef9SDimitry Andric // the PHI. 136e8d8bef9SDimitry Andric unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo()); 137e8d8bef9SDimitry Andric UseBlock = PN->getIncomingBlock(Num); 138e8d8bef9SDimitry Andric } 139*5f757f3fSDimitry Andric // Don't worry about dead users. 140*5f757f3fSDimitry Andric if (!DT.isReachableFromEntry(UseBlock)) 141*5f757f3fSDimitry Andric continue; 142*5f757f3fSDimitry Andric 143e8d8bef9SDimitry Andric if (SuccToSinkTo) 144e8d8bef9SDimitry Andric SuccToSinkTo = DT.findNearestCommonDominator(SuccToSinkTo, UseBlock); 145e8d8bef9SDimitry Andric else 146e8d8bef9SDimitry Andric SuccToSinkTo = UseBlock; 147e8d8bef9SDimitry Andric // The current basic block needs to dominate the candidate. 148e8d8bef9SDimitry Andric if (!DT.dominates(BB, SuccToSinkTo)) 149e8d8bef9SDimitry Andric return false; 1500b57cec5SDimitry Andric } 1510b57cec5SDimitry Andric 152e8d8bef9SDimitry Andric if (SuccToSinkTo) { 153e8d8bef9SDimitry Andric // The nearest common dominator may be in a parent loop of BB, which may not 154e8d8bef9SDimitry Andric // be beneficial. Find an ancestor. 155e8d8bef9SDimitry Andric while (SuccToSinkTo != BB && 156e8d8bef9SDimitry Andric !IsAcceptableTarget(Inst, SuccToSinkTo, DT, LI)) 157e8d8bef9SDimitry Andric SuccToSinkTo = DT.getNode(SuccToSinkTo)->getIDom()->getBlock(); 158e8d8bef9SDimitry Andric if (SuccToSinkTo == BB) 159e8d8bef9SDimitry Andric SuccToSinkTo = nullptr; 1600b57cec5SDimitry Andric } 1610b57cec5SDimitry Andric 1620b57cec5SDimitry Andric // If we couldn't find a block to sink to, ignore this instruction. 1630b57cec5SDimitry Andric if (!SuccToSinkTo) 1640b57cec5SDimitry Andric return false; 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Sink" << *Inst << " ("; 1670b57cec5SDimitry Andric Inst->getParent()->printAsOperand(dbgs(), false); dbgs() << " -> "; 1680b57cec5SDimitry Andric SuccToSinkTo->printAsOperand(dbgs(), false); dbgs() << ")\n"); 1690b57cec5SDimitry Andric 1700b57cec5SDimitry Andric // Move the instruction. 1710b57cec5SDimitry Andric Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt()); 1720b57cec5SDimitry Andric return true; 1730b57cec5SDimitry Andric } 1740b57cec5SDimitry Andric 1750b57cec5SDimitry Andric static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, 1760b57cec5SDimitry Andric AAResults &AA) { 1770b57cec5SDimitry Andric // Don't bother sinking code out of unreachable blocks. In addition to being 1780b57cec5SDimitry Andric // unprofitable, it can also lead to infinite looping, because in an 1790b57cec5SDimitry Andric // unreachable loop there may be nowhere to stop. 1800b57cec5SDimitry Andric if (!DT.isReachableFromEntry(&BB)) return false; 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric bool MadeChange = false; 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric // Walk the basic block bottom-up. Remember if we saw a store. 1850b57cec5SDimitry Andric BasicBlock::iterator I = BB.end(); 1860b57cec5SDimitry Andric --I; 1870b57cec5SDimitry Andric bool ProcessedBegin = false; 1880b57cec5SDimitry Andric SmallPtrSet<Instruction *, 8> Stores; 1890b57cec5SDimitry Andric do { 1900b57cec5SDimitry Andric Instruction *Inst = &*I; // The instruction to sink. 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric // Predecrement I (if it's not begin) so that it isn't invalidated by 1930b57cec5SDimitry Andric // sinking. 1940b57cec5SDimitry Andric ProcessedBegin = I == BB.begin(); 1950b57cec5SDimitry Andric if (!ProcessedBegin) 1960b57cec5SDimitry Andric --I; 1970b57cec5SDimitry Andric 198fe6060f1SDimitry Andric if (Inst->isDebugOrPseudoInst()) 1990b57cec5SDimitry Andric continue; 2000b57cec5SDimitry Andric 2010b57cec5SDimitry Andric if (SinkInstruction(Inst, Stores, DT, LI, AA)) { 2020b57cec5SDimitry Andric ++NumSunk; 2030b57cec5SDimitry Andric MadeChange = true; 2040b57cec5SDimitry Andric } 2050b57cec5SDimitry Andric 2060b57cec5SDimitry Andric // If we just processed the first instruction in the block, we're done. 2070b57cec5SDimitry Andric } while (!ProcessedBegin); 2080b57cec5SDimitry Andric 2090b57cec5SDimitry Andric return MadeChange; 2100b57cec5SDimitry Andric } 2110b57cec5SDimitry Andric 2120b57cec5SDimitry Andric static bool iterativelySinkInstructions(Function &F, DominatorTree &DT, 2130b57cec5SDimitry Andric LoopInfo &LI, AAResults &AA) { 2140b57cec5SDimitry Andric bool MadeChange, EverMadeChange = false; 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric do { 2170b57cec5SDimitry Andric MadeChange = false; 2180b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n"); 2190b57cec5SDimitry Andric // Process all basic blocks. 2200b57cec5SDimitry Andric for (BasicBlock &I : F) 2210b57cec5SDimitry Andric MadeChange |= ProcessBlock(I, DT, LI, AA); 2220b57cec5SDimitry Andric EverMadeChange |= MadeChange; 2230b57cec5SDimitry Andric NumSinkIter++; 2240b57cec5SDimitry Andric } while (MadeChange); 2250b57cec5SDimitry Andric 2260b57cec5SDimitry Andric return EverMadeChange; 2270b57cec5SDimitry Andric } 2280b57cec5SDimitry Andric 2290b57cec5SDimitry Andric PreservedAnalyses SinkingPass::run(Function &F, FunctionAnalysisManager &AM) { 2300b57cec5SDimitry Andric auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 2310b57cec5SDimitry Andric auto &LI = AM.getResult<LoopAnalysis>(F); 2320b57cec5SDimitry Andric auto &AA = AM.getResult<AAManager>(F); 2330b57cec5SDimitry Andric 2340b57cec5SDimitry Andric if (!iterativelySinkInstructions(F, DT, LI, AA)) 2350b57cec5SDimitry Andric return PreservedAnalyses::all(); 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric PreservedAnalyses PA; 2380b57cec5SDimitry Andric PA.preserveSet<CFGAnalyses>(); 2390b57cec5SDimitry Andric return PA; 2400b57cec5SDimitry Andric } 2410b57cec5SDimitry Andric 2420b57cec5SDimitry Andric namespace { 2430b57cec5SDimitry Andric class SinkingLegacyPass : public FunctionPass { 2440b57cec5SDimitry Andric public: 2450b57cec5SDimitry Andric static char ID; // Pass identification 2460b57cec5SDimitry Andric SinkingLegacyPass() : FunctionPass(ID) { 2470b57cec5SDimitry Andric initializeSinkingLegacyPassPass(*PassRegistry::getPassRegistry()); 2480b57cec5SDimitry Andric } 2490b57cec5SDimitry Andric 2500b57cec5SDimitry Andric bool runOnFunction(Function &F) override { 2510b57cec5SDimitry Andric auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2520b57cec5SDimitry Andric auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2530b57cec5SDimitry Andric auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2540b57cec5SDimitry Andric 2550b57cec5SDimitry Andric return iterativelySinkInstructions(F, DT, LI, AA); 2560b57cec5SDimitry Andric } 2570b57cec5SDimitry Andric 2580b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 2590b57cec5SDimitry Andric AU.setPreservesCFG(); 2600b57cec5SDimitry Andric FunctionPass::getAnalysisUsage(AU); 2610b57cec5SDimitry Andric AU.addRequired<AAResultsWrapperPass>(); 2620b57cec5SDimitry Andric AU.addRequired<DominatorTreeWrapperPass>(); 2630b57cec5SDimitry Andric AU.addRequired<LoopInfoWrapperPass>(); 2640b57cec5SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>(); 2650b57cec5SDimitry Andric AU.addPreserved<LoopInfoWrapperPass>(); 2660b57cec5SDimitry Andric } 2670b57cec5SDimitry Andric }; 2680b57cec5SDimitry Andric } // end anonymous namespace 2690b57cec5SDimitry Andric 2700b57cec5SDimitry Andric char SinkingLegacyPass::ID = 0; 2710b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false) 2720b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 2730b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2740b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2750b57cec5SDimitry Andric INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false) 2760b57cec5SDimitry Andric 2770b57cec5SDimitry Andric FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); } 278