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/ADT/DenseMap.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.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 VISIBILITY_HIDDEN MachineLICM
: public MachineFunctionPass
{
45 const TargetMachine
*TM
;
46 const TargetInstrInfo
*TII
;
48 // Various analyses that we use...
49 MachineLoopInfo
*LI
; // Current MachineLoopInfo
50 MachineDominatorTree
*DT
; // Machine dominator tree for the cur loop
51 MachineRegisterInfo
*RegInfo
; // Machine register information
53 // State that is updated as we process loops
54 bool Changed
; // True if a loop is changed.
55 MachineLoop
*CurLoop
; // The current loop we are working on.
56 MachineBasicBlock
*CurPreheader
; // The preheader for CurLoop.
58 // For each BB and opcode pair, keep a list of hoisted instructions.
59 DenseMap
<std::pair
<unsigned, unsigned>,
60 std::vector
<const MachineInstr
*> > CSEMap
;
62 static char ID
; // Pass identification, replacement for typeid
63 MachineLICM() : MachineFunctionPass(&ID
) {}
65 virtual bool runOnMachineFunction(MachineFunction
&MF
);
67 const char *getPassName() const { return "Machine Instruction LICM"; }
69 // FIXME: Loop preheaders?
70 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
72 AU
.addRequired
<MachineLoopInfo
>();
73 AU
.addRequired
<MachineDominatorTree
>();
74 AU
.addPreserved
<MachineLoopInfo
>();
75 AU
.addPreserved
<MachineDominatorTree
>();
76 MachineFunctionPass::getAnalysisUsage(AU
);
79 virtual void releaseMemory() {
84 /// IsLoopInvariantInst - Returns true if the instruction is loop
85 /// invariant. I.e., all virtual register operands are defined outside of
86 /// the loop, physical registers aren't accessed (explicitly or implicitly),
87 /// and the instruction is hoistable.
89 bool IsLoopInvariantInst(MachineInstr
&I
);
91 /// IsProfitableToHoist - Return true if it is potentially profitable to
92 /// hoist the given loop invariant.
93 bool IsProfitableToHoist(MachineInstr
&MI
);
95 /// HoistRegion - Walk the specified region of the CFG (defined by all
96 /// blocks dominated by the specified block, and that are in the current
97 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
98 /// visit definitions before uses, allowing us to hoist a loop body in one
99 /// pass without iteration.
101 void HoistRegion(MachineDomTreeNode
*N
);
103 /// Hoist - When an instruction is found to only use loop invariant operands
104 /// that is safe to hoist, this instruction is called to do the dirty work.
106 void Hoist(MachineInstr
&MI
);
108 } // end anonymous namespace
110 char MachineLICM::ID
= 0;
111 static RegisterPass
<MachineLICM
>
112 X("machinelicm", "Machine Loop Invariant Code Motion");
114 FunctionPass
*llvm::createMachineLICMPass() { return new MachineLICM(); }
116 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
117 /// loop that has a preheader.
118 static bool LoopIsOuterMostWithPreheader(MachineLoop
*CurLoop
) {
119 for (MachineLoop
*L
= CurLoop
->getParentLoop(); L
; L
= L
->getParentLoop())
120 if (L
->getLoopPreheader())
125 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
126 /// is not preserved so it is not a good idea to run LICM multiple times on one
129 bool MachineLICM::runOnMachineFunction(MachineFunction
&MF
) {
130 const Function
*F
= MF
.getFunction();
131 if (F
->hasFnAttr(Attribute::OptimizeForSize
))
134 DOUT
<< "******** Machine LICM ********\n";
137 TM
= &MF
.getTarget();
138 TII
= TM
->getInstrInfo();
139 RegInfo
= &MF
.getRegInfo();
141 // Get our Loop information...
142 LI
= &getAnalysis
<MachineLoopInfo
>();
143 DT
= &getAnalysis
<MachineDominatorTree
>();
145 for (MachineLoopInfo::iterator
146 I
= LI
->begin(), E
= LI
->end(); I
!= E
; ++I
) {
149 // Only visit outer-most preheader-sporting loops.
150 if (!LoopIsOuterMostWithPreheader(CurLoop
))
153 // Determine the block to which to hoist instructions. If we can't find a
154 // suitable loop preheader, we can't do any hoisting.
156 // FIXME: We are only hoisting if the basic block coming into this loop
157 // has only one successor. This isn't the case in general because we haven't
158 // broken critical edges or added preheaders.
159 CurPreheader
= CurLoop
->getLoopPreheader();
163 HoistRegion(DT
->getNode(CurLoop
->getHeader()));
169 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
170 /// dominated by the specified block, and that are in the current loop) in depth
171 /// first order w.r.t the DominatorTree. This allows us to visit definitions
172 /// before uses, allowing us to hoist a loop body in one pass without iteration.
174 void MachineLICM::HoistRegion(MachineDomTreeNode
*N
) {
175 assert(N
!= 0 && "Null dominator tree node?");
176 MachineBasicBlock
*BB
= N
->getBlock();
178 // If this subregion is not in the top level loop at all, exit.
179 if (!CurLoop
->contains(BB
)) return;
181 for (MachineBasicBlock::iterator
182 MII
= BB
->begin(), E
= BB
->end(); MII
!= E
; ) {
183 MachineBasicBlock::iterator NextMII
= MII
; ++NextMII
;
184 MachineInstr
&MI
= *MII
;
191 const std::vector
<MachineDomTreeNode
*> &Children
= N
->getChildren();
193 for (unsigned I
= 0, E
= Children
.size(); I
!= E
; ++I
)
194 HoistRegion(Children
[I
]);
197 /// IsLoopInvariantInst - Returns true if the instruction is loop
198 /// invariant. I.e., all virtual register operands are defined outside of the
199 /// loop, physical registers aren't accessed explicitly, and there are no side
200 /// effects that aren't captured by the operands or other flags.
202 bool MachineLICM::IsLoopInvariantInst(MachineInstr
&I
) {
203 const TargetInstrDesc
&TID
= I
.getDesc();
205 // Ignore stuff that we obviously can't hoist.
206 if (TID
.mayStore() || TID
.isCall() || TID
.isTerminator() ||
207 TID
.hasUnmodeledSideEffects())
211 // Okay, this instruction does a load. As a refinement, we allow the target
212 // to decide whether the loaded value is actually a constant. If so, we can
213 // actually use it as a load.
214 if (!TII
->isInvariantLoad(&I
))
215 // FIXME: we should be able to sink loads with no other side effects if
216 // there is nothing that can change memory from here until the end of
217 // block. This is a trivial form of alias analysis.
222 DOUT
<< "--- Checking if we can hoist " << I
;
223 if (I
.getDesc().getImplicitUses()) {
224 DOUT
<< " * Instruction has implicit uses:\n";
226 const TargetRegisterInfo
*TRI
= TM
->getRegisterInfo();
227 for (const unsigned *ImpUses
= I
.getDesc().getImplicitUses();
229 DOUT
<< " -> " << TRI
->getName(*ImpUses
) << "\n";
232 if (I
.getDesc().getImplicitDefs()) {
233 DOUT
<< " * Instruction has implicit defines:\n";
235 const TargetRegisterInfo
*TRI
= TM
->getRegisterInfo();
236 for (const unsigned *ImpDefs
= I
.getDesc().getImplicitDefs();
238 DOUT
<< " -> " << TRI
->getName(*ImpDefs
) << "\n";
242 if (I
.getDesc().getImplicitDefs() || I
.getDesc().getImplicitUses()) {
243 DOUT
<< "Cannot hoist with implicit defines or uses\n";
247 // The instruction is loop invariant if all of its operands are.
248 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
) {
249 const MachineOperand
&MO
= I
.getOperand(i
);
254 unsigned Reg
= MO
.getReg();
255 if (Reg
== 0) continue;
257 // Don't hoist an instruction that uses or defines a physical register.
258 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
264 assert(RegInfo
->getVRegDef(Reg
) &&
265 "Machine instr not mapped for this vreg?!");
267 // If the loop contains the definition of an operand, then the instruction
268 // isn't loop invariant.
269 if (CurLoop
->contains(RegInfo
->getVRegDef(Reg
)->getParent()))
273 // If we got this far, the instruction is loop invariant!
278 /// HasPHIUses - Return true if the specified register has any PHI use.
279 static bool HasPHIUses(unsigned Reg
, MachineRegisterInfo
*RegInfo
) {
280 for (MachineRegisterInfo::use_iterator UI
= RegInfo
->use_begin(Reg
),
281 UE
= RegInfo
->use_end(); UI
!= UE
; ++UI
) {
282 MachineInstr
*UseMI
= &*UI
;
283 if (UseMI
->getOpcode() == TargetInstrInfo::PHI
)
289 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
290 /// the given loop invariant.
291 bool MachineLICM::IsProfitableToHoist(MachineInstr
&MI
) {
292 if (MI
.getOpcode() == TargetInstrInfo::IMPLICIT_DEF
)
295 const TargetInstrDesc
&TID
= MI
.getDesc();
297 // FIXME: For now, only hoist re-materilizable instructions. LICM will
298 // increase register pressure. We want to make sure it doesn't increase
300 if (!TID
.mayLoad() && (!TID
.isRematerializable() ||
301 !TII
->isTriviallyReMaterializable(&MI
)))
304 // If result(s) of this instruction is used by PHIs, then don't hoist it.
305 // The presence of joins makes it difficult for current register allocator
306 // implementation to perform remat.
307 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
308 const MachineOperand
&MO
= MI
.getOperand(i
);
309 if (!MO
.isReg() || !MO
.isDef())
311 if (HasPHIUses(MO
.getReg(), RegInfo
))
318 static const MachineInstr
*LookForDuplicate(const MachineInstr
*MI
,
319 std::vector
<const MachineInstr
*> &PrevMIs
,
320 MachineRegisterInfo
*RegInfo
) {
321 unsigned NumOps
= MI
->getNumOperands();
322 for (unsigned i
= 0, e
= PrevMIs
.size(); i
!= e
; ++i
) {
323 const MachineInstr
*PrevMI
= PrevMIs
[i
];
324 unsigned NumOps2
= PrevMI
->getNumOperands();
325 if (NumOps
!= NumOps2
)
328 for (unsigned j
= 0; j
!= NumOps
; ++j
) {
329 const MachineOperand
&MO
= MI
->getOperand(j
);
330 if (MO
.isReg() && MO
.isDef()) {
331 if (RegInfo
->getRegClass(MO
.getReg()) !=
332 RegInfo
->getRegClass(PrevMI
->getOperand(j
).getReg())) {
338 if (!MO
.isIdenticalTo(PrevMI
->getOperand(j
))) {
349 /// Hoist - When an instruction is found to use only loop invariant operands
350 /// that are safe to hoist, this instruction is called to do the dirty work.
352 void MachineLICM::Hoist(MachineInstr
&MI
) {
353 if (!IsLoopInvariantInst(MI
)) return;
354 if (!IsProfitableToHoist(MI
)) return;
356 // Now move the instructions to the predecessor, inserting it before any
357 // terminator instructions.
359 errs() << "Hoisting " << MI
;
360 if (CurPreheader
->getBasicBlock())
361 errs() << " to MachineBasicBlock "
362 << CurPreheader
->getBasicBlock()->getName();
363 if (MI
.getParent()->getBasicBlock())
364 errs() << " from MachineBasicBlock "
365 << MI
.getParent()->getBasicBlock()->getName();
369 // Look for opportunity to CSE the hoisted instruction.
370 std::pair
<unsigned, unsigned> BBOpcPair
=
371 std::make_pair(CurPreheader
->getNumber(), MI
.getOpcode());
372 DenseMap
<std::pair
<unsigned, unsigned>,
373 std::vector
<const MachineInstr
*> >::iterator CI
= CSEMap
.find(BBOpcPair
);
374 bool DoneCSE
= false;
375 if (CI
!= CSEMap
.end()) {
376 const MachineInstr
*Dup
= LookForDuplicate(&MI
, CI
->second
, RegInfo
);
378 DOUT
<< "CSEing " << MI
;
379 DOUT
<< " with " << *Dup
;
380 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
381 const MachineOperand
&MO
= MI
.getOperand(i
);
382 if (MO
.isReg() && MO
.isDef())
383 RegInfo
->replaceRegWith(MO
.getReg(), Dup
->getOperand(i
).getReg());
385 MI
.eraseFromParent();
391 // Otherwise, splice the instruction to the preheader.
393 CurPreheader
->splice(CurPreheader
->getFirstTerminator(),
394 MI
.getParent(), &MI
);
395 // Add to the CSE map.
396 if (CI
!= CSEMap
.end())
397 CI
->second
.push_back(&MI
);
399 std::vector
<const MachineInstr
*> CSEMIs
;
400 CSEMIs
.push_back(&MI
);
401 CSEMap
.insert(std::make_pair(BBOpcPair
, CSEMIs
));