1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 // This pass does not attempt to throttle itself to limit register pressure.
14 // The register allocation phases are expected to perform rematerialization
15 // to recover when register pressure is high.
17 // This pass is not intended to be a replacement or a complete alternative
18 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19 // constructs that are not exposed before lowering and instruction selection.
21 //===----------------------------------------------------------------------===//
23 #define DEBUG_TYPE "machine-licm"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
39 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
40 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
43 class MachineLICM : public MachineFunctionPass {
44 const TargetMachine *TM;
45 const TargetInstrInfo *TII;
46 const TargetRegisterInfo *TRI;
47 BitVector AllocatableSet;
49 // Various analyses that we use...
50 AliasAnalysis *AA; // Alias analysis info.
51 MachineLoopInfo *LI; // Current MachineLoopInfo
52 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
53 MachineRegisterInfo *RegInfo; // Machine register information
55 // State that is updated as we process loops
56 bool Changed; // True if a loop is changed.
57 MachineLoop *CurLoop; // The current loop we are working on.
58 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
60 // For each BB and opcode pair, keep a list of hoisted instructions.
61 DenseMap<std::pair<unsigned, unsigned>,
62 std::vector<const MachineInstr*> > CSEMap;
64 static char ID; // Pass identification, replacement for typeid
65 MachineLICM() : MachineFunctionPass(&ID) {}
67 virtual bool runOnMachineFunction(MachineFunction &MF);
69 const char *getPassName() const { return "Machine Instruction LICM"; }
71 // FIXME: Loop preheaders?
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<MachineLoopInfo>();
75 AU.addRequired<MachineDominatorTree>();
76 AU.addRequired<AliasAnalysis>();
77 AU.addPreserved<MachineLoopInfo>();
78 AU.addPreserved<MachineDominatorTree>();
79 MachineFunctionPass::getAnalysisUsage(AU);
82 virtual void releaseMemory() {
87 /// IsLoopInvariantInst - Returns true if the instruction is loop
88 /// invariant. I.e., all virtual register operands are defined outside of
89 /// the loop, physical registers aren't accessed (explicitly or implicitly),
90 /// and the instruction is hoistable.
92 bool IsLoopInvariantInst(MachineInstr &I);
94 /// IsProfitableToHoist - Return true if it is potentially profitable to
95 /// hoist the given loop invariant.
96 bool IsProfitableToHoist(MachineInstr &MI);
98 /// HoistRegion - Walk the specified region of the CFG (defined by all
99 /// blocks dominated by the specified block, and that are in the current
100 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
101 /// visit definitions before uses, allowing us to hoist a loop body in one
102 /// pass without iteration.
104 void HoistRegion(MachineDomTreeNode *N);
106 /// Hoist - When an instruction is found to only use loop invariant operands
107 /// that is safe to hoist, this instruction is called to do the dirty work.
109 void Hoist(MachineInstr &MI);
111 } // end anonymous namespace
113 char MachineLICM::ID = 0;
114 static RegisterPass<MachineLICM>
115 X("machinelicm", "Machine Loop Invariant Code Motion");
117 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
119 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
120 /// loop that has a preheader.
121 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
122 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
123 if (L->getLoopPreheader())
128 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
129 /// is not preserved so it is not a good idea to run LICM multiple times on one
132 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
133 DEBUG(errs() << "******** Machine LICM ********\n");
136 TM = &MF.getTarget();
137 TII = TM->getInstrInfo();
138 TRI = TM->getRegisterInfo();
139 RegInfo = &MF.getRegInfo();
140 AllocatableSet = TRI->getAllocatableSet(MF);
142 // Get our Loop information...
143 LI = &getAnalysis<MachineLoopInfo>();
144 DT = &getAnalysis<MachineDominatorTree>();
145 AA = &getAnalysis<AliasAnalysis>();
147 for (MachineLoopInfo::iterator
148 I = LI->begin(), E = LI->end(); I != E; ++I) {
151 // Only visit outer-most preheader-sporting loops.
152 if (!LoopIsOuterMostWithPreheader(CurLoop))
155 // Determine the block to which to hoist instructions. If we can't find a
156 // suitable loop preheader, we can't do any hoisting.
158 // FIXME: We are only hoisting if the basic block coming into this loop
159 // has only one successor. This isn't the case in general because we haven't
160 // broken critical edges or added preheaders.
161 CurPreheader = CurLoop->getLoopPreheader();
165 HoistRegion(DT->getNode(CurLoop->getHeader()));
171 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
172 /// dominated by the specified block, and that are in the current loop) in depth
173 /// first order w.r.t the DominatorTree. This allows us to visit definitions
174 /// before uses, allowing us to hoist a loop body in one pass without iteration.
176 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
177 assert(N != 0 && "Null dominator tree node?");
178 MachineBasicBlock *BB = N->getBlock();
180 // If this subregion is not in the top level loop at all, exit.
181 if (!CurLoop->contains(BB)) return;
183 for (MachineBasicBlock::iterator
184 MII = BB->begin(), E = BB->end(); MII != E; ) {
185 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
186 MachineInstr &MI = *MII;
193 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
195 for (unsigned I = 0, E = Children.size(); I != E; ++I)
196 HoistRegion(Children[I]);
199 /// IsLoopInvariantInst - Returns true if the instruction is loop
200 /// invariant. I.e., all virtual register operands are defined outside of the
201 /// loop, physical registers aren't accessed explicitly, and there are no side
202 /// effects that aren't captured by the operands or other flags.
204 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
205 const TargetInstrDesc &TID = I.getDesc();
207 // Ignore stuff that we obviously can't hoist.
208 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
209 TID.hasUnmodeledSideEffects())
213 // Okay, this instruction does a load. As a refinement, we allow the target
214 // to decide whether the loaded value is actually a constant. If so, we can
215 // actually use it as a load.
216 if (!I.isInvariantLoad(AA))
217 // FIXME: we should be able to sink loads with no other side effects if
218 // there is nothing that can change memory from here until the end of
219 // block. This is a trivial form of alias analysis.
224 errs() << "--- Checking if we can hoist " << I;
225 if (I.getDesc().getImplicitUses()) {
226 errs() << " * Instruction has implicit uses:\n";
228 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
229 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
231 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
234 if (I.getDesc().getImplicitDefs()) {
235 errs() << " * Instruction has implicit defines:\n";
237 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
238 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
240 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
244 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
245 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
249 // The instruction is loop invariant if all of its operands are.
250 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
251 const MachineOperand &MO = I.getOperand(i);
256 unsigned Reg = MO.getReg();
257 if (Reg == 0) continue;
259 // Don't hoist an instruction that uses or defines a physical register.
260 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
262 // If the physreg has no defs anywhere, it's just an ambient register
263 // and we can freely move its uses. Alternatively, if it's allocatable,
264 // it could get allocated to something with a def during allocation.
265 if (!RegInfo->def_empty(Reg))
267 if (AllocatableSet.test(Reg))
269 // Check for a def among the register's aliases too.
270 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
271 unsigned AliasReg = *Alias;
272 if (!RegInfo->def_empty(AliasReg))
274 if (AllocatableSet.test(AliasReg))
277 // Otherwise it's safe to move.
279 } else if (!MO.isDead()) {
280 // A def that isn't dead. We can't move it.
288 assert(RegInfo->getVRegDef(Reg) &&
289 "Machine instr not mapped for this vreg?!");
291 // If the loop contains the definition of an operand, then the instruction
292 // isn't loop invariant.
293 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
297 // If we got this far, the instruction is loop invariant!
302 /// HasPHIUses - Return true if the specified register has any PHI use.
303 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
304 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
305 UE = RegInfo->use_end(); UI != UE; ++UI) {
306 MachineInstr *UseMI = &*UI;
307 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
313 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
314 /// the given loop invariant.
315 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
316 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
319 // FIXME: For now, only hoist re-materilizable instructions. LICM will
320 // increase register pressure. We want to make sure it doesn't increase
322 if (!TII->isTriviallyReMaterializable(&MI, AA))
325 // If result(s) of this instruction is used by PHIs, then don't hoist it.
326 // The presence of joins makes it difficult for current register allocator
327 // implementation to perform remat.
328 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
329 const MachineOperand &MO = MI.getOperand(i);
330 if (!MO.isReg() || !MO.isDef())
332 if (HasPHIUses(MO.getReg(), RegInfo))
339 static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
340 std::vector<const MachineInstr*> &PrevMIs,
341 MachineRegisterInfo *RegInfo) {
342 unsigned NumOps = MI->getNumOperands();
343 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
344 const MachineInstr *PrevMI = PrevMIs[i];
345 unsigned NumOps2 = PrevMI->getNumOperands();
346 if (NumOps != NumOps2)
349 for (unsigned j = 0; j != NumOps; ++j) {
350 const MachineOperand &MO = MI->getOperand(j);
351 if (MO.isReg() && MO.isDef()) {
352 if (RegInfo->getRegClass(MO.getReg()) !=
353 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
359 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
370 /// Hoist - When an instruction is found to use only loop invariant operands
371 /// that are safe to hoist, this instruction is called to do the dirty work.
373 void MachineLICM::Hoist(MachineInstr &MI) {
374 if (!IsLoopInvariantInst(MI)) return;
375 if (!IsProfitableToHoist(MI)) return;
377 // Now move the instructions to the predecessor, inserting it before any
378 // terminator instructions.
380 errs() << "Hoisting " << MI;
381 if (CurPreheader->getBasicBlock())
382 errs() << " to MachineBasicBlock "
383 << CurPreheader->getBasicBlock()->getName();
384 if (MI.getParent()->getBasicBlock())
385 errs() << " from MachineBasicBlock "
386 << MI.getParent()->getBasicBlock()->getName();
390 // Look for opportunity to CSE the hoisted instruction.
391 std::pair<unsigned, unsigned> BBOpcPair =
392 std::make_pair(CurPreheader->getNumber(), MI.getOpcode());
393 DenseMap<std::pair<unsigned, unsigned>,
394 std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
395 bool DoneCSE = false;
396 if (CI != CSEMap.end()) {
397 const MachineInstr *Dup = LookForDuplicate(&MI, CI->second, RegInfo);
399 DEBUG(errs() << "CSEing " << MI << " with " << *Dup);
400 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
401 const MachineOperand &MO = MI.getOperand(i);
402 if (MO.isReg() && MO.isDef())
403 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
405 MI.eraseFromParent();
411 // Otherwise, splice the instruction to the preheader.
413 CurPreheader->splice(CurPreheader->getFirstTerminator(),
414 MI.getParent(), &MI);
415 // Add to the CSE map.
416 if (CI != CSEMap.end())
417 CI->second.push_back(&MI);
419 std::vector<const MachineInstr*> CSEMIs;
420 CSEMIs.push_back(&MI);
421 CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));