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/MC/MCInstrItineraries.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
45 "Number of machine instructions hoisted out of loops");
47 "Number of instructions hoisted in low reg pressure situation");
48 STATISTIC(NumHighLatency,
49 "Number of high latency instructions hoisted");
51 "Number of hoisted machine instructions CSEed");
52 STATISTIC(NumPostRAHoisted,
53 "Number of machine instructions hoisted out of loops post regalloc");
56 class MachineLICM : public MachineFunctionPass {
59 const TargetMachine *TM;
60 const TargetInstrInfo *TII;
61 const TargetLowering *TLI;
62 const TargetRegisterInfo *TRI;
63 const MachineFrameInfo *MFI;
64 MachineRegisterInfo *MRI;
65 const InstrItineraryData *InstrItins;
67 // Various analyses that we use...
68 AliasAnalysis *AA; // Alias analysis info.
69 MachineLoopInfo *MLI; // Current MachineLoopInfo
70 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
72 // State that is updated as we process loops
73 bool Changed; // True if a loop is changed.
74 bool FirstInLoop; // True if it's the first LICM in the loop.
75 MachineLoop *CurLoop; // The current loop we are working on.
76 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
78 BitVector AllocatableSet;
80 // Track 'estimated' register pressure.
81 SmallSet<unsigned, 32> RegSeen;
82 SmallVector<unsigned, 8> RegPressure;
84 // Register pressure "limit" per register class. If the pressure
85 // is higher than the limit, then it's considered high.
86 SmallVector<unsigned, 8> RegLimit;
88 // Register pressure on path leading from loop preheader to current BB.
89 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
91 // For each opcode, keep a list of potential CSE instructions.
92 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
95 static char ID; // Pass identification, replacement for typeid
97 MachineFunctionPass(ID), PreRegAlloc(true) {
98 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
101 explicit MachineLICM(bool PreRA) :
102 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
103 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
106 virtual bool runOnMachineFunction(MachineFunction &MF);
108 const char *getPassName() const { return "Machine Instruction LICM"; }
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
111 AU.addRequired<MachineLoopInfo>();
112 AU.addRequired<MachineDominatorTree>();
113 AU.addRequired<AliasAnalysis>();
114 AU.addPreserved<MachineLoopInfo>();
115 AU.addPreserved<MachineDominatorTree>();
116 MachineFunctionPass::getAnalysisUsage(AU);
119 virtual void releaseMemory() {
124 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
125 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
131 /// CandidateInfo - Keep track of information about hoisting candidates.
132 struct CandidateInfo {
136 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
137 : MI(mi), Def(def), FI(fi) {}
140 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
141 /// invariants out to the preheader.
142 void HoistRegionPostRA();
144 /// HoistPostRA - When an instruction is found to only use loop invariant
145 /// operands that is safe to hoist, this instruction is called to do the
147 void HoistPostRA(MachineInstr *MI, unsigned Def);
149 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
150 /// gather register def and frame object update information.
151 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
152 SmallSet<int, 32> &StoredFIs,
153 SmallVector<CandidateInfo, 32> &Candidates);
155 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
157 void AddToLiveIns(unsigned Reg);
159 /// IsLICMCandidate - Returns true if the instruction may be a suitable
160 /// candidate for LICM. e.g. If the instruction is a call, then it's
161 /// obviously not safe to hoist it.
162 bool IsLICMCandidate(MachineInstr &I);
164 /// IsLoopInvariantInst - Returns true if the instruction is loop
165 /// invariant. I.e., all virtual register operands are defined outside of
166 /// the loop, physical registers aren't accessed (explicitly or implicitly),
167 /// and the instruction is hoistable.
169 bool IsLoopInvariantInst(MachineInstr &I);
171 /// IsGuaranteedToExecute - check to make sure that the MI dominates
172 /// all of the exit blocks. If it doesn't, then there is a path out of the
173 /// loop which does not execute this instruction, so we can't hoist it.
174 bool IsGuaranteedToExecute(MachineInstr *MI);
176 /// HasAnyPHIUse - Return true if the specified register is used by any
178 bool HasAnyPHIUse(unsigned Reg) const;
180 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
181 /// and an use in the current loop, return true if the target considered
183 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
186 bool IsCheapInstruction(MachineInstr &MI) const;
188 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
189 /// check if hoisting an instruction of the given cost matrix can cause high
190 /// register pressure.
191 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
193 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
194 /// the current block and update their register pressures to reflect the
195 /// effect of hoisting MI from the current block to the preheader.
196 void UpdateBackTraceRegPressure(const MachineInstr *MI);
198 /// IsProfitableToHoist - Return true if it is potentially profitable to
199 /// hoist the given loop invariant.
200 bool IsProfitableToHoist(MachineInstr &MI);
202 /// HoistRegion - Walk the specified region of the CFG (defined by all
203 /// blocks dominated by the specified block, and that are in the current
204 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
205 /// visit definitions before uses, allowing us to hoist a loop body in one
206 /// pass without iteration.
208 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
210 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
211 /// index, return the ID and cost of its representative register class by
213 void getRegisterClassIDAndCost(const MachineInstr *MI,
214 unsigned Reg, unsigned OpIdx,
215 unsigned &RCId, unsigned &RCCost) const;
217 /// InitRegPressure - Find all virtual register references that are liveout
218 /// of the preheader to initialize the starting "register pressure". Note
219 /// this does not count live through (livein but not used) registers.
220 void InitRegPressure(MachineBasicBlock *BB);
222 /// UpdateRegPressure - Update estimate of register pressure after the
223 /// specified instruction.
224 void UpdateRegPressure(const MachineInstr *MI);
226 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
227 /// the load itself could be hoisted. Return the unfolded and hoistable
228 /// load, or null if the load couldn't be unfolded or if it wouldn't
230 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
232 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
233 /// duplicate of MI. Return this instruction if it's found.
234 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
235 std::vector<const MachineInstr*> &PrevMIs);
237 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
238 /// the preheader that compute the same value. If it's found, do a RAU on
239 /// with the definition of the existing instruction rather than hoisting
240 /// the instruction to the preheader.
241 bool EliminateCSE(MachineInstr *MI,
242 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
244 /// Hoist - When an instruction is found to only use loop invariant operands
245 /// that is safe to hoist, this instruction is called to do the dirty work.
246 /// It returns true if the instruction is hoisted.
247 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
249 /// InitCSEMap - Initialize the CSE map with instructions that are in the
250 /// current loop preheader that may become duplicates of instructions that
251 /// are hoisted out of the loop.
252 void InitCSEMap(MachineBasicBlock *BB);
254 /// getCurPreheader - Get the preheader for the current loop, splitting
255 /// a critical edge if needed.
256 MachineBasicBlock *getCurPreheader();
258 } // end anonymous namespace
260 char MachineLICM::ID = 0;
261 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
262 "Machine Loop Invariant Code Motion", false, false)
263 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
264 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
265 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
266 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
267 "Machine Loop Invariant Code Motion", false, false)
269 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
270 return new MachineLICM(PreRegAlloc);
273 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
274 /// loop that has a unique predecessor.
275 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
276 // Check whether this loop even has a unique predecessor.
277 if (!CurLoop->getLoopPredecessor())
279 // Ok, now check to see if any of its outer loops do.
280 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
281 if (L->getLoopPredecessor())
283 // None of them did, so this is the outermost with a unique predecessor.
287 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
289 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
291 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
292 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
294 Changed = FirstInLoop = false;
295 TM = &MF.getTarget();
296 TII = TM->getInstrInfo();
297 TLI = TM->getTargetLowering();
298 TRI = TM->getRegisterInfo();
299 MFI = MF.getFrameInfo();
300 MRI = &MF.getRegInfo();
301 InstrItins = TM->getInstrItineraryData();
302 AllocatableSet = TRI->getAllocatableSet(MF);
305 // Estimate register pressure during pre-regalloc pass.
306 unsigned NumRC = TRI->getNumRegClasses();
307 RegPressure.resize(NumRC);
308 std::fill(RegPressure.begin(), RegPressure.end(), 0);
309 RegLimit.resize(NumRC);
310 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
311 E = TRI->regclass_end(); I != E; ++I)
312 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
315 // Get our Loop information...
316 MLI = &getAnalysis<MachineLoopInfo>();
317 DT = &getAnalysis<MachineDominatorTree>();
318 AA = &getAnalysis<AliasAnalysis>();
320 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
321 while (!Worklist.empty()) {
322 CurLoop = Worklist.pop_back_val();
325 // If this is done before regalloc, only visit outer-most preheader-sporting
327 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
328 Worklist.append(CurLoop->begin(), CurLoop->end());
335 // CSEMap is initialized for loop header when the first instruction is
337 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
339 HoistRegion(N, true);
347 /// InstructionStoresToFI - Return true if instruction stores to the
349 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
350 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
351 oe = MI->memoperands_end(); o != oe; ++o) {
352 if (!(*o)->isStore() || !(*o)->getValue())
354 if (const FixedStackPseudoSourceValue *Value =
355 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
356 if (Value->getFrameIndex() == FI)
363 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
364 /// gather register def and frame object update information.
365 void MachineLICM::ProcessMI(MachineInstr *MI,
366 unsigned *PhysRegDefs,
367 SmallSet<int, 32> &StoredFIs,
368 SmallVector<CandidateInfo, 32> &Candidates) {
369 bool RuledOut = false;
370 bool HasNonInvariantUse = false;
372 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
373 const MachineOperand &MO = MI->getOperand(i);
375 // Remember if the instruction stores to the frame index.
376 int FI = MO.getIndex();
377 if (!StoredFIs.count(FI) &&
378 MFI->isSpillSlotObjectIndex(FI) &&
379 InstructionStoresToFI(MI, FI))
380 StoredFIs.insert(FI);
381 HasNonInvariantUse = true;
387 unsigned Reg = MO.getReg();
390 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
391 "Not expecting virtual register!");
394 if (Reg && PhysRegDefs[Reg])
395 // If it's using a non-loop-invariant register, then it's obviously not
397 HasNonInvariantUse = true;
401 if (MO.isImplicit()) {
403 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
406 // Non-dead implicit def? This cannot be hoisted.
408 // No need to check if a dead implicit def is also defined by
409 // another instruction.
413 // FIXME: For now, avoid instructions with multiple defs, unless
414 // it's a dead implicit def.
420 // If we have already seen another instruction that defines the same
421 // register, then this is not safe.
422 if (++PhysRegDefs[Reg] > 1)
423 // MI defined register is seen defined by another instruction in
424 // the loop, it cannot be a LICM candidate.
426 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
427 if (++PhysRegDefs[*AS] > 1)
431 // Only consider reloads for now and remats which do not have register
432 // operands. FIXME: Consider unfold load folding instructions.
433 if (Def && !RuledOut) {
435 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
436 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
437 Candidates.push_back(CandidateInfo(MI, Def, FI));
441 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
442 /// invariants out to the preheader.
443 void MachineLICM::HoistRegionPostRA() {
444 unsigned NumRegs = TRI->getNumRegs();
445 unsigned *PhysRegDefs = new unsigned[NumRegs];
446 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
448 SmallVector<CandidateInfo, 32> Candidates;
449 SmallSet<int, 32> StoredFIs;
451 // Walk the entire region, count number of defs for each register, and
452 // collect potential LICM candidates.
453 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
454 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
455 MachineBasicBlock *BB = Blocks[i];
456 // Conservatively treat live-in's as an external def.
457 // FIXME: That means a reload that're reused in successor block(s) will not
459 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
460 E = BB->livein_end(); I != E; ++I) {
463 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
467 for (MachineBasicBlock::iterator
468 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
469 MachineInstr *MI = &*MII;
470 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
474 // Now evaluate whether the potential candidates qualify.
475 // 1. Check if the candidate defined register is defined by another
476 // instruction in the loop.
477 // 2. If the candidate is a load from stack slot (always true for now),
478 // check if the slot is stored anywhere in the loop.
479 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
480 if (Candidates[i].FI != INT_MIN &&
481 StoredFIs.count(Candidates[i].FI))
484 if (PhysRegDefs[Candidates[i].Def] == 1) {
486 MachineInstr *MI = Candidates[i].MI;
487 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
488 const MachineOperand &MO = MI->getOperand(j);
489 if (!MO.isReg() || MO.isDef() || !MO.getReg())
491 if (PhysRegDefs[MO.getReg()]) {
492 // If it's using a non-loop-invariant register, then it's obviously
493 // not safe to hoist.
499 HoistPostRA(MI, Candidates[i].Def);
503 delete[] PhysRegDefs;
506 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
507 /// loop, and make sure it is not killed by any instructions in the loop.
508 void MachineLICM::AddToLiveIns(unsigned Reg) {
509 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
510 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
511 MachineBasicBlock *BB = Blocks[i];
512 if (!BB->isLiveIn(Reg))
514 for (MachineBasicBlock::iterator
515 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
516 MachineInstr *MI = &*MII;
517 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
518 MachineOperand &MO = MI->getOperand(i);
519 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
520 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
527 /// HoistPostRA - When an instruction is found to only use loop invariant
528 /// operands that is safe to hoist, this instruction is called to do the
530 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
531 MachineBasicBlock *Preheader = getCurPreheader();
532 if (!Preheader) return;
534 // Now move the instructions to the predecessor, inserting it before any
535 // terminator instructions.
537 dbgs() << "Hoisting " << *MI;
538 if (Preheader->getBasicBlock())
539 dbgs() << " to MachineBasicBlock "
540 << Preheader->getName();
541 if (MI->getParent()->getBasicBlock())
542 dbgs() << " from MachineBasicBlock "
543 << MI->getParent()->getName();
547 // Splice the instruction to the preheader.
548 MachineBasicBlock *MBB = MI->getParent();
549 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
551 // Add register to livein list to all the BBs in the current loop since a
552 // loop invariant must be kept live throughout the whole loop. This is
553 // important to ensure later passes do not scavenge the def register.
560 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
561 /// dominated by the specified block, and that are in the current loop) in depth
562 /// first order w.r.t the DominatorTree. This allows us to visit definitions
563 /// before uses, allowing us to hoist a loop body in one pass without iteration.
565 void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
566 assert(N != 0 && "Null dominator tree node?");
567 MachineBasicBlock *BB = N->getBlock();
569 // If this subregion is not in the top level loop at all, exit.
570 if (!CurLoop->contains(BB)) return;
572 MachineBasicBlock *Preheader = getCurPreheader();
577 // Compute registers which are livein into the loop headers.
580 InitRegPressure(Preheader);
583 // Remember livein register pressure.
584 BackTrace.push_back(RegPressure);
586 for (MachineBasicBlock::iterator
587 MII = BB->begin(), E = BB->end(); MII != E; ) {
588 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
589 MachineInstr *MI = &*MII;
590 if (!Hoist(MI, Preheader))
591 UpdateRegPressure(MI);
595 // Don't hoist things out of a large switch statement. This often causes
596 // code to be hoisted that wasn't going to be executed, and increases
597 // register pressure in a situation where it's likely to matter.
598 if (BB->succ_size() < 25) {
599 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
600 for (unsigned I = 0, E = Children.size(); I != E; ++I)
601 HoistRegion(Children[I]);
604 BackTrace.pop_back();
607 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
608 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
611 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
612 /// index, return the ID and cost of its representative register class.
614 MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
615 unsigned Reg, unsigned OpIdx,
616 unsigned &RCId, unsigned &RCCost) const {
617 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
618 EVT VT = *RC->vt_begin();
619 if (VT == MVT::untyped) {
623 RCId = TLI->getRepRegClassFor(VT)->getID();
624 RCCost = TLI->getRepRegClassCostFor(VT);
628 /// InitRegPressure - Find all virtual register references that are liveout of
629 /// the preheader to initialize the starting "register pressure". Note this
630 /// does not count live through (livein but not used) registers.
631 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
632 std::fill(RegPressure.begin(), RegPressure.end(), 0);
634 // If the preheader has only a single predecessor and it ends with a
635 // fallthrough or an unconditional branch, then scan its predecessor for live
636 // defs as well. This happens whenever the preheader is created by splitting
637 // the critical edge from the loop predecessor to the loop header.
638 if (BB->pred_size() == 1) {
639 MachineBasicBlock *TBB = 0, *FBB = 0;
640 SmallVector<MachineOperand, 4> Cond;
641 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
642 InitRegPressure(*BB->pred_begin());
645 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
647 MachineInstr *MI = &*MII;
648 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
649 const MachineOperand &MO = MI->getOperand(i);
650 if (!MO.isReg() || MO.isImplicit())
652 unsigned Reg = MO.getReg();
653 if (!TargetRegisterInfo::isVirtualRegister(Reg))
656 bool isNew = RegSeen.insert(Reg);
657 unsigned RCId, RCCost;
658 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
660 RegPressure[RCId] += RCCost;
662 bool isKill = isOperandKill(MO, MRI);
663 if (isNew && !isKill)
664 // Haven't seen this, it must be a livein.
665 RegPressure[RCId] += RCCost;
666 else if (!isNew && isKill)
667 RegPressure[RCId] -= RCCost;
673 /// UpdateRegPressure - Update estimate of register pressure after the
674 /// specified instruction.
675 void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
676 if (MI->isImplicitDef())
679 SmallVector<unsigned, 4> Defs;
680 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
681 const MachineOperand &MO = MI->getOperand(i);
682 if (!MO.isReg() || MO.isImplicit())
684 unsigned Reg = MO.getReg();
685 if (!TargetRegisterInfo::isVirtualRegister(Reg))
688 bool isNew = RegSeen.insert(Reg);
691 else if (!isNew && isOperandKill(MO, MRI)) {
692 unsigned RCId, RCCost;
693 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
694 if (RCCost > RegPressure[RCId])
695 RegPressure[RCId] = 0;
697 RegPressure[RCId] -= RCCost;
702 while (!Defs.empty()) {
703 unsigned Reg = Defs.pop_back_val();
704 unsigned RCId, RCCost;
705 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
706 RegPressure[RCId] += RCCost;
711 /// IsLICMCandidate - Returns true if the instruction may be a suitable
712 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
713 /// not safe to hoist it.
714 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
715 // Check if it's safe to move the instruction.
716 bool DontMoveAcrossStore = true;
717 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
723 /// IsLoopInvariantInst - Returns true if the instruction is loop
724 /// invariant. I.e., all virtual register operands are defined outside of the
725 /// loop, physical registers aren't accessed explicitly, and there are no side
726 /// effects that aren't captured by the operands or other flags.
728 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
729 if (!IsLICMCandidate(I))
732 // The instruction is loop invariant if all of its operands are.
733 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
734 const MachineOperand &MO = I.getOperand(i);
739 unsigned Reg = MO.getReg();
740 if (Reg == 0) continue;
742 // Don't hoist an instruction that uses or defines a physical register.
743 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
745 // If the physreg has no defs anywhere, it's just an ambient register
746 // and we can freely move its uses. Alternatively, if it's allocatable,
747 // it could get allocated to something with a def during allocation.
748 if (!MRI->def_empty(Reg))
750 if (AllocatableSet.test(Reg))
752 // Check for a def among the register's aliases too.
753 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
754 unsigned AliasReg = *Alias;
755 if (!MRI->def_empty(AliasReg))
757 if (AllocatableSet.test(AliasReg))
760 // Otherwise it's safe to move.
762 } else if (!MO.isDead()) {
763 // A def that isn't dead. We can't move it.
765 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
766 // If the reg is live into the loop, we can't hoist an instruction
767 // which would clobber it.
775 assert(MRI->getVRegDef(Reg) &&
776 "Machine instr not mapped for this vreg?!");
778 // If the loop contains the definition of an operand, then the instruction
779 // isn't loop invariant.
780 if (CurLoop->contains(MRI->getVRegDef(Reg)))
784 // If we got this far, the instruction is loop invariant!
789 /// HasAnyPHIUse - Return true if the specified register is used by any
791 bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
792 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
793 UE = MRI->use_end(); UI != UE; ++UI) {
794 MachineInstr *UseMI = &*UI;
797 // Look pass copies as well.
798 if (UseMI->isCopy()) {
799 unsigned Def = UseMI->getOperand(0).getReg();
800 if (TargetRegisterInfo::isVirtualRegister(Def) &&
808 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
809 /// and an use in the current loop, return true if the target considered
811 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
812 unsigned DefIdx, unsigned Reg) const {
813 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
816 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
817 E = MRI->use_nodbg_end(); I != E; ++I) {
818 MachineInstr *UseMI = &*I;
819 if (UseMI->isCopyLike())
821 if (!CurLoop->contains(UseMI->getParent()))
823 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
824 const MachineOperand &MO = UseMI->getOperand(i);
825 if (!MO.isReg() || !MO.isUse())
827 unsigned MOReg = MO.getReg();
831 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
835 // Only look at the first in loop use.
842 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
843 /// the operand latency between its def and a use is one or less.
844 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
845 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
847 if (!InstrItins || InstrItins->isEmpty())
850 bool isCheap = false;
851 unsigned NumDefs = MI.getDesc().getNumDefs();
852 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
853 MachineOperand &DefMO = MI.getOperand(i);
854 if (!DefMO.isReg() || !DefMO.isDef())
857 unsigned Reg = DefMO.getReg();
858 if (TargetRegisterInfo::isPhysicalRegister(Reg))
861 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
869 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
870 /// if hoisting an instruction of the given cost matrix can cause high
871 /// register pressure.
872 bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
873 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
878 unsigned RCId = CI->first;
879 for (unsigned i = BackTrace.size(); i != 0; --i) {
880 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
881 if (RP[RCId] + CI->second >= RegLimit[RCId])
889 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
890 /// current block and update their register pressures to reflect the effect
891 /// of hoisting MI from the current block to the preheader.
892 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
893 if (MI->isImplicitDef())
896 // First compute the 'cost' of the instruction, i.e. its contribution
897 // to register pressure.
898 DenseMap<unsigned, int> Cost;
899 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
900 const MachineOperand &MO = MI->getOperand(i);
901 if (!MO.isReg() || MO.isImplicit())
903 unsigned Reg = MO.getReg();
904 if (!TargetRegisterInfo::isVirtualRegister(Reg))
907 unsigned RCId, RCCost;
908 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
910 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
911 if (CI != Cost.end())
912 CI->second += RCCost;
914 Cost.insert(std::make_pair(RCId, RCCost));
915 } else if (isOperandKill(MO, MRI)) {
916 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
917 if (CI != Cost.end())
918 CI->second -= RCCost;
920 Cost.insert(std::make_pair(RCId, -RCCost));
924 // Update register pressure of blocks from loop header to current block.
925 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
926 SmallVector<unsigned, 8> &RP = BackTrace[i];
927 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
929 unsigned RCId = CI->first;
930 RP[RCId] += CI->second;
935 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
936 /// the given loop invariant.
937 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
938 if (MI.isImplicitDef())
941 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
942 // will increase register pressure. It's probably not worth it if the
943 // instruction is cheap.
944 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
945 // these tend to help performance in low register pressure situation. The
946 // trade off is it may cause spill in high pressure situation. It will end up
947 // adding a store in the loop preheader. But the reload is no more expensive.
948 // The side benefit is these loads are frequently CSE'ed.
949 if (IsCheapInstruction(MI)) {
950 if (!TII->isTriviallyReMaterializable(&MI, AA))
953 // Estimate register pressure to determine whether to LICM the instruction.
954 // In low register pressure situation, we can be more aggressive about
955 // hoisting. Also, favors hoisting long latency instructions even in
956 // moderately high pressure situation.
957 // FIXME: If there are long latency loop-invariant instructions inside the
958 // loop at this point, why didn't the optimizer's LICM hoist them?
959 DenseMap<unsigned, int> Cost;
960 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
961 const MachineOperand &MO = MI.getOperand(i);
962 if (!MO.isReg() || MO.isImplicit())
964 unsigned Reg = MO.getReg();
965 if (!TargetRegisterInfo::isVirtualRegister(Reg))
968 unsigned RCId, RCCost;
969 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
971 if (HasHighOperandLatency(MI, i, Reg)) {
976 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
977 if (CI != Cost.end())
978 CI->second += RCCost;
980 Cost.insert(std::make_pair(RCId, RCCost));
981 } else if (isOperandKill(MO, MRI)) {
982 // Is a virtual register use is a kill, hoisting it out of the loop
983 // may actually reduce register pressure or be register pressure
985 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
986 if (CI != Cost.end())
987 CI->second -= RCCost;
989 Cost.insert(std::make_pair(RCId, -RCCost));
993 // Visit BBs from header to current BB, if hoisting this doesn't cause
994 // high register pressure, then it's safe to proceed.
995 if (!CanCauseHighRegPressure(Cost)) {
1000 // High register pressure situation, only hoist if the instruction is going to
1002 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1003 !MI.isInvariantLoad(AA))
1007 // If result(s) of this instruction is used by PHIs outside of the loop, then
1008 // don't hoist it if the instruction because it will introduce an extra copy.
1009 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1010 const MachineOperand &MO = MI.getOperand(i);
1011 if (!MO.isReg() || !MO.isDef())
1013 if (HasAnyPHIUse(MO.getReg()))
1020 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1021 // Don't unfold simple loads.
1022 if (MI->getDesc().canFoldAsLoad())
1025 // If not, we may be able to unfold a load and hoist that.
1026 // First test whether the instruction is loading from an amenable
1028 if (!MI->isInvariantLoad(AA))
1031 // Next determine the register class for a temporary register.
1032 unsigned LoadRegIndex;
1034 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1035 /*UnfoldLoad=*/true,
1036 /*UnfoldStore=*/false,
1038 if (NewOpc == 0) return 0;
1039 const MCInstrDesc &MID = TII->get(NewOpc);
1040 if (MID.getNumDefs() != 1) return 0;
1041 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
1042 // Ok, we're unfolding. Create a temporary register and do the unfold.
1043 unsigned Reg = MRI->createVirtualRegister(RC);
1045 MachineFunction &MF = *MI->getParent()->getParent();
1046 SmallVector<MachineInstr *, 2> NewMIs;
1048 TII->unfoldMemoryOperand(MF, MI, Reg,
1049 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1053 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1055 assert(NewMIs.size() == 2 &&
1056 "Unfolded a load into multiple instructions!");
1057 MachineBasicBlock *MBB = MI->getParent();
1058 MBB->insert(MI, NewMIs[0]);
1059 MBB->insert(MI, NewMIs[1]);
1060 // If unfolding produced a load that wasn't loop-invariant or profitable to
1061 // hoist, discard the new instructions and bail.
1062 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1063 NewMIs[0]->eraseFromParent();
1064 NewMIs[1]->eraseFromParent();
1068 // Update register pressure for the unfolded instruction.
1069 UpdateRegPressure(NewMIs[1]);
1071 // Otherwise we successfully unfolded a load that we can hoist.
1072 MI->eraseFromParent();
1076 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1077 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1078 const MachineInstr *MI = &*I;
1079 unsigned Opcode = MI->getOpcode();
1080 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1081 CI = CSEMap.find(Opcode);
1082 if (CI != CSEMap.end())
1083 CI->second.push_back(MI);
1085 std::vector<const MachineInstr*> CSEMIs;
1086 CSEMIs.push_back(MI);
1087 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1093 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1094 std::vector<const MachineInstr*> &PrevMIs) {
1095 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1096 const MachineInstr *PrevMI = PrevMIs[i];
1097 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
1103 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1104 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1105 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1106 // the undef property onto uses.
1107 if (CI == CSEMap.end() || MI->isImplicitDef())
1110 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1111 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1113 // Replace virtual registers defined by MI by their counterparts defined
1115 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1116 const MachineOperand &MO = MI->getOperand(i);
1118 // Physical registers may not differ here.
1119 assert((!MO.isReg() || MO.getReg() == 0 ||
1120 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1121 MO.getReg() == Dup->getOperand(i).getReg()) &&
1122 "Instructions with different phys regs are not identical!");
1124 if (MO.isReg() && MO.isDef() &&
1125 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
1126 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1127 MRI->clearKillFlags(Dup->getOperand(i).getReg());
1130 MI->eraseFromParent();
1137 /// IsGuaranteedToExecute - check to make sure that the instruction dominates
1138 /// all of the exit blocks. If it doesn't, then there is a path out of the loop
1139 /// which does not execute this instruction, so we can't hoist it.
1140 bool MachineLICM::IsGuaranteedToExecute(MachineInstr *MI) {
1141 // If the instruction is in the header block for the loop (which is very
1142 // common), it is always guaranteed to dominate the exit blocks. Since this
1143 // is a common case, and can save some work, check it now.
1144 if (MI->getParent() == CurLoop->getHeader())
1147 // Get the exit blocks for the current loop.
1148 SmallVector<MachineBasicBlock*, 8> ExitingBlocks;
1149 CurLoop->getExitingBlocks(ExitingBlocks);
1151 // Verify that the block dominates each of the exit blocks of the loop.
1152 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i)
1153 if (!DT->dominates(MI->getParent(), ExitingBlocks[i]))
1159 /// Hoist - When an instruction is found to use only loop invariant operands
1160 /// that are safe to hoist, this instruction is called to do the dirty work.
1162 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1163 // First check whether we should hoist this instruction.
1164 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1165 // If not, try unfolding a hoistable load.
1166 MI = ExtractHoistableLoad(MI);
1167 if (!MI) return false;
1169 if (!IsGuaranteedToExecute(MI))
1172 // Now move the instructions to the predecessor, inserting it before any
1173 // terminator instructions.
1175 dbgs() << "Hoisting " << *MI;
1176 if (Preheader->getBasicBlock())
1177 dbgs() << " to MachineBasicBlock "
1178 << Preheader->getName();
1179 if (MI->getParent()->getBasicBlock())
1180 dbgs() << " from MachineBasicBlock "
1181 << MI->getParent()->getName();
1185 // If this is the first instruction being hoisted to the preheader,
1186 // initialize the CSE map with potential common expressions.
1188 InitCSEMap(Preheader);
1189 FirstInLoop = false;
1192 // Look for opportunity to CSE the hoisted instruction.
1193 unsigned Opcode = MI->getOpcode();
1194 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1195 CI = CSEMap.find(Opcode);
1196 if (!EliminateCSE(MI, CI)) {
1197 // Otherwise, splice the instruction to the preheader.
1198 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1200 // Update register pressure for BBs from header to this block.
1201 UpdateBackTraceRegPressure(MI);
1203 // Clear the kill flags of any register this instruction defines,
1204 // since they may need to be live throughout the entire loop
1205 // rather than just live for part of it.
1206 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1207 MachineOperand &MO = MI->getOperand(i);
1208 if (MO.isReg() && MO.isDef() && !MO.isDead())
1209 MRI->clearKillFlags(MO.getReg());
1212 // Add to the CSE map.
1213 if (CI != CSEMap.end())
1214 CI->second.push_back(MI);
1216 std::vector<const MachineInstr*> CSEMIs;
1217 CSEMIs.push_back(MI);
1218 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1228 MachineBasicBlock *MachineLICM::getCurPreheader() {
1229 // Determine the block to which to hoist instructions. If we can't find a
1230 // suitable loop predecessor, we can't do any hoisting.
1232 // If we've tried to get a preheader and failed, don't try again.
1233 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1236 if (!CurPreheader) {
1237 CurPreheader = CurLoop->getLoopPreheader();
1238 if (!CurPreheader) {
1239 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1241 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1245 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1246 if (!CurPreheader) {
1247 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1252 return CurPreheader;