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/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
41 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
42 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
45 class MachineLICM : public MachineFunctionPass {
46 const TargetMachine *TM;
47 const TargetInstrInfo *TII;
48 const TargetRegisterInfo *TRI;
49 BitVector AllocatableSet;
51 // Various analyses that we use...
52 AliasAnalysis *AA; // Alias analysis info.
53 MachineLoopInfo *LI; // Current MachineLoopInfo
54 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
55 MachineRegisterInfo *RegInfo; // Machine register information
57 // State that is updated as we process loops
58 bool Changed; // True if a loop is changed.
59 MachineLoop *CurLoop; // The current loop we are working on.
60 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
62 // For each BB and opcode pair, keep a list of hoisted instructions.
63 DenseMap<std::pair<unsigned, unsigned>,
64 std::vector<const MachineInstr*> > CSEMap;
66 static char ID; // Pass identification, replacement for typeid
67 MachineLICM() : MachineFunctionPass(&ID) {}
69 virtual bool runOnMachineFunction(MachineFunction &MF);
71 const char *getPassName() const { return "Machine Instruction LICM"; }
73 // FIXME: Loop preheaders?
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<MachineLoopInfo>();
77 AU.addRequired<MachineDominatorTree>();
78 AU.addRequired<AliasAnalysis>();
79 AU.addPreserved<MachineLoopInfo>();
80 AU.addPreserved<MachineDominatorTree>();
81 MachineFunctionPass::getAnalysisUsage(AU);
84 virtual void releaseMemory() {
89 /// IsLoopInvariantInst - Returns true if the instruction is loop
90 /// invariant. I.e., all virtual register operands are defined outside of
91 /// the loop, physical registers aren't accessed (explicitly or implicitly),
92 /// and the instruction is hoistable.
94 bool IsLoopInvariantInst(MachineInstr &I);
96 /// IsProfitableToHoist - Return true if it is potentially profitable to
97 /// hoist the given loop invariant.
98 bool IsProfitableToHoist(MachineInstr &MI);
100 /// HoistRegion - Walk the specified region of the CFG (defined by all
101 /// blocks dominated by the specified block, and that are in the current
102 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
103 /// visit definitions before uses, allowing us to hoist a loop body in one
104 /// pass without iteration.
106 void HoistRegion(MachineDomTreeNode *N);
108 /// Hoist - When an instruction is found to only use loop invariant operands
109 /// that is safe to hoist, this instruction is called to do the dirty work.
111 void Hoist(MachineInstr *MI);
113 } // end anonymous namespace
115 char MachineLICM::ID = 0;
116 static RegisterPass<MachineLICM>
117 X("machinelicm", "Machine Loop Invariant Code Motion");
119 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
121 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
122 /// loop that has a preheader.
123 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
124 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
125 if (L->getLoopPreheader())
130 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
131 /// is not preserved so it is not a good idea to run LICM multiple times on one
134 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
135 DEBUG(errs() << "******** Machine LICM ********\n");
138 TM = &MF.getTarget();
139 TII = TM->getInstrInfo();
140 TRI = TM->getRegisterInfo();
141 RegInfo = &MF.getRegInfo();
142 AllocatableSet = TRI->getAllocatableSet(MF);
144 // Get our Loop information...
145 LI = &getAnalysis<MachineLoopInfo>();
146 DT = &getAnalysis<MachineDominatorTree>();
147 AA = &getAnalysis<AliasAnalysis>();
149 for (MachineLoopInfo::iterator
150 I = LI->begin(), E = LI->end(); I != E; ++I) {
153 // Only visit outer-most preheader-sporting loops.
154 if (!LoopIsOuterMostWithPreheader(CurLoop))
157 // Determine the block to which to hoist instructions. If we can't find a
158 // suitable loop preheader, we can't do any hoisting.
160 // FIXME: We are only hoisting if the basic block coming into this loop
161 // has only one successor. This isn't the case in general because we haven't
162 // broken critical edges or added preheaders.
163 CurPreheader = CurLoop->getLoopPreheader();
167 HoistRegion(DT->getNode(CurLoop->getHeader()));
173 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
174 /// dominated by the specified block, and that are in the current loop) in depth
175 /// first order w.r.t the DominatorTree. This allows us to visit definitions
176 /// before uses, allowing us to hoist a loop body in one pass without iteration.
178 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
179 assert(N != 0 && "Null dominator tree node?");
180 MachineBasicBlock *BB = N->getBlock();
182 // If this subregion is not in the top level loop at all, exit.
183 if (!CurLoop->contains(BB)) return;
185 for (MachineBasicBlock::iterator
186 MII = BB->begin(), E = BB->end(); MII != E; ) {
187 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
188 MachineInstr &MI = *MII;
195 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
197 for (unsigned I = 0, E = Children.size(); I != E; ++I)
198 HoistRegion(Children[I]);
201 /// IsLoopInvariantInst - Returns true if the instruction is loop
202 /// invariant. I.e., all virtual register operands are defined outside of the
203 /// loop, physical registers aren't accessed explicitly, and there are no side
204 /// effects that aren't captured by the operands or other flags.
206 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
207 const TargetInstrDesc &TID = I.getDesc();
209 // Ignore stuff that we obviously can't hoist.
210 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
211 TID.hasUnmodeledSideEffects())
215 // Okay, this instruction does a load. As a refinement, we allow the target
216 // to decide whether the loaded value is actually a constant. If so, we can
217 // actually use it as a load.
218 if (!I.isInvariantLoad(AA))
219 // FIXME: we should be able to sink loads with no other side effects if
220 // there is nothing that can change memory from here until the end of
221 // block. This is a trivial form of alias analysis.
226 errs() << "--- Checking if we can hoist " << I;
227 if (I.getDesc().getImplicitUses()) {
228 errs() << " * Instruction has implicit uses:\n";
230 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
231 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
233 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
236 if (I.getDesc().getImplicitDefs()) {
237 errs() << " * Instruction has implicit defines:\n";
239 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
240 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
242 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
246 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
247 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
251 // The instruction is loop invariant if all of its operands are.
252 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
253 const MachineOperand &MO = I.getOperand(i);
258 unsigned Reg = MO.getReg();
259 if (Reg == 0) continue;
261 // Don't hoist an instruction that uses or defines a physical register.
262 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
264 // If the physreg has no defs anywhere, it's just an ambient register
265 // and we can freely move its uses. Alternatively, if it's allocatable,
266 // it could get allocated to something with a def during allocation.
267 if (!RegInfo->def_empty(Reg))
269 if (AllocatableSet.test(Reg))
271 // Check for a def among the register's aliases too.
272 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
273 unsigned AliasReg = *Alias;
274 if (!RegInfo->def_empty(AliasReg))
276 if (AllocatableSet.test(AliasReg))
279 // Otherwise it's safe to move.
281 } else if (!MO.isDead()) {
282 // A def that isn't dead. We can't move it.
290 assert(RegInfo->getVRegDef(Reg) &&
291 "Machine instr not mapped for this vreg?!");
293 // If the loop contains the definition of an operand, then the instruction
294 // isn't loop invariant.
295 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
299 // If we got this far, the instruction is loop invariant!
304 /// HasPHIUses - Return true if the specified register has any PHI use.
305 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
306 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
307 UE = RegInfo->use_end(); UI != UE; ++UI) {
308 MachineInstr *UseMI = &*UI;
309 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
315 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
316 /// the given loop invariant.
317 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
318 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
321 // FIXME: For now, only hoist re-materilizable instructions. LICM will
322 // increase register pressure. We want to make sure it doesn't increase
324 if (!TII->isTriviallyReMaterializable(&MI, AA))
327 // If result(s) of this instruction is used by PHIs, then don't hoist it.
328 // The presence of joins makes it difficult for current register allocator
329 // implementation to perform remat.
330 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
331 const MachineOperand &MO = MI.getOperand(i);
332 if (!MO.isReg() || !MO.isDef())
334 if (HasPHIUses(MO.getReg(), RegInfo))
341 static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
342 std::vector<const MachineInstr*> &PrevMIs,
343 MachineRegisterInfo *RegInfo) {
344 unsigned NumOps = MI->getNumOperands();
345 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
346 const MachineInstr *PrevMI = PrevMIs[i];
347 unsigned NumOps2 = PrevMI->getNumOperands();
348 if (NumOps != NumOps2)
351 for (unsigned j = 0; j != NumOps; ++j) {
352 const MachineOperand &MO = MI->getOperand(j);
353 if (MO.isReg() && MO.isDef()) {
354 if (RegInfo->getRegClass(MO.getReg()) !=
355 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
361 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
372 /// Hoist - When an instruction is found to use only loop invariant operands
373 /// that are safe to hoist, this instruction is called to do the dirty work.
375 void MachineLICM::Hoist(MachineInstr *MI) {
376 // First check whether we should hoist this instruction.
377 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
378 // If not, we may be able to unfold a load and hoist that.
379 // First test whether the instruction is loading from an amenable
381 if (!MI->getDesc().mayLoad()) return;
382 if (!MI->hasOneMemOperand()) return;
383 MachineMemOperand *MMO = *MI->memoperands_begin();
384 if (MMO->isVolatile()) return;
385 MachineFunction &MF = *MI->getParent()->getParent();
386 if (!MMO->getValue()) return;
387 if (const PseudoSourceValue *PSV =
388 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
389 if (!PSV->isConstant(MF.getFrameInfo())) return;
391 if (!AA->pointsToConstantMemory(MMO->getValue())) return;
393 // Next determine the register class for a temporary register.
395 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
397 /*UnfoldStore=*/false);
398 if (NewOpc == 0) return;
399 const TargetInstrDesc &TID = TII->get(NewOpc);
400 if (TID.getNumDefs() != 1) return;
401 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(TRI);
402 // Ok, we're unfolding. Create a temporary register and do the unfold.
403 unsigned Reg = RegInfo->createVirtualRegister(RC);
404 SmallVector<MachineInstr *, 1> NewMIs;
406 TII->unfoldMemoryOperand(MF, MI, Reg,
407 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
411 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
413 assert(NewMIs.size() == 2 &&
414 "Unfolded a load into multiple instructions!");
415 MachineBasicBlock *MBB = MI->getParent();
416 MBB->insert(MI, NewMIs[0]);
417 MBB->insert(MI, NewMIs[1]);
418 MI->eraseFromParent();
419 // If unfolding produced a load that wasn't loop-invariant or profitable to
420 // hoist, re-fold it to undo the damage.
421 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
422 SmallVector<unsigned, 1> Ops;
423 for (unsigned i = 0, e = NewMIs[1]->getNumOperands(); i != e; ++i) {
424 MachineOperand &MO = NewMIs[1]->getOperand(i);
425 if (MO.isReg() && MO.getReg() == Reg) {
427 "Register defined by unfolded load is redefined "
428 "instead of just used!");
432 MI = TII->foldMemoryOperand(MF, NewMIs[1], Ops, NewMIs[0]);
433 assert(MI && "Re-fold failed!");
434 MBB->insert(NewMIs[1], MI);
435 NewMIs[0]->eraseFromParent();
436 NewMIs[1]->eraseFromParent();
439 // Otherwise we successfully unfolded a load that we can hoist.
443 // Now move the instructions to the predecessor, inserting it before any
444 // terminator instructions.
446 errs() << "Hoisting " << *MI;
447 if (CurPreheader->getBasicBlock())
448 errs() << " to MachineBasicBlock "
449 << CurPreheader->getBasicBlock()->getName();
450 if (MI->getParent()->getBasicBlock())
451 errs() << " from MachineBasicBlock "
452 << MI->getParent()->getBasicBlock()->getName();
456 // Look for opportunity to CSE the hoisted instruction.
457 std::pair<unsigned, unsigned> BBOpcPair =
458 std::make_pair(CurPreheader->getNumber(), MI->getOpcode());
459 DenseMap<std::pair<unsigned, unsigned>,
460 std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
461 bool DoneCSE = false;
462 if (CI != CSEMap.end()) {
463 const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo);
465 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
466 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
467 const MachineOperand &MO = MI->getOperand(i);
468 if (MO.isReg() && MO.isDef())
469 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
471 MI->eraseFromParent();
477 // Otherwise, splice the instruction to the preheader.
479 CurPreheader->splice(CurPreheader->getFirstTerminator(),
480 MI->getParent(), MI);
481 // Add to the CSE map.
482 if (CI != CSEMap.end())
483 CI->second.push_back(MI);
485 std::vector<const MachineInstr*> CSEMIs;
486 CSEMIs.push_back(MI);
487 CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));