blob: f33acf4a87f0f6e2947e332980a1e4ca19862be1 [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//
Chris Lattner081ce942007-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 Wendlingb958b0d2007-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 Lattnera8723bd2008-01-04 06:41:45 +000016#include "llvm/CodeGen/Passes.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000017#include "llvm/CodeGen/MachineDominators.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000018#include "llvm/CodeGen/MachineLoopInfo.h"
Bill Wendling129a9ac2008-01-02 19:32:43 +000019#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000020#include "llvm/Target/MRegisterInfo.h"
Bill Wendling3caa4702007-12-11 23:27:51 +000021#include "llvm/Target/TargetInstrInfo.h"
Bill Wendlingb958b0d2007-12-07 21:42:31 +000022#include "llvm/Target/TargetMachine.h"
Chris Lattnera8723bd2008-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 Wendlingb958b0d2007-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 Wendling7c7888b2007-12-08 01:47:01 +000035 cl::init(false), cl::Hidden,
36 cl::desc("Perform loop-invariant code motion on machine code"));
Bill Wendlingb958b0d2007-12-07 21:42:31 +000037}
38
Bill Wendling0fe34c22007-12-08 23:58:46 +000039STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Bill Wendling7c7888b2007-12-08 01:47:01 +000040
Bill Wendlingb958b0d2007-12-07 21:42:31 +000041namespace {
42 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
Bill Wendling129a9ac2008-01-02 19:32:43 +000043 const TargetMachine *TM;
Bill Wendling3caa4702007-12-11 23:27:51 +000044 const TargetInstrInfo *TII;
45 MachineFunction *CurMF; // Current MachineFunction
Bill Wendlingd9b9be62007-12-11 19:40:06 +000046
Bill Wendlingb958b0d2007-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 Wendling129a9ac2008-01-02 19:32:43 +000050 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendlingb958b0d2007-12-07 21:42:31 +000051
Bill Wendlingb958b0d2007-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 Wendlingb958b0d2007-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 {
Bill Wendlingb43ca192008-01-04 07:50:05 +000064 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingb958b0d2007-12-07 21:42:31 +000065 AU.setPreservesCFG();
66 AU.addRequired<MachineLoopInfo>();
67 AU.addRequired<MachineDominatorTree>();
68 }
69 private:
Bill Wendling7c7888b2007-12-08 01:47:01 +000070 /// VisitAllLoops - Visit all of the loops in depth first order and try to
71 /// hoist invariant instructions from them.
Bill Wendlingb958b0d2007-12-07 21:42:31 +000072 ///
Bill Wendling7c7888b2007-12-08 01:47:01 +000073 void VisitAllLoops(MachineLoop *L) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +000074 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
75
76 for (MachineLoop::iterator
Bill Wendling7c7888b2007-12-08 01:47:01 +000077 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
78 MachineLoop *ML = *I;
Bill Wendlingb958b0d2007-12-07 21:42:31 +000079
Bill Wendling7c7888b2007-12-08 01:47:01 +000080 // Traverse the body of the loop in depth first order on the dominator
81 // tree so that we are guaranteed to see definitions before we see uses.
82 VisitAllLoops(ML);
83 HoistRegion(DT->getNode(ML->getHeader()));
84 }
85
86 HoistRegion(DT->getNode(L->getHeader()));
Bill Wendlingb958b0d2007-12-07 21:42:31 +000087 }
88
Bill Wendling0fe34c22007-12-08 23:58:46 +000089 /// IsInSubLoop - A little predicate that returns true if the specified
Bill Wendlingb958b0d2007-12-07 21:42:31 +000090 /// basic block is in a subloop of the current one, not the current one
91 /// itself.
92 ///
Bill Wendling0fe34c22007-12-08 23:58:46 +000093 bool IsInSubLoop(MachineBasicBlock *BB) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +000094 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Bill Wendling2dfc9eb2007-12-11 18:45:11 +000095 return LI->getLoopFor(BB) != CurLoop;
Bill Wendlingb958b0d2007-12-07 21:42:31 +000096 }
97
Bill Wendling0fe34c22007-12-08 23:58:46 +000098 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingb958b0d2007-12-07 21:42:31 +000099 /// invariant. I.e., all virtual register operands are defined outside of
100 /// the loop, physical registers aren't accessed (explicitly or implicitly),
101 /// and the instruction is hoistable.
102 ///
Bill Wendling0fe34c22007-12-08 23:58:46 +0000103 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000104
105 /// FindPredecessors - Get all of the predecessors of the loop that are not
106 /// back-edges.
107 ///
Bill Wendling2dfc9eb2007-12-11 18:45:11 +0000108 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000109 const MachineBasicBlock *Header = CurLoop->getHeader();
110
111 for (MachineBasicBlock::const_pred_iterator
112 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
113 if (!CurLoop->contains(*I))
114 Preds.push_back(*I);
115 }
116
Bill Wendling7c7888b2007-12-08 01:47:01 +0000117 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
118 /// the predecessor basic block (but before the terminator instructions).
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000119 ///
Bill Wendling129a9ac2008-01-02 19:32:43 +0000120 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
121 MachineBasicBlock *FromMBB,
122 MachineInstr *MI) {
Bill Wendling3caa4702007-12-11 23:27:51 +0000123 DEBUG({
124 DOUT << "Hoisting " << *MI;
Bill Wendling129a9ac2008-01-02 19:32:43 +0000125 if (ToMBB->getBasicBlock())
Bill Wendling3caa4702007-12-11 23:27:51 +0000126 DOUT << " to MachineBasicBlock "
Bill Wendling129a9ac2008-01-02 19:32:43 +0000127 << ToMBB->getBasicBlock()->getName();
Bill Wendling3caa4702007-12-11 23:27:51 +0000128 DOUT << "\n";
129 });
Bill Wendling129a9ac2008-01-02 19:32:43 +0000130
131 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
132 MachineBasicBlock::iterator To, From = FromMBB->begin();
133
134 while (&*From != MI)
135 ++From;
136
137 assert(From != FromMBB->end() && "Didn't find instr in BB!");
138
139 To = From;
140 ToMBB->splice(WhereIter, FromMBB, From, ++To);
Bill Wendling7c7888b2007-12-08 01:47:01 +0000141 ++NumHoisted;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000142 }
143
144 /// HoistRegion - Walk the specified region of the CFG (defined by all
145 /// blocks dominated by the specified block, and that are in the current
146 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
147 /// visit definitions before uses, allowing us to hoist a loop body in one
148 /// pass without iteration.
149 ///
150 void HoistRegion(MachineDomTreeNode *N);
151
152 /// Hoist - When an instruction is found to only use loop invariant operands
153 /// that is safe to hoist, this instruction is called to do the dirty work.
154 ///
Bill Wendling7c7888b2007-12-08 01:47:01 +0000155 void Hoist(MachineInstr &MI);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000156 };
157
158 char MachineLICM::ID = 0;
159 RegisterPass<MachineLICM> X("machine-licm",
160 "Machine Loop Invariant Code Motion");
161} // end anonymous namespace
162
163FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
164
165/// Hoist expressions out of the specified loop. Note, alias info for inner loop
166/// is not preserved so it is not a good idea to run LICM multiple times on one
167/// loop.
168///
169bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
170 if (!PerformLICM) return false; // For debugging.
171
Bill Wendling14ba7ae2007-12-11 22:22:22 +0000172 DOUT << "******** Machine LICM ********\n";
173
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000174 Changed = false;
Bill Wendlingd9b9be62007-12-11 19:40:06 +0000175 CurMF = &MF;
Bill Wendling129a9ac2008-01-02 19:32:43 +0000176 TM = &CurMF->getTarget();
177 TII = TM->getInstrInfo();
Bill Wendlingdefbe512008-01-02 21:10:54 +0000178 RegInfo = &CurMF->getRegInfo();
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000179
180 // Get our Loop information...
181 LI = &getAnalysis<MachineLoopInfo>();
182 DT = &getAnalysis<MachineDominatorTree>();
183
184 for (MachineLoopInfo::iterator
185 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendling14ba7ae2007-12-11 22:22:22 +0000186 CurLoop = *I;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000187
188 // Visit all of the instructions of the loop. We want to visit the subloops
189 // first, though, so that we can hoist their invariants first into their
190 // containing loop before we process that loop.
Bill Wendling14ba7ae2007-12-11 22:22:22 +0000191 VisitAllLoops(CurLoop);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000192 }
193
194 return Changed;
195}
196
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000197/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
198/// dominated by the specified block, and that are in the current loop) in depth
199/// first order w.r.t the DominatorTree. This allows us to visit definitions
200/// before uses, allowing us to hoist a loop body in one pass without iteration.
201///
202void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
203 assert(N != 0 && "Null dominator tree node?");
204 MachineBasicBlock *BB = N->getBlock();
205
206 // If this subregion is not in the top level loop at all, exit.
207 if (!CurLoop->contains(BB)) return;
208
209 // Only need to process the contents of this block if it is not part of a
210 // subloop (which would already have been processed).
Bill Wendling0fe34c22007-12-08 23:58:46 +0000211 if (!IsInSubLoop(BB))
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000212 for (MachineBasicBlock::iterator
213 I = BB->begin(), E = BB->end(); I != E; ) {
214 MachineInstr &MI = *I++;
215
216 // Try hoisting the instruction out of the loop. We can only do this if
217 // all of the operands of the instruction are loop invariant and if it is
218 // safe to hoist the instruction.
Bill Wendling7c7888b2007-12-08 01:47:01 +0000219 Hoist(MI);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000220 }
221
222 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
223
224 for (unsigned I = 0, E = Children.size(); I != E; ++I)
225 HoistRegion(Children[I]);
226}
227
Bill Wendling0fe34c22007-12-08 23:58:46 +0000228/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000229/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling5b1d6652007-12-20 01:08:10 +0000230/// loop, physical registers aren't accessed explicitly, and there are no side
231/// effects that aren't captured by the operands or other flags.
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000232///
Bill Wendling0fe34c22007-12-08 23:58:46 +0000233bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Bill Wendling558e3bc2007-12-18 21:38:04 +0000234 DEBUG({
235 DOUT << "--- Checking if we can hoist " << I;
236 if (I.getInstrDescriptor()->ImplicitUses) {
237 DOUT << " * Instruction has implicit uses:\n";
238
Bill Wendling129a9ac2008-01-02 19:32:43 +0000239 const MRegisterInfo *MRI = TM->getRegisterInfo();
Bill Wendling558e3bc2007-12-18 21:38:04 +0000240 const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
241
242 for (; *ImpUses; ++ImpUses)
243 DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
244 }
245
246 if (I.getInstrDescriptor()->ImplicitDefs) {
247 DOUT << " * Instruction has implicit defines:\n";
248
Bill Wendling129a9ac2008-01-02 19:32:43 +0000249 const MRegisterInfo *MRI = TM->getRegisterInfo();
Bill Wendling558e3bc2007-12-18 21:38:04 +0000250 const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
251
252 for (; *ImpDefs; ++ImpDefs)
253 DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
254 }
255
256 if (TII->hasUnmodelledSideEffects(&I))
257 DOUT << " * Instruction has side effects.\n";
258 });
259
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000260 // The instruction is loop invariant if all of its operands are loop-invariant
261 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
262 const MachineOperand &MO = I.getOperand(i);
263
Bill Wendling558e3bc2007-12-18 21:38:04 +0000264 if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000265 continue;
266
267 unsigned Reg = MO.getReg();
268
269 // Don't hoist instructions that access physical registers.
270 if (!MRegisterInfo::isVirtualRegister(Reg))
271 return false;
272
Bill Wendling129a9ac2008-01-02 19:32:43 +0000273 assert(RegInfo->getVRegDef(Reg)&&"Machine instr not mapped for this vreg?");
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000274
275 // If the loop contains the definition of an operand, then the instruction
276 // isn't loop invariant.
Bill Wendling129a9ac2008-01-02 19:32:43 +0000277 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000278 return false;
279 }
280
Bill Wendling5b1d6652007-12-20 01:08:10 +0000281 // Don't hoist something that has unmodelled side effects.
Bill Wendling558e3bc2007-12-18 21:38:04 +0000282 if (TII->hasUnmodelledSideEffects(&I)) return false;
283
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000284 // If we got this far, the instruction is loop invariant!
285 return true;
286}
287
288/// Hoist - When an instruction is found to only use loop invariant operands
289/// that is safe to hoist, this instruction is called to do the dirty work.
290///
Bill Wendling7c7888b2007-12-08 01:47:01 +0000291void MachineLICM::Hoist(MachineInstr &MI) {
Bill Wendling0fe34c22007-12-08 23:58:46 +0000292 if (!IsLoopInvariantInst(MI)) return;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000293
294 std::vector<MachineBasicBlock*> Preds;
295
296 // Non-back-edge predecessors.
297 FindPredecessors(Preds);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000298
Bill Wendling7c7888b2007-12-08 01:47:01 +0000299 // Either we don't have any predecessors(?!) or we have more than one, which
300 // is forbidden.
301 if (Preds.empty() || Preds.size() != 1) return;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000302
Bill Wendling7c7888b2007-12-08 01:47:01 +0000303 // Check that the predecessor is qualified to take the hoisted
304 // instruction. I.e., there is only one edge from the predecessor, and it's to
305 // the loop header.
306 MachineBasicBlock *MBB = Preds.front();
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000307
Bill Wendling0fe34c22007-12-08 23:58:46 +0000308 // FIXME: We are assuming at first that the basic block coming into this loop
309 // has only one successor. This isn't the case in general because we haven't
310 // broken critical edges or added preheaders.
Bill Wendling7c7888b2007-12-08 01:47:01 +0000311 if (MBB->succ_size() != 1) return;
312 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
313 "The predecessor doesn't feed directly into the loop header!");
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000314
Bill Wendling7c7888b2007-12-08 01:47:01 +0000315 // Now move the instructions to the predecessor.
Bill Wendling129a9ac2008-01-02 19:32:43 +0000316 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000317 Changed = true;
Bill Wendlingb958b0d2007-12-07 21:42:31 +0000318}