blob: 200ca0bfbce171ace07c09bed0e31cd529778b8d [file] [log] [blame]
Bill Wendlingb958b0d2007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Bill Wendling and is distributed under the
6// University of Illinois Open Source 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
15#define DEBUG_TYPE "machine-licm"
Bill Wendling7c7888b2007-12-08 01:47:01 +000016#include "llvm/ADT/IndexedMap.h"
Bill Wendlingb958b0d2007-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 Wendlingb958b0d2007-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 Wendling3caa4702007-12-11 23:27:51 +000029#include "llvm/Target/TargetInstrInfo.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000030#include "llvm/Target/TargetMachine.h"
Bill Wendlingb958b0d2007-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 Wendling7c7888b2007-12-08 01:47:01 +000038 cl::init(false), cl::Hidden,
39 cl::desc("Perform loop-invariant code motion on machine code"));
Bill Wendlingb958b0d2007-12-07 21:42:31 +000040}
41
Bill Wendling0fe34c22007-12-08 23:58:46 +000042STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Bill Wendling7c7888b2007-12-08 01:47:01 +000043
Bill Wendlingb958b0d2007-12-07 21:42:31 +000044namespace {
45 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
Bill Wendling3caa4702007-12-11 23:27:51 +000046 const TargetInstrInfo *TII;
47 MachineFunction *CurMF; // Current MachineFunction
Bill Wendlingd9b9be62007-12-11 19:40:06 +000048
Bill Wendlingb958b0d2007-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 Wendlingb958b0d2007-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 Wendling7c7888b2007-12-08 01:47:01 +000058 IndexedMap<const MachineInstr*, VirtReg2IndexFunctor> VRegDefs;
Bill Wendlingb958b0d2007-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 Wendling7c7888b2007-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 Wendlingb958b0d2007-12-07 21:42:31 +000075 ///
Bill Wendling7c7888b2007-12-08 01:47:01 +000076 void VisitAllLoops(MachineLoop *L) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +000077 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
78
79 for (MachineLoop::iterator
Bill Wendling7c7888b2007-12-08 01:47:01 +000080 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
81 MachineLoop *ML = *I;
Bill Wendlingb958b0d2007-12-07 21:42:31 +000082
Bill Wendling7c7888b2007-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 Wendlingb958b0d2007-12-07 21:42:31 +000090 }
91
92 /// MapVirtualRegisterDefs - Create a map of which machine instruction
93 /// defines a virtual register.
94 ///
Bill Wendlingd9b9be62007-12-11 19:40:06 +000095 void MapVirtualRegisterDefs();
Bill Wendlingb958b0d2007-12-07 21:42:31 +000096
Bill Wendling0fe34c22007-12-08 23:58:46 +000097 /// IsInSubLoop - A little predicate that returns true if the specified
Bill Wendlingb958b0d2007-12-07 21:42:31 +000098 /// basic block is in a subloop of the current one, not the current one
99 /// itself.
100 ///
Bill Wendling0fe34c22007-12-08 23:58:46 +0000101 bool IsInSubLoop(MachineBasicBlock *BB) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000102 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Bill Wendling2dfc9eb2007-12-11 18:45:11 +0000103 return LI->getLoopFor(BB) != CurLoop;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000104 }
105
Bill Wendling0fe34c22007-12-08 23:58:46 +0000106 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingb958b0d2007-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 Wendling0fe34c22007-12-08 23:58:46 +0000111 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000112
113 /// FindPredecessors - Get all of the predecessors of the loop that are not
114 /// back-edges.
115 ///
Bill Wendling2dfc9eb2007-12-11 18:45:11 +0000116 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
Bill Wendlingb958b0d2007-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 Wendling7c7888b2007-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 Wendlingb958b0d2007-12-07 21:42:31 +0000127 ///
Bill Wendling7c7888b2007-12-08 01:47:01 +0000128 void MoveInstToEndOfBlock(MachineBasicBlock *MBB, MachineInstr *MI) {
Bill Wendling3caa4702007-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 Wendlingb958b0d2007-12-07 21:42:31 +0000136 MachineBasicBlock::iterator Iter = MBB->getFirstTerminator();
137 MBB->insert(Iter, MI);
Bill Wendling7c7888b2007-12-08 01:47:01 +0000138 ++NumHoisted;
Bill Wendlingb958b0d2007-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 Wendling7c7888b2007-12-08 01:47:01 +0000152 void Hoist(MachineInstr &MI);
Bill Wendlingb958b0d2007-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 Wendling14ba7ae2007-12-11 22:22:22 +0000169 DOUT << "******** Machine LICM ********\n";
170
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000171 Changed = false;
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000172 CurMF = &MF;
173 TII = CurMF->getTarget().getInstrInfo();
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000174
175 // Get our Loop information...
176 LI = &getAnalysis<MachineLoopInfo>();
177 DT = &getAnalysis<MachineDominatorTree>();
178
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000179 MapVirtualRegisterDefs();
180
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000181 for (MachineLoopInfo::iterator
182 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendling14ba7ae2007-12-11 22:22:22 +0000183 CurLoop = *I;
Bill Wendlingb958b0d2007-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 Wendling14ba7ae2007-12-11 22:22:22 +0000188 VisitAllLoops(CurLoop);
Bill Wendlingb958b0d2007-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 Wendlingd9b9be62007-12-11 19:40:06 +0000197void MachineLICM::MapVirtualRegisterDefs() {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000198 for (MachineFunction::const_iterator
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000199 I = CurMF->begin(), E = CurMF->end(); I != E; ++I) {
Bill Wendlingb958b0d2007-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 Wendling7c7888b2007-12-08 01:47:01 +0000206 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000207 const MachineOperand &MO = MI.getOperand(i);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000208
209 if (MO.isRegister() && MO.isDef() &&
Bill Wendling3caa4702007-12-11 23:27:51 +0000210 MRegisterInfo::isVirtualRegister(MO.getReg())) {
211 VRegDefs.grow(MO.getReg());
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000212 VRegDefs[MO.getReg()] = &MI;
Bill Wendling3caa4702007-12-11 23:27:51 +0000213 }
Bill Wendlingb958b0d2007-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 Wendling0fe34c22007-12-08 23:58:46 +0000233 if (!IsInSubLoop(BB))
Bill Wendlingb958b0d2007-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 Wendling7c7888b2007-12-08 01:47:01 +0000241 Hoist(MI);
Bill Wendlingb958b0d2007-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 Wendling0fe34c22007-12-08 23:58:46 +0000250/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000251/// invariant. I.e., all virtual register operands are defined outside of the
252/// loop, physical registers aren't accessed (explicitly or implicitly), and the
253/// instruction is hoistable.
254///
Bill Wendling0fe34c22007-12-08 23:58:46 +0000255bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Bill Wendling558e3bc2007-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
284#if 0
285 // FIXME: Don't hoist if this instruction implicitly reads physical registers.
286 if (I.getInstrDescriptor()->ImplicitUses ||
287 I.getInstrDescriptor()->ImplicitDefs)
288 return false;
289#endif
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000290
291 // The instruction is loop invariant if all of its operands are loop-invariant
292 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
293 const MachineOperand &MO = I.getOperand(i);
294
Bill Wendling558e3bc2007-12-18 21:38:04 +0000295 if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000296 continue;
297
298 unsigned Reg = MO.getReg();
299
300 // Don't hoist instructions that access physical registers.
301 if (!MRegisterInfo::isVirtualRegister(Reg))
302 return false;
303
Bill Wendling7c7888b2007-12-08 01:47:01 +0000304 assert(VRegDefs[Reg] && "Machine instr not mapped for this vreg?");
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000305
306 // If the loop contains the definition of an operand, then the instruction
307 // isn't loop invariant.
308 if (CurLoop->contains(VRegDefs[Reg]->getParent()))
309 return false;
310 }
311
Bill Wendling558e3bc2007-12-18 21:38:04 +0000312 // Don't hoist something that has side effects.
313 if (TII->hasUnmodelledSideEffects(&I)) return false;
314
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000315 // If we got this far, the instruction is loop invariant!
316 return true;
317}
318
319/// Hoist - When an instruction is found to only use loop invariant operands
320/// that is safe to hoist, this instruction is called to do the dirty work.
321///
Bill Wendling7c7888b2007-12-08 01:47:01 +0000322void MachineLICM::Hoist(MachineInstr &MI) {
Bill Wendling0fe34c22007-12-08 23:58:46 +0000323 if (!IsLoopInvariantInst(MI)) return;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000324
325 std::vector<MachineBasicBlock*> Preds;
326
327 // Non-back-edge predecessors.
328 FindPredecessors(Preds);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000329
Bill Wendling7c7888b2007-12-08 01:47:01 +0000330 // Either we don't have any predecessors(?!) or we have more than one, which
331 // is forbidden.
332 if (Preds.empty() || Preds.size() != 1) return;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000333
Bill Wendling7c7888b2007-12-08 01:47:01 +0000334 // Check that the predecessor is qualified to take the hoisted
335 // instruction. I.e., there is only one edge from the predecessor, and it's to
336 // the loop header.
337 MachineBasicBlock *MBB = Preds.front();
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000338
Bill Wendling0fe34c22007-12-08 23:58:46 +0000339 // FIXME: We are assuming at first that the basic block coming into this loop
340 // has only one successor. This isn't the case in general because we haven't
341 // broken critical edges or added preheaders.
Bill Wendling7c7888b2007-12-08 01:47:01 +0000342 if (MBB->succ_size() != 1) return;
343 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
344 "The predecessor doesn't feed directly into the loop header!");
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000345
Bill Wendling7c7888b2007-12-08 01:47:01 +0000346 // Now move the instructions to the predecessor.
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000347 MachineInstr *NewMI = MI.clone();
348 MoveInstToEndOfBlock(MBB, NewMI);
349
350 // Update VRegDefs.
351 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
352 const MachineOperand &MO = NewMI->getOperand(i);
353
354 if (MO.isRegister() && MO.isDef() &&
Bill Wendling3caa4702007-12-11 23:27:51 +0000355 MRegisterInfo::isVirtualRegister(MO.getReg())) {
356 VRegDefs.grow(MO.getReg());
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000357 VRegDefs[MO.getReg()] = NewMI;
Bill Wendling3caa4702007-12-11 23:27:51 +0000358 }
Bill Wendlinge91b2ef2007-12-11 19:17:04 +0000359 }
Bill Wendling7c7888b2007-12-08 01:47:01 +0000360
361 // Hoisting was successful! Remove bothersome instruction now.
362 MI.getParent()->remove(&MI);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000363 Changed = true;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000364}