blob: 10f52a6195533f83cd4e4f7d235f0bbaa1b9d334 [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/Statistic.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Debug.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000027
28using namespace llvm;
29
Bill Wendling041b3f82007-12-08 23:58:46 +000030STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Bill Wendlingb48519c2007-12-08 01:47:01 +000031
Bill Wendling0f940c92007-12-07 21:42:31 +000032namespace {
33 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
Bill Wendling9258cd32008-01-02 19:32:43 +000034 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000035 const TargetInstrInfo *TII;
Bill Wendling12ebf142007-12-11 19:40:06 +000036
Bill Wendling0f940c92007-12-07 21:42:31 +000037 // Various analyses that we use...
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000038 MachineLoopInfo *LI; // Current MachineLoopInfo
39 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling9258cd32008-01-02 19:32:43 +000040 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000041
Bill Wendling0f940c92007-12-07 21:42:31 +000042 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000043 bool Changed; // True if a loop is changed.
44 MachineLoop *CurLoop; // The current loop we are working on.
Bill Wendling0f940c92007-12-07 21:42:31 +000045 public:
46 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000047 MachineLICM() : MachineFunctionPass(&ID) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000048
49 virtual bool runOnMachineFunction(MachineFunction &MF);
50
Dan Gohman72241702008-12-18 01:37:56 +000051 const char *getPassName() const { return "Machine Instruction LICM"; }
52
Bill Wendling074223a2008-03-10 08:13:01 +000053 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000054 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.setPreservesCFG();
56 AU.addRequired<MachineLoopInfo>();
57 AU.addRequired<MachineDominatorTree>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000058 AU.addPreserved<MachineLoopInfo>();
59 AU.addPreserved<MachineDominatorTree>();
60 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000061 }
62 private:
Bill Wendlingb48519c2007-12-08 01:47:01 +000063 /// VisitAllLoops - Visit all of the loops in depth first order and try to
64 /// hoist invariant instructions from them.
Bill Wendling0f940c92007-12-07 21:42:31 +000065 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +000066 void VisitAllLoops(MachineLoop *L) {
Bill Wendling0f940c92007-12-07 21:42:31 +000067 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
68
69 for (MachineLoop::iterator
Bill Wendlingb48519c2007-12-08 01:47:01 +000070 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
71 MachineLoop *ML = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +000072
Bill Wendlingb48519c2007-12-08 01:47:01 +000073 // Traverse the body of the loop in depth first order on the dominator
74 // tree so that we are guaranteed to see definitions before we see uses.
75 VisitAllLoops(ML);
76 HoistRegion(DT->getNode(ML->getHeader()));
77 }
78
79 HoistRegion(DT->getNode(L->getHeader()));
Bill Wendling0f940c92007-12-07 21:42:31 +000080 }
81
Bill Wendling041b3f82007-12-08 23:58:46 +000082 /// IsInSubLoop - A little predicate that returns true if the specified
Bill Wendling0f940c92007-12-07 21:42:31 +000083 /// basic block is in a subloop of the current one, not the current one
84 /// itself.
85 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000086 bool IsInSubLoop(MachineBasicBlock *BB) {
Bill Wendling0f940c92007-12-07 21:42:31 +000087 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Bill Wendling650b0522007-12-11 18:45:11 +000088 return LI->getLoopFor(BB) != CurLoop;
Bill Wendling0f940c92007-12-07 21:42:31 +000089 }
90
Bill Wendling041b3f82007-12-08 23:58:46 +000091 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000092 /// invariant. I.e., all virtual register operands are defined outside of
93 /// the loop, physical registers aren't accessed (explicitly or implicitly),
94 /// and the instruction is hoistable.
95 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000096 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +000097
98 /// FindPredecessors - Get all of the predecessors of the loop that are not
99 /// back-edges.
100 ///
Bill Wendling650b0522007-12-11 18:45:11 +0000101 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000102 const MachineBasicBlock *Header = CurLoop->getHeader();
103
104 for (MachineBasicBlock::const_pred_iterator
105 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
106 if (!CurLoop->contains(*I))
107 Preds.push_back(*I);
108 }
109
Bill Wendlingb48519c2007-12-08 01:47:01 +0000110 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
111 /// the predecessor basic block (but before the terminator instructions).
Bill Wendling0f940c92007-12-07 21:42:31 +0000112 ///
Bill Wendling9258cd32008-01-02 19:32:43 +0000113 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
114 MachineBasicBlock *FromMBB,
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000115 MachineInstr *MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000116
117 /// HoistRegion - Walk the specified region of the CFG (defined by all
118 /// blocks dominated by the specified block, and that are in the current
119 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
120 /// visit definitions before uses, allowing us to hoist a loop body in one
121 /// pass without iteration.
122 ///
123 void HoistRegion(MachineDomTreeNode *N);
124
125 /// Hoist - When an instruction is found to only use loop invariant operands
126 /// that is safe to hoist, this instruction is called to do the dirty work.
127 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000128 void Hoist(MachineInstr &MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000129 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000130} // end anonymous namespace
131
Dan Gohman844731a2008-05-13 00:00:25 +0000132char MachineLICM::ID = 0;
133static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000134X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000135
Bill Wendling0f940c92007-12-07 21:42:31 +0000136FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
137
138/// Hoist expressions out of the specified loop. Note, alias info for inner loop
139/// is not preserved so it is not a good idea to run LICM multiple times on one
140/// loop.
141///
142bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000143 DOUT << "******** Machine LICM ********\n";
144
Bill Wendling0f940c92007-12-07 21:42:31 +0000145 Changed = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000146 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000147 TII = TM->getInstrInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000148 RegInfo = &MF.getRegInfo();
Bill Wendling0f940c92007-12-07 21:42:31 +0000149
150 // Get our Loop information...
151 LI = &getAnalysis<MachineLoopInfo>();
152 DT = &getAnalysis<MachineDominatorTree>();
153
154 for (MachineLoopInfo::iterator
155 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000156 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000157
158 // Visit all of the instructions of the loop. We want to visit the subloops
159 // first, though, so that we can hoist their invariants first into their
160 // containing loop before we process that loop.
Bill Wendlinga17ad592007-12-11 22:22:22 +0000161 VisitAllLoops(CurLoop);
Bill Wendling0f940c92007-12-07 21:42:31 +0000162 }
163
164 return Changed;
165}
166
Bill Wendling0f940c92007-12-07 21:42:31 +0000167/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
168/// dominated by the specified block, and that are in the current loop) in depth
169/// first order w.r.t the DominatorTree. This allows us to visit definitions
170/// before uses, allowing us to hoist a loop body in one pass without iteration.
171///
172void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
173 assert(N != 0 && "Null dominator tree node?");
174 MachineBasicBlock *BB = N->getBlock();
175
176 // If this subregion is not in the top level loop at all, exit.
177 if (!CurLoop->contains(BB)) return;
178
179 // Only need to process the contents of this block if it is not part of a
180 // subloop (which would already have been processed).
Bill Wendling041b3f82007-12-08 23:58:46 +0000181 if (!IsInSubLoop(BB))
Bill Wendling0f940c92007-12-07 21:42:31 +0000182 for (MachineBasicBlock::iterator
183 I = BB->begin(), E = BB->end(); I != E; ) {
184 MachineInstr &MI = *I++;
185
186 // Try hoisting the instruction out of the loop. We can only do this if
187 // all of the operands of the instruction are loop invariant and if it is
188 // safe to hoist the instruction.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000189 Hoist(MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000190 }
191
192 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
193
194 for (unsigned I = 0, E = Children.size(); I != E; ++I)
195 HoistRegion(Children[I]);
196}
197
Bill Wendling041b3f82007-12-08 23:58:46 +0000198/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000199/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000200/// loop, physical registers aren't accessed explicitly, and there are no side
201/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000202///
Bill Wendling041b3f82007-12-08 23:58:46 +0000203bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000204 const TargetInstrDesc &TID = I.getDesc();
205
206 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000207 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000208 TID.hasUnmodeledSideEffects())
209 return false;
210
211 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000212 // Okay, this instruction does a load. As a refinement, we allow the target
213 // to decide whether the loaded value is actually a constant. If so, we can
214 // actually use it as a load.
215 if (!TII->isInvariantLoad(&I))
Chris Lattnera22edc82008-01-10 23:08:24 +0000216 // FIXME: we should be able to sink loads with no other side effects if
217 // there is nothing that can change memory from here until the end of
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000218 // block. This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000219 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000220 }
Bill Wendling074223a2008-03-10 08:13:01 +0000221
Bill Wendling280f4562007-12-18 21:38:04 +0000222 DEBUG({
223 DOUT << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000224 if (I.getDesc().getImplicitUses()) {
Bill Wendling280f4562007-12-18 21:38:04 +0000225 DOUT << " * Instruction has implicit uses:\n";
226
Dan Gohman6f0d0242008-02-10 18:45:23 +0000227 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000228 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000229 *ImpUses; ++ImpUses)
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000230 DOUT << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000231 }
232
Chris Lattner749c6f62008-01-07 07:27:27 +0000233 if (I.getDesc().getImplicitDefs()) {
Bill Wendling280f4562007-12-18 21:38:04 +0000234 DOUT << " * Instruction has implicit defines:\n";
235
Dan Gohman6f0d0242008-02-10 18:45:23 +0000236 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000237 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000238 *ImpDefs; ++ImpDefs)
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000239 DOUT << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000240 }
Bill Wendling280f4562007-12-18 21:38:04 +0000241 });
242
Bill Wendlingd3361e92008-08-18 00:33:49 +0000243 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
244 DOUT << "Cannot hoist with implicit defines or uses\n";
245 return false;
246 }
247
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000248 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000249 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
250 const MachineOperand &MO = I.getOperand(i);
251
Dan Gohmand735b802008-10-03 15:45:36 +0000252 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000253 continue;
254
255 if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
256 // Don't hoist an instruction that defines a physical register.
257 return false;
258
259 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000260 continue;
261
262 unsigned Reg = MO.getReg();
Bill Wendling074223a2008-03-10 08:13:01 +0000263 if (Reg == 0) continue;
Bill Wendling0f940c92007-12-07 21:42:31 +0000264
265 // Don't hoist instructions that access physical registers.
Bill Wendling074223a2008-03-10 08:13:01 +0000266 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Bill Wendling0f940c92007-12-07 21:42:31 +0000267 return false;
268
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000269 assert(RegInfo->getVRegDef(Reg) &&
270 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000271
272 // If the loop contains the definition of an operand, then the instruction
273 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000274 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000275 return false;
276 }
277
278 // If we got this far, the instruction is loop invariant!
279 return true;
280}
281
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000282/// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of the
283/// predecessor basic block (but before the terminator instructions).
284///
285void MachineLICM::MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
286 MachineBasicBlock *FromMBB,
287 MachineInstr *MI) {
288 DEBUG({
289 DOUT << "Hoisting " << *MI;
290 if (ToMBB->getBasicBlock())
291 DOUT << " to MachineBasicBlock "
292 << ToMBB->getBasicBlock()->getName();
293 if (FromMBB->getBasicBlock())
294 DOUT << " from MachineBasicBlock "
295 << FromMBB->getBasicBlock()->getName();
296 DOUT << "\n";
297 });
298
299 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
300 MachineBasicBlock::iterator To, From = FromMBB->begin();
301
302 while (&*From != MI)
303 ++From;
304
305 assert(From != FromMBB->end() && "Didn't find instr in BB!");
306
307 To = From;
308 ToMBB->splice(WhereIter, FromMBB, From, ++To);
309 ++NumHoisted;
310}
311
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000312/// Hoist - When an instruction is found to use only loop invariant operands
313/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000314///
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 Wendlingacb04ec2008-08-31 02:30:23 +0000327 // Check that the predecessor is qualified to take the hoisted instruction.
328 // I.e., there is only one edge from the predecessor, and it's to the loop
329 // header.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000330 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 Wendling9258cd32008-01-02 19:32:43 +0000340 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000341 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000342}