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/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
43 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
46 class MachineLICM : public MachineFunctionPass {
47 MachineConstantPool *MCP;
48 const TargetMachine *TM;
49 const TargetInstrInfo *TII;
50 const TargetRegisterInfo *TRI;
51 BitVector AllocatableSet;
53 // Various analyses that we use...
54 AliasAnalysis *AA; // Alias analysis info.
55 MachineLoopInfo *LI; // Current MachineLoopInfo
56 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
57 MachineRegisterInfo *RegInfo; // Machine register information
59 // State that is updated as we process loops
60 bool Changed; // True if a loop is changed.
61 bool FirstInLoop; // True if it's the first LICM in the loop.
62 MachineLoop *CurLoop; // The current loop we are working on.
63 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
65 // For each opcode, keep a list of potentail CSE instructions.
66 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
68 static char ID; // Pass identification, replacement for typeid
69 MachineLICM() : MachineFunctionPass(&ID) {}
71 virtual bool runOnMachineFunction(MachineFunction &MF);
73 const char *getPassName() const { return "Machine Instruction LICM"; }
75 // FIXME: Loop preheaders?
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<MachineLoopInfo>();
79 AU.addRequired<MachineDominatorTree>();
80 AU.addRequired<AliasAnalysis>();
81 AU.addPreserved<MachineLoopInfo>();
82 AU.addPreserved<MachineDominatorTree>();
83 MachineFunctionPass::getAnalysisUsage(AU);
86 virtual void releaseMemory() {
91 /// IsLoopInvariantInst - Returns true if the instruction is loop
92 /// invariant. I.e., all virtual register operands are defined outside of
93 /// the loop, physical registers aren't accessed (explicitly or implicitly),
94 /// and the instruction is hoistable.
96 bool IsLoopInvariantInst(MachineInstr &I);
98 /// IsProfitableToHoist - Return true if it is potentially profitable to
99 /// hoist the given loop invariant.
100 bool IsProfitableToHoist(MachineInstr &MI);
102 /// HoistRegion - Walk the specified region of the CFG (defined by all
103 /// blocks dominated by the specified block, and that are in the current
104 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
105 /// visit definitions before uses, allowing us to hoist a loop body in one
106 /// pass without iteration.
108 void HoistRegion(MachineDomTreeNode *N);
110 /// isLoadFromConstantMemory - Return true if the given instruction is a
111 /// load from constant memory.
112 bool isLoadFromConstantMemory(MachineInstr *MI);
114 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
115 /// the load itself could be hoisted. Return the unfolded and hoistable
116 /// load, or null if the load couldn't be unfolded or if it wouldn't
118 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
120 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
121 /// duplicate of MI. Return this instruction if it's found.
122 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
123 std::vector<const MachineInstr*> &PrevMIs);
125 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
126 /// the preheader that compute the same value. If it's found, do a RAU on
127 /// with the definition of the existing instruction rather than hoisting
128 /// the instruction to the preheader.
129 bool EliminateCSE(MachineInstr *MI,
130 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
132 /// Hoist - When an instruction is found to only use loop invariant operands
133 /// that is safe to hoist, this instruction is called to do the dirty work.
135 void Hoist(MachineInstr *MI);
137 /// InitCSEMap - Initialize the CSE map with instructions that are in the
138 /// current loop preheader that may become duplicates of instructions that
139 /// are hoisted out of the loop.
140 void InitCSEMap(MachineBasicBlock *BB);
142 } // end anonymous namespace
144 char MachineLICM::ID = 0;
145 static RegisterPass<MachineLICM>
146 X("machinelicm", "Machine Loop Invariant Code Motion");
148 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
150 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
151 /// loop that has a preheader.
152 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
153 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
154 if (L->getLoopPreheader())
159 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
160 /// is not preserved so it is not a good idea to run LICM multiple times on one
163 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
164 DEBUG(dbgs() << "******** Machine LICM ********\n");
166 Changed = FirstInLoop = false;
167 MCP = MF.getConstantPool();
168 TM = &MF.getTarget();
169 TII = TM->getInstrInfo();
170 TRI = TM->getRegisterInfo();
171 RegInfo = &MF.getRegInfo();
172 AllocatableSet = TRI->getAllocatableSet(MF);
174 // Get our Loop information...
175 LI = &getAnalysis<MachineLoopInfo>();
176 DT = &getAnalysis<MachineDominatorTree>();
177 AA = &getAnalysis<AliasAnalysis>();
179 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
182 // Only visit outer-most preheader-sporting loops.
183 if (!LoopIsOuterMostWithPreheader(CurLoop))
186 // Determine the block to which to hoist instructions. If we can't find a
187 // suitable loop preheader, we can't do any hoisting.
189 // FIXME: We are only hoisting if the basic block coming into this loop
190 // has only one successor. This isn't the case in general because we haven't
191 // broken critical edges or added preheaders.
192 CurPreheader = CurLoop->getLoopPreheader();
196 // CSEMap is initialized for loop header when the first instruction is
199 HoistRegion(DT->getNode(CurLoop->getHeader()));
206 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
207 /// dominated by the specified block, and that are in the current loop) in depth
208 /// first order w.r.t the DominatorTree. This allows us to visit definitions
209 /// before uses, allowing us to hoist a loop body in one pass without iteration.
211 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
212 assert(N != 0 && "Null dominator tree node?");
213 MachineBasicBlock *BB = N->getBlock();
215 // If this subregion is not in the top level loop at all, exit.
216 if (!CurLoop->contains(BB)) return;
218 for (MachineBasicBlock::iterator
219 MII = BB->begin(), E = BB->end(); MII != E; ) {
220 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
225 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
227 for (unsigned I = 0, E = Children.size(); I != E; ++I)
228 HoistRegion(Children[I]);
231 /// IsLoopInvariantInst - Returns true if the instruction is loop
232 /// invariant. I.e., all virtual register operands are defined outside of the
233 /// loop, physical registers aren't accessed explicitly, and there are no side
234 /// effects that aren't captured by the operands or other flags.
236 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
237 const TargetInstrDesc &TID = I.getDesc();
239 // Ignore stuff that we obviously can't hoist.
240 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
241 TID.hasUnmodeledSideEffects())
245 // Okay, this instruction does a load. As a refinement, we allow the target
246 // to decide whether the loaded value is actually a constant. If so, we can
247 // actually use it as a load.
248 if (!I.isInvariantLoad(AA))
249 // FIXME: we should be able to hoist loads with no other side effects if
250 // there are no other instructions which can change memory in this loop.
251 // This is a trivial form of alias analysis.
256 dbgs() << "--- Checking if we can hoist " << I;
257 if (I.getDesc().getImplicitUses()) {
258 dbgs() << " * Instruction has implicit uses:\n";
260 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
261 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
263 dbgs() << " -> " << TRI->getName(*ImpUses) << "\n";
266 if (I.getDesc().getImplicitDefs()) {
267 dbgs() << " * Instruction has implicit defines:\n";
269 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
270 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
272 dbgs() << " -> " << TRI->getName(*ImpDefs) << "\n";
276 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
277 DEBUG(dbgs() << "Cannot hoist with implicit defines or uses\n");
281 // The instruction is loop invariant if all of its operands are.
282 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
283 const MachineOperand &MO = I.getOperand(i);
288 unsigned Reg = MO.getReg();
289 if (Reg == 0) continue;
291 // Don't hoist an instruction that uses or defines a physical register.
292 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
294 // If the physreg has no defs anywhere, it's just an ambient register
295 // and we can freely move its uses. Alternatively, if it's allocatable,
296 // it could get allocated to something with a def during allocation.
297 if (!RegInfo->def_empty(Reg))
299 if (AllocatableSet.test(Reg))
301 // Check for a def among the register's aliases too.
302 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
303 unsigned AliasReg = *Alias;
304 if (!RegInfo->def_empty(AliasReg))
306 if (AllocatableSet.test(AliasReg))
309 // Otherwise it's safe to move.
311 } else if (!MO.isDead()) {
312 // A def that isn't dead. We can't move it.
320 assert(RegInfo->getVRegDef(Reg) &&
321 "Machine instr not mapped for this vreg?!");
323 // If the loop contains the definition of an operand, then the instruction
324 // isn't loop invariant.
325 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
329 // If we got this far, the instruction is loop invariant!
334 /// HasPHIUses - Return true if the specified register has any PHI use.
335 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
336 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
337 UE = RegInfo->use_end(); UI != UE; ++UI) {
338 MachineInstr *UseMI = &*UI;
339 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
345 /// isLoadFromConstantMemory - Return true if the given instruction is a
346 /// load from constant memory. Machine LICM will hoist these even if they are
347 /// not re-materializable.
348 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
349 if (!MI->getDesc().mayLoad()) return false;
350 if (!MI->hasOneMemOperand()) return false;
351 MachineMemOperand *MMO = *MI->memoperands_begin();
352 if (MMO->isVolatile()) return false;
353 if (!MMO->getValue()) return false;
354 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
356 MachineFunction &MF = *MI->getParent()->getParent();
357 return PSV->isConstant(MF.getFrameInfo());
359 return AA->pointsToConstantMemory(MMO->getValue());
363 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
364 /// the given loop invariant.
365 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
366 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
369 // FIXME: For now, only hoist re-materilizable instructions. LICM will
370 // increase register pressure. We want to make sure it doesn't increase
372 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
373 // these tend to help performance in low register pressure situation. The
374 // trade off is it may cause spill in high pressure situation. It will end up
375 // adding a store in the loop preheader. But the reload is no more expensive.
376 // The side benefit is these loads are frequently CSE'ed.
377 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
378 if (!isLoadFromConstantMemory(&MI))
382 // If result(s) of this instruction is used by PHIs, then don't hoist it.
383 // The presence of joins makes it difficult for current register allocator
384 // implementation to perform remat.
385 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
386 const MachineOperand &MO = MI.getOperand(i);
387 if (!MO.isReg() || !MO.isDef())
389 if (HasPHIUses(MO.getReg(), RegInfo))
396 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
397 // If not, we may be able to unfold a load and hoist that.
398 // First test whether the instruction is loading from an amenable
400 if (!isLoadFromConstantMemory(MI))
403 // Next determine the register class for a temporary register.
404 unsigned LoadRegIndex;
406 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
408 /*UnfoldStore=*/false,
410 if (NewOpc == 0) return 0;
411 const TargetInstrDesc &TID = TII->get(NewOpc);
412 if (TID.getNumDefs() != 1) return 0;
413 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
414 // Ok, we're unfolding. Create a temporary register and do the unfold.
415 unsigned Reg = RegInfo->createVirtualRegister(RC);
417 MachineFunction &MF = *MI->getParent()->getParent();
418 SmallVector<MachineInstr *, 2> NewMIs;
420 TII->unfoldMemoryOperand(MF, MI, Reg,
421 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
425 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
427 assert(NewMIs.size() == 2 &&
428 "Unfolded a load into multiple instructions!");
429 MachineBasicBlock *MBB = MI->getParent();
430 MBB->insert(MI, NewMIs[0]);
431 MBB->insert(MI, NewMIs[1]);
432 // If unfolding produced a load that wasn't loop-invariant or profitable to
433 // hoist, discard the new instructions and bail.
434 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
435 NewMIs[0]->eraseFromParent();
436 NewMIs[1]->eraseFromParent();
439 // Otherwise we successfully unfolded a load that we can hoist.
440 MI->eraseFromParent();
444 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
445 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
446 const MachineInstr *MI = &*I;
447 // FIXME: For now, only hoist re-materilizable instructions. LICM will
448 // increase register pressure. We want to make sure it doesn't increase
450 if (TII->isTriviallyReMaterializable(MI, AA)) {
451 unsigned Opcode = MI->getOpcode();
452 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
453 CI = CSEMap.find(Opcode);
454 if (CI != CSEMap.end())
455 CI->second.push_back(MI);
457 std::vector<const MachineInstr*> CSEMIs;
458 CSEMIs.push_back(MI);
459 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
466 MachineLICM::LookForDuplicate(const MachineInstr *MI,
467 std::vector<const MachineInstr*> &PrevMIs) {
468 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
469 const MachineInstr *PrevMI = PrevMIs[i];
470 if (TII->isIdentical(MI, PrevMI, RegInfo))
476 bool MachineLICM::EliminateCSE(MachineInstr *MI,
477 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
478 if (CI == CSEMap.end())
481 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
482 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
483 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
484 const MachineOperand &MO = MI->getOperand(i);
485 if (MO.isReg() && MO.isDef())
486 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
488 MI->eraseFromParent();
495 /// Hoist - When an instruction is found to use only loop invariant operands
496 /// that are safe to hoist, this instruction is called to do the dirty work.
498 void MachineLICM::Hoist(MachineInstr *MI) {
499 // First check whether we should hoist this instruction.
500 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
501 // If not, try unfolding a hoistable load.
502 MI = ExtractHoistableLoad(MI);
506 // Now move the instructions to the predecessor, inserting it before any
507 // terminator instructions.
509 dbgs() << "Hoisting " << *MI;
510 if (CurPreheader->getBasicBlock())
511 dbgs() << " to MachineBasicBlock "
512 << CurPreheader->getName();
513 if (MI->getParent()->getBasicBlock())
514 dbgs() << " from MachineBasicBlock "
515 << MI->getParent()->getName();
519 // If this is the first instruction being hoisted to the preheader,
520 // initialize the CSE map with potential common expressions.
521 InitCSEMap(CurPreheader);
523 // Look for opportunity to CSE the hoisted instruction.
524 unsigned Opcode = MI->getOpcode();
525 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
526 CI = CSEMap.find(Opcode);
527 if (!EliminateCSE(MI, CI)) {
528 // Otherwise, splice the instruction to the preheader.
529 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
531 // Add to the CSE map.
532 if (CI != CSEMap.end())
533 CI->second.push_back(MI);
535 std::vector<const MachineInstr*> CSEMIs;
536 CSEMIs.push_back(MI);
537 CSEMap.insert(std::make_pair(Opcode, CSEMIs));