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 TrackRegPressure("rp-aware-machine-licm",
48 cl::desc("Register pressure aware machine LICM"),
49 cl::init(false), cl::Hidden);
51 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
52 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
53 STATISTIC(NumPostRAHoisted,
54 "Number of machine instructions hoisted out of loops post regalloc");
57 class MachineLICM : public MachineFunctionPass {
60 const TargetMachine *TM;
61 const TargetInstrInfo *TII;
62 const TargetLowering *TLI;
63 const TargetRegisterInfo *TRI;
64 const MachineFrameInfo *MFI;
65 MachineRegisterInfo *MRI;
66 const InstrItineraryData *InstrItins;
68 // Various analyses that we use...
69 AliasAnalysis *AA; // Alias analysis info.
70 MachineLoopInfo *MLI; // Current MachineLoopInfo
71 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
73 // State that is updated as we process loops
74 bool Changed; // True if a loop is changed.
75 bool FirstInLoop; // True if it's the first LICM in the loop.
76 MachineLoop *CurLoop; // The current loop we are working on.
77 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
79 BitVector AllocatableSet;
81 // Track 'estimated' register pressure.
82 SmallVector<unsigned, 8> RegPressure;
83 SmallVector<unsigned, 8> RegLimit;
85 // For each opcode, keep a list of potential CSE instructions.
86 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
89 static char ID; // Pass identification, replacement for typeid
91 MachineFunctionPass(ID), PreRegAlloc(true) {}
93 explicit MachineLICM(bool PreRA) :
94 MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
96 virtual bool runOnMachineFunction(MachineFunction &MF);
98 const char *getPassName() const { return "Machine Instruction LICM"; }
100 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.setPreservesCFG();
102 AU.addRequired<MachineLoopInfo>();
103 AU.addRequired<MachineDominatorTree>();
104 AU.addRequired<AliasAnalysis>();
105 AU.addPreserved<MachineLoopInfo>();
106 AU.addPreserved<MachineDominatorTree>();
107 MachineFunctionPass::getAnalysisUsage(AU);
110 virtual void releaseMemory() {
117 /// CandidateInfo - Keep track of information about hoisting candidates.
118 struct CandidateInfo {
122 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
123 : MI(mi), Def(def), FI(fi) {}
126 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
127 /// invariants out to the preheader.
128 void HoistRegionPostRA();
130 /// HoistPostRA - When an instruction is found to only use loop invariant
131 /// operands that is safe to hoist, this instruction is called to do the
133 void HoistPostRA(MachineInstr *MI, unsigned Def);
135 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
136 /// gather register def and frame object update information.
137 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
138 SmallSet<int, 32> &StoredFIs,
139 SmallVector<CandidateInfo, 32> &Candidates);
141 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
143 void AddToLiveIns(unsigned Reg);
145 /// IsLICMCandidate - Returns true if the instruction may be a suitable
146 /// candidate for LICM. e.g. If the instruction is a call, then it's
147 /// obviously not safe to hoist it.
148 bool IsLICMCandidate(MachineInstr &I);
150 /// IsLoopInvariantInst - Returns true if the instruction is loop
151 /// invariant. I.e., all virtual register operands are defined outside of
152 /// the loop, physical registers aren't accessed (explicitly or implicitly),
153 /// and the instruction is hoistable.
155 bool IsLoopInvariantInst(MachineInstr &I);
157 /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
158 /// and an use in the current loop.
159 int ComputeOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
161 /// IsProfitableToHoist - Return true if it is potentially profitable to
162 /// hoist the given loop invariant.
163 bool IsProfitableToHoist(MachineInstr &MI);
165 /// HoistRegion - Walk the specified region of the CFG (defined by all
166 /// blocks dominated by the specified block, and that are in the current
167 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
168 /// visit definitions before uses, allowing us to hoist a loop body in one
169 /// pass without iteration.
171 void HoistRegion(MachineDomTreeNode *N);
173 /// InitRegPressure - Find all virtual register references that are livein
174 /// to the block to initialize the starting "register pressure". Note this
175 /// does not count live through (livein but not used) registers.
176 void InitRegPressure(MachineBasicBlock *BB);
178 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
179 /// register pressure before and after executing a specifi instruction.
180 void UpdateRegPressureBefore(const MachineInstr *MI);
181 void UpdateRegPressureAfter(const MachineInstr *MI);
183 /// isLoadFromConstantMemory - Return true if the given instruction is a
184 /// load from constant memory.
185 bool isLoadFromConstantMemory(MachineInstr *MI);
187 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
188 /// the load itself could be hoisted. Return the unfolded and hoistable
189 /// load, or null if the load couldn't be unfolded or if it wouldn't
191 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
193 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
194 /// duplicate of MI. Return this instruction if it's found.
195 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
196 std::vector<const MachineInstr*> &PrevMIs);
198 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
199 /// the preheader that compute the same value. If it's found, do a RAU on
200 /// with the definition of the existing instruction rather than hoisting
201 /// the instruction to the preheader.
202 bool EliminateCSE(MachineInstr *MI,
203 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
205 /// Hoist - When an instruction is found to only use loop invariant operands
206 /// that is safe to hoist, this instruction is called to do the dirty work.
208 void Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
210 /// InitCSEMap - Initialize the CSE map with instructions that are in the
211 /// current loop preheader that may become duplicates of instructions that
212 /// are hoisted out of the loop.
213 void InitCSEMap(MachineBasicBlock *BB);
215 /// getCurPreheader - Get the preheader for the current loop, splitting
216 /// a critical edge if needed.
217 MachineBasicBlock *getCurPreheader();
219 } // end anonymous namespace
221 char MachineLICM::ID = 0;
222 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
223 "Machine Loop Invariant Code Motion", false, false)
224 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
225 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
226 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
227 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
228 "Machine Loop Invariant Code Motion", false, false)
230 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
231 return new MachineLICM(PreRegAlloc);
234 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
235 /// loop that has a unique predecessor.
236 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
237 // Check whether this loop even has a unique predecessor.
238 if (!CurLoop->getLoopPredecessor())
240 // Ok, now check to see if any of its outer loops do.
241 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
242 if (L->getLoopPredecessor())
244 // None of them did, so this is the outermost with a unique predecessor.
248 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
250 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
252 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
254 Changed = FirstInLoop = false;
255 TM = &MF.getTarget();
256 TII = TM->getInstrInfo();
257 TLI = TM->getTargetLowering();
258 TRI = TM->getRegisterInfo();
259 MFI = MF.getFrameInfo();
260 MRI = &MF.getRegInfo();
261 InstrItins = TM->getInstrItineraryData();
262 AllocatableSet = TRI->getAllocatableSet(MF);
265 // Estimate register pressure during pre-regalloc pass.
266 unsigned NumRC = TRI->getNumRegClasses();
267 RegPressure.resize(NumRC);
268 RegLimit.resize(NumRC);
269 std::fill(RegPressure.begin(), RegPressure.end(), 0);
270 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
271 E = TRI->regclass_end(); I != E; ++I)
272 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
275 // Get our Loop information...
276 MLI = &getAnalysis<MachineLoopInfo>();
277 DT = &getAnalysis<MachineDominatorTree>();
278 AA = &getAnalysis<AliasAnalysis>();
280 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
281 while (!Worklist.empty()) {
282 CurLoop = Worklist.pop_back_val();
285 // If this is done before regalloc, only visit outer-most preheader-sporting
287 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
288 Worklist.append(CurLoop->begin(), CurLoop->end());
295 // CSEMap is initialized for loop header when the first instruction is
297 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
307 /// InstructionStoresToFI - Return true if instruction stores to the
309 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
310 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
311 oe = MI->memoperands_end(); o != oe; ++o) {
312 if (!(*o)->isStore() || !(*o)->getValue())
314 if (const FixedStackPseudoSourceValue *Value =
315 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
316 if (Value->getFrameIndex() == FI)
323 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
324 /// gather register def and frame object update information.
325 void MachineLICM::ProcessMI(MachineInstr *MI,
326 unsigned *PhysRegDefs,
327 SmallSet<int, 32> &StoredFIs,
328 SmallVector<CandidateInfo, 32> &Candidates) {
329 bool RuledOut = false;
330 bool HasNonInvariantUse = false;
332 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
333 const MachineOperand &MO = MI->getOperand(i);
335 // Remember if the instruction stores to the frame index.
336 int FI = MO.getIndex();
337 if (!StoredFIs.count(FI) &&
338 MFI->isSpillSlotObjectIndex(FI) &&
339 InstructionStoresToFI(MI, FI))
340 StoredFIs.insert(FI);
341 HasNonInvariantUse = true;
347 unsigned Reg = MO.getReg();
350 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
351 "Not expecting virtual register!");
354 if (Reg && PhysRegDefs[Reg])
355 // If it's using a non-loop-invariant register, then it's obviously not
357 HasNonInvariantUse = true;
361 if (MO.isImplicit()) {
363 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
366 // Non-dead implicit def? This cannot be hoisted.
368 // No need to check if a dead implicit def is also defined by
369 // another instruction.
373 // FIXME: For now, avoid instructions with multiple defs, unless
374 // it's a dead implicit def.
380 // If we have already seen another instruction that defines the same
381 // register, then this is not safe.
382 if (++PhysRegDefs[Reg] > 1)
383 // MI defined register is seen defined by another instruction in
384 // the loop, it cannot be a LICM candidate.
386 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
387 if (++PhysRegDefs[*AS] > 1)
391 // Only consider reloads for now and remats which do not have register
392 // operands. FIXME: Consider unfold load folding instructions.
393 if (Def && !RuledOut) {
395 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
396 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
397 Candidates.push_back(CandidateInfo(MI, Def, FI));
401 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
402 /// invariants out to the preheader.
403 void MachineLICM::HoistRegionPostRA() {
404 unsigned NumRegs = TRI->getNumRegs();
405 unsigned *PhysRegDefs = new unsigned[NumRegs];
406 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
408 SmallVector<CandidateInfo, 32> Candidates;
409 SmallSet<int, 32> StoredFIs;
411 // Walk the entire region, count number of defs for each register, and
412 // collect potential LICM candidates.
413 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
414 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
415 MachineBasicBlock *BB = Blocks[i];
416 // Conservatively treat live-in's as an external def.
417 // FIXME: That means a reload that're reused in successor block(s) will not
419 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
420 E = BB->livein_end(); I != E; ++I) {
423 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
427 for (MachineBasicBlock::iterator
428 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
429 MachineInstr *MI = &*MII;
430 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
434 // Now evaluate whether the potential candidates qualify.
435 // 1. Check if the candidate defined register is defined by another
436 // instruction in the loop.
437 // 2. If the candidate is a load from stack slot (always true for now),
438 // check if the slot is stored anywhere in the loop.
439 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
440 if (Candidates[i].FI != INT_MIN &&
441 StoredFIs.count(Candidates[i].FI))
444 if (PhysRegDefs[Candidates[i].Def] == 1) {
446 MachineInstr *MI = Candidates[i].MI;
447 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
448 const MachineOperand &MO = MI->getOperand(j);
449 if (!MO.isReg() || MO.isDef() || !MO.getReg())
451 if (PhysRegDefs[MO.getReg()]) {
452 // If it's using a non-loop-invariant register, then it's obviously
453 // not safe to hoist.
459 HoistPostRA(MI, Candidates[i].Def);
463 delete[] PhysRegDefs;
466 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
467 /// loop, and make sure it is not killed by any instructions in the loop.
468 void MachineLICM::AddToLiveIns(unsigned Reg) {
469 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
470 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
471 MachineBasicBlock *BB = Blocks[i];
472 if (!BB->isLiveIn(Reg))
474 for (MachineBasicBlock::iterator
475 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
476 MachineInstr *MI = &*MII;
477 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
478 MachineOperand &MO = MI->getOperand(i);
479 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
480 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
487 /// HoistPostRA - When an instruction is found to only use loop invariant
488 /// operands that is safe to hoist, this instruction is called to do the
490 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
491 MachineBasicBlock *Preheader = getCurPreheader();
492 if (!Preheader) return;
494 // Now move the instructions to the predecessor, inserting it before any
495 // terminator instructions.
497 dbgs() << "Hoisting " << *MI;
498 if (Preheader->getBasicBlock())
499 dbgs() << " to MachineBasicBlock "
500 << Preheader->getName();
501 if (MI->getParent()->getBasicBlock())
502 dbgs() << " from MachineBasicBlock "
503 << MI->getParent()->getName();
507 // Splice the instruction to the preheader.
508 MachineBasicBlock *MBB = MI->getParent();
509 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
511 // Add register to livein list to all the BBs in the current loop since a
512 // loop invariant must be kept live throughout the whole loop. This is
513 // important to ensure later passes do not scavenge the def register.
520 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
521 /// dominated by the specified block, and that are in the current loop) in depth
522 /// first order w.r.t the DominatorTree. This allows us to visit definitions
523 /// before uses, allowing us to hoist a loop body in one pass without iteration.
525 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
526 assert(N != 0 && "Null dominator tree node?");
527 MachineBasicBlock *BB = N->getBlock();
529 // If this subregion is not in the top level loop at all, exit.
530 if (!CurLoop->contains(BB)) return;
532 MachineBasicBlock *Preheader = getCurPreheader();
534 if (TrackRegPressure)
537 for (MachineBasicBlock::iterator
538 MII = BB->begin(), E = BB->end(); MII != E; ) {
539 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
540 MachineInstr *MI = &*MII;
542 if (TrackRegPressure)
543 UpdateRegPressureBefore(MI);
544 Hoist(MI, Preheader);
545 if (TrackRegPressure)
546 UpdateRegPressureAfter(MI);
552 // Don't hoist things out of a large switch statement. This often causes
553 // code to be hoisted that wasn't going to be executed, and increases
554 // register pressure in a situation where it's likely to matter.
555 if (BB->succ_size() < 25) {
556 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
557 for (unsigned I = 0, E = Children.size(); I != E; ++I)
558 HoistRegion(Children[I]);
562 /// InitRegPressure - Find all virtual register references that are livein to
563 /// the block to initialize the starting "register pressure". Note this does
564 /// not count live through (livein but not used) registers.
565 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
566 SmallSet<unsigned, 16> Seen;
568 std::fill(RegPressure.begin(), RegPressure.end(), 0);
569 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
571 MachineInstr *MI = &*MII;
572 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
573 const MachineOperand &MO = MI->getOperand(i);
574 if (!MO.isReg() || MO.isImplicit())
576 unsigned Reg = MO.getReg();
577 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
579 if (!Seen.insert(Reg))
583 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
584 EVT VT = *RC->vt_begin();
585 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
586 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
591 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
592 /// register pressure before and after executing a specifi instruction.
593 void MachineLICM::UpdateRegPressureBefore(const MachineInstr *MI) {
594 if (MI->isImplicitDef() || MI->isPHI())
597 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
598 const MachineOperand &MO = MI->getOperand(i);
599 if (!MO.isReg() || MO.isImplicit() || !MO.isUse() || !MO.isKill())
601 unsigned Reg = MO.getReg();
602 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
605 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
606 EVT VT = *RC->vt_begin();
607 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
608 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
610 assert(RCCost <= RegPressure[RCId]);
611 RegPressure[RCId] -= RCCost;
615 void MachineLICM::UpdateRegPressureAfter(const MachineInstr *MI) {
616 if (MI->isImplicitDef() || MI->isPHI())
619 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
620 const MachineOperand &MO = MI->getOperand(i);
621 if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
623 unsigned Reg = MO.getReg();
624 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
627 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
628 EVT VT = *RC->vt_begin();
629 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
630 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
631 RegPressure[RCId] += RCCost;
635 /// IsLICMCandidate - Returns true if the instruction may be a suitable
636 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
637 /// not safe to hoist it.
638 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
639 // Check if it's safe to move the instruction.
640 bool DontMoveAcrossStore = true;
641 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
647 /// IsLoopInvariantInst - Returns true if the instruction is loop
648 /// invariant. I.e., all virtual register operands are defined outside of the
649 /// loop, physical registers aren't accessed explicitly, and there are no side
650 /// effects that aren't captured by the operands or other flags.
652 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
653 if (!IsLICMCandidate(I))
656 // The instruction is loop invariant if all of its operands are.
657 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
658 const MachineOperand &MO = I.getOperand(i);
663 unsigned Reg = MO.getReg();
664 if (Reg == 0) continue;
666 // Don't hoist an instruction that uses or defines a physical register.
667 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
669 // If the physreg has no defs anywhere, it's just an ambient register
670 // and we can freely move its uses. Alternatively, if it's allocatable,
671 // it could get allocated to something with a def during allocation.
672 if (!MRI->def_empty(Reg))
674 if (AllocatableSet.test(Reg))
676 // Check for a def among the register's aliases too.
677 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
678 unsigned AliasReg = *Alias;
679 if (!MRI->def_empty(AliasReg))
681 if (AllocatableSet.test(AliasReg))
684 // Otherwise it's safe to move.
686 } else if (!MO.isDead()) {
687 // A def that isn't dead. We can't move it.
689 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
690 // If the reg is live into the loop, we can't hoist an instruction
691 // which would clobber it.
699 assert(MRI->getVRegDef(Reg) &&
700 "Machine instr not mapped for this vreg?!");
702 // If the loop contains the definition of an operand, then the instruction
703 // isn't loop invariant.
704 if (CurLoop->contains(MRI->getVRegDef(Reg)))
708 // If we got this far, the instruction is loop invariant!
713 /// HasPHIUses - Return true if the specified register has any PHI use.
714 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
715 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
716 UE = MRI->use_end(); UI != UE; ++UI) {
717 MachineInstr *UseMI = &*UI;
724 /// isLoadFromConstantMemory - Return true if the given instruction is a
725 /// load from constant memory. Machine LICM will hoist these even if they are
726 /// not re-materializable.
727 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
728 if (!MI->getDesc().mayLoad()) return false;
729 if (!MI->hasOneMemOperand()) return false;
730 MachineMemOperand *MMO = *MI->memoperands_begin();
731 if (MMO->isVolatile()) return false;
732 if (!MMO->getValue()) return false;
733 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
735 MachineFunction &MF = *MI->getParent()->getParent();
736 return PSV->isConstant(MF.getFrameInfo());
738 return AA->pointsToConstantMemory(MMO->getValue());
742 /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
743 /// and an use in the current loop.
744 int MachineLICM::ComputeOperandLatency(MachineInstr &MI,
745 unsigned DefIdx, unsigned Reg) {
746 if (MRI->use_nodbg_empty(Reg))
747 // No use? Return arbitrary large number!
751 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
752 E = MRI->use_nodbg_end(); I != E; ++I) {
753 MachineInstr *UseMI = &*I;
754 if (!CurLoop->contains(UseMI->getParent()))
756 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
757 const MachineOperand &MO = UseMI->getOperand(i);
758 if (!MO.isReg() || !MO.isUse())
760 unsigned MOReg = MO.getReg();
764 int UseCycle = TII->getOperandLatency(InstrItins, &MI, DefIdx, UseMI, i);
765 Latency = std::max(Latency, UseCycle);
773 Latency = InstrItins->getOperandCycle(MI.getDesc().getSchedClass(), DefIdx);
778 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
779 /// the given loop invariant.
780 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
781 if (MI.isImplicitDef())
784 // FIXME: For now, only hoist re-materilizable instructions. LICM will
785 // increase register pressure. We want to make sure it doesn't increase
787 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
788 // these tend to help performance in low register pressure situation. The
789 // trade off is it may cause spill in high pressure situation. It will end up
790 // adding a store in the loop preheader. But the reload is no more expensive.
791 // The side benefit is these loads are frequently CSE'ed.
792 if (!TrackRegPressure || MI.getDesc().isAsCheapAsAMove()) {
793 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
794 !isLoadFromConstantMemory(&MI))
797 // In low register pressure situation, we can be more aggressive about
798 // hoisting. Also, favors hoisting long latency instructions even in
799 // moderately high pressure situation.
801 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
802 const MachineOperand &MO = MI.getOperand(i);
803 if (!MO.isReg() || MO.isImplicit())
805 unsigned Reg = MO.getReg();
806 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
808 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
809 EVT VT = *RC->vt_begin();
810 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
811 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
814 if (RegPressure[RCId] >= RegLimit[RCId]) {
815 // Hoisting this instruction may actually reduce register pressure
817 int Pressure = RegPressure[RCId] - RCCost;
818 assert(Pressure >= 0);
819 Delta -= (int)RegLimit[RCId] - Pressure;
822 if (InstrItins && !InstrItins->isEmpty()) {
823 int Cycle = ComputeOperandLatency(MI, i, Reg);
825 // FIXME: Target specific high latency limit?
828 if (RegPressure[RCId] >= RegLimit[RCId])
831 int Pressure = RegPressure[RCId] + RCCost;
832 if (Pressure > (int)RegLimit[RCId])
833 Delta += Pressure - RegLimit[RCId];
841 // High register pressure situation, only hoist if the instruction is going to
843 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
844 !isLoadFromConstantMemory(&MI))
848 // If result(s) of this instruction is used by PHIs, then don't hoist it.
849 // The presence of joins makes it difficult for current register allocator
850 // implementation to perform remat.
851 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
852 const MachineOperand &MO = MI.getOperand(i);
853 if (!MO.isReg() || !MO.isDef())
855 if (HasPHIUses(MO.getReg(), MRI))
862 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
863 // Don't unfold simple loads.
864 if (MI->getDesc().canFoldAsLoad())
867 // If not, we may be able to unfold a load and hoist that.
868 // First test whether the instruction is loading from an amenable
870 if (!isLoadFromConstantMemory(MI))
873 // Next determine the register class for a temporary register.
874 unsigned LoadRegIndex;
876 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
878 /*UnfoldStore=*/false,
880 if (NewOpc == 0) return 0;
881 const TargetInstrDesc &TID = TII->get(NewOpc);
882 if (TID.getNumDefs() != 1) return 0;
883 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
884 // Ok, we're unfolding. Create a temporary register and do the unfold.
885 unsigned Reg = MRI->createVirtualRegister(RC);
887 MachineFunction &MF = *MI->getParent()->getParent();
888 SmallVector<MachineInstr *, 2> NewMIs;
890 TII->unfoldMemoryOperand(MF, MI, Reg,
891 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
895 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
897 assert(NewMIs.size() == 2 &&
898 "Unfolded a load into multiple instructions!");
899 MachineBasicBlock *MBB = MI->getParent();
900 MBB->insert(MI, NewMIs[0]);
901 MBB->insert(MI, NewMIs[1]);
902 // If unfolding produced a load that wasn't loop-invariant or profitable to
903 // hoist, discard the new instructions and bail.
904 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
905 NewMIs[0]->eraseFromParent();
906 NewMIs[1]->eraseFromParent();
909 // Otherwise we successfully unfolded a load that we can hoist.
910 MI->eraseFromParent();
914 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
915 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
916 const MachineInstr *MI = &*I;
917 // FIXME: For now, only hoist re-materilizable instructions. LICM will
918 // increase register pressure. We want to make sure it doesn't increase
920 if (TII->isTriviallyReMaterializable(MI, AA)) {
921 unsigned Opcode = MI->getOpcode();
922 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
923 CI = CSEMap.find(Opcode);
924 if (CI != CSEMap.end())
925 CI->second.push_back(MI);
927 std::vector<const MachineInstr*> CSEMIs;
928 CSEMIs.push_back(MI);
929 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
936 MachineLICM::LookForDuplicate(const MachineInstr *MI,
937 std::vector<const MachineInstr*> &PrevMIs) {
938 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
939 const MachineInstr *PrevMI = PrevMIs[i];
940 if (TII->produceSameValue(MI, PrevMI))
946 bool MachineLICM::EliminateCSE(MachineInstr *MI,
947 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
948 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
949 // the undef property onto uses.
950 if (CI == CSEMap.end() || MI->isImplicitDef())
953 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
954 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
956 // Replace virtual registers defined by MI by their counterparts defined
958 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
959 const MachineOperand &MO = MI->getOperand(i);
961 // Physical registers may not differ here.
962 assert((!MO.isReg() || MO.getReg() == 0 ||
963 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
964 MO.getReg() == Dup->getOperand(i).getReg()) &&
965 "Instructions with different phys regs are not identical!");
967 if (MO.isReg() && MO.isDef() &&
968 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
969 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
970 MRI->clearKillFlags(Dup->getOperand(i).getReg());
973 MI->eraseFromParent();
980 /// Hoist - When an instruction is found to use only loop invariant operands
981 /// that are safe to hoist, this instruction is called to do the dirty work.
983 void MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
984 // First check whether we should hoist this instruction.
985 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
986 // If not, try unfolding a hoistable load.
987 MI = ExtractHoistableLoad(MI);
991 // Now move the instructions to the predecessor, inserting it before any
992 // terminator instructions.
994 dbgs() << "Hoisting " << *MI;
995 if (Preheader->getBasicBlock())
996 dbgs() << " to MachineBasicBlock "
997 << Preheader->getName();
998 if (MI->getParent()->getBasicBlock())
999 dbgs() << " from MachineBasicBlock "
1000 << MI->getParent()->getName();
1004 // If this is the first instruction being hoisted to the preheader,
1005 // initialize the CSE map with potential common expressions.
1007 InitCSEMap(Preheader);
1008 FirstInLoop = false;
1011 // Look for opportunity to CSE the hoisted instruction.
1012 unsigned Opcode = MI->getOpcode();
1013 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1014 CI = CSEMap.find(Opcode);
1015 if (!EliminateCSE(MI, CI)) {
1016 // Otherwise, splice the instruction to the preheader.
1017 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1019 // Clear the kill flags of any register this instruction defines,
1020 // since they may need to be live throughout the entire loop
1021 // rather than just live for part of it.
1022 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1023 MachineOperand &MO = MI->getOperand(i);
1024 if (MO.isReg() && MO.isDef() && !MO.isDead())
1025 MRI->clearKillFlags(MO.getReg());
1028 // Add to the CSE map.
1029 if (CI != CSEMap.end())
1030 CI->second.push_back(MI);
1032 std::vector<const MachineInstr*> CSEMIs;
1033 CSEMIs.push_back(MI);
1034 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1042 MachineBasicBlock *MachineLICM::getCurPreheader() {
1043 // Determine the block to which to hoist instructions. If we can't find a
1044 // suitable loop predecessor, we can't do any hoisting.
1046 // If we've tried to get a preheader and failed, don't try again.
1047 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1050 if (!CurPreheader) {
1051 CurPreheader = CurLoop->getLoopPreheader();
1052 if (!CurPreheader) {
1053 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1055 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1059 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1060 if (!CurPreheader) {
1061 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1066 return CurPreheader;