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 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
109 /// the load itself could be hoisted. Return the unfolded and hoistable
110 /// load, or null if the load couldn't be unfolded or if it wouldn't
112 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
114 /// Hoist - When an instruction is found to only use loop invariant operands
115 /// that is safe to hoist, this instruction is called to do the dirty work.
117 void Hoist(MachineInstr *MI);
119 } // end anonymous namespace
121 char MachineLICM::ID = 0;
122 static RegisterPass<MachineLICM>
123 X("machinelicm", "Machine Loop Invariant Code Motion");
125 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
127 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
128 /// loop that has a preheader.
129 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
130 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
131 if (L->getLoopPreheader())
136 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
137 /// is not preserved so it is not a good idea to run LICM multiple times on one
140 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
141 DEBUG(errs() << "******** Machine LICM ********\n");
144 TM = &MF.getTarget();
145 TII = TM->getInstrInfo();
146 TRI = TM->getRegisterInfo();
147 RegInfo = &MF.getRegInfo();
148 AllocatableSet = TRI->getAllocatableSet(MF);
150 // Get our Loop information...
151 LI = &getAnalysis<MachineLoopInfo>();
152 DT = &getAnalysis<MachineDominatorTree>();
153 AA = &getAnalysis<AliasAnalysis>();
155 for (MachineLoopInfo::iterator
156 I = LI->begin(), E = LI->end(); I != E; ++I) {
159 // Only visit outer-most preheader-sporting loops.
160 if (!LoopIsOuterMostWithPreheader(CurLoop))
163 // Determine the block to which to hoist instructions. If we can't find a
164 // suitable loop preheader, we can't do any hoisting.
166 // FIXME: We are only hoisting if the basic block coming into this loop
167 // has only one successor. This isn't the case in general because we haven't
168 // broken critical edges or added preheaders.
169 CurPreheader = CurLoop->getLoopPreheader();
173 HoistRegion(DT->getNode(CurLoop->getHeader()));
179 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
180 /// dominated by the specified block, and that are in the current loop) in depth
181 /// first order w.r.t the DominatorTree. This allows us to visit definitions
182 /// before uses, allowing us to hoist a loop body in one pass without iteration.
184 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
185 assert(N != 0 && "Null dominator tree node?");
186 MachineBasicBlock *BB = N->getBlock();
188 // If this subregion is not in the top level loop at all, exit.
189 if (!CurLoop->contains(BB)) return;
191 for (MachineBasicBlock::iterator
192 MII = BB->begin(), E = BB->end(); MII != E; ) {
193 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
194 MachineInstr &MI = *MII;
201 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
203 for (unsigned I = 0, E = Children.size(); I != E; ++I)
204 HoistRegion(Children[I]);
207 /// IsLoopInvariantInst - Returns true if the instruction is loop
208 /// invariant. I.e., all virtual register operands are defined outside of the
209 /// loop, physical registers aren't accessed explicitly, and there are no side
210 /// effects that aren't captured by the operands or other flags.
212 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
213 const TargetInstrDesc &TID = I.getDesc();
215 // Ignore stuff that we obviously can't hoist.
216 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
217 TID.hasUnmodeledSideEffects())
221 // Okay, this instruction does a load. As a refinement, we allow the target
222 // to decide whether the loaded value is actually a constant. If so, we can
223 // actually use it as a load.
224 if (!I.isInvariantLoad(AA))
225 // FIXME: we should be able to sink loads with no other side effects if
226 // there is nothing that can change memory from here until the end of
227 // block. This is a trivial form of alias analysis.
232 errs() << "--- Checking if we can hoist " << I;
233 if (I.getDesc().getImplicitUses()) {
234 errs() << " * Instruction has implicit uses:\n";
236 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
237 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
239 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
242 if (I.getDesc().getImplicitDefs()) {
243 errs() << " * Instruction has implicit defines:\n";
245 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
246 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
248 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
252 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
253 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
257 // The instruction is loop invariant if all of its operands are.
258 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
259 const MachineOperand &MO = I.getOperand(i);
264 unsigned Reg = MO.getReg();
265 if (Reg == 0) continue;
267 // Don't hoist an instruction that uses or defines a physical register.
268 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
270 // If the physreg has no defs anywhere, it's just an ambient register
271 // and we can freely move its uses. Alternatively, if it's allocatable,
272 // it could get allocated to something with a def during allocation.
273 if (!RegInfo->def_empty(Reg))
275 if (AllocatableSet.test(Reg))
277 // Check for a def among the register's aliases too.
278 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
279 unsigned AliasReg = *Alias;
280 if (!RegInfo->def_empty(AliasReg))
282 if (AllocatableSet.test(AliasReg))
285 // Otherwise it's safe to move.
287 } else if (!MO.isDead()) {
288 // A def that isn't dead. We can't move it.
296 assert(RegInfo->getVRegDef(Reg) &&
297 "Machine instr not mapped for this vreg?!");
299 // If the loop contains the definition of an operand, then the instruction
300 // isn't loop invariant.
301 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
305 // If we got this far, the instruction is loop invariant!
310 /// HasPHIUses - Return true if the specified register has any PHI use.
311 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
312 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
313 UE = RegInfo->use_end(); UI != UE; ++UI) {
314 MachineInstr *UseMI = &*UI;
315 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
321 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
322 /// the given loop invariant.
323 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
324 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
327 // FIXME: For now, only hoist re-materilizable instructions. LICM will
328 // increase register pressure. We want to make sure it doesn't increase
330 if (!TII->isTriviallyReMaterializable(&MI, AA))
333 // If result(s) of this instruction is used by PHIs, then don't hoist it.
334 // The presence of joins makes it difficult for current register allocator
335 // implementation to perform remat.
336 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
337 const MachineOperand &MO = MI.getOperand(i);
338 if (!MO.isReg() || !MO.isDef())
340 if (HasPHIUses(MO.getReg(), RegInfo))
347 static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
348 std::vector<const MachineInstr*> &PrevMIs,
349 MachineRegisterInfo *RegInfo) {
350 unsigned NumOps = MI->getNumOperands();
351 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
352 const MachineInstr *PrevMI = PrevMIs[i];
353 unsigned NumOps2 = PrevMI->getNumOperands();
354 if (NumOps != NumOps2)
357 for (unsigned j = 0; j != NumOps; ++j) {
358 const MachineOperand &MO = MI->getOperand(j);
359 if (MO.isReg() && MO.isDef()) {
360 if (RegInfo->getRegClass(MO.getReg()) !=
361 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
367 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
378 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
379 // If not, we may be able to unfold a load and hoist that.
380 // First test whether the instruction is loading from an amenable
382 if (!MI->getDesc().mayLoad()) return 0;
383 if (!MI->hasOneMemOperand()) return 0;
384 MachineMemOperand *MMO = *MI->memoperands_begin();
385 if (MMO->isVolatile()) return 0;
386 MachineFunction &MF = *MI->getParent()->getParent();
387 if (!MMO->getValue()) return 0;
388 if (const PseudoSourceValue *PSV =
389 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
390 if (!PSV->isConstant(MF.getFrameInfo())) return 0;
392 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
394 // Next determine the register class for a temporary register.
396 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
398 /*UnfoldStore=*/false);
399 if (NewOpc == 0) return 0;
400 const TargetInstrDesc &TID = TII->get(NewOpc);
401 if (TID.getNumDefs() != 1) return 0;
402 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(TRI);
403 // Ok, we're unfolding. Create a temporary register and do the unfold.
404 unsigned Reg = RegInfo->createVirtualRegister(RC);
405 SmallVector<MachineInstr *, 2> NewMIs;
407 TII->unfoldMemoryOperand(MF, MI, Reg,
408 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
412 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
414 assert(NewMIs.size() == 2 &&
415 "Unfolded a load into multiple instructions!");
416 MachineBasicBlock *MBB = MI->getParent();
417 MBB->insert(MI, NewMIs[0]);
418 MBB->insert(MI, NewMIs[1]);
419 // If unfolding produced a load that wasn't loop-invariant or profitable to
420 // hoist, discard the new instructions and bail.
421 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
422 NewMIs[0]->eraseFromParent();
423 NewMIs[1]->eraseFromParent();
426 // Otherwise we successfully unfolded a load that we can hoist.
427 MI->eraseFromParent();
431 /// Hoist - When an instruction is found to use only loop invariant operands
432 /// that are safe to hoist, this instruction is called to do the dirty work.
434 void MachineLICM::Hoist(MachineInstr *MI) {
435 // First check whether we should hoist this instruction.
436 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
437 // If not, try unfolding a hoistable load.
438 MI = ExtractHoistableLoad(MI);
442 // Now move the instructions to the predecessor, inserting it before any
443 // terminator instructions.
445 errs() << "Hoisting " << *MI;
446 if (CurPreheader->getBasicBlock())
447 errs() << " to MachineBasicBlock "
448 << CurPreheader->getBasicBlock()->getName();
449 if (MI->getParent()->getBasicBlock())
450 errs() << " from MachineBasicBlock "
451 << MI->getParent()->getBasicBlock()->getName();
455 // Look for opportunity to CSE the hoisted instruction.
456 std::pair<unsigned, unsigned> BBOpcPair =
457 std::make_pair(CurPreheader->getNumber(), MI->getOpcode());
458 DenseMap<std::pair<unsigned, unsigned>,
459 std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
460 bool DoneCSE = false;
461 if (CI != CSEMap.end()) {
462 const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo);
464 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
465 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
466 const MachineOperand &MO = MI->getOperand(i);
467 if (MO.isReg() && MO.isDef())
468 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
470 MI->eraseFromParent();
476 // Otherwise, splice the instruction to the preheader.
478 CurPreheader->splice(CurPreheader->getFirstTerminator(),
479 MI->getParent(), MI);
480 // Add to the CSE map.
481 if (CI != CSEMap.end())
482 CI->second.push_back(MI);
484 std::vector<const MachineInstr*> CSEMIs;
485 CSEMIs.push_back(MI);
486 CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));