Home | History | Annotate | Download | only in Scalar
      1 //===-- Sink.cpp - Code Sinking -------------------------------------------===//
      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 pass moves instructions into successor blocks, when possible, so that
     11 // they aren't executed on paths where their results aren't needed.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "llvm/Transforms/Scalar.h"
     16 #include "llvm/ADT/Statistic.h"
     17 #include "llvm/Analysis/AliasAnalysis.h"
     18 #include "llvm/Analysis/LoopInfo.h"
     19 #include "llvm/Analysis/ValueTracking.h"
     20 #include "llvm/IR/CFG.h"
     21 #include "llvm/IR/DataLayout.h"
     22 #include "llvm/IR/Dominators.h"
     23 #include "llvm/IR/IntrinsicInst.h"
     24 #include "llvm/Support/Debug.h"
     25 #include "llvm/Support/raw_ostream.h"
     26 using namespace llvm;
     27 
     28 #define DEBUG_TYPE "sink"
     29 
     30 STATISTIC(NumSunk, "Number of instructions sunk");
     31 STATISTIC(NumSinkIter, "Number of sinking iterations");
     32 
     33 namespace {
     34   class Sinking : public FunctionPass {
     35     DominatorTree *DT;
     36     LoopInfo *LI;
     37     AliasAnalysis *AA;
     38     const DataLayout *DL;
     39 
     40   public:
     41     static char ID; // Pass identification
     42     Sinking() : FunctionPass(ID) {
     43       initializeSinkingPass(*PassRegistry::getPassRegistry());
     44     }
     45 
     46     bool runOnFunction(Function &F) override;
     47 
     48     void getAnalysisUsage(AnalysisUsage &AU) const override {
     49       AU.setPreservesCFG();
     50       FunctionPass::getAnalysisUsage(AU);
     51       AU.addRequired<AliasAnalysis>();
     52       AU.addRequired<DominatorTreeWrapperPass>();
     53       AU.addRequired<LoopInfo>();
     54       AU.addPreserved<DominatorTreeWrapperPass>();
     55       AU.addPreserved<LoopInfo>();
     56     }
     57   private:
     58     bool ProcessBlock(BasicBlock &BB);
     59     bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores);
     60     bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
     61     bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
     62   };
     63 } // end anonymous namespace
     64 
     65 char Sinking::ID = 0;
     66 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
     67 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
     68 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
     69 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
     70 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
     71 
     72 FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
     73 
     74 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
     75 /// occur in blocks dominated by the specified block.
     76 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
     77                                       BasicBlock *BB) const {
     78   // Ignoring debug uses is necessary so debug info doesn't affect the code.
     79   // This may leave a referencing dbg_value in the original block, before
     80   // the definition of the vreg.  Dwarf generator handles this although the
     81   // user might not get the right info at runtime.
     82   for (Use &U : Inst->uses()) {
     83     // Determine the block of the use.
     84     Instruction *UseInst = cast<Instruction>(U.getUser());
     85     BasicBlock *UseBlock = UseInst->getParent();
     86     if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
     87       // PHI nodes use the operand in the predecessor block, not the block with
     88       // the PHI.
     89       unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
     90       UseBlock = PN->getIncomingBlock(Num);
     91     }
     92     // Check that it dominates.
     93     if (!DT->dominates(BB, UseBlock))
     94       return false;
     95   }
     96   return true;
     97 }
     98 
     99 bool Sinking::runOnFunction(Function &F) {
    100   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
    101   LI = &getAnalysis<LoopInfo>();
    102   AA = &getAnalysis<AliasAnalysis>();
    103   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
    104   DL = DLP ? &DLP->getDataLayout() : nullptr;
    105 
    106   bool MadeChange, EverMadeChange = false;
    107 
    108   do {
    109     MadeChange = false;
    110     DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
    111     // Process all basic blocks.
    112     for (Function::iterator I = F.begin(), E = F.end();
    113          I != E; ++I)
    114       MadeChange |= ProcessBlock(*I);
    115     EverMadeChange |= MadeChange;
    116     NumSinkIter++;
    117   } while (MadeChange);
    118 
    119   return EverMadeChange;
    120 }
    121 
    122 bool Sinking::ProcessBlock(BasicBlock &BB) {
    123   // Can't sink anything out of a block that has less than two successors.
    124   if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
    125 
    126   // Don't bother sinking code out of unreachable blocks. In addition to being
    127   // unprofitable, it can also lead to infinite looping, because in an
    128   // unreachable loop there may be nowhere to stop.
    129   if (!DT->isReachableFromEntry(&BB)) return false;
    130 
    131   bool MadeChange = false;
    132 
    133   // Walk the basic block bottom-up.  Remember if we saw a store.
    134   BasicBlock::iterator I = BB.end();
    135   --I;
    136   bool ProcessedBegin = false;
    137   SmallPtrSet<Instruction *, 8> Stores;
    138   do {
    139     Instruction *Inst = I;  // The instruction to sink.
    140 
    141     // Predecrement I (if it's not begin) so that it isn't invalidated by
    142     // sinking.
    143     ProcessedBegin = I == BB.begin();
    144     if (!ProcessedBegin)
    145       --I;
    146 
    147     if (isa<DbgInfoIntrinsic>(Inst))
    148       continue;
    149 
    150     if (SinkInstruction(Inst, Stores))
    151       ++NumSunk, MadeChange = true;
    152 
    153     // If we just processed the first instruction in the block, we're done.
    154   } while (!ProcessedBegin);
    155 
    156   return MadeChange;
    157 }
    158 
    159 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
    160                          SmallPtrSet<Instruction *, 8> &Stores) {
    161 
    162   if (Inst->mayWriteToMemory()) {
    163     Stores.insert(Inst);
    164     return false;
    165   }
    166 
    167   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
    168     AliasAnalysis::Location Loc = AA->getLocation(L);
    169     for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
    170          E = Stores.end(); I != E; ++I)
    171       if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
    172         return false;
    173   }
    174 
    175   if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
    176     return false;
    177 
    178   return true;
    179 }
    180 
    181 /// IsAcceptableTarget - Return true if it is possible to sink the instruction
    182 /// in the specified basic block.
    183 bool Sinking::IsAcceptableTarget(Instruction *Inst,
    184                                  BasicBlock *SuccToSinkTo) const {
    185   assert(Inst && "Instruction to be sunk is null");
    186   assert(SuccToSinkTo && "Candidate sink target is null");
    187 
    188   // It is not possible to sink an instruction into its own block.  This can
    189   // happen with loops.
    190   if (Inst->getParent() == SuccToSinkTo)
    191     return false;
    192 
    193   // If the block has multiple predecessors, this would introduce computation
    194   // on different code paths.  We could split the critical edge, but for now we
    195   // just punt.
    196   // FIXME: Split critical edges if not backedges.
    197   if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
    198     // We cannot sink a load across a critical edge - there may be stores in
    199     // other code paths.
    200     if (!isSafeToSpeculativelyExecute(Inst, DL))
    201       return false;
    202 
    203     // We don't want to sink across a critical edge if we don't dominate the
    204     // successor. We could be introducing calculations to new code paths.
    205     if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
    206       return false;
    207 
    208     // Don't sink instructions into a loop.
    209     Loop *succ = LI->getLoopFor(SuccToSinkTo);
    210     Loop *cur = LI->getLoopFor(Inst->getParent());
    211     if (succ != nullptr && succ != cur)
    212       return false;
    213   }
    214 
    215   // Finally, check that all the uses of the instruction are actually
    216   // dominated by the candidate
    217   return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
    218 }
    219 
    220 /// SinkInstruction - Determine whether it is safe to sink the specified machine
    221 /// instruction out of its current block into a successor.
    222 bool Sinking::SinkInstruction(Instruction *Inst,
    223                               SmallPtrSet<Instruction *, 8> &Stores) {
    224 
    225   // Don't sink static alloca instructions.  CodeGen assumes allocas outside the
    226   // entry block are dynamically sized stack objects.
    227   if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
    228     if (AI->isStaticAlloca())
    229       return false;
    230 
    231   // Check if it's safe to move the instruction.
    232   if (!isSafeToMove(Inst, AA, Stores))
    233     return false;
    234 
    235   // FIXME: This should include support for sinking instructions within the
    236   // block they are currently in to shorten the live ranges.  We often get
    237   // instructions sunk into the top of a large block, but it would be better to
    238   // also sink them down before their first use in the block.  This xform has to
    239   // be careful not to *increase* register pressure though, e.g. sinking
    240   // "x = y + z" down if it kills y and z would increase the live ranges of y
    241   // and z and only shrink the live range of x.
    242 
    243   // SuccToSinkTo - This is the successor to sink this instruction to, once we
    244   // decide.
    245   BasicBlock *SuccToSinkTo = nullptr;
    246 
    247   // Instructions can only be sunk if all their uses are in blocks
    248   // dominated by one of the successors.
    249   // Look at all the postdominators and see if we can sink it in one.
    250   DomTreeNode *DTN = DT->getNode(Inst->getParent());
    251   for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
    252       I != E && SuccToSinkTo == nullptr; ++I) {
    253     BasicBlock *Candidate = (*I)->getBlock();
    254     if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
    255         IsAcceptableTarget(Inst, Candidate))
    256       SuccToSinkTo = Candidate;
    257   }
    258 
    259   // If no suitable postdominator was found, look at all the successors and
    260   // decide which one we should sink to, if any.
    261   for (succ_iterator I = succ_begin(Inst->getParent()),
    262       E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
    263     if (IsAcceptableTarget(Inst, *I))
    264       SuccToSinkTo = *I;
    265   }
    266 
    267   // If we couldn't find a block to sink to, ignore this instruction.
    268   if (!SuccToSinkTo)
    269     return false;
    270 
    271   DEBUG(dbgs() << "Sink" << *Inst << " (";
    272         Inst->getParent()->printAsOperand(dbgs(), false);
    273         dbgs() << " -> ";
    274         SuccToSinkTo->printAsOperand(dbgs(), false);
    275         dbgs() << ")\n");
    276 
    277   // Move the instruction.
    278   Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
    279   return true;
    280 }
    281