Sink.cpp 9.9 KB

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