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/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
40 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
41 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
44 class MachineLICM : public MachineFunctionPass {
45 const TargetMachine *TM;
46 const TargetInstrInfo *TII;
47 const TargetRegisterInfo *TRI;
48 BitVector AllocatableSet;
50 // Various analyses that we use...
51 AliasAnalysis *AA; // Alias analysis info.
52 MachineLoopInfo *LI; // Current MachineLoopInfo
53 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
54 MachineRegisterInfo *RegInfo; // Machine register information
56 // State that is updated as we process loops
57 bool Changed; // True if a loop is changed.
58 MachineLoop *CurLoop; // The current loop we are working on.
59 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
61 // For each BB and opcode pair, keep a list of hoisted instructions.
62 DenseMap<std::pair<unsigned, unsigned>,
63 std::vector<const MachineInstr*> > CSEMap;
65 static char ID; // Pass identification, replacement for typeid
66 MachineLICM() : MachineFunctionPass(&ID) {}
68 virtual bool runOnMachineFunction(MachineFunction &MF);
70 const char *getPassName() const { return "Machine Instruction LICM"; }
72 // FIXME: Loop preheaders?
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<MachineLoopInfo>();
76 AU.addRequired<MachineDominatorTree>();
77 AU.addRequired<AliasAnalysis>();
78 AU.addPreserved<MachineLoopInfo>();
79 AU.addPreserved<MachineDominatorTree>();
80 MachineFunctionPass::getAnalysisUsage(AU);
83 virtual void releaseMemory() {
88 /// IsLoopInvariantInst - Returns true if the instruction is loop
89 /// invariant. I.e., all virtual register operands are defined outside of
90 /// the loop, physical registers aren't accessed (explicitly or implicitly),
91 /// and the instruction is hoistable.
93 bool IsLoopInvariantInst(MachineInstr &I);
95 /// IsProfitableToHoist - Return true if it is potentially profitable to
96 /// hoist the given loop invariant.
97 bool IsProfitableToHoist(MachineInstr &MI);
99 /// HoistRegion - Walk the specified region of the CFG (defined by all
100 /// blocks dominated by the specified block, and that are in the current
101 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
102 /// visit definitions before uses, allowing us to hoist a loop body in one
103 /// pass without iteration.
105 void HoistRegion(MachineDomTreeNode *N);
107 /// Hoist - When an instruction is found to only use loop invariant operands
108 /// that is safe to hoist, this instruction is called to do the dirty work.
110 void Hoist(MachineInstr &MI);
112 } // end anonymous namespace
114 char MachineLICM::ID = 0;
115 static RegisterPass<MachineLICM>
116 X("machinelicm", "Machine Loop Invariant Code Motion");
118 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
120 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
121 /// loop that has a preheader.
122 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
123 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
124 if (L->getLoopPreheader())
129 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
130 /// is not preserved so it is not a good idea to run LICM multiple times on one
133 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
134 DEBUG(errs() << "******** Machine LICM ********\n");
137 TM = &MF.getTarget();
138 TII = TM->getInstrInfo();
139 TRI = TM->getRegisterInfo();
140 RegInfo = &MF.getRegInfo();
141 AllocatableSet = TRI->getAllocatableSet(MF);
143 // Get our Loop information...
144 LI = &getAnalysis<MachineLoopInfo>();
145 DT = &getAnalysis<MachineDominatorTree>();
146 AA = &getAnalysis<AliasAnalysis>();
148 for (MachineLoopInfo::iterator
149 I = LI->begin(), E = LI->end(); I != E; ++I) {
152 // Only visit outer-most preheader-sporting loops.
153 if (!LoopIsOuterMostWithPreheader(CurLoop))
156 // Determine the block to which to hoist instructions. If we can't find a
157 // suitable loop preheader, we can't do any hoisting.
159 // FIXME: We are only hoisting if the basic block coming into this loop
160 // has only one successor. This isn't the case in general because we haven't
161 // broken critical edges or added preheaders.
162 CurPreheader = CurLoop->getLoopPreheader();
166 HoistRegion(DT->getNode(CurLoop->getHeader()));
172 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
173 /// dominated by the specified block, and that are in the current loop) in depth
174 /// first order w.r.t the DominatorTree. This allows us to visit definitions
175 /// before uses, allowing us to hoist a loop body in one pass without iteration.
177 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
178 assert(N != 0 && "Null dominator tree node?");
179 MachineBasicBlock *BB = N->getBlock();
181 // If this subregion is not in the top level loop at all, exit.
182 if (!CurLoop->contains(BB)) return;
184 for (MachineBasicBlock::iterator
185 MII = BB->begin(), E = BB->end(); MII != E; ) {
186 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
187 MachineInstr &MI = *MII;
194 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
196 for (unsigned I = 0, E = Children.size(); I != E; ++I)
197 HoistRegion(Children[I]);
200 /// IsLoopInvariantInst - Returns true if the instruction is loop
201 /// invariant. I.e., all virtual register operands are defined outside of the
202 /// loop, physical registers aren't accessed explicitly, and there are no side
203 /// effects that aren't captured by the operands or other flags.
205 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
206 const TargetInstrDesc &TID = I.getDesc();
208 // Ignore stuff that we obviously can't hoist.
209 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
210 TID.hasUnmodeledSideEffects())
214 // Okay, this instruction does a load. As a refinement, we allow the target
215 // to decide whether the loaded value is actually a constant. If so, we can
216 // actually use it as a load.
217 if (!I.isInvariantLoad(AA))
218 // FIXME: we should be able to sink loads with no other side effects if
219 // there is nothing that can change memory from here until the end of
220 // block. This is a trivial form of alias analysis.
225 errs() << "--- Checking if we can hoist " << I;
226 if (I.getDesc().getImplicitUses()) {
227 errs() << " * Instruction has implicit uses:\n";
229 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
230 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
232 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
235 if (I.getDesc().getImplicitDefs()) {
236 errs() << " * Instruction has implicit defines:\n";
238 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
239 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
241 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
245 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
246 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
250 // The instruction is loop invariant if all of its operands are.
251 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
252 const MachineOperand &MO = I.getOperand(i);
257 unsigned Reg = MO.getReg();
258 if (Reg == 0) continue;
260 // Don't hoist an instruction that uses or defines a physical register.
261 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
263 // If the physreg has no defs anywhere, it's just an ambient register
264 // and we can freely move its uses. Alternatively, if it's allocatable,
265 // it could get allocated to something with a def during allocation.
266 if (!RegInfo->def_empty(Reg))
268 if (AllocatableSet.test(Reg))
270 // Check for a def among the register's aliases too.
271 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
272 unsigned AliasReg = *Alias;
273 if (!RegInfo->def_empty(AliasReg))
275 if (AllocatableSet.test(AliasReg))
278 // Otherwise it's safe to move.
280 } else if (!MO.isDead()) {
281 // A def that isn't dead. We can't move it.
289 assert(RegInfo->getVRegDef(Reg) &&
290 "Machine instr not mapped for this vreg?!");
292 // If the loop contains the definition of an operand, then the instruction
293 // isn't loop invariant.
294 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
298 // If we got this far, the instruction is loop invariant!
303 /// HasPHIUses - Return true if the specified register has any PHI use.
304 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
305 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
306 UE = RegInfo->use_end(); UI != UE; ++UI) {
307 MachineInstr *UseMI = &*UI;
308 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
314 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
315 /// the given loop invariant.
316 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
317 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
320 // FIXME: For now, only hoist re-materilizable instructions. LICM will
321 // increase register pressure. We want to make sure it doesn't increase
323 if (!TII->isTriviallyReMaterializable(&MI, AA))
326 // If result(s) of this instruction is used by PHIs, then don't hoist it.
327 // The presence of joins makes it difficult for current register allocator
328 // implementation to perform remat.
329 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
330 const MachineOperand &MO = MI.getOperand(i);
331 if (!MO.isReg() || !MO.isDef())
333 if (HasPHIUses(MO.getReg(), RegInfo))
340 static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
341 std::vector<const MachineInstr*> &PrevMIs,
342 MachineRegisterInfo *RegInfo) {
343 unsigned NumOps = MI->getNumOperands();
344 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
345 const MachineInstr *PrevMI = PrevMIs[i];
346 unsigned NumOps2 = PrevMI->getNumOperands();
347 if (NumOps != NumOps2)
350 for (unsigned j = 0; j != NumOps; ++j) {
351 const MachineOperand &MO = MI->getOperand(j);
352 if (MO.isReg() && MO.isDef()) {
353 if (RegInfo->getRegClass(MO.getReg()) !=
354 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
360 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
371 /// Hoist - When an instruction is found to use only loop invariant operands
372 /// that are safe to hoist, this instruction is called to do the dirty work.
374 void MachineLICM::Hoist(MachineInstr &MI) {
375 if (!IsLoopInvariantInst(MI)) return;
376 if (!IsProfitableToHoist(MI)) return;
378 // Now move the instructions to the predecessor, inserting it before any
379 // terminator instructions.
381 errs() << "Hoisting " << MI;
382 if (CurPreheader->getBasicBlock())
383 errs() << " to MachineBasicBlock "
384 << CurPreheader->getBasicBlock()->getName();
385 if (MI.getParent()->getBasicBlock())
386 errs() << " from MachineBasicBlock "
387 << MI.getParent()->getBasicBlock()->getName();
391 // Look for opportunity to CSE the hoisted instruction.
392 std::pair<unsigned, unsigned> BBOpcPair =
393 std::make_pair(CurPreheader->getNumber(), MI.getOpcode());
394 DenseMap<std::pair<unsigned, unsigned>,
395 std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
396 bool DoneCSE = false;
397 if (CI != CSEMap.end()) {
398 const MachineInstr *Dup = LookForDuplicate(&MI, CI->second, RegInfo);
400 DEBUG(errs() << "CSEing " << MI << " with " << *Dup);
401 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
402 const MachineOperand &MO = MI.getOperand(i);
403 if (MO.isReg() && MO.isDef())
404 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
406 MI.eraseFromParent();
412 // Otherwise, splice the instruction to the preheader.
414 CurPreheader->splice(CurPreheader->getFirstTerminator(),
415 MI.getParent(), &MI);
416 // Add to the CSE map.
417 if (CI != CSEMap.end())
418 CI->second.push_back(&MI);
420 std::vector<const MachineInstr*> CSEMIs;
421 CSEMIs.push_back(&MI);
422 CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));