blob: 4ba63bc9b50aee8a3a79e02b0c6881b26e8bbf7b [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"
Bill Wendling0f940c92007-12-07 21:42:31 +000020#include "llvm/Target/MRegisterInfo.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
31namespace {
32 // Hidden options to help debugging
33 cl::opt<bool>
34 PerformLICM("machine-licm",
Bill Wendlingb48519c2007-12-08 01:47:01 +000035 cl::init(false), cl::Hidden,
36 cl::desc("Perform loop-invariant code motion on machine code"));
Bill Wendling0f940c92007-12-07 21:42:31 +000037}
38
Bill Wendling041b3f82007-12-08 23:58:46 +000039STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Bill Wendlingb48519c2007-12-08 01:47:01 +000040
Bill Wendling0f940c92007-12-07 21:42:31 +000041namespace {
42 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
Bill Wendling9258cd32008-01-02 19:32:43 +000043 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000044 const TargetInstrInfo *TII;
45 MachineFunction *CurMF; // Current MachineFunction
Bill Wendling12ebf142007-12-11 19:40:06 +000046
Bill Wendling0f940c92007-12-07 21:42:31 +000047 // Various analyses that we use...
48 MachineLoopInfo *LI; // Current MachineLoopInfo
49 MachineDominatorTree *DT; // Machine dominator tree for the current Loop
Bill Wendling9258cd32008-01-02 19:32:43 +000050 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000051
Bill Wendling0f940c92007-12-07 21:42:31 +000052 // State that is updated as we process loops
53 bool Changed; // True if a loop is changed.
54 MachineLoop *CurLoop; // The current loop we are working on.
Bill Wendling0f940c92007-12-07 21:42:31 +000055 public:
56 static char ID; // Pass identification, replacement for typeid
57 MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
58
59 virtual bool runOnMachineFunction(MachineFunction &MF);
60
61 /// FIXME: Loop preheaders?
62 ///
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.setPreservesCFG();
65 AU.addRequired<MachineLoopInfo>();
66 AU.addRequired<MachineDominatorTree>();
67 }
68 private:
Bill Wendlingb48519c2007-12-08 01:47:01 +000069 /// VisitAllLoops - Visit all of the loops in depth first order and try to
70 /// hoist invariant instructions from them.
Bill Wendling0f940c92007-12-07 21:42:31 +000071 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +000072 void VisitAllLoops(MachineLoop *L) {
Bill Wendling0f940c92007-12-07 21:42:31 +000073 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
74
75 for (MachineLoop::iterator
Bill Wendlingb48519c2007-12-08 01:47:01 +000076 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
77 MachineLoop *ML = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +000078
Bill Wendlingb48519c2007-12-08 01:47:01 +000079 // Traverse the body of the loop in depth first order on the dominator
80 // tree so that we are guaranteed to see definitions before we see uses.
81 VisitAllLoops(ML);
82 HoistRegion(DT->getNode(ML->getHeader()));
83 }
84
85 HoistRegion(DT->getNode(L->getHeader()));
Bill Wendling0f940c92007-12-07 21:42:31 +000086 }
87
Bill Wendling041b3f82007-12-08 23:58:46 +000088 /// IsInSubLoop - A little predicate that returns true if the specified
Bill Wendling0f940c92007-12-07 21:42:31 +000089 /// basic block is in a subloop of the current one, not the current one
90 /// itself.
91 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000092 bool IsInSubLoop(MachineBasicBlock *BB) {
Bill Wendling0f940c92007-12-07 21:42:31 +000093 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Bill Wendling650b0522007-12-11 18:45:11 +000094 return LI->getLoopFor(BB) != CurLoop;
Bill Wendling0f940c92007-12-07 21:42:31 +000095 }
96
Bill Wendling041b3f82007-12-08 23:58:46 +000097 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000098 /// invariant. I.e., all virtual register operands are defined outside of
99 /// the loop, physical registers aren't accessed (explicitly or implicitly),
100 /// and the instruction is hoistable.
101 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000102 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000103
104 /// FindPredecessors - Get all of the predecessors of the loop that are not
105 /// back-edges.
106 ///
Bill Wendling650b0522007-12-11 18:45:11 +0000107 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000108 const MachineBasicBlock *Header = CurLoop->getHeader();
109
110 for (MachineBasicBlock::const_pred_iterator
111 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
112 if (!CurLoop->contains(*I))
113 Preds.push_back(*I);
114 }
115
Bill Wendlingb48519c2007-12-08 01:47:01 +0000116 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
117 /// the predecessor basic block (but before the terminator instructions).
Bill Wendling0f940c92007-12-07 21:42:31 +0000118 ///
Bill Wendling9258cd32008-01-02 19:32:43 +0000119 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
120 MachineBasicBlock *FromMBB,
121 MachineInstr *MI) {
Bill Wendlingefe2be72007-12-11 23:27:51 +0000122 DEBUG({
123 DOUT << "Hoisting " << *MI;
Bill Wendling9258cd32008-01-02 19:32:43 +0000124 if (ToMBB->getBasicBlock())
Bill Wendlingefe2be72007-12-11 23:27:51 +0000125 DOUT << " to MachineBasicBlock "
Bill Wendling9258cd32008-01-02 19:32:43 +0000126 << ToMBB->getBasicBlock()->getName();
Bill Wendlingefe2be72007-12-11 23:27:51 +0000127 DOUT << "\n";
128 });
Bill Wendling9258cd32008-01-02 19:32:43 +0000129
130 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
131 MachineBasicBlock::iterator To, From = FromMBB->begin();
132
133 while (&*From != MI)
134 ++From;
135
136 assert(From != FromMBB->end() && "Didn't find instr in BB!");
137
138 To = From;
139 ToMBB->splice(WhereIter, FromMBB, From, ++To);
Bill Wendlingb48519c2007-12-08 01:47:01 +0000140 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000141 }
142
143 /// HoistRegion - Walk the specified region of the CFG (defined by all
144 /// blocks dominated by the specified block, and that are in the current
145 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
146 /// visit definitions before uses, allowing us to hoist a loop body in one
147 /// pass without iteration.
148 ///
149 void HoistRegion(MachineDomTreeNode *N);
150
151 /// Hoist - When an instruction is found to only use loop invariant operands
152 /// that is safe to hoist, this instruction is called to do the dirty work.
153 ///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000154 void Hoist(MachineInstr &MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000155 };
156
157 char MachineLICM::ID = 0;
158 RegisterPass<MachineLICM> X("machine-licm",
159 "Machine Loop Invariant Code Motion");
160} // end anonymous namespace
161
162FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
163
164/// Hoist expressions out of the specified loop. Note, alias info for inner loop
165/// is not preserved so it is not a good idea to run LICM multiple times on one
166/// loop.
167///
168bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
169 if (!PerformLICM) return false; // For debugging.
170
Bill Wendlinga17ad592007-12-11 22:22:22 +0000171 DOUT << "******** Machine LICM ********\n";
172
Bill Wendling0f940c92007-12-07 21:42:31 +0000173 Changed = false;
Bill Wendling12ebf142007-12-11 19:40:06 +0000174 CurMF = &MF;
Bill Wendling9258cd32008-01-02 19:32:43 +0000175 TM = &CurMF->getTarget();
176 TII = TM->getInstrInfo();
Bill Wendlingdde059a2008-01-02 21:10:54 +0000177 RegInfo = &CurMF->getRegInfo();
Bill Wendling0f940c92007-12-07 21:42:31 +0000178
179 // Get our Loop information...
180 LI = &getAnalysis<MachineLoopInfo>();
181 DT = &getAnalysis<MachineDominatorTree>();
182
183 for (MachineLoopInfo::iterator
184 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000185 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000186
187 // Visit all of the instructions of the loop. We want to visit the subloops
188 // first, though, so that we can hoist their invariants first into their
189 // containing loop before we process that loop.
Bill Wendlinga17ad592007-12-11 22:22:22 +0000190 VisitAllLoops(CurLoop);
Bill Wendling0f940c92007-12-07 21:42:31 +0000191 }
192
193 return Changed;
194}
195
Bill Wendling0f940c92007-12-07 21:42:31 +0000196/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
197/// dominated by the specified block, and that are in the current loop) in depth
198/// first order w.r.t the DominatorTree. This allows us to visit definitions
199/// before uses, allowing us to hoist a loop body in one pass without iteration.
200///
201void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
202 assert(N != 0 && "Null dominator tree node?");
203 MachineBasicBlock *BB = N->getBlock();
204
205 // If this subregion is not in the top level loop at all, exit.
206 if (!CurLoop->contains(BB)) return;
207
208 // Only need to process the contents of this block if it is not part of a
209 // subloop (which would already have been processed).
Bill Wendling041b3f82007-12-08 23:58:46 +0000210 if (!IsInSubLoop(BB))
Bill Wendling0f940c92007-12-07 21:42:31 +0000211 for (MachineBasicBlock::iterator
212 I = BB->begin(), E = BB->end(); I != E; ) {
213 MachineInstr &MI = *I++;
214
215 // Try hoisting the instruction out of the loop. We can only do this if
216 // all of the operands of the instruction are loop invariant and if it is
217 // safe to hoist the instruction.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000218 Hoist(MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000219 }
220
221 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
222
223 for (unsigned I = 0, E = Children.size(); I != E; ++I)
224 HoistRegion(Children[I]);
225}
226
Bill Wendling041b3f82007-12-08 23:58:46 +0000227/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000228/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000229/// loop, physical registers aren't accessed explicitly, and there are no side
230/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000231///
Bill Wendling041b3f82007-12-08 23:58:46 +0000232bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Bill Wendling280f4562007-12-18 21:38:04 +0000233 DEBUG({
234 DOUT << "--- Checking if we can hoist " << I;
235 if (I.getInstrDescriptor()->ImplicitUses) {
236 DOUT << " * Instruction has implicit uses:\n";
237
Bill Wendling9258cd32008-01-02 19:32:43 +0000238 const MRegisterInfo *MRI = TM->getRegisterInfo();
Bill Wendling280f4562007-12-18 21:38:04 +0000239 const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
240
241 for (; *ImpUses; ++ImpUses)
242 DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
243 }
244
245 if (I.getInstrDescriptor()->ImplicitDefs) {
246 DOUT << " * Instruction has implicit defines:\n";
247
Bill Wendling9258cd32008-01-02 19:32:43 +0000248 const MRegisterInfo *MRI = TM->getRegisterInfo();
Bill Wendling280f4562007-12-18 21:38:04 +0000249 const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
250
251 for (; *ImpDefs; ++ImpDefs)
252 DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
253 }
254
255 if (TII->hasUnmodelledSideEffects(&I))
256 DOUT << " * Instruction has side effects.\n";
257 });
258
Bill Wendling0f940c92007-12-07 21:42:31 +0000259 // The instruction is loop invariant if all of its operands are loop-invariant
260 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
261 const MachineOperand &MO = I.getOperand(i);
262
Bill Wendling280f4562007-12-18 21:38:04 +0000263 if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000264 continue;
265
266 unsigned Reg = MO.getReg();
267
268 // Don't hoist instructions that access physical registers.
269 if (!MRegisterInfo::isVirtualRegister(Reg))
270 return false;
271
Bill Wendling9258cd32008-01-02 19:32:43 +0000272 assert(RegInfo->getVRegDef(Reg)&&"Machine instr not mapped for this vreg?");
Bill Wendling0f940c92007-12-07 21:42:31 +0000273
274 // If the loop contains the definition of an operand, then the instruction
275 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000276 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000277 return false;
278 }
279
Bill Wendling60ff1a32007-12-20 01:08:10 +0000280 // Don't hoist something that has unmodelled side effects.
Bill Wendling280f4562007-12-18 21:38:04 +0000281 if (TII->hasUnmodelledSideEffects(&I)) return false;
282
Bill Wendling0f940c92007-12-07 21:42:31 +0000283 // If we got this far, the instruction is loop invariant!
284 return true;
285}
286
287/// Hoist - When an instruction is found to only use loop invariant operands
288/// that is safe to hoist, this instruction is called to do the dirty work.
289///
Bill Wendlingb48519c2007-12-08 01:47:01 +0000290void MachineLICM::Hoist(MachineInstr &MI) {
Bill Wendling041b3f82007-12-08 23:58:46 +0000291 if (!IsLoopInvariantInst(MI)) return;
Bill Wendling0f940c92007-12-07 21:42:31 +0000292
293 std::vector<MachineBasicBlock*> Preds;
294
295 // Non-back-edge predecessors.
296 FindPredecessors(Preds);
Bill Wendling0f940c92007-12-07 21:42:31 +0000297
Bill Wendlingb48519c2007-12-08 01:47:01 +0000298 // Either we don't have any predecessors(?!) or we have more than one, which
299 // is forbidden.
300 if (Preds.empty() || Preds.size() != 1) return;
Bill Wendling0f940c92007-12-07 21:42:31 +0000301
Bill Wendlingb48519c2007-12-08 01:47:01 +0000302 // Check that the predecessor is qualified to take the hoisted
303 // instruction. I.e., there is only one edge from the predecessor, and it's to
304 // the loop header.
305 MachineBasicBlock *MBB = Preds.front();
Bill Wendling0f940c92007-12-07 21:42:31 +0000306
Bill Wendling041b3f82007-12-08 23:58:46 +0000307 // FIXME: We are assuming at first that the basic block coming into this loop
308 // has only one successor. This isn't the case in general because we haven't
309 // broken critical edges or added preheaders.
Bill Wendlingb48519c2007-12-08 01:47:01 +0000310 if (MBB->succ_size() != 1) return;
311 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
312 "The predecessor doesn't feed directly into the loop header!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000313
Bill Wendlingb48519c2007-12-08 01:47:01 +0000314 // Now move the instructions to the predecessor.
Bill Wendling9258cd32008-01-02 19:32:43 +0000315 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000316 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000317}