blob: 99252b2e6069cb2503eaee2ad46c2be368783b66 [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"
Chris Lattnerac695822008-01-04 06:41:45 +000016#include "llvm/CodeGen/Passes.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000017#include "llvm/CodeGen/MachineDominators.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000018#include "llvm/CodeGen/MachineLoopInfo.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000019#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000020#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000021#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000022#include "llvm/Target/TargetMachine.h"
Chris Lattnerac695822008-01-04 06:41:45 +000023#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"
Bill Wendling0f940c92007-12-07 21:42:31 +000028
29using namespace llvm;
30
Bill Wendling041b3f82007-12-08 23:58:46 +000031STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Bill Wendlingb48519c2007-12-08 01:47:01 +000032
Bill Wendling0f940c92007-12-07 21:42:31 +000033namespace {
34 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
Bill Wendling9258cd32008-01-02 19:32:43 +000035 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000036 const TargetInstrInfo *TII;
Bill Wendling12ebf142007-12-11 19:40:06 +000037
Bill Wendling0f940c92007-12-07 21:42:31 +000038 // Various analyses that we use...
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000039 MachineLoopInfo *LI; // Current MachineLoopInfo
40 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling9258cd32008-01-02 19:32:43 +000041 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000042
Bill Wendling0f940c92007-12-07 21:42:31 +000043 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000044 bool Changed; // True if a loop is changed.
45 MachineLoop *CurLoop; // The current loop we are working on.
Bill Wendling0f940c92007-12-07 21:42:31 +000046 public:
47 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000048 MachineLICM() : MachineFunctionPass(&ID) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000049
50 virtual bool runOnMachineFunction(MachineFunction &MF);
51
Bill Wendling074223a2008-03-10 08:13:01 +000052 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000053 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.setPreservesCFG();
55 AU.addRequired<MachineLoopInfo>();
56 AU.addRequired<MachineDominatorTree>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000057 AU.addPreserved<MachineLoopInfo>();
58 AU.addPreserved<MachineDominatorTree>();
59 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000060 }
61 private:
Bill Wendlingb48519c2007-12-08 01:47:01 +000062 /// VisitAllLoops - Visit all of the loops in depth first order and try to
63 /// hoist invariant instructions from them.
Bill Wendling0f940c92007-12-07 21:42:31 +000064 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +000065 void VisitAllLoops(MachineLoop *L) {
Bill Wendling0f940c92007-12-07 21:42:31 +000066 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
67
68 for (MachineLoop::iterator
Bill Wendlingb48519c2007-12-08 01:47:01 +000069 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
70 MachineLoop *ML = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +000071
Bill Wendlingb48519c2007-12-08 01:47:01 +000072 // Traverse the body of the loop in depth first order on the dominator
73 // tree so that we are guaranteed to see definitions before we see uses.
74 VisitAllLoops(ML);
75 HoistRegion(DT->getNode(ML->getHeader()));
76 }
77
78 HoistRegion(DT->getNode(L->getHeader()));
Bill Wendling0f940c92007-12-07 21:42:31 +000079 }
80
Bill Wendling041b3f82007-12-08 23:58:46 +000081 /// IsInSubLoop - A little predicate that returns true if the specified
Bill Wendling0f940c92007-12-07 21:42:31 +000082 /// basic block is in a subloop of the current one, not the current one
83 /// itself.
84 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000085 bool IsInSubLoop(MachineBasicBlock *BB) {
Bill Wendling0f940c92007-12-07 21:42:31 +000086 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Bill Wendling650b0522007-12-11 18:45:11 +000087 return LI->getLoopFor(BB) != CurLoop;
Bill Wendling0f940c92007-12-07 21:42:31 +000088 }
89
Bill Wendling041b3f82007-12-08 23:58:46 +000090 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000091 /// invariant. I.e., all virtual register operands are defined outside of
92 /// the loop, physical registers aren't accessed (explicitly or implicitly),
93 /// and the instruction is hoistable.
94 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000095 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +000096
97 /// FindPredecessors - Get all of the predecessors of the loop that are not
98 /// back-edges.
99 ///
Bill Wendling650b0522007-12-11 18:45:11 +0000100 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000101 const MachineBasicBlock *Header = CurLoop->getHeader();
102
103 for (MachineBasicBlock::const_pred_iterator
104 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
105 if (!CurLoop->contains(*I))
106 Preds.push_back(*I);
107 }
108
Bill Wendlingb48519c2007-12-08 01:47:01 +0000109 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
110 /// the predecessor basic block (but before the terminator instructions).
Bill Wendling0f940c92007-12-07 21:42:31 +0000111 ///
Bill Wendling9258cd32008-01-02 19:32:43 +0000112 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
113 MachineBasicBlock *FromMBB,
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000114 MachineInstr *MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000115
116 /// HoistRegion - Walk the specified region of the CFG (defined by all
117 /// blocks dominated by the specified block, and that are in the current
118 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
119 /// visit definitions before uses, allowing us to hoist a loop body in one
120 /// pass without iteration.
121 ///
122 void HoistRegion(MachineDomTreeNode *N);
123
124 /// Hoist - When an instruction is found to only use loop invariant operands
125 /// that is safe to hoist, this instruction is called to do the dirty work.
126 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000127 void Hoist(MachineInstr &MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000128 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000129} // end anonymous namespace
130
Dan Gohman844731a2008-05-13 00:00:25 +0000131char MachineLICM::ID = 0;
132static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000133X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000134
Bill Wendling0f940c92007-12-07 21:42:31 +0000135FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
136
137/// Hoist expressions out of the specified loop. Note, alias info for inner loop
138/// is not preserved so it is not a good idea to run LICM multiple times on one
139/// loop.
140///
141bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000142 DOUT << "******** Machine LICM ********\n";
143
Bill Wendling0f940c92007-12-07 21:42:31 +0000144 Changed = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000145 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000146 TII = TM->getInstrInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000147 RegInfo = &MF.getRegInfo();
Bill Wendling0f940c92007-12-07 21:42:31 +0000148
149 // Get our Loop information...
150 LI = &getAnalysis<MachineLoopInfo>();
151 DT = &getAnalysis<MachineDominatorTree>();
152
153 for (MachineLoopInfo::iterator
154 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000155 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000156
157 // Visit all of the instructions of the loop. We want to visit the subloops
158 // first, though, so that we can hoist their invariants first into their
159 // containing loop before we process that loop.
Bill Wendlinga17ad592007-12-11 22:22:22 +0000160 VisitAllLoops(CurLoop);
Bill Wendling0f940c92007-12-07 21:42:31 +0000161 }
162
163 return Changed;
164}
165
Bill Wendling0f940c92007-12-07 21:42:31 +0000166/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
167/// dominated by the specified block, and that are in the current loop) in depth
168/// first order w.r.t the DominatorTree. This allows us to visit definitions
169/// before uses, allowing us to hoist a loop body in one pass without iteration.
170///
171void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
172 assert(N != 0 && "Null dominator tree node?");
173 MachineBasicBlock *BB = N->getBlock();
174
175 // If this subregion is not in the top level loop at all, exit.
176 if (!CurLoop->contains(BB)) return;
177
178 // Only need to process the contents of this block if it is not part of a
179 // subloop (which would already have been processed).
Bill Wendling041b3f82007-12-08 23:58:46 +0000180 if (!IsInSubLoop(BB))
Bill Wendling0f940c92007-12-07 21:42:31 +0000181 for (MachineBasicBlock::iterator
182 I = BB->begin(), E = BB->end(); I != E; ) {
183 MachineInstr &MI = *I++;
184
185 // Try hoisting the instruction out of the loop. We can only do this if
186 // all of the operands of the instruction are loop invariant and if it is
187 // safe to hoist the instruction.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000188 Hoist(MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000189 }
190
191 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
192
193 for (unsigned I = 0, E = Children.size(); I != E; ++I)
194 HoistRegion(Children[I]);
195}
196
Bill Wendling041b3f82007-12-08 23:58:46 +0000197/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000198/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000199/// loop, physical registers aren't accessed explicitly, and there are no side
200/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000201///
Bill Wendling041b3f82007-12-08 23:58:46 +0000202bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000203 const TargetInstrDesc &TID = I.getDesc();
204
205 // Ignore stuff that we obviously can't hoist.
206 if (TID.mayStore() || TID.isCall() || TID.isReturn() || TID.isBranch() ||
207 TID.hasUnmodeledSideEffects())
208 return false;
209
210 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000211 // Okay, this instruction does a load. As a refinement, we allow the target
212 // to decide whether the loaded value is actually a constant. If so, we can
213 // actually use it as a load.
214 if (!TII->isInvariantLoad(&I))
Chris Lattnera22edc82008-01-10 23:08:24 +0000215 // FIXME: we should be able to sink loads with no other side effects if
216 // there is nothing that can change memory from here until the end of
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000217 // block. This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000218 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000219 }
Bill Wendling074223a2008-03-10 08:13:01 +0000220
Bill Wendling280f4562007-12-18 21:38:04 +0000221 DEBUG({
222 DOUT << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000223 if (I.getDesc().getImplicitUses()) {
Bill Wendling280f4562007-12-18 21:38:04 +0000224 DOUT << " * Instruction has implicit uses:\n";
225
Dan Gohman6f0d0242008-02-10 18:45:23 +0000226 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000227 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000228 *ImpUses; ++ImpUses)
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000229 DOUT << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000230 }
231
Chris Lattner749c6f62008-01-07 07:27:27 +0000232 if (I.getDesc().getImplicitDefs()) {
Bill Wendling280f4562007-12-18 21:38:04 +0000233 DOUT << " * Instruction has implicit defines:\n";
234
Dan Gohman6f0d0242008-02-10 18:45:23 +0000235 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000236 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000237 *ImpDefs; ++ImpDefs)
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000238 DOUT << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000239 }
Bill Wendling280f4562007-12-18 21:38:04 +0000240 });
241
Bill Wendlingd3361e92008-08-18 00:33:49 +0000242 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
243 DOUT << "Cannot hoist with implicit defines or uses\n";
244 return false;
245 }
246
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000247 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000248 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
249 const MachineOperand &MO = I.getOperand(i);
250
Dan Gohmand735b802008-10-03 15:45:36 +0000251 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000252 continue;
253
254 if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
255 // Don't hoist an instruction that defines a physical register.
256 return false;
257
258 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000259 continue;
260
261 unsigned Reg = MO.getReg();
Bill Wendling074223a2008-03-10 08:13:01 +0000262 if (Reg == 0) continue;
Bill Wendling0f940c92007-12-07 21:42:31 +0000263
264 // Don't hoist instructions that access physical registers.
Bill Wendling074223a2008-03-10 08:13:01 +0000265 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Bill Wendling0f940c92007-12-07 21:42:31 +0000266 return false;
267
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000268 assert(RegInfo->getVRegDef(Reg) &&
269 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000270
271 // If the loop contains the definition of an operand, then the instruction
272 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000273 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000274 return false;
275 }
276
277 // If we got this far, the instruction is loop invariant!
278 return true;
279}
280
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000281/// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of the
282/// predecessor basic block (but before the terminator instructions).
283///
284void MachineLICM::MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
285 MachineBasicBlock *FromMBB,
286 MachineInstr *MI) {
287 DEBUG({
288 DOUT << "Hoisting " << *MI;
289 if (ToMBB->getBasicBlock())
290 DOUT << " to MachineBasicBlock "
291 << ToMBB->getBasicBlock()->getName();
292 if (FromMBB->getBasicBlock())
293 DOUT << " from MachineBasicBlock "
294 << FromMBB->getBasicBlock()->getName();
295 DOUT << "\n";
296 });
297
298 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
299 MachineBasicBlock::iterator To, From = FromMBB->begin();
300
301 while (&*From != MI)
302 ++From;
303
304 assert(From != FromMBB->end() && "Didn't find instr in BB!");
305
306 To = From;
307 ToMBB->splice(WhereIter, FromMBB, From, ++To);
308 ++NumHoisted;
309}
310
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000311/// Hoist - When an instruction is found to use only loop invariant operands
312/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000313///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000314void MachineLICM::Hoist(MachineInstr &MI) {
Bill Wendling041b3f82007-12-08 23:58:46 +0000315 if (!IsLoopInvariantInst(MI)) return;
Bill Wendling0f940c92007-12-07 21:42:31 +0000316
317 std::vector<MachineBasicBlock*> Preds;
318
319 // Non-back-edge predecessors.
320 FindPredecessors(Preds);
Bill Wendling0f940c92007-12-07 21:42:31 +0000321
Bill Wendlingb48519c2007-12-08 01:47:01 +0000322 // Either we don't have any predecessors(?!) or we have more than one, which
323 // is forbidden.
324 if (Preds.empty() || Preds.size() != 1) return;
Bill Wendling0f940c92007-12-07 21:42:31 +0000325
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000326 // Check that the predecessor is qualified to take the hoisted instruction.
327 // I.e., there is only one edge from the predecessor, and it's to the loop
328 // header.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000329 MachineBasicBlock *MBB = Preds.front();
Bill Wendling0f940c92007-12-07 21:42:31 +0000330
Bill Wendling041b3f82007-12-08 23:58:46 +0000331 // FIXME: We are assuming at first that the basic block coming into this loop
332 // has only one successor. This isn't the case in general because we haven't
333 // broken critical edges or added preheaders.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000334 if (MBB->succ_size() != 1) return;
335 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
336 "The predecessor doesn't feed directly into the loop header!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000337
Bill Wendlingb48519c2007-12-08 01:47:01 +0000338 // Now move the instructions to the predecessor.
Bill Wendling9258cd32008-01-02 19:32:43 +0000339 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000340 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000341}