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/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
43 static cl::opt<bool> HoistLdConst("licm-const-load",
44 cl::desc("LICM load from constant memory"),
45 cl::init(false), cl::Hidden);
47 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
48 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
51 class MachineLICM : public MachineFunctionPass {
52 MachineConstantPool *MCP;
53 const TargetMachine *TM;
54 const TargetInstrInfo *TII;
55 const TargetRegisterInfo *TRI;
56 BitVector AllocatableSet;
58 // Various analyses that we use...
59 AliasAnalysis *AA; // Alias analysis info.
60 MachineLoopInfo *LI; // Current MachineLoopInfo
61 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
62 MachineRegisterInfo *RegInfo; // Machine register information
64 // State that is updated as we process loops
65 bool Changed; // True if a loop is changed.
66 bool FirstInLoop; // True if it's the first LICM in the loop.
67 MachineLoop *CurLoop; // The current loop we are working on.
68 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
70 // For each opcode, keep a list of potentail CSE instructions.
71 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
73 static char ID; // Pass identification, replacement for typeid
74 MachineLICM() : MachineFunctionPass(&ID) {}
76 virtual bool runOnMachineFunction(MachineFunction &MF);
78 const char *getPassName() const { return "Machine Instruction LICM"; }
80 // FIXME: Loop preheaders?
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequired<MachineLoopInfo>();
84 AU.addRequired<MachineDominatorTree>();
85 AU.addRequired<AliasAnalysis>();
86 AU.addPreserved<MachineLoopInfo>();
87 AU.addPreserved<MachineDominatorTree>();
88 MachineFunctionPass::getAnalysisUsage(AU);
91 virtual void releaseMemory() {
96 /// IsLoopInvariantInst - Returns true if the instruction is loop
97 /// invariant. I.e., all virtual register operands are defined outside of
98 /// the loop, physical registers aren't accessed (explicitly or implicitly),
99 /// and the instruction is hoistable.
101 bool IsLoopInvariantInst(MachineInstr &I);
103 /// IsProfitableToHoist - Return true if it is potentially profitable to
104 /// hoist the given loop invariant.
105 bool IsProfitableToHoist(MachineInstr &MI, bool &isConstLd);
107 /// HoistRegion - Walk the specified region of the CFG (defined by all
108 /// blocks dominated by the specified block, and that are in the current
109 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
110 /// visit definitions before uses, allowing us to hoist a loop body in one
111 /// pass without iteration.
113 void HoistRegion(MachineDomTreeNode *N);
115 /// isLoadFromConstantMemory - Return true if the given instruction is a
116 /// load from constant memory.
117 bool isLoadFromConstantMemory(MachineInstr *MI);
119 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
120 /// the load itself could be hoisted. Return the unfolded and hoistable
121 /// load, or null if the load couldn't be unfolded or if it wouldn't
123 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
125 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
126 /// duplicate of MI. Return this instruction if it's found.
127 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
128 std::vector<const MachineInstr*> &PrevMIs);
130 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
131 /// the preheader that compute the same value. If it's found, do a RAU on
132 /// with the definition of the existing instruction rather than hoisting
133 /// the instruction to the preheader.
134 bool EliminateCSE(MachineInstr *MI,
135 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
137 /// Hoist - When an instruction is found to only use loop invariant operands
138 /// that is safe to hoist, this instruction is called to do the dirty work.
140 void Hoist(MachineInstr *MI);
142 /// InitCSEMap - Initialize the CSE map with instructions that are in the
143 /// current loop preheader that may become duplicates of instructions that
144 /// are hoisted out of the loop.
145 void InitCSEMap(MachineBasicBlock *BB);
147 } // end anonymous namespace
149 char MachineLICM::ID = 0;
150 static RegisterPass<MachineLICM>
151 X("machinelicm", "Machine Loop Invariant Code Motion");
153 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
155 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
156 /// loop that has a preheader.
157 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
158 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
159 if (L->getLoopPreheader())
164 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
165 /// is not preserved so it is not a good idea to run LICM multiple times on one
168 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
169 DEBUG(errs() << "******** Machine LICM ********\n");
171 Changed = FirstInLoop = false;
172 MCP = MF.getConstantPool();
173 TM = &MF.getTarget();
174 TII = TM->getInstrInfo();
175 TRI = TM->getRegisterInfo();
176 RegInfo = &MF.getRegInfo();
177 AllocatableSet = TRI->getAllocatableSet(MF);
179 // Get our Loop information...
180 LI = &getAnalysis<MachineLoopInfo>();
181 DT = &getAnalysis<MachineDominatorTree>();
182 AA = &getAnalysis<AliasAnalysis>();
184 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
187 // Only visit outer-most preheader-sporting loops.
188 if (!LoopIsOuterMostWithPreheader(CurLoop))
191 // Determine the block to which to hoist instructions. If we can't find a
192 // suitable loop preheader, we can't do any hoisting.
194 // FIXME: We are only hoisting if the basic block coming into this loop
195 // has only one successor. This isn't the case in general because we haven't
196 // broken critical edges or added preheaders.
197 CurPreheader = CurLoop->getLoopPreheader();
201 // CSEMap is initialized for loop header when the first instruction is
204 HoistRegion(DT->getNode(CurLoop->getHeader()));
211 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
212 /// dominated by the specified block, and that are in the current loop) in depth
213 /// first order w.r.t the DominatorTree. This allows us to visit definitions
214 /// before uses, allowing us to hoist a loop body in one pass without iteration.
216 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
217 assert(N != 0 && "Null dominator tree node?");
218 MachineBasicBlock *BB = N->getBlock();
220 // If this subregion is not in the top level loop at all, exit.
221 if (!CurLoop->contains(BB)) return;
223 for (MachineBasicBlock::iterator
224 MII = BB->begin(), E = BB->end(); MII != E; ) {
225 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
230 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
232 for (unsigned I = 0, E = Children.size(); I != E; ++I)
233 HoistRegion(Children[I]);
236 /// IsLoopInvariantInst - Returns true if the instruction is loop
237 /// invariant. I.e., all virtual register operands are defined outside of the
238 /// loop, physical registers aren't accessed explicitly, and there are no side
239 /// effects that aren't captured by the operands or other flags.
241 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
242 const TargetInstrDesc &TID = I.getDesc();
244 // Ignore stuff that we obviously can't hoist.
245 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
246 TID.hasUnmodeledSideEffects())
250 // Okay, this instruction does a load. As a refinement, we allow the target
251 // to decide whether the loaded value is actually a constant. If so, we can
252 // actually use it as a load.
253 if (!I.isInvariantLoad(AA))
254 // FIXME: we should be able to hoist loads with no other side effects if
255 // there are no other instructions which can change memory in this loop.
256 // This is a trivial form of alias analysis.
261 errs() << "--- Checking if we can hoist " << I;
262 if (I.getDesc().getImplicitUses()) {
263 errs() << " * Instruction has implicit uses:\n";
265 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
266 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
268 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
271 if (I.getDesc().getImplicitDefs()) {
272 errs() << " * Instruction has implicit defines:\n";
274 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
275 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
277 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
281 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
282 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
286 // The instruction is loop invariant if all of its operands are.
287 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
288 const MachineOperand &MO = I.getOperand(i);
293 unsigned Reg = MO.getReg();
294 if (Reg == 0) continue;
296 // Don't hoist an instruction that uses or defines a physical register.
297 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
299 // If the physreg has no defs anywhere, it's just an ambient register
300 // and we can freely move its uses. Alternatively, if it's allocatable,
301 // it could get allocated to something with a def during allocation.
302 if (!RegInfo->def_empty(Reg))
304 if (AllocatableSet.test(Reg))
306 // Check for a def among the register's aliases too.
307 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
308 unsigned AliasReg = *Alias;
309 if (!RegInfo->def_empty(AliasReg))
311 if (AllocatableSet.test(AliasReg))
314 // Otherwise it's safe to move.
316 } else if (!MO.isDead()) {
317 // A def that isn't dead. We can't move it.
325 assert(RegInfo->getVRegDef(Reg) &&
326 "Machine instr not mapped for this vreg?!");
328 // If the loop contains the definition of an operand, then the instruction
329 // isn't loop invariant.
330 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
334 // If we got this far, the instruction is loop invariant!
339 /// HasPHIUses - Return true if the specified register has any PHI use.
340 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
341 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
342 UE = RegInfo->use_end(); UI != UE; ++UI) {
343 MachineInstr *UseMI = &*UI;
344 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
350 /// isLoadFromConstantMemory - Return true if the given instruction is a
351 /// load from constant memory. Machine LICM will hoist these even if they are
352 /// not re-materializable.
353 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
354 if (!MI->getDesc().mayLoad()) return false;
355 if (!MI->hasOneMemOperand()) return false;
356 MachineMemOperand *MMO = *MI->memoperands_begin();
357 if (MMO->isVolatile()) return false;
358 if (!MMO->getValue()) return false;
359 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
361 MachineFunction &MF = *MI->getParent()->getParent();
362 return PSV->isConstant(MF.getFrameInfo());
364 return AA->pointsToConstantMemory(MMO->getValue());
368 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
369 /// the given loop invariant.
370 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI, bool &isConstLd) {
373 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
376 // FIXME: For now, only hoist re-materilizable instructions. LICM will
377 // increase register pressure. We want to make sure it doesn't increase
379 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
380 // these tend to help performance in low register pressure situation. The
381 // trade off is it may cause spill in high pressure situation. It will end up
382 // adding a store in the loop preheader. But the reload is no more expensive.
383 // The side benefit is these loads are frequently CSE'ed.
384 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
385 if (!HoistLdConst || !isLoadFromConstantMemory(&MI))
390 // If result(s) of this instruction is used by PHIs, then don't hoist it.
391 // The presence of joins makes it difficult for current register allocator
392 // implementation to perform remat.
393 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
394 const MachineOperand &MO = MI.getOperand(i);
395 if (!MO.isReg() || !MO.isDef())
397 if (HasPHIUses(MO.getReg(), RegInfo))
404 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
405 // If not, we may be able to unfold a load and hoist that.
406 // First test whether the instruction is loading from an amenable
408 if (!isLoadFromConstantMemory(MI))
411 // Next determine the register class for a temporary register.
412 unsigned LoadRegIndex;
414 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
416 /*UnfoldStore=*/false,
418 if (NewOpc == 0) return 0;
419 const TargetInstrDesc &TID = TII->get(NewOpc);
420 if (TID.getNumDefs() != 1) return 0;
421 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
422 // Ok, we're unfolding. Create a temporary register and do the unfold.
423 unsigned Reg = RegInfo->createVirtualRegister(RC);
425 MachineFunction &MF = *MI->getParent()->getParent();
426 SmallVector<MachineInstr *, 2> NewMIs;
428 TII->unfoldMemoryOperand(MF, MI, Reg,
429 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
433 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
435 assert(NewMIs.size() == 2 &&
436 "Unfolded a load into multiple instructions!");
437 MachineBasicBlock *MBB = MI->getParent();
438 MBB->insert(MI, NewMIs[0]);
439 MBB->insert(MI, NewMIs[1]);
440 // If unfolding produced a load that wasn't loop-invariant or profitable to
441 // hoist, discard the new instructions and bail.
443 if (!IsLoopInvariantInst(*NewMIs[0]) ||
444 !IsProfitableToHoist(*NewMIs[0], isConstLd)) {
445 NewMIs[0]->eraseFromParent();
446 NewMIs[1]->eraseFromParent();
449 // Otherwise we successfully unfolded a load that we can hoist.
450 MI->eraseFromParent();
454 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
455 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
456 const MachineInstr *MI = &*I;
457 // FIXME: For now, only hoist re-materilizable instructions. LICM will
458 // increase register pressure. We want to make sure it doesn't increase
460 if (TII->isTriviallyReMaterializable(MI, AA)) {
461 unsigned Opcode = MI->getOpcode();
462 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
463 CI = CSEMap.find(Opcode);
464 if (CI != CSEMap.end())
465 CI->second.push_back(MI);
467 std::vector<const MachineInstr*> CSEMIs;
468 CSEMIs.push_back(MI);
469 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
476 MachineLICM::LookForDuplicate(const MachineInstr *MI,
477 std::vector<const MachineInstr*> &PrevMIs) {
478 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
479 const MachineInstr *PrevMI = PrevMIs[i];
480 if (TII->isIdentical(MI, PrevMI, RegInfo))
486 bool MachineLICM::EliminateCSE(MachineInstr *MI,
487 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
488 if (CI == CSEMap.end())
491 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
492 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
493 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
494 const MachineOperand &MO = MI->getOperand(i);
495 if (MO.isReg() && MO.isDef())
496 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
498 MI->eraseFromParent();
505 /// Hoist - When an instruction is found to use only loop invariant operands
506 /// that are safe to hoist, this instruction is called to do the dirty work.
508 void MachineLICM::Hoist(MachineInstr *MI) {
509 // First check whether we should hoist this instruction.
511 if (!IsLoopInvariantInst(*MI) ||
512 !IsProfitableToHoist(*MI, isConstLd)) {
513 // If not, try unfolding a hoistable load.
514 MI = ExtractHoistableLoad(MI);
518 // Now move the instructions to the predecessor, inserting it before any
519 // terminator instructions.
521 errs() << "Hoisting ";
523 errs() << "load from constant mem ";
525 if (CurPreheader->getBasicBlock())
526 errs() << " to MachineBasicBlock "
527 << CurPreheader->getName();
528 if (MI->getParent()->getBasicBlock())
529 errs() << " from MachineBasicBlock "
530 << MI->getParent()->getName();
534 // If this is the first instruction being hoisted to the preheader,
535 // initialize the CSE map with potential common expressions.
536 InitCSEMap(CurPreheader);
538 // Look for opportunity to CSE the hoisted instruction.
539 unsigned Opcode = MI->getOpcode();
540 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
541 CI = CSEMap.find(Opcode);
542 if (!EliminateCSE(MI, CI)) {
543 // Otherwise, splice the instruction to the preheader.
544 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
546 // Add to the CSE map.
547 if (CI != CSEMap.end())
548 CI->second.push_back(MI);
550 std::vector<const MachineInstr*> CSEMIs;
551 CSEMIs.push_back(MI);
552 CSEMap.insert(std::make_pair(Opcode, CSEMIs));