blob: a7e3a8060df3fcd42a4c70c23a4da91b5fa9afd5 [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
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
15#define DEBUG_TYPE "machine-licm"
Bill Wendlingb48519c2007-12-08 01:47:01 +000016#include "llvm/ADT/IndexedMap.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/CodeGen/MachineBasicBlock.h"
20#include "llvm/CodeGen/MachineDominators.h"
21#include "llvm/CodeGen/MachineInstr.h"
22#include "llvm/CodeGen/MachineLoopInfo.h"
23#include "llvm/CodeGen/Passes.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000024#include "llvm/Support/CFG.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Target/MRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000029#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000030#include "llvm/Target/TargetMachine.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000031
32using namespace llvm;
33
34namespace {
35 // Hidden options to help debugging
36 cl::opt<bool>
37 PerformLICM("machine-licm",
Bill Wendlingb48519c2007-12-08 01:47:01 +000038 cl::init(false), cl::Hidden,
39 cl::desc("Perform loop-invariant code motion on machine code"));
Bill Wendling0f940c92007-12-07 21:42:31 +000040}
41
Bill Wendling041b3f82007-12-08 23:58:46 +000042STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Bill Wendlingb48519c2007-12-08 01:47:01 +000043
Bill Wendling0f940c92007-12-07 21:42:31 +000044namespace {
45 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
Bill Wendlingefe2be72007-12-11 23:27:51 +000046 const TargetInstrInfo *TII;
47 MachineFunction *CurMF; // Current MachineFunction
Bill Wendling12ebf142007-12-11 19:40:06 +000048
Bill Wendling0f940c92007-12-07 21:42:31 +000049 // Various analyses that we use...
50 MachineLoopInfo *LI; // Current MachineLoopInfo
51 MachineDominatorTree *DT; // Machine dominator tree for the current Loop
52
Bill Wendling0f940c92007-12-07 21:42:31 +000053 // State that is updated as we process loops
54 bool Changed; // True if a loop is changed.
55 MachineLoop *CurLoop; // The current loop we are working on.
56
57 // Map the def of a virtual register to the machine instruction.
Bill Wendlingb48519c2007-12-08 01:47:01 +000058 IndexedMap<const MachineInstr*, VirtReg2IndexFunctor> VRegDefs;
Bill Wendling0f940c92007-12-07 21:42:31 +000059 public:
60 static char ID; // Pass identification, replacement for typeid
61 MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
62
63 virtual bool runOnMachineFunction(MachineFunction &MF);
64
65 /// FIXME: Loop preheaders?
66 ///
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.setPreservesCFG();
69 AU.addRequired<MachineLoopInfo>();
70 AU.addRequired<MachineDominatorTree>();
71 }
72 private:
Bill Wendlingb48519c2007-12-08 01:47:01 +000073 /// VisitAllLoops - Visit all of the loops in depth first order and try to
74 /// hoist invariant instructions from them.
Bill Wendling0f940c92007-12-07 21:42:31 +000075 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +000076 void VisitAllLoops(MachineLoop *L) {
Bill Wendling0f940c92007-12-07 21:42:31 +000077 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
78
79 for (MachineLoop::iterator
Bill Wendlingb48519c2007-12-08 01:47:01 +000080 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
81 MachineLoop *ML = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +000082
Bill Wendlingb48519c2007-12-08 01:47:01 +000083 // Traverse the body of the loop in depth first order on the dominator
84 // tree so that we are guaranteed to see definitions before we see uses.
85 VisitAllLoops(ML);
86 HoistRegion(DT->getNode(ML->getHeader()));
87 }
88
89 HoistRegion(DT->getNode(L->getHeader()));
Bill Wendling0f940c92007-12-07 21:42:31 +000090 }
91
92 /// MapVirtualRegisterDefs - Create a map of which machine instruction
93 /// defines a virtual register.
94 ///
Bill Wendling12ebf142007-12-11 19:40:06 +000095 void MapVirtualRegisterDefs();
Bill Wendling0f940c92007-12-07 21:42:31 +000096
Bill Wendling041b3f82007-12-08 23:58:46 +000097 /// IsInSubLoop - A little predicate that returns true if the specified
Bill Wendling0f940c92007-12-07 21:42:31 +000098 /// basic block is in a subloop of the current one, not the current one
99 /// itself.
100 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000101 bool IsInSubLoop(MachineBasicBlock *BB) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000102 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Bill Wendling650b0522007-12-11 18:45:11 +0000103 return LI->getLoopFor(BB) != CurLoop;
Bill Wendling0f940c92007-12-07 21:42:31 +0000104 }
105
Bill Wendling041b3f82007-12-08 23:58:46 +0000106 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000107 /// invariant. I.e., all virtual register operands are defined outside of
108 /// the loop, physical registers aren't accessed (explicitly or implicitly),
109 /// and the instruction is hoistable.
110 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000111 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000112
113 /// FindPredecessors - Get all of the predecessors of the loop that are not
114 /// back-edges.
115 ///
Bill Wendling650b0522007-12-11 18:45:11 +0000116 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000117 const MachineBasicBlock *Header = CurLoop->getHeader();
118
119 for (MachineBasicBlock::const_pred_iterator
120 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
121 if (!CurLoop->contains(*I))
122 Preds.push_back(*I);
123 }
124
Bill Wendlingb48519c2007-12-08 01:47:01 +0000125 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
126 /// the predecessor basic block (but before the terminator instructions).
Bill Wendling0f940c92007-12-07 21:42:31 +0000127 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000128 void MoveInstToEndOfBlock(MachineBasicBlock *MBB, MachineInstr *MI) {
Bill Wendlingefe2be72007-12-11 23:27:51 +0000129 DEBUG({
130 DOUT << "Hoisting " << *MI;
131 if (MBB->getBasicBlock())
132 DOUT << " to MachineBasicBlock "
133 << MBB->getBasicBlock()->getName();
134 DOUT << "\n";
135 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000136 MachineBasicBlock::iterator Iter = MBB->getFirstTerminator();
137 MBB->insert(Iter, MI);
Bill Wendlingb48519c2007-12-08 01:47:01 +0000138 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000139 }
140
141 /// HoistRegion - Walk the specified region of the CFG (defined by all
142 /// blocks dominated by the specified block, and that are in the current
143 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
144 /// visit definitions before uses, allowing us to hoist a loop body in one
145 /// pass without iteration.
146 ///
147 void HoistRegion(MachineDomTreeNode *N);
148
149 /// Hoist - When an instruction is found to only use loop invariant operands
150 /// that is safe to hoist, this instruction is called to do the dirty work.
151 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000152 void Hoist(MachineInstr &MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000153 };
154
155 char MachineLICM::ID = 0;
156 RegisterPass<MachineLICM> X("machine-licm",
157 "Machine Loop Invariant Code Motion");
158} // end anonymous namespace
159
160FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
161
162/// Hoist expressions out of the specified loop. Note, alias info for inner loop
163/// is not preserved so it is not a good idea to run LICM multiple times on one
164/// loop.
165///
166bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
167 if (!PerformLICM) return false; // For debugging.
168
Bill Wendlinga17ad592007-12-11 22:22:22 +0000169 DOUT << "******** Machine LICM ********\n";
170
Bill Wendling0f940c92007-12-07 21:42:31 +0000171 Changed = false;
Bill Wendling12ebf142007-12-11 19:40:06 +0000172 CurMF = &MF;
173 TII = CurMF->getTarget().getInstrInfo();
Bill Wendling0f940c92007-12-07 21:42:31 +0000174
175 // Get our Loop information...
176 LI = &getAnalysis<MachineLoopInfo>();
177 DT = &getAnalysis<MachineDominatorTree>();
178
Bill Wendling12ebf142007-12-11 19:40:06 +0000179 MapVirtualRegisterDefs();
180
Bill Wendling0f940c92007-12-07 21:42:31 +0000181 for (MachineLoopInfo::iterator
182 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000183 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000184
185 // Visit all of the instructions of the loop. We want to visit the subloops
186 // first, though, so that we can hoist their invariants first into their
187 // containing loop before we process that loop.
Bill Wendlinga17ad592007-12-11 22:22:22 +0000188 VisitAllLoops(CurLoop);
Bill Wendling0f940c92007-12-07 21:42:31 +0000189 }
190
191 return Changed;
192}
193
194/// MapVirtualRegisterDefs - Create a map of which machine instruction defines a
195/// virtual register.
196///
Bill Wendling12ebf142007-12-11 19:40:06 +0000197void MachineLICM::MapVirtualRegisterDefs() {
Bill Wendling0f940c92007-12-07 21:42:31 +0000198 for (MachineFunction::const_iterator
Bill Wendling12ebf142007-12-11 19:40:06 +0000199 I = CurMF->begin(), E = CurMF->end(); I != E; ++I) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000200 const MachineBasicBlock &MBB = *I;
201
202 for (MachineBasicBlock::const_iterator
203 II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
204 const MachineInstr &MI = *II;
205
Bill Wendlingb48519c2007-12-08 01:47:01 +0000206 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
Bill Wendling28bd5f02007-12-11 19:17:04 +0000207 const MachineOperand &MO = MI.getOperand(i);
Bill Wendling0f940c92007-12-07 21:42:31 +0000208
209 if (MO.isRegister() && MO.isDef() &&
Bill Wendlingefe2be72007-12-11 23:27:51 +0000210 MRegisterInfo::isVirtualRegister(MO.getReg())) {
211 VRegDefs.grow(MO.getReg());
Bill Wendling0f940c92007-12-07 21:42:31 +0000212 VRegDefs[MO.getReg()] = &MI;
Bill Wendlingefe2be72007-12-11 23:27:51 +0000213 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000214 }
215 }
216 }
217}
218
219/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
220/// dominated by the specified block, and that are in the current loop) in depth
221/// first order w.r.t the DominatorTree. This allows us to visit definitions
222/// before uses, allowing us to hoist a loop body in one pass without iteration.
223///
224void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
225 assert(N != 0 && "Null dominator tree node?");
226 MachineBasicBlock *BB = N->getBlock();
227
228 // If this subregion is not in the top level loop at all, exit.
229 if (!CurLoop->contains(BB)) return;
230
231 // Only need to process the contents of this block if it is not part of a
232 // subloop (which would already have been processed).
Bill Wendling041b3f82007-12-08 23:58:46 +0000233 if (!IsInSubLoop(BB))
Bill Wendling0f940c92007-12-07 21:42:31 +0000234 for (MachineBasicBlock::iterator
235 I = BB->begin(), E = BB->end(); I != E; ) {
236 MachineInstr &MI = *I++;
237
238 // Try hoisting the instruction out of the loop. We can only do this if
239 // all of the operands of the instruction are loop invariant and if it is
240 // safe to hoist the instruction.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000241 Hoist(MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000242 }
243
244 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
245
246 for (unsigned I = 0, E = Children.size(); I != E; ++I)
247 HoistRegion(Children[I]);
248}
249
Bill Wendling041b3f82007-12-08 23:58:46 +0000250/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000251/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000252/// loop, physical registers aren't accessed explicitly, and there are no side
253/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000254///
Bill Wendling041b3f82007-12-08 23:58:46 +0000255bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Bill Wendling280f4562007-12-18 21:38:04 +0000256 DEBUG({
257 DOUT << "--- Checking if we can hoist " << I;
258 if (I.getInstrDescriptor()->ImplicitUses) {
259 DOUT << " * Instruction has implicit uses:\n";
260
261 const TargetMachine &TM = CurMF->getTarget();
262 const MRegisterInfo *MRI = TM.getRegisterInfo();
263 const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
264
265 for (; *ImpUses; ++ImpUses)
266 DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
267 }
268
269 if (I.getInstrDescriptor()->ImplicitDefs) {
270 DOUT << " * Instruction has implicit defines:\n";
271
272 const TargetMachine &TM = CurMF->getTarget();
273 const MRegisterInfo *MRI = TM.getRegisterInfo();
274 const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
275
276 for (; *ImpDefs; ++ImpDefs)
277 DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
278 }
279
280 if (TII->hasUnmodelledSideEffects(&I))
281 DOUT << " * Instruction has side effects.\n";
282 });
283
Bill Wendling0f940c92007-12-07 21:42:31 +0000284 // The instruction is loop invariant if all of its operands are loop-invariant
285 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
286 const MachineOperand &MO = I.getOperand(i);
287
Bill Wendling280f4562007-12-18 21:38:04 +0000288 if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000289 continue;
290
291 unsigned Reg = MO.getReg();
292
293 // Don't hoist instructions that access physical registers.
294 if (!MRegisterInfo::isVirtualRegister(Reg))
295 return false;
296
Bill Wendlingb48519c2007-12-08 01:47:01 +0000297 assert(VRegDefs[Reg] && "Machine instr not mapped for this vreg?");
Bill Wendling0f940c92007-12-07 21:42:31 +0000298
299 // If the loop contains the definition of an operand, then the instruction
300 // isn't loop invariant.
301 if (CurLoop->contains(VRegDefs[Reg]->getParent()))
302 return false;
303 }
304
Bill Wendling60ff1a32007-12-20 01:08:10 +0000305 // Don't hoist something that has unmodelled side effects.
Bill Wendling280f4562007-12-18 21:38:04 +0000306 if (TII->hasUnmodelledSideEffects(&I)) return false;
307
Bill Wendling0f940c92007-12-07 21:42:31 +0000308 // If we got this far, the instruction is loop invariant!
309 return true;
310}
311
312/// Hoist - When an instruction is found to only use loop invariant operands
313/// that is safe to hoist, this instruction is called to do the dirty work.
314///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000315void MachineLICM::Hoist(MachineInstr &MI) {
Bill Wendling041b3f82007-12-08 23:58:46 +0000316 if (!IsLoopInvariantInst(MI)) return;
Bill Wendling0f940c92007-12-07 21:42:31 +0000317
318 std::vector<MachineBasicBlock*> Preds;
319
320 // Non-back-edge predecessors.
321 FindPredecessors(Preds);
Bill Wendling0f940c92007-12-07 21:42:31 +0000322
Bill Wendlingb48519c2007-12-08 01:47:01 +0000323 // Either we don't have any predecessors(?!) or we have more than one, which
324 // is forbidden.
325 if (Preds.empty() || Preds.size() != 1) return;
Bill Wendling0f940c92007-12-07 21:42:31 +0000326
Bill Wendlingb48519c2007-12-08 01:47:01 +0000327 // Check that the predecessor is qualified to take the hoisted
328 // instruction. I.e., there is only one edge from the predecessor, and it's to
329 // the loop header.
330 MachineBasicBlock *MBB = Preds.front();
Bill Wendling0f940c92007-12-07 21:42:31 +0000331
Bill Wendling041b3f82007-12-08 23:58:46 +0000332 // FIXME: We are assuming at first that the basic block coming into this loop
333 // has only one successor. This isn't the case in general because we haven't
334 // broken critical edges or added preheaders.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000335 if (MBB->succ_size() != 1) return;
336 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
337 "The predecessor doesn't feed directly into the loop header!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000338
Bill Wendlingb48519c2007-12-08 01:47:01 +0000339 // Now move the instructions to the predecessor.
Bill Wendling28bd5f02007-12-11 19:17:04 +0000340 MachineInstr *NewMI = MI.clone();
341 MoveInstToEndOfBlock(MBB, NewMI);
342
343 // Update VRegDefs.
344 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
345 const MachineOperand &MO = NewMI->getOperand(i);
346
347 if (MO.isRegister() && MO.isDef() &&
Bill Wendlingefe2be72007-12-11 23:27:51 +0000348 MRegisterInfo::isVirtualRegister(MO.getReg())) {
349 VRegDefs.grow(MO.getReg());
Bill Wendling28bd5f02007-12-11 19:17:04 +0000350 VRegDefs[MO.getReg()] = NewMI;
Bill Wendlingefe2be72007-12-11 23:27:51 +0000351 }
Bill Wendling28bd5f02007-12-11 19:17:04 +0000352 }
Bill Wendlingb48519c2007-12-08 01:47:01 +0000353
354 // Hoisting was successful! Remove bothersome instruction now.
355 MI.getParent()->remove(&MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000356 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000357}