LLVM API Documentation

Sink.cpp
Go to the documentation of this file.
00001 //===-- Sink.cpp - Code Sinking -------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass moves instructions into successor blocks, when possible, so that
00011 // they aren't executed on paths where their results aren't needed.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/ADT/Statistic.h"
00017 #include "llvm/Analysis/AliasAnalysis.h"
00018 #include "llvm/Analysis/LoopInfo.h"
00019 #include "llvm/Analysis/ValueTracking.h"
00020 #include "llvm/IR/CFG.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/Dominators.h"
00023 #include "llvm/IR/IntrinsicInst.h"
00024 #include "llvm/Support/Debug.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 using namespace llvm;
00027 
00028 #define DEBUG_TYPE "sink"
00029 
00030 STATISTIC(NumSunk, "Number of instructions sunk");
00031 STATISTIC(NumSinkIter, "Number of sinking iterations");
00032 
00033 namespace {
00034   class Sinking : public FunctionPass {
00035     DominatorTree *DT;
00036     LoopInfo *LI;
00037     AliasAnalysis *AA;
00038     const DataLayout *DL;
00039 
00040   public:
00041     static char ID; // Pass identification
00042     Sinking() : FunctionPass(ID) {
00043       initializeSinkingPass(*PassRegistry::getPassRegistry());
00044     }
00045 
00046     bool runOnFunction(Function &F) override;
00047 
00048     void getAnalysisUsage(AnalysisUsage &AU) const override {
00049       AU.setPreservesCFG();
00050       FunctionPass::getAnalysisUsage(AU);
00051       AU.addRequired<AliasAnalysis>();
00052       AU.addRequired<DominatorTreeWrapperPass>();
00053       AU.addRequired<LoopInfo>();
00054       AU.addPreserved<DominatorTreeWrapperPass>();
00055       AU.addPreserved<LoopInfo>();
00056     }
00057   private:
00058     bool ProcessBlock(BasicBlock &BB);
00059     bool SinkInstruction(Instruction *I, SmallPtrSetImpl<Instruction*> &Stores);
00060     bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
00061     bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
00062   };
00063 } // end anonymous namespace
00064 
00065 char Sinking::ID = 0;
00066 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
00067 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
00068 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00069 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00070 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
00071 
00072 FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
00073 
00074 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
00075 /// occur in blocks dominated by the specified block.
00076 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
00077                                       BasicBlock *BB) const {
00078   // Ignoring debug uses is necessary so debug info doesn't affect the code.
00079   // This may leave a referencing dbg_value in the original block, before
00080   // the definition of the vreg.  Dwarf generator handles this although the
00081   // user might not get the right info at runtime.
00082   for (Use &U : Inst->uses()) {
00083     // Determine the block of the use.
00084     Instruction *UseInst = cast<Instruction>(U.getUser());
00085     BasicBlock *UseBlock = UseInst->getParent();
00086     if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
00087       // PHI nodes use the operand in the predecessor block, not the block with
00088       // the PHI.
00089       unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
00090       UseBlock = PN->getIncomingBlock(Num);
00091     }
00092     // Check that it dominates.
00093     if (!DT->dominates(BB, UseBlock))
00094       return false;
00095   }
00096   return true;
00097 }
00098 
00099 bool Sinking::runOnFunction(Function &F) {
00100   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00101   LI = &getAnalysis<LoopInfo>();
00102   AA = &getAnalysis<AliasAnalysis>();
00103   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00104   DL = DLP ? &DLP->getDataLayout() : nullptr;
00105 
00106   bool MadeChange, EverMadeChange = false;
00107 
00108   do {
00109     MadeChange = false;
00110     DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
00111     // Process all basic blocks.
00112     for (Function::iterator I = F.begin(), E = F.end();
00113          I != E; ++I)
00114       MadeChange |= ProcessBlock(*I);
00115     EverMadeChange |= MadeChange;
00116     NumSinkIter++;
00117   } while (MadeChange);
00118 
00119   return EverMadeChange;
00120 }
00121 
00122 bool Sinking::ProcessBlock(BasicBlock &BB) {
00123   // Can't sink anything out of a block that has less than two successors.
00124   if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
00125 
00126   // Don't bother sinking code out of unreachable blocks. In addition to being
00127   // unprofitable, it can also lead to infinite looping, because in an
00128   // unreachable loop there may be nowhere to stop.
00129   if (!DT->isReachableFromEntry(&BB)) return false;
00130 
00131   bool MadeChange = false;
00132 
00133   // Walk the basic block bottom-up.  Remember if we saw a store.
00134   BasicBlock::iterator I = BB.end();
00135   --I;
00136   bool ProcessedBegin = false;
00137   SmallPtrSet<Instruction *, 8> Stores;
00138   do {
00139     Instruction *Inst = I;  // The instruction to sink.
00140 
00141     // Predecrement I (if it's not begin) so that it isn't invalidated by
00142     // sinking.
00143     ProcessedBegin = I == BB.begin();
00144     if (!ProcessedBegin)
00145       --I;
00146 
00147     if (isa<DbgInfoIntrinsic>(Inst))
00148       continue;
00149 
00150     if (SinkInstruction(Inst, Stores))
00151       ++NumSunk, MadeChange = true;
00152 
00153     // If we just processed the first instruction in the block, we're done.
00154   } while (!ProcessedBegin);
00155 
00156   return MadeChange;
00157 }
00158 
00159 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
00160                          SmallPtrSetImpl<Instruction *> &Stores) {
00161 
00162   if (Inst->mayWriteToMemory()) {
00163     Stores.insert(Inst);
00164     return false;
00165   }
00166 
00167   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
00168     AliasAnalysis::Location Loc = AA->getLocation(L);
00169     for (Instruction *S : Stores)
00170       if (AA->getModRefInfo(S, Loc) & AliasAnalysis::Mod)
00171         return false;
00172   }
00173 
00174   if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
00175     return false;
00176 
00177   return true;
00178 }
00179 
00180 /// IsAcceptableTarget - Return true if it is possible to sink the instruction
00181 /// in the specified basic block.
00182 bool Sinking::IsAcceptableTarget(Instruction *Inst,
00183                                  BasicBlock *SuccToSinkTo) const {
00184   assert(Inst && "Instruction to be sunk is null");
00185   assert(SuccToSinkTo && "Candidate sink target is null");
00186 
00187   // It is not possible to sink an instruction into its own block.  This can
00188   // happen with loops.
00189   if (Inst->getParent() == SuccToSinkTo)
00190     return false;
00191 
00192   // If the block has multiple predecessors, this would introduce computation
00193   // on different code paths.  We could split the critical edge, but for now we
00194   // just punt.
00195   // FIXME: Split critical edges if not backedges.
00196   if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
00197     // We cannot sink a load across a critical edge - there may be stores in
00198     // other code paths.
00199     if (!isSafeToSpeculativelyExecute(Inst, DL))
00200       return false;
00201 
00202     // We don't want to sink across a critical edge if we don't dominate the
00203     // successor. We could be introducing calculations to new code paths.
00204     if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
00205       return false;
00206 
00207     // Don't sink instructions into a loop.
00208     Loop *succ = LI->getLoopFor(SuccToSinkTo);
00209     Loop *cur = LI->getLoopFor(Inst->getParent());
00210     if (succ != nullptr && succ != cur)
00211       return false;
00212   }
00213 
00214   // Finally, check that all the uses of the instruction are actually
00215   // dominated by the candidate
00216   return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
00217 }
00218 
00219 /// SinkInstruction - Determine whether it is safe to sink the specified machine
00220 /// instruction out of its current block into a successor.
00221 bool Sinking::SinkInstruction(Instruction *Inst,
00222                               SmallPtrSetImpl<Instruction *> &Stores) {
00223 
00224   // Don't sink static alloca instructions.  CodeGen assumes allocas outside the
00225   // entry block are dynamically sized stack objects.
00226   if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
00227     if (AI->isStaticAlloca())
00228       return false;
00229 
00230   // Check if it's safe to move the instruction.
00231   if (!isSafeToMove(Inst, AA, Stores))
00232     return false;
00233 
00234   // FIXME: This should include support for sinking instructions within the
00235   // block they are currently in to shorten the live ranges.  We often get
00236   // instructions sunk into the top of a large block, but it would be better to
00237   // also sink them down before their first use in the block.  This xform has to
00238   // be careful not to *increase* register pressure though, e.g. sinking
00239   // "x = y + z" down if it kills y and z would increase the live ranges of y
00240   // and z and only shrink the live range of x.
00241 
00242   // SuccToSinkTo - This is the successor to sink this instruction to, once we
00243   // decide.
00244   BasicBlock *SuccToSinkTo = nullptr;
00245 
00246   // Instructions can only be sunk if all their uses are in blocks
00247   // dominated by one of the successors.
00248   // Look at all the postdominators and see if we can sink it in one.
00249   DomTreeNode *DTN = DT->getNode(Inst->getParent());
00250   for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
00251       I != E && SuccToSinkTo == nullptr; ++I) {
00252     BasicBlock *Candidate = (*I)->getBlock();
00253     if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
00254         IsAcceptableTarget(Inst, Candidate))
00255       SuccToSinkTo = Candidate;
00256   }
00257 
00258   // If no suitable postdominator was found, look at all the successors and
00259   // decide which one we should sink to, if any.
00260   for (succ_iterator I = succ_begin(Inst->getParent()),
00261       E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
00262     if (IsAcceptableTarget(Inst, *I))
00263       SuccToSinkTo = *I;
00264   }
00265 
00266   // If we couldn't find a block to sink to, ignore this instruction.
00267   if (!SuccToSinkTo)
00268     return false;
00269 
00270   DEBUG(dbgs() << "Sink" << *Inst << " (";
00271         Inst->getParent()->printAsOperand(dbgs(), false);
00272         dbgs() << " -> ";
00273         SuccToSinkTo->printAsOperand(dbgs(), false);
00274         dbgs() << ")\n");
00275 
00276   // Move the instruction.
00277   Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
00278   return true;
00279 }