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 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/PseudoSourceValue.h"
34 #include "llvm/MC/MCInstrItineraries.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "machine-licm"
48 AvoidSpeculation("avoid-speculation",
49 cl::desc("MachineLICM should avoid speculation"),
50 cl::init(true), cl::Hidden);
53 "Number of machine instructions hoisted out of loops");
55 "Number of instructions hoisted in low reg pressure situation");
56 STATISTIC(NumHighLatency,
57 "Number of high latency instructions hoisted");
59 "Number of hoisted machine instructions CSEed");
60 STATISTIC(NumPostRAHoisted,
61 "Number of machine instructions hoisted out of loops post regalloc");
64 class MachineLICM : public MachineFunctionPass {
65 const TargetInstrInfo *TII;
66 const TargetLoweringBase *TLI;
67 const TargetRegisterInfo *TRI;
68 const MachineFrameInfo *MFI;
69 MachineRegisterInfo *MRI;
70 const InstrItineraryData *InstrItins;
73 // Various analyses that we use...
74 AliasAnalysis *AA; // Alias analysis info.
75 MachineLoopInfo *MLI; // Current MachineLoopInfo
76 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
78 // State that is updated as we process loops
79 bool Changed; // True if a loop is changed.
80 bool FirstInLoop; // True if it's the first LICM in the loop.
81 MachineLoop *CurLoop; // The current loop we are working on.
82 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
84 // Exit blocks for CurLoop.
85 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
87 bool isExitBlock(const MachineBasicBlock *MBB) const {
88 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
92 // Track 'estimated' register pressure.
93 SmallSet<unsigned, 32> RegSeen;
94 SmallVector<unsigned, 8> RegPressure;
96 // Register pressure "limit" per register class. If the pressure
97 // is higher than the limit, then it's considered high.
98 SmallVector<unsigned, 8> RegLimit;
100 // Register pressure on path leading from loop preheader to current BB.
101 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
103 // For each opcode, keep a list of potential CSE instructions.
104 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
112 // If a MBB does not dominate loop exiting blocks then it may not safe
113 // to hoist loads from this block.
114 // Tri-state: 0 - false, 1 - true, 2 - unknown
115 unsigned SpeculationState;
118 static char ID; // Pass identification, replacement for typeid
120 MachineFunctionPass(ID), PreRegAlloc(true) {
121 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
124 explicit MachineLICM(bool PreRA) :
125 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
126 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
129 bool runOnMachineFunction(MachineFunction &MF) override;
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 AU.addRequired<MachineLoopInfo>();
133 AU.addRequired<MachineDominatorTree>();
134 AU.addRequired<AliasAnalysis>();
135 AU.addPreserved<MachineLoopInfo>();
136 AU.addPreserved<MachineDominatorTree>();
137 MachineFunctionPass::getAnalysisUsage(AU);
140 void releaseMemory() override {
149 /// CandidateInfo - Keep track of information about hoisting candidates.
150 struct CandidateInfo {
154 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
155 : MI(mi), Def(def), FI(fi) {}
158 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
159 /// invariants out to the preheader.
160 void HoistRegionPostRA();
162 /// HoistPostRA - When an instruction is found to only use loop invariant
163 /// operands that is safe to hoist, this instruction is called to do the
165 void HoistPostRA(MachineInstr *MI, unsigned Def);
167 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
168 /// gather register def and frame object update information.
169 void ProcessMI(MachineInstr *MI,
170 BitVector &PhysRegDefs,
171 BitVector &PhysRegClobbers,
172 SmallSet<int, 32> &StoredFIs,
173 SmallVectorImpl<CandidateInfo> &Candidates);
175 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
177 void AddToLiveIns(unsigned Reg);
179 /// IsLICMCandidate - Returns true if the instruction may be a suitable
180 /// candidate for LICM. e.g. If the instruction is a call, then it's
181 /// obviously not safe to hoist it.
182 bool IsLICMCandidate(MachineInstr &I);
184 /// IsLoopInvariantInst - Returns true if the instruction is loop
185 /// invariant. I.e., all virtual register operands are defined outside of
186 /// the loop, physical registers aren't accessed (explicitly or implicitly),
187 /// and the instruction is hoistable.
189 bool IsLoopInvariantInst(MachineInstr &I);
191 /// HasLoopPHIUse - Return true if the specified instruction is used by any
192 /// phi node in the current loop.
193 bool HasLoopPHIUse(const MachineInstr *MI) const;
195 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
196 /// and an use in the current loop, return true if the target considered
198 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
201 bool IsCheapInstruction(MachineInstr &MI) const;
203 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
204 /// check if hoisting an instruction of the given cost matrix can cause high
205 /// register pressure.
206 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
208 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
209 /// the current block and update their register pressures to reflect the
210 /// effect of hoisting MI from the current block to the preheader.
211 void UpdateBackTraceRegPressure(const MachineInstr *MI);
213 /// IsProfitableToHoist - Return true if it is potentially profitable to
214 /// hoist the given loop invariant.
215 bool IsProfitableToHoist(MachineInstr &MI);
217 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
218 /// If not then a load from this mbb may not be safe to hoist.
219 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
221 void EnterScope(MachineBasicBlock *MBB);
223 void ExitScope(MachineBasicBlock *MBB);
225 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
226 /// dominator tree node if its a leaf or all of its children are done. Walk
227 /// up the dominator tree to destroy ancestors which are now done.
228 void ExitScopeIfDone(MachineDomTreeNode *Node,
229 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
230 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
232 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
233 /// blocks dominated by the specified header block, and that are in the
234 /// current loop) in depth first order w.r.t the DominatorTree. This allows
235 /// us to visit definitions before uses, allowing us to hoist a loop body in
236 /// one pass without iteration.
238 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
239 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
241 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
242 /// index, return the ID and cost of its representative register class by
244 void getRegisterClassIDAndCost(const MachineInstr *MI,
245 unsigned Reg, unsigned OpIdx,
246 unsigned &RCId, unsigned &RCCost) const;
248 /// InitRegPressure - Find all virtual register references that are liveout
249 /// of the preheader to initialize the starting "register pressure". Note
250 /// this does not count live through (livein but not used) registers.
251 void InitRegPressure(MachineBasicBlock *BB);
253 /// UpdateRegPressure - Update estimate of register pressure after the
254 /// specified instruction.
255 void UpdateRegPressure(const MachineInstr *MI);
257 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
258 /// the load itself could be hoisted. Return the unfolded and hoistable
259 /// load, or null if the load couldn't be unfolded or if it wouldn't
261 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
263 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
264 /// duplicate of MI. Return this instruction if it's found.
265 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
266 std::vector<const MachineInstr*> &PrevMIs);
268 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
269 /// the preheader that compute the same value. If it's found, do a RAU on
270 /// with the definition of the existing instruction rather than hoisting
271 /// the instruction to the preheader.
272 bool EliminateCSE(MachineInstr *MI,
273 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
275 /// MayCSE - Return true if the given instruction will be CSE'd if it's
276 /// hoisted out of the loop.
277 bool MayCSE(MachineInstr *MI);
279 /// Hoist - When an instruction is found to only use loop invariant operands
280 /// that is safe to hoist, this instruction is called to do the dirty work.
281 /// It returns true if the instruction is hoisted.
282 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
284 /// InitCSEMap - Initialize the CSE map with instructions that are in the
285 /// current loop preheader that may become duplicates of instructions that
286 /// are hoisted out of the loop.
287 void InitCSEMap(MachineBasicBlock *BB);
289 /// getCurPreheader - Get the preheader for the current loop, splitting
290 /// a critical edge if needed.
291 MachineBasicBlock *getCurPreheader();
293 } // end anonymous namespace
295 char MachineLICM::ID = 0;
296 char &llvm::MachineLICMID = MachineLICM::ID;
297 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
298 "Machine Loop Invariant Code Motion", false, false)
299 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
300 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
301 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
302 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
303 "Machine Loop Invariant Code Motion", false, false)
305 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
306 /// loop that has a unique predecessor.
307 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
308 // Check whether this loop even has a unique predecessor.
309 if (!CurLoop->getLoopPredecessor())
311 // Ok, now check to see if any of its outer loops do.
312 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
313 if (L->getLoopPredecessor())
315 // None of them did, so this is the outermost with a unique predecessor.
319 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
320 if (skipOptnoneFunction(*MF.getFunction()))
323 Changed = FirstInLoop = false;
324 TII = MF.getSubtarget().getInstrInfo();
325 TLI = MF.getSubtarget().getTargetLowering();
326 TRI = MF.getSubtarget().getRegisterInfo();
327 MFI = MF.getFrameInfo();
328 MRI = &MF.getRegInfo();
329 InstrItins = MF.getSubtarget().getInstrItineraryData();
331 PreRegAlloc = MRI->isSSA();
334 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
336 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
337 DEBUG(dbgs() << MF.getName() << " ********\n");
340 // Estimate register pressure during pre-regalloc pass.
341 unsigned NumRC = TRI->getNumRegClasses();
342 RegPressure.resize(NumRC);
343 std::fill(RegPressure.begin(), RegPressure.end(), 0);
344 RegLimit.resize(NumRC);
345 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
346 E = TRI->regclass_end(); I != E; ++I)
347 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
350 // Get our Loop information...
351 MLI = &getAnalysis<MachineLoopInfo>();
352 DT = &getAnalysis<MachineDominatorTree>();
353 AA = &getAnalysis<AliasAnalysis>();
355 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
356 while (!Worklist.empty()) {
357 CurLoop = Worklist.pop_back_val();
358 CurPreheader = nullptr;
361 // If this is done before regalloc, only visit outer-most preheader-sporting
363 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
364 Worklist.append(CurLoop->begin(), CurLoop->end());
368 CurLoop->getExitBlocks(ExitBlocks);
373 // CSEMap is initialized for loop header when the first instruction is
375 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
385 /// InstructionStoresToFI - Return true if instruction stores to the
387 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
388 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
389 oe = MI->memoperands_end(); o != oe; ++o) {
390 if (!(*o)->isStore() || !(*o)->getPseudoValue())
392 if (const FixedStackPseudoSourceValue *Value =
393 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
394 if (Value->getFrameIndex() == FI)
401 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
402 /// gather register def and frame object update information.
403 void MachineLICM::ProcessMI(MachineInstr *MI,
404 BitVector &PhysRegDefs,
405 BitVector &PhysRegClobbers,
406 SmallSet<int, 32> &StoredFIs,
407 SmallVectorImpl<CandidateInfo> &Candidates) {
408 bool RuledOut = false;
409 bool HasNonInvariantUse = false;
411 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
412 const MachineOperand &MO = MI->getOperand(i);
414 // Remember if the instruction stores to the frame index.
415 int FI = MO.getIndex();
416 if (!StoredFIs.count(FI) &&
417 MFI->isSpillSlotObjectIndex(FI) &&
418 InstructionStoresToFI(MI, FI))
419 StoredFIs.insert(FI);
420 HasNonInvariantUse = true;
424 // We can't hoist an instruction defining a physreg that is clobbered in
426 if (MO.isRegMask()) {
427 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
433 unsigned Reg = MO.getReg();
436 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
437 "Not expecting virtual register!");
440 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
441 // If it's using a non-loop-invariant register, then it's obviously not
443 HasNonInvariantUse = true;
447 if (MO.isImplicit()) {
448 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
449 PhysRegClobbers.set(*AI);
451 // Non-dead implicit def? This cannot be hoisted.
453 // No need to check if a dead implicit def is also defined by
454 // another instruction.
458 // FIXME: For now, avoid instructions with multiple defs, unless
459 // it's a dead implicit def.
465 // If we have already seen another instruction that defines the same
466 // register, then this is not safe. Two defs is indicated by setting a
467 // PhysRegClobbers bit.
468 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
469 if (PhysRegDefs.test(*AS))
470 PhysRegClobbers.set(*AS);
471 PhysRegDefs.set(*AS);
473 if (PhysRegClobbers.test(Reg))
474 // MI defined register is seen defined by another instruction in
475 // the loop, it cannot be a LICM candidate.
479 // Only consider reloads for now and remats which do not have register
480 // operands. FIXME: Consider unfold load folding instructions.
481 if (Def && !RuledOut) {
483 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
484 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
485 Candidates.push_back(CandidateInfo(MI, Def, FI));
489 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
490 /// invariants out to the preheader.
491 void MachineLICM::HoistRegionPostRA() {
492 MachineBasicBlock *Preheader = getCurPreheader();
496 unsigned NumRegs = TRI->getNumRegs();
497 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
498 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
500 SmallVector<CandidateInfo, 32> Candidates;
501 SmallSet<int, 32> StoredFIs;
503 // Walk the entire region, count number of defs for each register, and
504 // collect potential LICM candidates.
505 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
506 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
507 MachineBasicBlock *BB = Blocks[i];
509 // If the header of the loop containing this basic block is a landing pad,
510 // then don't try to hoist instructions out of this loop.
511 const MachineLoop *ML = MLI->getLoopFor(BB);
512 if (ML && ML->getHeader()->isLandingPad()) continue;
514 // Conservatively treat live-in's as an external def.
515 // FIXME: That means a reload that're reused in successor block(s) will not
517 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
518 E = BB->livein_end(); I != E; ++I) {
520 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
521 PhysRegDefs.set(*AI);
524 SpeculationState = SpeculateUnknown;
525 for (MachineBasicBlock::iterator
526 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
527 MachineInstr *MI = &*MII;
528 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
532 // Gather the registers read / clobbered by the terminator.
533 BitVector TermRegs(NumRegs);
534 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
535 if (TI != Preheader->end()) {
536 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
537 const MachineOperand &MO = TI->getOperand(i);
540 unsigned Reg = MO.getReg();
543 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
548 // Now evaluate whether the potential candidates qualify.
549 // 1. Check if the candidate defined register is defined by another
550 // instruction in the loop.
551 // 2. If the candidate is a load from stack slot (always true for now),
552 // check if the slot is stored anywhere in the loop.
553 // 3. Make sure candidate def should not clobber
554 // registers read by the terminator. Similarly its def should not be
555 // clobbered by the terminator.
556 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
557 if (Candidates[i].FI != INT_MIN &&
558 StoredFIs.count(Candidates[i].FI))
561 unsigned Def = Candidates[i].Def;
562 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
564 MachineInstr *MI = Candidates[i].MI;
565 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
566 const MachineOperand &MO = MI->getOperand(j);
567 if (!MO.isReg() || MO.isDef() || !MO.getReg())
569 unsigned Reg = MO.getReg();
570 if (PhysRegDefs.test(Reg) ||
571 PhysRegClobbers.test(Reg)) {
572 // If it's using a non-loop-invariant register, then it's obviously
573 // not safe to hoist.
579 HoistPostRA(MI, Candidates[i].Def);
584 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
585 /// loop, and make sure it is not killed by any instructions in the loop.
586 void MachineLICM::AddToLiveIns(unsigned Reg) {
587 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
588 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
589 MachineBasicBlock *BB = Blocks[i];
590 if (!BB->isLiveIn(Reg))
592 for (MachineBasicBlock::iterator
593 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
594 MachineInstr *MI = &*MII;
595 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
596 MachineOperand &MO = MI->getOperand(i);
597 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
598 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
605 /// HoistPostRA - When an instruction is found to only use loop invariant
606 /// operands that is safe to hoist, this instruction is called to do the
608 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
609 MachineBasicBlock *Preheader = getCurPreheader();
611 // Now move the instructions to the predecessor, inserting it before any
612 // terminator instructions.
613 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
614 << MI->getParent()->getNumber() << ": " << *MI);
616 // Splice the instruction to the preheader.
617 MachineBasicBlock *MBB = MI->getParent();
618 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
620 // Add register to livein list to all the BBs in the current loop since a
621 // loop invariant must be kept live throughout the whole loop. This is
622 // important to ensure later passes do not scavenge the def register.
629 // IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
630 // If not then a load from this mbb may not be safe to hoist.
631 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
632 if (SpeculationState != SpeculateUnknown)
633 return SpeculationState == SpeculateFalse;
635 if (BB != CurLoop->getHeader()) {
636 // Check loop exiting blocks.
637 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
638 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
639 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
640 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
641 SpeculationState = SpeculateTrue;
646 SpeculationState = SpeculateFalse;
650 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
651 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
653 // Remember livein register pressure.
654 BackTrace.push_back(RegPressure);
657 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
658 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
659 BackTrace.pop_back();
662 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
663 /// dominator tree node if its a leaf or all of its children are done. Walk
664 /// up the dominator tree to destroy ancestors which are now done.
665 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
666 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
667 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
668 if (OpenChildren[Node])
672 ExitScope(Node->getBlock());
674 // Now traverse upwards to pop ancestors whose offsprings are all done.
675 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
676 unsigned Left = --OpenChildren[Parent];
679 ExitScope(Parent->getBlock());
684 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
685 /// blocks dominated by the specified header block, and that are in the
686 /// current loop) in depth first order w.r.t the DominatorTree. This allows
687 /// us to visit definitions before uses, allowing us to hoist a loop body in
688 /// one pass without iteration.
690 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
691 SmallVector<MachineDomTreeNode*, 32> Scopes;
692 SmallVector<MachineDomTreeNode*, 8> WorkList;
693 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
694 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
696 // Perform a DFS walk to determine the order of visit.
697 WorkList.push_back(HeaderN);
699 MachineDomTreeNode *Node = WorkList.pop_back_val();
700 assert(Node && "Null dominator tree node?");
701 MachineBasicBlock *BB = Node->getBlock();
703 // If the header of the loop containing this basic block is a landing pad,
704 // then don't try to hoist instructions out of this loop.
705 const MachineLoop *ML = MLI->getLoopFor(BB);
706 if (ML && ML->getHeader()->isLandingPad())
709 // If this subregion is not in the top level loop at all, exit.
710 if (!CurLoop->contains(BB))
713 Scopes.push_back(Node);
714 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
715 unsigned NumChildren = Children.size();
717 // Don't hoist things out of a large switch statement. This often causes
718 // code to be hoisted that wasn't going to be executed, and increases
719 // register pressure in a situation where it's likely to matter.
720 if (BB->succ_size() >= 25)
723 OpenChildren[Node] = NumChildren;
724 // Add children in reverse order as then the next popped worklist node is
725 // the first child of this node. This means we ultimately traverse the
726 // DOM tree in exactly the same order as if we'd recursed.
727 for (int i = (int)NumChildren-1; i >= 0; --i) {
728 MachineDomTreeNode *Child = Children[i];
729 ParentMap[Child] = Node;
730 WorkList.push_back(Child);
732 } while (!WorkList.empty());
734 if (Scopes.size() != 0) {
735 MachineBasicBlock *Preheader = getCurPreheader();
739 // Compute registers which are livein into the loop headers.
742 InitRegPressure(Preheader);
746 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
747 MachineDomTreeNode *Node = Scopes[i];
748 MachineBasicBlock *MBB = Node->getBlock();
750 MachineBasicBlock *Preheader = getCurPreheader();
757 SpeculationState = SpeculateUnknown;
758 for (MachineBasicBlock::iterator
759 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
760 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
761 MachineInstr *MI = &*MII;
762 if (!Hoist(MI, Preheader))
763 UpdateRegPressure(MI);
767 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
768 ExitScopeIfDone(Node, OpenChildren, ParentMap);
772 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
773 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
776 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
777 /// index, return the ID and cost of its representative register class.
779 MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
780 unsigned Reg, unsigned OpIdx,
781 unsigned &RCId, unsigned &RCCost) const {
782 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
783 MVT VT = *RC->vt_begin();
784 if (VT == MVT::Untyped) {
788 RCId = TLI->getRepRegClassFor(VT)->getID();
789 RCCost = TLI->getRepRegClassCostFor(VT);
793 /// InitRegPressure - Find all virtual register references that are liveout of
794 /// the preheader to initialize the starting "register pressure". Note this
795 /// does not count live through (livein but not used) registers.
796 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
797 std::fill(RegPressure.begin(), RegPressure.end(), 0);
799 // If the preheader has only a single predecessor and it ends with a
800 // fallthrough or an unconditional branch, then scan its predecessor for live
801 // defs as well. This happens whenever the preheader is created by splitting
802 // the critical edge from the loop predecessor to the loop header.
803 if (BB->pred_size() == 1) {
804 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
805 SmallVector<MachineOperand, 4> Cond;
806 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
807 InitRegPressure(*BB->pred_begin());
810 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
812 MachineInstr *MI = &*MII;
813 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
814 const MachineOperand &MO = MI->getOperand(i);
815 if (!MO.isReg() || MO.isImplicit())
817 unsigned Reg = MO.getReg();
818 if (!TargetRegisterInfo::isVirtualRegister(Reg))
821 bool isNew = RegSeen.insert(Reg);
822 unsigned RCId, RCCost;
823 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
825 RegPressure[RCId] += RCCost;
827 bool isKill = isOperandKill(MO, MRI);
828 if (isNew && !isKill)
829 // Haven't seen this, it must be a livein.
830 RegPressure[RCId] += RCCost;
831 else if (!isNew && isKill)
832 RegPressure[RCId] -= RCCost;
838 /// UpdateRegPressure - Update estimate of register pressure after the
839 /// specified instruction.
840 void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
841 if (MI->isImplicitDef())
844 SmallVector<unsigned, 4> Defs;
845 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
846 const MachineOperand &MO = MI->getOperand(i);
847 if (!MO.isReg() || MO.isImplicit())
849 unsigned Reg = MO.getReg();
850 if (!TargetRegisterInfo::isVirtualRegister(Reg))
853 bool isNew = RegSeen.insert(Reg);
856 else if (!isNew && isOperandKill(MO, MRI)) {
857 unsigned RCId, RCCost;
858 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
859 if (RCCost > RegPressure[RCId])
860 RegPressure[RCId] = 0;
862 RegPressure[RCId] -= RCCost;
867 while (!Defs.empty()) {
868 unsigned Reg = Defs.pop_back_val();
869 unsigned RCId, RCCost;
870 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
871 RegPressure[RCId] += RCCost;
876 /// isLoadFromGOTOrConstantPool - Return true if this machine instruction
877 /// loads from global offset table or constant pool.
878 static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
879 assert (MI.mayLoad() && "Expected MI that loads!");
880 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
881 E = MI.memoperands_end(); I != E; ++I) {
882 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
883 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
890 /// IsLICMCandidate - Returns true if the instruction may be a suitable
891 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
892 /// not safe to hoist it.
893 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
894 // Check if it's safe to move the instruction.
895 bool DontMoveAcrossStore = true;
896 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
899 // If it is load then check if it is guaranteed to execute by making sure that
900 // it dominates all exiting blocks. If it doesn't, then there is a path out of
901 // the loop which does not execute this load, so we can't hoist it. Loads
902 // from constant memory are not safe to speculate all the time, for example
903 // indexed load from a jump table.
904 // Stores and side effects are already checked by isSafeToMove.
905 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
906 !IsGuaranteedToExecute(I.getParent()))
912 /// IsLoopInvariantInst - Returns true if the instruction is loop
913 /// invariant. I.e., all virtual register operands are defined outside of the
914 /// loop, physical registers aren't accessed explicitly, and there are no side
915 /// effects that aren't captured by the operands or other flags.
917 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
918 if (!IsLICMCandidate(I))
921 // The instruction is loop invariant if all of its operands are.
922 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
923 const MachineOperand &MO = I.getOperand(i);
928 unsigned Reg = MO.getReg();
929 if (Reg == 0) continue;
931 // Don't hoist an instruction that uses or defines a physical register.
932 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
934 // If the physreg has no defs anywhere, it's just an ambient register
935 // and we can freely move its uses. Alternatively, if it's allocatable,
936 // it could get allocated to something with a def during allocation.
937 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
939 // Otherwise it's safe to move.
941 } else if (!MO.isDead()) {
942 // A def that isn't dead. We can't move it.
944 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
945 // If the reg is live into the loop, we can't hoist an instruction
946 // which would clobber it.
954 assert(MRI->getVRegDef(Reg) &&
955 "Machine instr not mapped for this vreg?!");
957 // If the loop contains the definition of an operand, then the instruction
958 // isn't loop invariant.
959 if (CurLoop->contains(MRI->getVRegDef(Reg)))
963 // If we got this far, the instruction is loop invariant!
968 /// HasLoopPHIUse - Return true if the specified instruction is used by a
969 /// phi node and hoisting it could cause a copy to be inserted.
970 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
971 SmallVector<const MachineInstr*, 8> Work(1, MI);
973 MI = Work.pop_back_val();
974 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
975 if (!MO->isReg() || !MO->isDef())
977 unsigned Reg = MO->getReg();
978 if (!TargetRegisterInfo::isVirtualRegister(Reg))
980 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
981 // A PHI may cause a copy to be inserted.
983 // A PHI inside the loop causes a copy because the live range of Reg is
984 // extended across the PHI.
985 if (CurLoop->contains(&UseMI))
987 // A PHI in an exit block can cause a copy to be inserted if the PHI
988 // has multiple predecessors in the loop with different values.
989 // For now, approximate by rejecting all exit blocks.
990 if (isExitBlock(UseMI.getParent()))
994 // Look past copies as well.
995 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
996 Work.push_back(&UseMI);
999 } while (!Work.empty());
1003 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1004 /// and an use in the current loop, return true if the target considered
1006 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
1007 unsigned DefIdx, unsigned Reg) const {
1008 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
1011 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1012 if (UseMI.isCopyLike())
1014 if (!CurLoop->contains(UseMI.getParent()))
1016 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1017 const MachineOperand &MO = UseMI.getOperand(i);
1018 if (!MO.isReg() || !MO.isUse())
1020 unsigned MOReg = MO.getReg();
1024 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
1028 // Only look at the first in loop use.
1035 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1036 /// the operand latency between its def and a use is one or less.
1037 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
1038 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
1040 if (!InstrItins || InstrItins->isEmpty())
1043 bool isCheap = false;
1044 unsigned NumDefs = MI.getDesc().getNumDefs();
1045 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1046 MachineOperand &DefMO = MI.getOperand(i);
1047 if (!DefMO.isReg() || !DefMO.isDef())
1050 unsigned Reg = DefMO.getReg();
1051 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1054 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1062 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
1063 /// if hoisting an instruction of the given cost matrix can cause high
1064 /// register pressure.
1065 bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1067 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1069 if (CI->second <= 0)
1072 unsigned RCId = CI->first;
1073 unsigned Limit = RegLimit[RCId];
1074 int Cost = CI->second;
1076 // Don't hoist cheap instructions if they would increase register pressure,
1077 // even if we're under the limit.
1081 for (unsigned i = BackTrace.size(); i != 0; --i) {
1082 SmallVectorImpl<unsigned> &RP = BackTrace[i-1];
1083 if (RP[RCId] + Cost >= Limit)
1091 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1092 /// current block and update their register pressures to reflect the effect
1093 /// of hoisting MI from the current block to the preheader.
1094 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1095 if (MI->isImplicitDef())
1098 // First compute the 'cost' of the instruction, i.e. its contribution
1099 // to register pressure.
1100 DenseMap<unsigned, int> Cost;
1101 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1102 const MachineOperand &MO = MI->getOperand(i);
1103 if (!MO.isReg() || MO.isImplicit())
1105 unsigned Reg = MO.getReg();
1106 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1109 unsigned RCId, RCCost;
1110 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
1112 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1113 if (CI != Cost.end())
1114 CI->second += RCCost;
1116 Cost.insert(std::make_pair(RCId, RCCost));
1117 } else if (isOperandKill(MO, MRI)) {
1118 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1119 if (CI != Cost.end())
1120 CI->second -= RCCost;
1122 Cost.insert(std::make_pair(RCId, -RCCost));
1126 // Update register pressure of blocks from loop header to current block.
1127 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
1128 SmallVectorImpl<unsigned> &RP = BackTrace[i];
1129 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1131 unsigned RCId = CI->first;
1132 RP[RCId] += CI->second;
1137 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1138 /// the given loop invariant.
1139 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1140 if (MI.isImplicitDef())
1143 // Besides removing computation from the loop, hoisting an instruction has
1146 // - The value defined by the instruction becomes live across the entire
1147 // loop. This increases register pressure in the loop.
1149 // - If the value is used by a PHI in the loop, a copy will be required for
1150 // lowering the PHI after extending the live range.
1152 // - When hoisting the last use of a value in the loop, that value no longer
1153 // needs to be live in the loop. This lowers register pressure in the loop.
1155 bool CheapInstr = IsCheapInstruction(MI);
1156 bool CreatesCopy = HasLoopPHIUse(&MI);
1158 // Don't hoist a cheap instruction if it would create a copy in the loop.
1159 if (CheapInstr && CreatesCopy) {
1160 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1164 // Rematerializable instructions should always be hoisted since the register
1165 // allocator can just pull them down again when needed.
1166 if (TII->isTriviallyReMaterializable(&MI, AA))
1169 // Estimate register pressure to determine whether to LICM the instruction.
1170 // In low register pressure situation, we can be more aggressive about
1171 // hoisting. Also, favors hoisting long latency instructions even in
1172 // moderately high pressure situation.
1173 // Cheap instructions will only be hoisted if they don't increase register
1175 // FIXME: If there are long latency loop-invariant instructions inside the
1176 // loop at this point, why didn't the optimizer's LICM hoist them?
1177 DenseMap<unsigned, int> Cost;
1178 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1179 const MachineOperand &MO = MI.getOperand(i);
1180 if (!MO.isReg() || MO.isImplicit())
1182 unsigned Reg = MO.getReg();
1183 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1186 unsigned RCId, RCCost;
1187 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1189 if (HasHighOperandLatency(MI, i, Reg)) {
1190 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1194 Cost[RCId] += RCCost;
1195 } else if (isOperandKill(MO, MRI)) {
1196 // Is a virtual register use is a kill, hoisting it out of the loop
1197 // may actually reduce register pressure or be register pressure
1199 Cost[RCId] -= RCCost;
1203 // Visit BBs from header to current BB, if hoisting this doesn't cause
1204 // high register pressure, then it's safe to proceed.
1205 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1206 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1211 // Don't risk increasing register pressure if it would create copies.
1213 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1217 // Do not "speculate" in high register pressure situation. If an
1218 // instruction is not guaranteed to be executed in the loop, it's best to be
1220 if (AvoidSpeculation &&
1221 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1222 DEBUG(dbgs() << "Won't speculate: " << MI);
1226 // High register pressure situation, only hoist if the instruction is going
1228 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1229 !MI.isInvariantLoad(AA)) {
1230 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1237 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1238 // Don't unfold simple loads.
1239 if (MI->canFoldAsLoad())
1242 // If not, we may be able to unfold a load and hoist that.
1243 // First test whether the instruction is loading from an amenable
1245 if (!MI->isInvariantLoad(AA))
1248 // Next determine the register class for a temporary register.
1249 unsigned LoadRegIndex;
1251 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1252 /*UnfoldLoad=*/true,
1253 /*UnfoldStore=*/false,
1255 if (NewOpc == 0) return nullptr;
1256 const MCInstrDesc &MID = TII->get(NewOpc);
1257 if (MID.getNumDefs() != 1) return nullptr;
1258 MachineFunction &MF = *MI->getParent()->getParent();
1259 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1260 // Ok, we're unfolding. Create a temporary register and do the unfold.
1261 unsigned Reg = MRI->createVirtualRegister(RC);
1263 SmallVector<MachineInstr *, 2> NewMIs;
1265 TII->unfoldMemoryOperand(MF, MI, Reg,
1266 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1270 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1272 assert(NewMIs.size() == 2 &&
1273 "Unfolded a load into multiple instructions!");
1274 MachineBasicBlock *MBB = MI->getParent();
1275 MachineBasicBlock::iterator Pos = MI;
1276 MBB->insert(Pos, NewMIs[0]);
1277 MBB->insert(Pos, NewMIs[1]);
1278 // If unfolding produced a load that wasn't loop-invariant or profitable to
1279 // hoist, discard the new instructions and bail.
1280 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1281 NewMIs[0]->eraseFromParent();
1282 NewMIs[1]->eraseFromParent();
1286 // Update register pressure for the unfolded instruction.
1287 UpdateRegPressure(NewMIs[1]);
1289 // Otherwise we successfully unfolded a load that we can hoist.
1290 MI->eraseFromParent();
1294 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1295 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1296 const MachineInstr *MI = &*I;
1297 unsigned Opcode = MI->getOpcode();
1298 CSEMap[Opcode].push_back(MI);
1303 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1304 std::vector<const MachineInstr*> &PrevMIs) {
1305 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1306 const MachineInstr *PrevMI = PrevMIs[i];
1307 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
1313 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1314 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1315 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1316 // the undef property onto uses.
1317 if (CI == CSEMap.end() || MI->isImplicitDef())
1320 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1321 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1323 // Replace virtual registers defined by MI by their counterparts defined
1325 SmallVector<unsigned, 2> Defs;
1326 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1327 const MachineOperand &MO = MI->getOperand(i);
1329 // Physical registers may not differ here.
1330 assert((!MO.isReg() || MO.getReg() == 0 ||
1331 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1332 MO.getReg() == Dup->getOperand(i).getReg()) &&
1333 "Instructions with different phys regs are not identical!");
1335 if (MO.isReg() && MO.isDef() &&
1336 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1340 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1341 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1342 unsigned Idx = Defs[i];
1343 unsigned Reg = MI->getOperand(Idx).getReg();
1344 unsigned DupReg = Dup->getOperand(Idx).getReg();
1345 OrigRCs.push_back(MRI->getRegClass(DupReg));
1347 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1348 // Restore old RCs if more than one defs.
1349 for (unsigned j = 0; j != i; ++j)
1350 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1355 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1356 unsigned Idx = Defs[i];
1357 unsigned Reg = MI->getOperand(Idx).getReg();
1358 unsigned DupReg = Dup->getOperand(Idx).getReg();
1359 MRI->replaceRegWith(Reg, DupReg);
1360 MRI->clearKillFlags(DupReg);
1363 MI->eraseFromParent();
1370 /// MayCSE - Return true if the given instruction will be CSE'd if it's
1371 /// hoisted out of the loop.
1372 bool MachineLICM::MayCSE(MachineInstr *MI) {
1373 unsigned Opcode = MI->getOpcode();
1374 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1375 CI = CSEMap.find(Opcode);
1376 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1377 // the undef property onto uses.
1378 if (CI == CSEMap.end() || MI->isImplicitDef())
1381 return LookForDuplicate(MI, CI->second) != nullptr;
1384 /// Hoist - When an instruction is found to use only loop invariant operands
1385 /// that are safe to hoist, this instruction is called to do the dirty work.
1387 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1388 // First check whether we should hoist this instruction.
1389 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1390 // If not, try unfolding a hoistable load.
1391 MI = ExtractHoistableLoad(MI);
1392 if (!MI) return false;
1395 // Now move the instructions to the predecessor, inserting it before any
1396 // terminator instructions.
1398 dbgs() << "Hoisting " << *MI;
1399 if (Preheader->getBasicBlock())
1400 dbgs() << " to MachineBasicBlock "
1401 << Preheader->getName();
1402 if (MI->getParent()->getBasicBlock())
1403 dbgs() << " from MachineBasicBlock "
1404 << MI->getParent()->getName();
1408 // If this is the first instruction being hoisted to the preheader,
1409 // initialize the CSE map with potential common expressions.
1411 InitCSEMap(Preheader);
1412 FirstInLoop = false;
1415 // Look for opportunity to CSE the hoisted instruction.
1416 unsigned Opcode = MI->getOpcode();
1417 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1418 CI = CSEMap.find(Opcode);
1419 if (!EliminateCSE(MI, CI)) {
1420 // Otherwise, splice the instruction to the preheader.
1421 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1423 // Update register pressure for BBs from header to this block.
1424 UpdateBackTraceRegPressure(MI);
1426 // Clear the kill flags of any register this instruction defines,
1427 // since they may need to be live throughout the entire loop
1428 // rather than just live for part of it.
1429 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1430 MachineOperand &MO = MI->getOperand(i);
1431 if (MO.isReg() && MO.isDef() && !MO.isDead())
1432 MRI->clearKillFlags(MO.getReg());
1435 // Add to the CSE map.
1436 if (CI != CSEMap.end())
1437 CI->second.push_back(MI);
1439 CSEMap[Opcode].push_back(MI);
1448 MachineBasicBlock *MachineLICM::getCurPreheader() {
1449 // Determine the block to which to hoist instructions. If we can't find a
1450 // suitable loop predecessor, we can't do any hoisting.
1452 // If we've tried to get a preheader and failed, don't try again.
1453 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1456 if (!CurPreheader) {
1457 CurPreheader = CurLoop->getLoopPreheader();
1458 if (!CurPreheader) {
1459 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1461 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1465 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1466 if (!CurPreheader) {
1467 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1472 return CurPreheader;