1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "machine-licm"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineDominators.h"
18 #include "llvm/CodeGen/MachineLoopInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/Target/MRegisterInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
31 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
34 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
35 const TargetMachine *TM;
36 const TargetInstrInfo *TII;
37 MachineFunction *CurMF; // Current MachineFunction
39 // Various analyses that we use...
40 MachineLoopInfo *LI; // Current MachineLoopInfo
41 MachineDominatorTree *DT; // Machine dominator tree for the current Loop
42 MachineRegisterInfo *RegInfo; // Machine register information
44 // State that is updated as we process loops
45 bool Changed; // True if a loop is changed.
46 MachineLoop *CurLoop; // The current loop we are working on.
48 static char ID; // Pass identification, replacement for typeid
49 MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
51 virtual bool runOnMachineFunction(MachineFunction &MF);
53 /// FIXME: Loop preheaders?
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired<MachineLoopInfo>();
58 AU.addRequired<MachineDominatorTree>();
59 AU.addPreserved<MachineLoopInfo>();
60 AU.addPreserved<MachineDominatorTree>();
61 MachineFunctionPass::getAnalysisUsage(AU);
64 /// VisitAllLoops - Visit all of the loops in depth first order and try to
65 /// hoist invariant instructions from them.
67 void VisitAllLoops(MachineLoop *L) {
68 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
70 for (MachineLoop::iterator
71 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
74 // Traverse the body of the loop in depth first order on the dominator
75 // tree so that we are guaranteed to see definitions before we see uses.
77 HoistRegion(DT->getNode(ML->getHeader()));
80 HoistRegion(DT->getNode(L->getHeader()));
83 /// IsInSubLoop - A little predicate that returns true if the specified
84 /// basic block is in a subloop of the current one, not the current one
87 bool IsInSubLoop(MachineBasicBlock *BB) {
88 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
89 return LI->getLoopFor(BB) != CurLoop;
92 /// IsLoopInvariantInst - Returns true if the instruction is loop
93 /// invariant. I.e., all virtual register operands are defined outside of
94 /// the loop, physical registers aren't accessed (explicitly or implicitly),
95 /// and the instruction is hoistable.
97 bool IsLoopInvariantInst(MachineInstr &I);
99 /// FindPredecessors - Get all of the predecessors of the loop that are not
102 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
103 const MachineBasicBlock *Header = CurLoop->getHeader();
105 for (MachineBasicBlock::const_pred_iterator
106 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
107 if (!CurLoop->contains(*I))
111 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
112 /// the predecessor basic block (but before the terminator instructions).
114 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
115 MachineBasicBlock *FromMBB,
118 DOUT << "Hoisting " << *MI;
119 if (ToMBB->getBasicBlock())
120 DOUT << " to MachineBasicBlock "
121 << ToMBB->getBasicBlock()->getName();
125 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
126 MachineBasicBlock::iterator To, From = FromMBB->begin();
131 assert(From != FromMBB->end() && "Didn't find instr in BB!");
134 ToMBB->splice(WhereIter, FromMBB, From, ++To);
138 /// HoistRegion - Walk the specified region of the CFG (defined by all
139 /// blocks dominated by the specified block, and that are in the current
140 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
141 /// visit definitions before uses, allowing us to hoist a loop body in one
142 /// pass without iteration.
144 void HoistRegion(MachineDomTreeNode *N);
146 /// Hoist - When an instruction is found to only use loop invariant operands
147 /// that is safe to hoist, this instruction is called to do the dirty work.
149 void Hoist(MachineInstr &MI);
152 char MachineLICM::ID = 0;
153 RegisterPass<MachineLICM> X("machine-licm",
154 "Machine Loop Invariant Code Motion");
155 } // end anonymous namespace
157 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
159 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
160 /// is not preserved so it is not a good idea to run LICM multiple times on one
163 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
164 DOUT << "******** Machine LICM ********\n";
168 TM = &CurMF->getTarget();
169 TII = TM->getInstrInfo();
170 RegInfo = &CurMF->getRegInfo();
172 // Get our Loop information...
173 LI = &getAnalysis<MachineLoopInfo>();
174 DT = &getAnalysis<MachineDominatorTree>();
176 for (MachineLoopInfo::iterator
177 I = LI->begin(), E = LI->end(); I != E; ++I) {
180 // Visit all of the instructions of the loop. We want to visit the subloops
181 // first, though, so that we can hoist their invariants first into their
182 // containing loop before we process that loop.
183 VisitAllLoops(CurLoop);
189 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
190 /// dominated by the specified block, and that are in the current loop) in depth
191 /// first order w.r.t the DominatorTree. This allows us to visit definitions
192 /// before uses, allowing us to hoist a loop body in one pass without iteration.
194 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
195 assert(N != 0 && "Null dominator tree node?");
196 MachineBasicBlock *BB = N->getBlock();
198 // If this subregion is not in the top level loop at all, exit.
199 if (!CurLoop->contains(BB)) return;
201 // Only need to process the contents of this block if it is not part of a
202 // subloop (which would already have been processed).
203 if (!IsInSubLoop(BB))
204 for (MachineBasicBlock::iterator
205 I = BB->begin(), E = BB->end(); I != E; ) {
206 MachineInstr &MI = *I++;
208 // Try hoisting the instruction out of the loop. We can only do this if
209 // all of the operands of the instruction are loop invariant and if it is
210 // safe to hoist the instruction.
214 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
216 for (unsigned I = 0, E = Children.size(); I != E; ++I)
217 HoistRegion(Children[I]);
220 /// IsLoopInvariantInst - Returns true if the instruction is loop
221 /// invariant. I.e., all virtual register operands are defined outside of the
222 /// loop, physical registers aren't accessed explicitly, and there are no side
223 /// effects that aren't captured by the operands or other flags.
225 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
227 DOUT << "--- Checking if we can hoist " << I;
228 if (I.getInstrDescriptor()->ImplicitUses) {
229 DOUT << " * Instruction has implicit uses:\n";
231 const MRegisterInfo *MRI = TM->getRegisterInfo();
232 const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
234 for (; *ImpUses; ++ImpUses)
235 DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
238 if (I.getInstrDescriptor()->ImplicitDefs) {
239 DOUT << " * Instruction has implicit defines:\n";
241 const MRegisterInfo *MRI = TM->getRegisterInfo();
242 const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
244 for (; *ImpDefs; ++ImpDefs)
245 DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
248 if (TII->hasUnmodelledSideEffects(&I))
249 DOUT << " * Instruction has side effects.\n";
252 // The instruction is loop invariant if all of its operands are loop-invariant
253 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
254 const MachineOperand &MO = I.getOperand(i);
256 if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
259 unsigned Reg = MO.getReg();
261 // Don't hoist instructions that access physical registers.
262 if (!MRegisterInfo::isVirtualRegister(Reg))
265 assert(RegInfo->getVRegDef(Reg)&&"Machine instr not mapped for this vreg?");
267 // If the loop contains the definition of an operand, then the instruction
268 // isn't loop invariant.
269 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
273 // Don't hoist something that has unmodelled side effects.
274 if (TII->hasUnmodelledSideEffects(&I)) return false;
276 // If we got this far, the instruction is loop invariant!
280 /// Hoist - When an instruction is found to only use loop invariant operands
281 /// that is safe to hoist, this instruction is called to do the dirty work.
283 void MachineLICM::Hoist(MachineInstr &MI) {
284 if (!IsLoopInvariantInst(MI)) return;
286 std::vector<MachineBasicBlock*> Preds;
288 // Non-back-edge predecessors.
289 FindPredecessors(Preds);
291 // Either we don't have any predecessors(?!) or we have more than one, which
293 if (Preds.empty() || Preds.size() != 1) return;
295 // Check that the predecessor is qualified to take the hoisted
296 // instruction. I.e., there is only one edge from the predecessor, and it's to
298 MachineBasicBlock *MBB = Preds.front();
300 // FIXME: We are assuming at first that the basic block coming into this loop
301 // has only one successor. This isn't the case in general because we haven't
302 // broken critical edges or added preheaders.
303 if (MBB->succ_size() != 1) return;
304 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
305 "The predecessor doesn't feed directly into the loop header!");
307 // Now move the instructions to the predecessor.
308 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);