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/TargetLowering.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetInstrItineraries.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/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
47 "Number of machine instructions hoisted out of loops");
49 "Number of instructions hoisted in low reg pressure situation");
50 STATISTIC(NumHighLatency,
51 "Number of high latency instructions hoisted");
53 "Number of hoisted machine instructions CSEed");
54 STATISTIC(NumPostRAHoisted,
55 "Number of machine instructions hoisted out of loops post regalloc");
58 class MachineLICM : public MachineFunctionPass {
61 const TargetMachine *TM;
62 const TargetInstrInfo *TII;
63 const TargetLowering *TLI;
64 const TargetRegisterInfo *TRI;
65 const MachineFrameInfo *MFI;
66 MachineRegisterInfo *MRI;
67 const InstrItineraryData *InstrItins;
69 // Various analyses that we use...
70 AliasAnalysis *AA; // Alias analysis info.
71 MachineLoopInfo *MLI; // Current MachineLoopInfo
72 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
74 // State that is updated as we process loops
75 bool Changed; // True if a loop is changed.
76 bool FirstInLoop; // True if it's the first LICM in the loop.
77 MachineLoop *CurLoop; // The current loop we are working on.
78 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
80 BitVector AllocatableSet;
82 // Track 'estimated' register pressure.
83 SmallSet<unsigned, 32> RegSeen;
84 SmallVector<unsigned, 8> RegPressure;
86 // Register pressure "limit" per register class. If the pressure
87 // is higher than the limit, then it's considered high.
88 SmallVector<unsigned, 8> RegLimit;
90 // Register pressure on path leading from loop preheader to current BB.
91 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
93 // For each opcode, keep a list of potential CSE instructions.
94 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
97 static char ID; // Pass identification, replacement for typeid
99 MachineFunctionPass(ID), PreRegAlloc(true) {
100 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
103 explicit MachineLICM(bool PreRA) :
104 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
105 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
108 virtual bool runOnMachineFunction(MachineFunction &MF);
110 const char *getPassName() const { return "Machine Instruction LICM"; }
112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.setPreservesCFG();
114 AU.addRequired<MachineLoopInfo>();
115 AU.addRequired<MachineDominatorTree>();
116 AU.addRequired<AliasAnalysis>();
117 AU.addPreserved<MachineLoopInfo>();
118 AU.addPreserved<MachineDominatorTree>();
119 MachineFunctionPass::getAnalysisUsage(AU);
122 virtual void releaseMemory() {
127 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
128 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
134 /// CandidateInfo - Keep track of information about hoisting candidates.
135 struct CandidateInfo {
139 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
140 : MI(mi), Def(def), FI(fi) {}
143 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
144 /// invariants out to the preheader.
145 void HoistRegionPostRA();
147 /// HoistPostRA - When an instruction is found to only use loop invariant
148 /// operands that is safe to hoist, this instruction is called to do the
150 void HoistPostRA(MachineInstr *MI, unsigned Def);
152 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
153 /// gather register def and frame object update information.
154 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
155 SmallSet<int, 32> &StoredFIs,
156 SmallVector<CandidateInfo, 32> &Candidates);
158 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
160 void AddToLiveIns(unsigned Reg);
162 /// IsLICMCandidate - Returns true if the instruction may be a suitable
163 /// candidate for LICM. e.g. If the instruction is a call, then it's
164 /// obviously not safe to hoist it.
165 bool IsLICMCandidate(MachineInstr &I);
167 /// IsLoopInvariantInst - Returns true if the instruction is loop
168 /// invariant. I.e., all virtual register operands are defined outside of
169 /// the loop, physical registers aren't accessed (explicitly or implicitly),
170 /// and the instruction is hoistable.
172 bool IsLoopInvariantInst(MachineInstr &I);
174 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
175 /// and an use in the current loop, return true if the target considered
177 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
179 /// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
180 /// if hoisting an instruction of the given cost matrix can cause high
181 /// register pressure.
182 bool IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost);
184 /// IsProfitableToHoist - Return true if it is potentially profitable to
185 /// hoist the given loop invariant.
186 bool IsProfitableToHoist(MachineInstr &MI);
188 /// HoistRegion - Walk the specified region of the CFG (defined by all
189 /// blocks dominated by the specified block, and that are in the current
190 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
191 /// visit definitions before uses, allowing us to hoist a loop body in one
192 /// pass without iteration.
194 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
196 /// InitRegPressure - Find all virtual register references that are liveout
197 /// of the preheader to initialize the starting "register pressure". Note
198 /// this does not count live through (livein but not used) registers.
199 void InitRegPressure(MachineBasicBlock *BB);
201 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
202 /// register pressure before and after executing a specifi instruction.
203 void UpdateRegPressureBefore(const MachineInstr *MI,
204 SmallVector<unsigned, 4> &Defs);
205 void UpdateRegPressureAfter(SmallVector<unsigned, 4> &Defs);
207 /// isLoadFromConstantMemory - Return true if the given instruction is a
208 /// load from constant memory.
209 bool isLoadFromConstantMemory(MachineInstr *MI);
211 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
212 /// the load itself could be hoisted. Return the unfolded and hoistable
213 /// load, or null if the load couldn't be unfolded or if it wouldn't
215 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
217 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
218 /// duplicate of MI. Return this instruction if it's found.
219 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
220 std::vector<const MachineInstr*> &PrevMIs);
222 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
223 /// the preheader that compute the same value. If it's found, do a RAU on
224 /// with the definition of the existing instruction rather than hoisting
225 /// the instruction to the preheader.
226 bool EliminateCSE(MachineInstr *MI,
227 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
229 /// Hoist - When an instruction is found to only use loop invariant operands
230 /// that is safe to hoist, this instruction is called to do the dirty work.
232 void Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
234 /// InitCSEMap - Initialize the CSE map with instructions that are in the
235 /// current loop preheader that may become duplicates of instructions that
236 /// are hoisted out of the loop.
237 void InitCSEMap(MachineBasicBlock *BB);
239 /// getCurPreheader - Get the preheader for the current loop, splitting
240 /// a critical edge if needed.
241 MachineBasicBlock *getCurPreheader();
243 } // end anonymous namespace
245 char MachineLICM::ID = 0;
246 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
247 "Machine Loop Invariant Code Motion", false, false)
248 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
249 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
250 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
251 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
252 "Machine Loop Invariant Code Motion", false, false)
254 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
255 return new MachineLICM(PreRegAlloc);
258 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
259 /// loop that has a unique predecessor.
260 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
261 // Check whether this loop even has a unique predecessor.
262 if (!CurLoop->getLoopPredecessor())
264 // Ok, now check to see if any of its outer loops do.
265 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
266 if (L->getLoopPredecessor())
268 // None of them did, so this is the outermost with a unique predecessor.
272 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
274 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
276 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
277 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
279 Changed = FirstInLoop = false;
280 TM = &MF.getTarget();
281 TII = TM->getInstrInfo();
282 TLI = TM->getTargetLowering();
283 TRI = TM->getRegisterInfo();
284 MFI = MF.getFrameInfo();
285 MRI = &MF.getRegInfo();
286 InstrItins = TM->getInstrItineraryData();
287 AllocatableSet = TRI->getAllocatableSet(MF);
290 // Estimate register pressure during pre-regalloc pass.
291 unsigned NumRC = TRI->getNumRegClasses();
292 RegPressure.resize(NumRC);
293 std::fill(RegPressure.begin(), RegPressure.end(), 0);
294 RegLimit.resize(NumRC);
295 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
296 E = TRI->regclass_end(); I != E; ++I)
297 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
300 // Get our Loop information...
301 MLI = &getAnalysis<MachineLoopInfo>();
302 DT = &getAnalysis<MachineDominatorTree>();
303 AA = &getAnalysis<AliasAnalysis>();
305 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
306 while (!Worklist.empty()) {
307 CurLoop = Worklist.pop_back_val();
310 // If this is done before regalloc, only visit outer-most preheader-sporting
312 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
313 Worklist.append(CurLoop->begin(), CurLoop->end());
320 // CSEMap is initialized for loop header when the first instruction is
322 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
324 HoistRegion(N, true);
332 /// InstructionStoresToFI - Return true if instruction stores to the
334 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
335 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
336 oe = MI->memoperands_end(); o != oe; ++o) {
337 if (!(*o)->isStore() || !(*o)->getValue())
339 if (const FixedStackPseudoSourceValue *Value =
340 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
341 if (Value->getFrameIndex() == FI)
348 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
349 /// gather register def and frame object update information.
350 void MachineLICM::ProcessMI(MachineInstr *MI,
351 unsigned *PhysRegDefs,
352 SmallSet<int, 32> &StoredFIs,
353 SmallVector<CandidateInfo, 32> &Candidates) {
354 bool RuledOut = false;
355 bool HasNonInvariantUse = false;
357 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
358 const MachineOperand &MO = MI->getOperand(i);
360 // Remember if the instruction stores to the frame index.
361 int FI = MO.getIndex();
362 if (!StoredFIs.count(FI) &&
363 MFI->isSpillSlotObjectIndex(FI) &&
364 InstructionStoresToFI(MI, FI))
365 StoredFIs.insert(FI);
366 HasNonInvariantUse = true;
372 unsigned Reg = MO.getReg();
375 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
376 "Not expecting virtual register!");
379 if (Reg && PhysRegDefs[Reg])
380 // If it's using a non-loop-invariant register, then it's obviously not
382 HasNonInvariantUse = true;
386 if (MO.isImplicit()) {
388 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
391 // Non-dead implicit def? This cannot be hoisted.
393 // No need to check if a dead implicit def is also defined by
394 // another instruction.
398 // FIXME: For now, avoid instructions with multiple defs, unless
399 // it's a dead implicit def.
405 // If we have already seen another instruction that defines the same
406 // register, then this is not safe.
407 if (++PhysRegDefs[Reg] > 1)
408 // MI defined register is seen defined by another instruction in
409 // the loop, it cannot be a LICM candidate.
411 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
412 if (++PhysRegDefs[*AS] > 1)
416 // Only consider reloads for now and remats which do not have register
417 // operands. FIXME: Consider unfold load folding instructions.
418 if (Def && !RuledOut) {
420 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
421 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
422 Candidates.push_back(CandidateInfo(MI, Def, FI));
426 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
427 /// invariants out to the preheader.
428 void MachineLICM::HoistRegionPostRA() {
429 unsigned NumRegs = TRI->getNumRegs();
430 unsigned *PhysRegDefs = new unsigned[NumRegs];
431 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
433 SmallVector<CandidateInfo, 32> Candidates;
434 SmallSet<int, 32> StoredFIs;
436 // Walk the entire region, count number of defs for each register, and
437 // collect potential LICM candidates.
438 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
439 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
440 MachineBasicBlock *BB = Blocks[i];
441 // Conservatively treat live-in's as an external def.
442 // FIXME: That means a reload that're reused in successor block(s) will not
444 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
445 E = BB->livein_end(); I != E; ++I) {
448 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
452 for (MachineBasicBlock::iterator
453 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
454 MachineInstr *MI = &*MII;
455 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
459 // Now evaluate whether the potential candidates qualify.
460 // 1. Check if the candidate defined register is defined by another
461 // instruction in the loop.
462 // 2. If the candidate is a load from stack slot (always true for now),
463 // check if the slot is stored anywhere in the loop.
464 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
465 if (Candidates[i].FI != INT_MIN &&
466 StoredFIs.count(Candidates[i].FI))
469 if (PhysRegDefs[Candidates[i].Def] == 1) {
471 MachineInstr *MI = Candidates[i].MI;
472 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
473 const MachineOperand &MO = MI->getOperand(j);
474 if (!MO.isReg() || MO.isDef() || !MO.getReg())
476 if (PhysRegDefs[MO.getReg()]) {
477 // If it's using a non-loop-invariant register, then it's obviously
478 // not safe to hoist.
484 HoistPostRA(MI, Candidates[i].Def);
488 delete[] PhysRegDefs;
491 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
492 /// loop, and make sure it is not killed by any instructions in the loop.
493 void MachineLICM::AddToLiveIns(unsigned Reg) {
494 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
495 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
496 MachineBasicBlock *BB = Blocks[i];
497 if (!BB->isLiveIn(Reg))
499 for (MachineBasicBlock::iterator
500 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
501 MachineInstr *MI = &*MII;
502 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = MI->getOperand(i);
504 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
505 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
512 /// HoistPostRA - When an instruction is found to only use loop invariant
513 /// operands that is safe to hoist, this instruction is called to do the
515 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
516 MachineBasicBlock *Preheader = getCurPreheader();
517 if (!Preheader) return;
519 // Now move the instructions to the predecessor, inserting it before any
520 // terminator instructions.
522 dbgs() << "Hoisting " << *MI;
523 if (Preheader->getBasicBlock())
524 dbgs() << " to MachineBasicBlock "
525 << Preheader->getName();
526 if (MI->getParent()->getBasicBlock())
527 dbgs() << " from MachineBasicBlock "
528 << MI->getParent()->getName();
532 // Splice the instruction to the preheader.
533 MachineBasicBlock *MBB = MI->getParent();
534 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
536 // Add register to livein list to all the BBs in the current loop since a
537 // loop invariant must be kept live throughout the whole loop. This is
538 // important to ensure later passes do not scavenge the def register.
545 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
546 /// dominated by the specified block, and that are in the current loop) in depth
547 /// first order w.r.t the DominatorTree. This allows us to visit definitions
548 /// before uses, allowing us to hoist a loop body in one pass without iteration.
550 void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
551 assert(N != 0 && "Null dominator tree node?");
552 MachineBasicBlock *BB = N->getBlock();
554 // If this subregion is not in the top level loop at all, exit.
555 if (!CurLoop->contains(BB)) return;
557 MachineBasicBlock *Preheader = getCurPreheader();
562 // Compute registers which are liveout of preheader.
565 InitRegPressure(Preheader);
568 // Remember livein register pressure.
569 BackTrace.push_back(RegPressure);
571 SmallVector<unsigned, 4> Defs;
572 for (MachineBasicBlock::iterator
573 MII = BB->begin(), E = BB->end(); MII != E; ) {
574 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
575 MachineInstr *MI = &*MII;
577 assert(Defs.empty());
578 UpdateRegPressureBefore(MI, Defs);
579 Hoist(MI, Preheader);
580 UpdateRegPressureAfter(Defs);
585 // Don't hoist things out of a large switch statement. This often causes
586 // code to be hoisted that wasn't going to be executed, and increases
587 // register pressure in a situation where it's likely to matter.
588 if (BB->succ_size() < 25) {
589 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
590 for (unsigned I = 0, E = Children.size(); I != E; ++I)
591 HoistRegion(Children[I]);
594 BackTrace.pop_back();
597 /// InitRegPressure - Find all virtual register references that are liveout of
598 /// the preheader to initialize the starting "register pressure". Note this
599 /// does not count live through (livein but not used) registers.
600 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
601 std::fill(RegPressure.begin(), RegPressure.end(), 0);
603 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
605 MachineInstr *MI = &*MII;
606 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
607 const MachineOperand &MO = MI->getOperand(i);
608 if (!MO.isReg() || MO.isImplicit())
610 unsigned Reg = MO.getReg();
611 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
614 bool isNew = RegSeen.insert(Reg);
615 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
616 EVT VT = *RC->vt_begin();
617 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
619 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
621 if (isNew && !MO.isKill())
622 // Haven't seen this, it must be a livein.
623 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
624 else if (!isNew && MO.isKill())
625 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
631 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
632 /// register pressure before and after executing a specifi instruction.
633 void MachineLICM::UpdateRegPressureBefore(const MachineInstr *MI,
634 SmallVector<unsigned, 4> &Defs) {
635 bool NoImpact = MI->isImplicitDef() || MI->isPHI();
637 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
638 const MachineOperand &MO = MI->getOperand(i);
639 if (!MO.isReg() || MO.isImplicit())
641 unsigned Reg = MO.getReg();
642 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
645 bool isNew = RegSeen.insert(Reg);
652 if (!isNew && MO.isKill()) {
653 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
654 EVT VT = *RC->vt_begin();
655 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
656 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
658 assert(RCCost <= RegPressure[RCId]);
659 RegPressure[RCId] -= RCCost;
665 void MachineLICM::UpdateRegPressureAfter(SmallVector<unsigned, 4> &Defs) {
666 while (!Defs.empty()) {
667 unsigned Reg = Defs.pop_back_val();
669 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
670 EVT VT = *RC->vt_begin();
671 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
672 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
673 RegPressure[RCId] += RCCost;
677 /// IsLICMCandidate - Returns true if the instruction may be a suitable
678 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
679 /// not safe to hoist it.
680 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
681 // Check if it's safe to move the instruction.
682 bool DontMoveAcrossStore = true;
683 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
689 /// IsLoopInvariantInst - Returns true if the instruction is loop
690 /// invariant. I.e., all virtual register operands are defined outside of the
691 /// loop, physical registers aren't accessed explicitly, and there are no side
692 /// effects that aren't captured by the operands or other flags.
694 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
695 if (!IsLICMCandidate(I))
698 // The instruction is loop invariant if all of its operands are.
699 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
700 const MachineOperand &MO = I.getOperand(i);
705 unsigned Reg = MO.getReg();
706 if (Reg == 0) continue;
708 // Don't hoist an instruction that uses or defines a physical register.
709 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
711 // If the physreg has no defs anywhere, it's just an ambient register
712 // and we can freely move its uses. Alternatively, if it's allocatable,
713 // it could get allocated to something with a def during allocation.
714 if (!MRI->def_empty(Reg))
716 if (AllocatableSet.test(Reg))
718 // Check for a def among the register's aliases too.
719 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
720 unsigned AliasReg = *Alias;
721 if (!MRI->def_empty(AliasReg))
723 if (AllocatableSet.test(AliasReg))
726 // Otherwise it's safe to move.
728 } else if (!MO.isDead()) {
729 // A def that isn't dead. We can't move it.
731 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
732 // If the reg is live into the loop, we can't hoist an instruction
733 // which would clobber it.
741 assert(MRI->getVRegDef(Reg) &&
742 "Machine instr not mapped for this vreg?!");
744 // If the loop contains the definition of an operand, then the instruction
745 // isn't loop invariant.
746 if (CurLoop->contains(MRI->getVRegDef(Reg)))
750 // If we got this far, the instruction is loop invariant!
755 /// HasPHIUses - Return true if the specified register has any PHI use.
756 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
757 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
758 UE = MRI->use_end(); UI != UE; ++UI) {
759 MachineInstr *UseMI = &*UI;
766 /// isLoadFromConstantMemory - Return true if the given instruction is a
767 /// load from constant memory. Machine LICM will hoist these even if they are
768 /// not re-materializable.
769 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
770 if (!MI->getDesc().mayLoad()) return false;
771 if (!MI->hasOneMemOperand()) return false;
772 MachineMemOperand *MMO = *MI->memoperands_begin();
773 if (MMO->isVolatile()) return false;
774 if (!MMO->getValue()) return false;
775 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
777 MachineFunction &MF = *MI->getParent()->getParent();
778 return PSV->isConstant(MF.getFrameInfo());
780 return AA->pointsToConstantMemory(AliasAnalysis::Location(MMO->getValue(),
782 MMO->getTBAAInfo()));
786 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
787 /// and an use in the current loop, return true if the target considered
789 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
790 unsigned DefIdx, unsigned Reg) {
791 if (MRI->use_nodbg_empty(Reg))
794 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
795 E = MRI->use_nodbg_end(); I != E; ++I) {
796 MachineInstr *UseMI = &*I;
797 if (!CurLoop->contains(UseMI->getParent()))
799 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
800 const MachineOperand &MO = UseMI->getOperand(i);
801 if (!MO.isReg() || !MO.isUse())
803 unsigned MOReg = MO.getReg();
807 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
811 // Only look at the first in loop use.
818 /// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
819 /// if hoisting an instruction of the given cost matrix can cause high
820 /// register pressure.
821 bool MachineLICM::IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost) {
822 for (unsigned i = BackTrace.size(); i != 0; --i) {
823 bool AnyIncrease = false;
824 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
825 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
830 unsigned RCId = CI->first;
831 if (RP[RCId] + CI->second >= RegLimit[RCId])
836 // Hoisting the instruction doesn't increase register pressure.
843 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
844 /// the given loop invariant.
845 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
846 if (MI.isImplicitDef())
849 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
850 // will increase register pressure. It's probably not worth it if the
851 // instruction is cheap.
852 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
853 // these tend to help performance in low register pressure situation. The
854 // trade off is it may cause spill in high pressure situation. It will end up
855 // adding a store in the loop preheader. But the reload is no more expensive.
856 // The side benefit is these loads are frequently CSE'ed.
857 if (MI.getDesc().isAsCheapAsAMove()) {
858 if (!TII->isTriviallyReMaterializable(&MI, AA))
861 // Estimate register pressure to determine whether to LICM the instruction.
862 // In low register pressure situation, we can be more aggressive about
863 // hoisting. Also, favors hoisting long latency instructions even in
864 // moderately high pressure situation.
865 DenseMap<unsigned, int> Cost;
866 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
867 const MachineOperand &MO = MI.getOperand(i);
868 if (!MO.isReg() || MO.isImplicit())
870 unsigned Reg = MO.getReg();
871 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
874 if (HasHighOperandLatency(MI, i, Reg)) {
879 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
880 EVT VT = *RC->vt_begin();
881 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
882 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
883 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
884 // If the instruction is not register pressure neutrail (or better),
885 // check if hoisting it will cause high register pressure in BB's
886 // leading up to this point.
887 if (CI != Cost.end())
888 CI->second += RCCost;
890 Cost.insert(std::make_pair(RCId, RCCost));
891 } else if (MO.isKill()) {
892 // Is a virtual register use is a kill, hoisting it out of the loop
893 // may actually reduce register pressure or be register pressure
895 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
896 EVT VT = *RC->vt_begin();
897 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
898 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
899 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
900 if (CI != Cost.end())
901 CI->second -= RCCost;
903 Cost.insert(std::make_pair(RCId, -RCCost));
907 // Visit BBs from preheader to current BB, if hoisting this doesn't cause
908 // high register pressure, then it's safe to proceed.
909 if (!IncreaseHighRegPressure(Cost)) {
914 // High register pressure situation, only hoist if the instruction is going to
916 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
917 !isLoadFromConstantMemory(&MI))
921 // If result(s) of this instruction is used by PHIs, then don't hoist it.
922 // The presence of joins makes it difficult for current register allocator
923 // implementation to perform remat.
924 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
925 const MachineOperand &MO = MI.getOperand(i);
926 if (!MO.isReg() || !MO.isDef())
928 if (HasPHIUses(MO.getReg(), MRI))
935 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
936 // Don't unfold simple loads.
937 if (MI->getDesc().canFoldAsLoad())
940 // If not, we may be able to unfold a load and hoist that.
941 // First test whether the instruction is loading from an amenable
943 if (!isLoadFromConstantMemory(MI))
946 // Next determine the register class for a temporary register.
947 unsigned LoadRegIndex;
949 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
951 /*UnfoldStore=*/false,
953 if (NewOpc == 0) return 0;
954 const TargetInstrDesc &TID = TII->get(NewOpc);
955 if (TID.getNumDefs() != 1) return 0;
956 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
957 // Ok, we're unfolding. Create a temporary register and do the unfold.
958 unsigned Reg = MRI->createVirtualRegister(RC);
960 MachineFunction &MF = *MI->getParent()->getParent();
961 SmallVector<MachineInstr *, 2> NewMIs;
963 TII->unfoldMemoryOperand(MF, MI, Reg,
964 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
968 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
970 assert(NewMIs.size() == 2 &&
971 "Unfolded a load into multiple instructions!");
972 MachineBasicBlock *MBB = MI->getParent();
973 MBB->insert(MI, NewMIs[0]);
974 MBB->insert(MI, NewMIs[1]);
975 // If unfolding produced a load that wasn't loop-invariant or profitable to
976 // hoist, discard the new instructions and bail.
977 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
978 NewMIs[0]->eraseFromParent();
979 NewMIs[1]->eraseFromParent();
982 // Otherwise we successfully unfolded a load that we can hoist.
983 MI->eraseFromParent();
987 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
988 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
989 const MachineInstr *MI = &*I;
990 // FIXME: For now, only hoist re-materilizable instructions. LICM will
991 // increase register pressure. We want to make sure it doesn't increase
993 if (TII->isTriviallyReMaterializable(MI, AA)) {
994 unsigned Opcode = MI->getOpcode();
995 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
996 CI = CSEMap.find(Opcode);
997 if (CI != CSEMap.end())
998 CI->second.push_back(MI);
1000 std::vector<const MachineInstr*> CSEMIs;
1001 CSEMIs.push_back(MI);
1002 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1009 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1010 std::vector<const MachineInstr*> &PrevMIs) {
1011 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1012 const MachineInstr *PrevMI = PrevMIs[i];
1013 if (TII->produceSameValue(MI, PrevMI))
1019 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1020 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1021 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1022 // the undef property onto uses.
1023 if (CI == CSEMap.end() || MI->isImplicitDef())
1026 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1027 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1029 // Replace virtual registers defined by MI by their counterparts defined
1031 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1032 const MachineOperand &MO = MI->getOperand(i);
1034 // Physical registers may not differ here.
1035 assert((!MO.isReg() || MO.getReg() == 0 ||
1036 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1037 MO.getReg() == Dup->getOperand(i).getReg()) &&
1038 "Instructions with different phys regs are not identical!");
1040 if (MO.isReg() && MO.isDef() &&
1041 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
1042 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1043 MRI->clearKillFlags(Dup->getOperand(i).getReg());
1046 MI->eraseFromParent();
1053 /// Hoist - When an instruction is found to use only loop invariant operands
1054 /// that are safe to hoist, this instruction is called to do the dirty work.
1056 void MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1057 // First check whether we should hoist this instruction.
1058 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1059 // If not, try unfolding a hoistable load.
1060 MI = ExtractHoistableLoad(MI);
1064 // Now move the instructions to the predecessor, inserting it before any
1065 // terminator instructions.
1067 dbgs() << "Hoisting " << *MI;
1068 if (Preheader->getBasicBlock())
1069 dbgs() << " to MachineBasicBlock "
1070 << Preheader->getName();
1071 if (MI->getParent()->getBasicBlock())
1072 dbgs() << " from MachineBasicBlock "
1073 << MI->getParent()->getName();
1077 // If this is the first instruction being hoisted to the preheader,
1078 // initialize the CSE map with potential common expressions.
1080 InitCSEMap(Preheader);
1081 FirstInLoop = false;
1084 // Look for opportunity to CSE the hoisted instruction.
1085 unsigned Opcode = MI->getOpcode();
1086 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1087 CI = CSEMap.find(Opcode);
1088 if (!EliminateCSE(MI, CI)) {
1089 // Otherwise, splice the instruction to the preheader.
1090 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1092 // Clear the kill flags of any register this instruction defines,
1093 // since they may need to be live throughout the entire loop
1094 // rather than just live for part of it.
1095 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1096 MachineOperand &MO = MI->getOperand(i);
1097 if (MO.isReg() && MO.isDef() && !MO.isDead())
1098 MRI->clearKillFlags(MO.getReg());
1101 // Add to the CSE map.
1102 if (CI != CSEMap.end())
1103 CI->second.push_back(MI);
1105 std::vector<const MachineInstr*> CSEMIs;
1106 CSEMIs.push_back(MI);
1107 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1115 MachineBasicBlock *MachineLICM::getCurPreheader() {
1116 // Determine the block to which to hoist instructions. If we can't find a
1117 // suitable loop predecessor, we can't do any hoisting.
1119 // If we've tried to get a preheader and failed, don't try again.
1120 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1123 if (!CurPreheader) {
1124 CurPreheader = CurLoop->getLoopPreheader();
1125 if (!CurPreheader) {
1126 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1128 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1132 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1133 if (!CurPreheader) {
1134 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1139 return CurPreheader;