/3rd_party/llvm/lib/Transforms/Scalar/Sink.cpp

https://code.google.com/p/softart/ · C++ · 270 lines · 163 code · 41 blank · 66 comment · 48 complexity · cbbb94ecdf77cdcbd3452280720ed720 MD5 · raw file

  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. #define DEBUG_TYPE "sink"
  15. #include "llvm/Transforms/Scalar.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/Analysis/AliasAnalysis.h"
  18. #include "llvm/Analysis/Dominators.h"
  19. #include "llvm/Analysis/LoopInfo.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/Assembly/Writer.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/Support/CFG.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace llvm;
  27. STATISTIC(NumSunk, "Number of instructions sunk");
  28. STATISTIC(NumSinkIter, "Number of sinking iterations");
  29. namespace {
  30. class Sinking : public FunctionPass {
  31. DominatorTree *DT;
  32. LoopInfo *LI;
  33. AliasAnalysis *AA;
  34. public:
  35. static char ID; // Pass identification
  36. Sinking() : FunctionPass(ID) {
  37. initializeSinkingPass(*PassRegistry::getPassRegistry());
  38. }
  39. virtual bool runOnFunction(Function &F);
  40. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  41. AU.setPreservesCFG();
  42. FunctionPass::getAnalysisUsage(AU);
  43. AU.addRequired<AliasAnalysis>();
  44. AU.addRequired<DominatorTree>();
  45. AU.addRequired<LoopInfo>();
  46. AU.addPreserved<DominatorTree>();
  47. AU.addPreserved<LoopInfo>();
  48. }
  49. private:
  50. bool ProcessBlock(BasicBlock &BB);
  51. bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores);
  52. bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
  53. bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
  54. };
  55. } // end anonymous namespace
  56. char Sinking::ID = 0;
  57. INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
  58. INITIALIZE_PASS_DEPENDENCY(LoopInfo)
  59. INITIALIZE_PASS_DEPENDENCY(DominatorTree)
  60. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  61. INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
  62. FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
  63. /// AllUsesDominatedByBlock - Return true if all uses of the specified value
  64. /// occur in blocks dominated by the specified block.
  65. bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
  66. BasicBlock *BB) const {
  67. // Ignoring debug uses is necessary so debug info doesn't affect the code.
  68. // This may leave a referencing dbg_value in the original block, before
  69. // the definition of the vreg. Dwarf generator handles this although the
  70. // user might not get the right info at runtime.
  71. for (Value::use_iterator I = Inst->use_begin(),
  72. E = Inst->use_end(); I != E; ++I) {
  73. // Determine the block of the use.
  74. Instruction *UseInst = cast<Instruction>(*I);
  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(I.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<DominatorTree>();
  90. LI = &getAnalysis<LoopInfo>();
  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. SmallPtrSet<Instruction *, 8> &Stores) {
  135. if (Inst->mayWriteToMemory()) {
  136. Stores.insert(Inst);
  137. return false;
  138. }
  139. if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
  140. AliasAnalysis::Location Loc = AA->getLocation(L);
  141. for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
  142. E = Stores.end(); I != E; ++I)
  143. if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
  144. return false;
  145. }
  146. if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
  147. return false;
  148. return true;
  149. }
  150. /// IsAcceptableTarget - Return true if it is possible to sink the instruction
  151. /// in the specified basic block.
  152. bool Sinking::IsAcceptableTarget(Instruction *Inst,
  153. BasicBlock *SuccToSinkTo) const {
  154. assert(Inst && "Instruction to be sunk is null");
  155. assert(SuccToSinkTo && "Candidate sink target is null");
  156. // It is not possible to sink an instruction into its own block. This can
  157. // happen with loops.
  158. if (Inst->getParent() == SuccToSinkTo)
  159. return false;
  160. // If the block has multiple predecessors, this would introduce computation
  161. // on different code paths. We could split the critical edge, but for now we
  162. // just punt.
  163. // FIXME: Split critical edges if not backedges.
  164. if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
  165. // We cannot sink a load across a critical edge - there may be stores in
  166. // other code paths.
  167. if (!isSafeToSpeculativelyExecute(Inst))
  168. return false;
  169. // We don't want to sink across a critical edge if we don't dominate the
  170. // successor. We could be introducing calculations to new code paths.
  171. if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
  172. return false;
  173. // Don't sink instructions into a loop.
  174. Loop *succ = LI->getLoopFor(SuccToSinkTo);
  175. Loop *cur = LI->getLoopFor(Inst->getParent());
  176. if (succ != 0 && succ != cur)
  177. return false;
  178. }
  179. // Finally, check that all the uses of the instruction are actually
  180. // dominated by the candidate
  181. return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
  182. }
  183. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  184. /// instruction out of its current block into a successor.
  185. bool Sinking::SinkInstruction(Instruction *Inst,
  186. SmallPtrSet<Instruction *, 8> &Stores) {
  187. // Check if it's safe to move the instruction.
  188. if (!isSafeToMove(Inst, AA, Stores))
  189. return false;
  190. // FIXME: This should include support for sinking instructions within the
  191. // block they are currently in to shorten the live ranges. We often get
  192. // instructions sunk into the top of a large block, but it would be better to
  193. // also sink them down before their first use in the block. This xform has to
  194. // be careful not to *increase* register pressure though, e.g. sinking
  195. // "x = y + z" down if it kills y and z would increase the live ranges of y
  196. // and z and only shrink the live range of x.
  197. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  198. // decide.
  199. BasicBlock *SuccToSinkTo = 0;
  200. // Instructions can only be sunk if all their uses are in blocks
  201. // dominated by one of the successors.
  202. // Look at all the postdominators and see if we can sink it in one.
  203. DomTreeNode *DTN = DT->getNode(Inst->getParent());
  204. for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
  205. I != E && SuccToSinkTo == 0; ++I) {
  206. BasicBlock *Candidate = (*I)->getBlock();
  207. if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
  208. IsAcceptableTarget(Inst, Candidate))
  209. SuccToSinkTo = Candidate;
  210. }
  211. // If no suitable postdominator was found, look at all the successors and
  212. // decide which one we should sink to, if any.
  213. for (succ_iterator I = succ_begin(Inst->getParent()),
  214. E = succ_end(Inst->getParent()); I != E && SuccToSinkTo == 0; ++I) {
  215. if (IsAcceptableTarget(Inst, *I))
  216. SuccToSinkTo = *I;
  217. }
  218. // If we couldn't find a block to sink to, ignore this instruction.
  219. if (SuccToSinkTo == 0)
  220. return false;
  221. DEBUG(dbgs() << "Sink" << *Inst << " (";
  222. WriteAsOperand(dbgs(), Inst->getParent(), false);
  223. dbgs() << " -> ";
  224. WriteAsOperand(dbgs(), SuccToSinkTo, false);
  225. dbgs() << ")\n");
  226. // Move the instruction.
  227. Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
  228. return true;
  229. }