MachineLICM.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
  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 performs loop invariant code motion on machine instructions. We
  11. // attempt to remove as much code from the body of a loop as possible.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "machine-licm"
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/CodeGen/MachineDominators.h"
  17. #include "llvm/CodeGen/MachineLoopInfo.h"
  18. #include "llvm/CodeGen/MachineRegisterInfo.h"
  19. #include "llvm/Target/TargetRegisterInfo.h"
  20. #include "llvm/Target/TargetInstrInfo.h"
  21. #include "llvm/Target/TargetMachine.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Compiler.h"
  25. #include "llvm/Support/Debug.h"
  26. using namespace llvm;
  27. STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
  28. namespace {
  29. class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
  30. const TargetMachine *TM;
  31. const TargetInstrInfo *TII;
  32. // Various analyses that we use...
  33. MachineLoopInfo *LI; // Current MachineLoopInfo
  34. MachineDominatorTree *DT; // Machine dominator tree for the cur loop
  35. MachineRegisterInfo *RegInfo; // Machine register information
  36. // State that is updated as we process loops
  37. bool Changed; // True if a loop is changed.
  38. MachineLoop *CurLoop; // The current loop we are working on.
  39. public:
  40. static char ID; // Pass identification, replacement for typeid
  41. MachineLICM() : MachineFunctionPass(&ID) {}
  42. virtual bool runOnMachineFunction(MachineFunction &MF);
  43. const char *getPassName() const { return "Machine Instruction LICM"; }
  44. // FIXME: Loop preheaders?
  45. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  46. AU.setPreservesCFG();
  47. AU.addRequired<MachineLoopInfo>();
  48. AU.addRequired<MachineDominatorTree>();
  49. AU.addPreserved<MachineLoopInfo>();
  50. AU.addPreserved<MachineDominatorTree>();
  51. MachineFunctionPass::getAnalysisUsage(AU);
  52. }
  53. private:
  54. /// VisitAllLoops - Visit all of the loops in depth first order and try to
  55. /// hoist invariant instructions from them.
  56. ///
  57. void VisitAllLoops(MachineLoop *L) {
  58. const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
  59. for (MachineLoop::iterator
  60. I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
  61. MachineLoop *ML = *I;
  62. // Traverse the body of the loop in depth first order on the dominator
  63. // tree so that we are guaranteed to see definitions before we see uses.
  64. VisitAllLoops(ML);
  65. HoistRegion(DT->getNode(ML->getHeader()));
  66. }
  67. HoistRegion(DT->getNode(L->getHeader()));
  68. }
  69. /// IsInSubLoop - A little predicate that returns true if the specified
  70. /// basic block is in a subloop of the current one, not the current one
  71. /// itself.
  72. ///
  73. bool IsInSubLoop(MachineBasicBlock *BB) {
  74. assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
  75. return LI->getLoopFor(BB) != CurLoop;
  76. }
  77. /// IsLoopInvariantInst - Returns true if the instruction is loop
  78. /// invariant. I.e., all virtual register operands are defined outside of
  79. /// the loop, physical registers aren't accessed (explicitly or implicitly),
  80. /// and the instruction is hoistable.
  81. ///
  82. bool IsLoopInvariantInst(MachineInstr &I);
  83. /// FindPredecessors - Get all of the predecessors of the loop that are not
  84. /// back-edges.
  85. ///
  86. void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
  87. const MachineBasicBlock *Header = CurLoop->getHeader();
  88. for (MachineBasicBlock::const_pred_iterator
  89. I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
  90. if (!CurLoop->contains(*I))
  91. Preds.push_back(*I);
  92. }
  93. /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
  94. /// the predecessor basic block (but before the terminator instructions).
  95. ///
  96. void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
  97. MachineBasicBlock *FromMBB,
  98. MachineInstr *MI);
  99. /// HoistRegion - Walk the specified region of the CFG (defined by all
  100. /// blocks dominated by the specified block, and that are in the current
  101. /// loop) in depth first order w.r.t the DominatorTree. This allows us to
  102. /// visit definitions before uses, allowing us to hoist a loop body in one
  103. /// pass without iteration.
  104. ///
  105. void HoistRegion(MachineDomTreeNode *N);
  106. /// Hoist - When an instruction is found to only use loop invariant operands
  107. /// that is safe to hoist, this instruction is called to do the dirty work.
  108. ///
  109. void Hoist(MachineInstr &MI);
  110. };
  111. } // end anonymous namespace
  112. char MachineLICM::ID = 0;
  113. static RegisterPass<MachineLICM>
  114. X("machinelicm", "Machine Loop Invariant Code Motion");
  115. FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
  116. /// Hoist expressions out of the specified loop. Note, alias info for inner loop
  117. /// is not preserved so it is not a good idea to run LICM multiple times on one
  118. /// loop.
  119. ///
  120. bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
  121. DOUT << "******** Machine LICM ********\n";
  122. Changed = false;
  123. TM = &MF.getTarget();
  124. TII = TM->getInstrInfo();
  125. RegInfo = &MF.getRegInfo();
  126. // Get our Loop information...
  127. LI = &getAnalysis<MachineLoopInfo>();
  128. DT = &getAnalysis<MachineDominatorTree>();
  129. for (MachineLoopInfo::iterator
  130. I = LI->begin(), E = LI->end(); I != E; ++I) {
  131. CurLoop = *I;
  132. // Visit all of the instructions of the loop. We want to visit the subloops
  133. // first, though, so that we can hoist their invariants first into their
  134. // containing loop before we process that loop.
  135. VisitAllLoops(CurLoop);
  136. }
  137. return Changed;
  138. }
  139. /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
  140. /// dominated by the specified block, and that are in the current loop) in depth
  141. /// first order w.r.t the DominatorTree. This allows us to visit definitions
  142. /// before uses, allowing us to hoist a loop body in one pass without iteration.
  143. ///
  144. void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
  145. assert(N != 0 && "Null dominator tree node?");
  146. MachineBasicBlock *BB = N->getBlock();
  147. // If this subregion is not in the top level loop at all, exit.
  148. if (!CurLoop->contains(BB)) return;
  149. // Only need to process the contents of this block if it is not part of a
  150. // subloop (which would already have been processed).
  151. if (!IsInSubLoop(BB))
  152. for (MachineBasicBlock::iterator
  153. I = BB->begin(), E = BB->end(); I != E; ) {
  154. MachineInstr &MI = *I++;
  155. // Try hoisting the instruction out of the loop. We can only do this if
  156. // all of the operands of the instruction are loop invariant and if it is
  157. // safe to hoist the instruction.
  158. Hoist(MI);
  159. }
  160. const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
  161. for (unsigned I = 0, E = Children.size(); I != E; ++I)
  162. HoistRegion(Children[I]);
  163. }
  164. /// IsLoopInvariantInst - Returns true if the instruction is loop
  165. /// invariant. I.e., all virtual register operands are defined outside of the
  166. /// loop, physical registers aren't accessed explicitly, and there are no side
  167. /// effects that aren't captured by the operands or other flags.
  168. ///
  169. bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
  170. const TargetInstrDesc &TID = I.getDesc();
  171. // Ignore stuff that we obviously can't hoist.
  172. if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
  173. TID.hasUnmodeledSideEffects())
  174. return false;
  175. if (TID.mayLoad()) {
  176. // Okay, this instruction does a load. As a refinement, we allow the target
  177. // to decide whether the loaded value is actually a constant. If so, we can
  178. // actually use it as a load.
  179. if (!TII->isInvariantLoad(&I))
  180. // FIXME: we should be able to sink loads with no other side effects if
  181. // there is nothing that can change memory from here until the end of
  182. // block. This is a trivial form of alias analysis.
  183. return false;
  184. }
  185. DEBUG({
  186. DOUT << "--- Checking if we can hoist " << I;
  187. if (I.getDesc().getImplicitUses()) {
  188. DOUT << " * Instruction has implicit uses:\n";
  189. const TargetRegisterInfo *TRI = TM->getRegisterInfo();
  190. for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
  191. *ImpUses; ++ImpUses)
  192. DOUT << " -> " << TRI->getName(*ImpUses) << "\n";
  193. }
  194. if (I.getDesc().getImplicitDefs()) {
  195. DOUT << " * Instruction has implicit defines:\n";
  196. const TargetRegisterInfo *TRI = TM->getRegisterInfo();
  197. for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
  198. *ImpDefs; ++ImpDefs)
  199. DOUT << " -> " << TRI->getName(*ImpDefs) << "\n";
  200. }
  201. });
  202. if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
  203. DOUT << "Cannot hoist with implicit defines or uses\n";
  204. return false;
  205. }
  206. // The instruction is loop invariant if all of its operands are.
  207. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  208. const MachineOperand &MO = I.getOperand(i);
  209. if (!MO.isReg())
  210. continue;
  211. if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
  212. // Don't hoist an instruction that defines a physical register.
  213. return false;
  214. if (!MO.isUse())
  215. continue;
  216. unsigned Reg = MO.getReg();
  217. if (Reg == 0) continue;
  218. // Don't hoist instructions that access physical registers.
  219. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  220. return false;
  221. assert(RegInfo->getVRegDef(Reg) &&
  222. "Machine instr not mapped for this vreg?!");
  223. // If the loop contains the definition of an operand, then the instruction
  224. // isn't loop invariant.
  225. if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
  226. return false;
  227. }
  228. // If we got this far, the instruction is loop invariant!
  229. return true;
  230. }
  231. /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of the
  232. /// predecessor basic block (but before the terminator instructions).
  233. ///
  234. void MachineLICM::MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
  235. MachineBasicBlock *FromMBB,
  236. MachineInstr *MI) {
  237. DEBUG({
  238. DOUT << "Hoisting " << *MI;
  239. if (ToMBB->getBasicBlock())
  240. DOUT << " to MachineBasicBlock "
  241. << ToMBB->getBasicBlock()->getName();
  242. if (FromMBB->getBasicBlock())
  243. DOUT << " from MachineBasicBlock "
  244. << FromMBB->getBasicBlock()->getName();
  245. DOUT << "\n";
  246. });
  247. MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
  248. MachineBasicBlock::iterator To, From = FromMBB->begin();
  249. while (&*From != MI)
  250. ++From;
  251. assert(From != FromMBB->end() && "Didn't find instr in BB!");
  252. To = From;
  253. ToMBB->splice(WhereIter, FromMBB, From, ++To);
  254. ++NumHoisted;
  255. }
  256. /// Hoist - When an instruction is found to use only loop invariant operands
  257. /// that are safe to hoist, this instruction is called to do the dirty work.
  258. ///
  259. void MachineLICM::Hoist(MachineInstr &MI) {
  260. if (!IsLoopInvariantInst(MI)) return;
  261. std::vector<MachineBasicBlock*> Preds;
  262. // Non-back-edge predecessors.
  263. FindPredecessors(Preds);
  264. // Either we don't have any predecessors(?!) or we have more than one, which
  265. // is forbidden.
  266. if (Preds.empty() || Preds.size() != 1) return;
  267. // Check that the predecessor is qualified to take the hoisted instruction.
  268. // I.e., there is only one edge from the predecessor, and it's to the loop
  269. // header.
  270. MachineBasicBlock *MBB = Preds.front();
  271. // FIXME: We are assuming at first that the basic block coming into this loop
  272. // has only one successor. This isn't the case in general because we haven't
  273. // broken critical edges or added preheaders.
  274. if (MBB->succ_size() != 1) return;
  275. assert(*MBB->succ_begin() == CurLoop->getHeader() &&
  276. "The predecessor doesn't feed directly into the loop header!");
  277. // Now move the instructions to the predecessor.
  278. MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
  279. Changed = true;
  280. }