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/MachineFrameInfo.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/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
43 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
44 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
45 STATISTIC(NumPostRAHoisted,
46 "Number of machine instructions hoisted out of loops post regalloc");
49 class MachineLICM : public MachineFunctionPass {
52 const TargetMachine *TM;
53 const TargetInstrInfo *TII;
54 const TargetRegisterInfo *TRI;
55 const MachineFrameInfo *MFI;
56 MachineRegisterInfo *RegInfo;
58 // Various analyses that we use...
59 AliasAnalysis *AA; // Alias analysis info.
60 MachineLoopInfo *MLI; // Current MachineLoopInfo
61 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
63 // State that is updated as we process loops
64 bool Changed; // True if a loop is changed.
65 MachineLoop *CurLoop; // The current loop we are working on.
66 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
68 BitVector AllocatableSet;
70 // For each opcode, keep a list of potentail CSE instructions.
71 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
74 static char ID; // Pass identification, replacement for typeid
76 MachineFunctionPass(&ID), PreRegAlloc(true) {}
78 explicit MachineLICM(bool PreRA) :
79 MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
81 virtual bool runOnMachineFunction(MachineFunction &MF);
83 const char *getPassName() const { return "Machine Instruction LICM"; }
85 // FIXME: Loop preheaders?
86 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.addRequired<MachineLoopInfo>();
89 AU.addRequired<MachineDominatorTree>();
90 AU.addRequired<AliasAnalysis>();
91 AU.addPreserved<MachineLoopInfo>();
92 AU.addPreserved<MachineDominatorTree>();
93 MachineFunctionPass::getAnalysisUsage(AU);
96 virtual void releaseMemory() {
101 /// CandidateInfo - Keep track of information about hoisting candidates.
102 struct CandidateInfo {
106 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
107 : MI(mi), Def(def), FI(fi) {}
110 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
111 /// invariants out to the preheader.
112 void HoistRegionPostRA(MachineDomTreeNode *N);
114 /// HoistPostRA - When an instruction is found to only use loop invariant
115 /// operands that is safe to hoist, this instruction is called to do the
117 void HoistPostRA(MachineInstr *MI, unsigned Def);
119 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
120 /// gather register def and frame object update information.
121 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
122 SmallSet<int, 32> &StoredFIs,
123 SmallVector<CandidateInfo, 32> &Candidates);
125 /// AddToLiveIns - Add 'Reg' to the livein sets of BBs in the backedge path
126 /// from MBB to LoopHeader (inclusive).
127 void AddToLiveIns(unsigned Reg,
128 MachineBasicBlock *MBB, MachineBasicBlock *LoopHeader);
130 /// IsLICMCandidate - Returns true if the instruction may be a suitable
131 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
132 /// not safe to hoist it.
133 bool IsLICMCandidate(MachineInstr &I);
135 /// IsLoopInvariantInst - Returns true if the instruction is loop
136 /// invariant. I.e., all virtual register operands are defined outside of
137 /// the loop, physical registers aren't accessed (explicitly or implicitly),
138 /// and the instruction is hoistable.
140 bool IsLoopInvariantInst(MachineInstr &I);
142 /// IsProfitableToHoist - Return true if it is potentially profitable to
143 /// hoist the given loop invariant.
144 bool IsProfitableToHoist(MachineInstr &MI);
146 /// HoistRegion - Walk the specified region of the CFG (defined by all
147 /// blocks dominated by the specified block, and that are in the current
148 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
149 /// visit definitions before uses, allowing us to hoist a loop body in one
150 /// pass without iteration.
152 void HoistRegion(MachineDomTreeNode *N);
154 /// isLoadFromConstantMemory - Return true if the given instruction is a
155 /// load from constant memory.
156 bool isLoadFromConstantMemory(MachineInstr *MI);
158 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
159 /// the load itself could be hoisted. Return the unfolded and hoistable
160 /// load, or null if the load couldn't be unfolded or if it wouldn't
162 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
164 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
165 /// duplicate of MI. Return this instruction if it's found.
166 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
167 std::vector<const MachineInstr*> &PrevMIs);
169 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
170 /// the preheader that compute the same value. If it's found, do a RAU on
171 /// with the definition of the existing instruction rather than hoisting
172 /// the instruction to the preheader.
173 bool EliminateCSE(MachineInstr *MI,
174 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
176 /// Hoist - When an instruction is found to only use loop invariant operands
177 /// that is safe to hoist, this instruction is called to do the dirty work.
179 void Hoist(MachineInstr *MI);
181 /// InitCSEMap - Initialize the CSE map with instructions that are in the
182 /// current loop preheader that may become duplicates of instructions that
183 /// are hoisted out of the loop.
184 void InitCSEMap(MachineBasicBlock *BB);
186 } // end anonymous namespace
188 char MachineLICM::ID = 0;
189 static RegisterPass<MachineLICM>
190 X("machinelicm", "Machine Loop Invariant Code Motion");
192 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
193 return new MachineLICM(PreRegAlloc);
196 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
197 /// loop that has a preheader.
198 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
199 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
200 if (L->getLoopPreheader())
205 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
207 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
209 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
212 TM = &MF.getTarget();
213 TII = TM->getInstrInfo();
214 TRI = TM->getRegisterInfo();
215 MFI = MF.getFrameInfo();
216 RegInfo = &MF.getRegInfo();
217 AllocatableSet = TRI->getAllocatableSet(MF);
219 // Get our Loop information...
220 MLI = &getAnalysis<MachineLoopInfo>();
221 DT = &getAnalysis<MachineDominatorTree>();
222 AA = &getAnalysis<AliasAnalysis>();
224 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I){
227 // If this is done before regalloc, only visit outer-most preheader-sporting
229 if (PreRegAlloc && !LoopIsOuterMostWithPreheader(CurLoop))
232 // Determine the block to which to hoist instructions. If we can't find a
233 // suitable loop preheader, we can't do any hoisting.
235 // FIXME: We are only hoisting if the basic block coming into this loop
236 // has only one successor. This isn't the case in general because we haven't
237 // broken critical edges or added preheaders.
238 CurPreheader = CurLoop->getLoopPreheader();
242 // CSEMap is initialized for loop header when the first instruction is
244 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
246 HoistRegionPostRA(N);
256 /// InstructionStoresToFI - Return true if instruction stores to the
258 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
259 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
260 oe = MI->memoperands_end(); o != oe; ++o) {
261 if (!(*o)->isStore() || !(*o)->getValue())
263 if (const FixedStackPseudoSourceValue *Value =
264 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
265 if (Value->getFrameIndex() == FI)
272 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
273 /// gather register def and frame object update information.
274 void MachineLICM::ProcessMI(MachineInstr *MI,
275 unsigned *PhysRegDefs,
276 SmallSet<int, 32> &StoredFIs,
277 SmallVector<CandidateInfo, 32> &Candidates) {
278 bool RuledOut = false;
279 bool HasRegFIUse = false;
281 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
282 const MachineOperand &MO = MI->getOperand(i);
284 // Remember if the instruction stores to the frame index.
285 int FI = MO.getIndex();
286 if (!StoredFIs.count(FI) &&
287 MFI->isSpillSlotObjectIndex(FI) &&
288 InstructionStoresToFI(MI, FI))
289 StoredFIs.insert(FI);
296 unsigned Reg = MO.getReg();
299 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
300 "Not expecting virtual register!");
307 if (MO.isImplicit()) {
309 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
312 // Non-dead implicit def? This cannot be hoisted.
314 // No need to check if a dead implicit def is also defined by
315 // another instruction.
319 // FIXME: For now, avoid instructions with multiple defs, unless
320 // it's a dead implicit def.
326 // If we have already seen another instruction that defines the same
327 // register, then this is not safe.
328 if (++PhysRegDefs[Reg] > 1)
329 // MI defined register is seen defined by another instruction in
330 // the loop, it cannot be a LICM candidate.
332 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
333 if (++PhysRegDefs[*AS] > 1)
337 // Only consider reloads for now and remats which do not have register
338 // operands. FIXME: Consider unfold load folding instructions.
339 if (Def && !RuledOut) {
341 // FIXME: Also hoist instructions if all source operands are live in
343 if ((!HasRegFIUse && IsLICMCandidate(*MI)) ||
344 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
345 Candidates.push_back(CandidateInfo(MI, Def, FI));
349 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
350 /// invariants out to the preheader.
351 void MachineLICM::HoistRegionPostRA(MachineDomTreeNode *N) {
352 assert(N != 0 && "Null dominator tree node?");
354 unsigned NumRegs = TRI->getNumRegs();
355 unsigned *PhysRegDefs = new unsigned[NumRegs];
356 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
358 SmallVector<CandidateInfo, 32> Candidates;
359 SmallSet<int, 32> StoredFIs;
361 // Walk the entire region, count number of defs for each register, and
362 // return potential LICM candidates.
363 SmallVector<MachineDomTreeNode*, 8> WorkList;
364 WorkList.push_back(N);
366 N = WorkList.pop_back_val();
367 MachineBasicBlock *BB = N->getBlock();
369 if (!CurLoop->contains(MLI->getLoopFor(BB)))
371 // Conservatively treat live-in's as an external def.
372 // FIXME: That means a reload that're reused in successor block(s) will not
374 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
375 E = BB->livein_end(); I != E; ++I) {
378 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
382 for (MachineBasicBlock::iterator
383 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
384 MachineInstr *MI = &*MII;
385 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
388 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
389 for (unsigned I = 0, E = Children.size(); I != E; ++I)
390 WorkList.push_back(Children[I]);
391 } while (!WorkList.empty());
393 // Now evaluate whether the potential candidates qualify.
394 // 1. Check if the candidate defined register is defined by another
395 // instruction in the loop.
396 // 2. If the candidate is a load from stack slot (always true for now),
397 // check if the slot is stored anywhere in the loop.
398 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
399 if (Candidates[i].FI != INT_MIN &&
400 StoredFIs.count(Candidates[i].FI))
403 if (PhysRegDefs[Candidates[i].Def] == 1)
404 HoistPostRA(Candidates[i].MI, Candidates[i].Def);
407 delete[] PhysRegDefs;
410 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
411 /// backedge path from MBB to LoopHeader.
412 void MachineLICM::AddToLiveIns(unsigned Reg, MachineBasicBlock *MBB,
413 MachineBasicBlock *LoopHeader) {
414 SmallPtrSet<MachineBasicBlock*, 4> Visited;
415 SmallVector<MachineBasicBlock*, 4> WorkList;
416 WorkList.push_back(MBB);
418 MBB = WorkList.pop_back_val();
419 if (!Visited.insert(MBB))
422 if (MBB == LoopHeader)
424 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
425 E = MBB->pred_end(); PI != E; ++PI)
426 WorkList.push_back(*PI);
427 } while (!WorkList.empty());
430 /// HoistPostRA - When an instruction is found to only use loop invariant
431 /// operands that is safe to hoist, this instruction is called to do the
433 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
434 // Now move the instructions to the predecessor, inserting it before any
435 // terminator instructions.
437 dbgs() << "Hoisting " << *MI;
438 if (CurPreheader->getBasicBlock())
439 dbgs() << " to MachineBasicBlock "
440 << CurPreheader->getName();
441 if (MI->getParent()->getBasicBlock())
442 dbgs() << " from MachineBasicBlock "
443 << MI->getParent()->getName();
447 // Splice the instruction to the preheader.
448 MachineBasicBlock *MBB = MI->getParent();
449 CurPreheader->splice(CurPreheader->getFirstTerminator(), MBB, MI);
451 // Add register to livein list to BBs in the path from loop header to original
452 // BB. Note, currently it's not necessary to worry about adding it to all BB's
453 // with uses. Reload that're reused in successor block(s) are not being
455 AddToLiveIns(Def, MBB, CurLoop->getHeader());
461 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
462 /// dominated by the specified block, and that are in the current loop) in depth
463 /// first order w.r.t the DominatorTree. This allows us to visit definitions
464 /// before uses, allowing us to hoist a loop body in one pass without iteration.
466 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
467 assert(N != 0 && "Null dominator tree node?");
468 MachineBasicBlock *BB = N->getBlock();
470 // If this subregion is not in the top level loop at all, exit.
471 if (!CurLoop->contains(BB)) return;
473 for (MachineBasicBlock::iterator
474 MII = BB->begin(), E = BB->end(); MII != E; ) {
475 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
480 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
481 for (unsigned I = 0, E = Children.size(); I != E; ++I)
482 HoistRegion(Children[I]);
485 /// IsLICMCandidate - Returns true if the instruction may be a suitable
486 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
487 /// not safe to hoist it.
488 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
489 const TargetInstrDesc &TID = I.getDesc();
491 // Ignore stuff that we obviously can't hoist.
492 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
493 TID.hasUnmodeledSideEffects())
497 // Okay, this instruction does a load. As a refinement, we allow the target
498 // to decide whether the loaded value is actually a constant. If so, we can
499 // actually use it as a load.
500 if (!I.isInvariantLoad(AA))
501 // FIXME: we should be able to hoist loads with no other side effects if
502 // there are no other instructions which can change memory in this loop.
503 // This is a trivial form of alias analysis.
509 /// IsLoopInvariantInst - Returns true if the instruction is loop
510 /// invariant. I.e., all virtual register operands are defined outside of the
511 /// loop, physical registers aren't accessed explicitly, and there are no side
512 /// effects that aren't captured by the operands or other flags.
514 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
515 if (!IsLICMCandidate(I))
518 // The instruction is loop invariant if all of its operands are.
519 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
520 const MachineOperand &MO = I.getOperand(i);
525 unsigned Reg = MO.getReg();
526 if (Reg == 0) continue;
528 // Don't hoist an instruction that uses or defines a physical register.
529 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
531 // If the physreg has no defs anywhere, it's just an ambient register
532 // and we can freely move its uses. Alternatively, if it's allocatable,
533 // it could get allocated to something with a def during allocation.
534 if (!RegInfo->def_empty(Reg))
536 if (AllocatableSet.test(Reg))
538 // Check for a def among the register's aliases too.
539 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
540 unsigned AliasReg = *Alias;
541 if (!RegInfo->def_empty(AliasReg))
543 if (AllocatableSet.test(AliasReg))
546 // Otherwise it's safe to move.
548 } else if (!MO.isDead()) {
549 // A def that isn't dead. We can't move it.
551 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
552 // If the reg is live into the loop, we can't hoist an instruction
553 // which would clobber it.
561 assert(RegInfo->getVRegDef(Reg) &&
562 "Machine instr not mapped for this vreg?!");
564 // If the loop contains the definition of an operand, then the instruction
565 // isn't loop invariant.
566 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
570 // If we got this far, the instruction is loop invariant!
575 /// HasPHIUses - Return true if the specified register has any PHI use.
576 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
577 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
578 UE = RegInfo->use_end(); UI != UE; ++UI) {
579 MachineInstr *UseMI = &*UI;
586 /// isLoadFromConstantMemory - Return true if the given instruction is a
587 /// load from constant memory. Machine LICM will hoist these even if they are
588 /// not re-materializable.
589 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
590 if (!MI->getDesc().mayLoad()) return false;
591 if (!MI->hasOneMemOperand()) return false;
592 MachineMemOperand *MMO = *MI->memoperands_begin();
593 if (MMO->isVolatile()) return false;
594 if (!MMO->getValue()) return false;
595 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
597 MachineFunction &MF = *MI->getParent()->getParent();
598 return PSV->isConstant(MF.getFrameInfo());
600 return AA->pointsToConstantMemory(MMO->getValue());
604 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
605 /// the given loop invariant.
606 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
607 if (MI.isImplicitDef())
610 // FIXME: For now, only hoist re-materilizable instructions. LICM will
611 // increase register pressure. We want to make sure it doesn't increase
613 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
614 // these tend to help performance in low register pressure situation. The
615 // trade off is it may cause spill in high pressure situation. It will end up
616 // adding a store in the loop preheader. But the reload is no more expensive.
617 // The side benefit is these loads are frequently CSE'ed.
618 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
619 if (!isLoadFromConstantMemory(&MI))
623 // If result(s) of this instruction is used by PHIs, then don't hoist it.
624 // The presence of joins makes it difficult for current register allocator
625 // implementation to perform remat.
626 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
627 const MachineOperand &MO = MI.getOperand(i);
628 if (!MO.isReg() || !MO.isDef())
630 if (HasPHIUses(MO.getReg(), RegInfo))
637 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
638 // If not, we may be able to unfold a load and hoist that.
639 // First test whether the instruction is loading from an amenable
641 if (!isLoadFromConstantMemory(MI))
644 // Next determine the register class for a temporary register.
645 unsigned LoadRegIndex;
647 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
649 /*UnfoldStore=*/false,
651 if (NewOpc == 0) return 0;
652 const TargetInstrDesc &TID = TII->get(NewOpc);
653 if (TID.getNumDefs() != 1) return 0;
654 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
655 // Ok, we're unfolding. Create a temporary register and do the unfold.
656 unsigned Reg = RegInfo->createVirtualRegister(RC);
658 MachineFunction &MF = *MI->getParent()->getParent();
659 SmallVector<MachineInstr *, 2> NewMIs;
661 TII->unfoldMemoryOperand(MF, MI, Reg,
662 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
666 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
668 assert(NewMIs.size() == 2 &&
669 "Unfolded a load into multiple instructions!");
670 MachineBasicBlock *MBB = MI->getParent();
671 MBB->insert(MI, NewMIs[0]);
672 MBB->insert(MI, NewMIs[1]);
673 // If unfolding produced a load that wasn't loop-invariant or profitable to
674 // hoist, discard the new instructions and bail.
675 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
676 NewMIs[0]->eraseFromParent();
677 NewMIs[1]->eraseFromParent();
680 // Otherwise we successfully unfolded a load that we can hoist.
681 MI->eraseFromParent();
685 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
686 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
687 const MachineInstr *MI = &*I;
688 // FIXME: For now, only hoist re-materilizable instructions. LICM will
689 // increase register pressure. We want to make sure it doesn't increase
691 if (TII->isTriviallyReMaterializable(MI, AA)) {
692 unsigned Opcode = MI->getOpcode();
693 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
694 CI = CSEMap.find(Opcode);
695 if (CI != CSEMap.end())
696 CI->second.push_back(MI);
698 std::vector<const MachineInstr*> CSEMIs;
699 CSEMIs.push_back(MI);
700 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
707 MachineLICM::LookForDuplicate(const MachineInstr *MI,
708 std::vector<const MachineInstr*> &PrevMIs) {
709 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
710 const MachineInstr *PrevMI = PrevMIs[i];
711 if (TII->produceSameValue(MI, PrevMI))
717 bool MachineLICM::EliminateCSE(MachineInstr *MI,
718 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
719 if (CI == CSEMap.end())
722 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
723 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
725 // Replace virtual registers defined by MI by their counterparts defined
727 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
728 const MachineOperand &MO = MI->getOperand(i);
730 // Physical registers may not differ here.
731 assert((!MO.isReg() || MO.getReg() == 0 ||
732 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
733 MO.getReg() == Dup->getOperand(i).getReg()) &&
734 "Instructions with different phys regs are not identical!");
736 if (MO.isReg() && MO.isDef() &&
737 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
738 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
740 MI->eraseFromParent();
747 /// Hoist - When an instruction is found to use only loop invariant operands
748 /// that are safe to hoist, this instruction is called to do the dirty work.
750 void MachineLICM::Hoist(MachineInstr *MI) {
751 // First check whether we should hoist this instruction.
752 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
753 // If not, try unfolding a hoistable load.
754 MI = ExtractHoistableLoad(MI);
758 // Now move the instructions to the predecessor, inserting it before any
759 // terminator instructions.
761 dbgs() << "Hoisting " << *MI;
762 if (CurPreheader->getBasicBlock())
763 dbgs() << " to MachineBasicBlock "
764 << CurPreheader->getName();
765 if (MI->getParent()->getBasicBlock())
766 dbgs() << " from MachineBasicBlock "
767 << MI->getParent()->getName();
771 // If this is the first instruction being hoisted to the preheader,
772 // initialize the CSE map with potential common expressions.
773 InitCSEMap(CurPreheader);
775 // Look for opportunity to CSE the hoisted instruction.
776 unsigned Opcode = MI->getOpcode();
777 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
778 CI = CSEMap.find(Opcode);
779 if (!EliminateCSE(MI, CI)) {
780 // Otherwise, splice the instruction to the preheader.
781 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
783 // Add to the CSE map.
784 if (CI != CSEMap.end())
785 CI->second.push_back(MI);
787 std::vector<const MachineInstr*> CSEMIs;
788 CSEMIs.push_back(MI);
789 CSEMap.insert(std::make_pair(Opcode, CSEMIs));