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 is not intended to be a replacement or a complete alternative
14 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15 // constructs that are not exposed before lowering and instruction selection.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/CodeGen/TargetSchedule.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
41 #define DEBUG_TYPE "machine-licm"
44 AvoidSpeculation("avoid-speculation",
45 cl::desc("MachineLICM should avoid speculation"),
46 cl::init(true), cl::Hidden);
49 HoistCheapInsts("hoist-cheap-insts",
50 cl::desc("MachineLICM should hoist even cheap instructions"),
51 cl::init(false), cl::Hidden);
54 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
55 cl::desc("MachineLICM should sink instructions into "
56 "loops to avoid register spills"),
57 cl::init(false), cl::Hidden);
60 "Number of machine instructions hoisted out of loops");
62 "Number of instructions hoisted in low reg pressure situation");
63 STATISTIC(NumHighLatency,
64 "Number of high latency instructions hoisted");
66 "Number of hoisted machine instructions CSEed");
67 STATISTIC(NumPostRAHoisted,
68 "Number of machine instructions hoisted out of loops post regalloc");
71 class MachineLICM : public MachineFunctionPass {
72 const TargetInstrInfo *TII;
73 const TargetLoweringBase *TLI;
74 const TargetRegisterInfo *TRI;
75 const MachineFrameInfo *MFI;
76 MachineRegisterInfo *MRI;
77 TargetSchedModel SchedModel;
80 // Various analyses that we use...
81 AliasAnalysis *AA; // Alias analysis info.
82 MachineLoopInfo *MLI; // Current MachineLoopInfo
83 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
85 // State that is updated as we process loops
86 bool Changed; // True if a loop is changed.
87 bool FirstInLoop; // True if it's the first LICM in the loop.
88 MachineLoop *CurLoop; // The current loop we are working on.
89 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
91 // Exit blocks for CurLoop.
92 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
94 bool isExitBlock(const MachineBasicBlock *MBB) const {
95 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
99 // Track 'estimated' register pressure.
100 SmallSet<unsigned, 32> RegSeen;
101 SmallVector<unsigned, 8> RegPressure;
103 // Register pressure "limit" per register pressure set. If the pressure
104 // is higher than the limit, then it's considered high.
105 SmallVector<unsigned, 8> RegLimit;
107 // Register pressure on path leading from loop preheader to current BB.
108 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
110 // For each opcode, keep a list of potential CSE instructions.
111 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
119 // If a MBB does not dominate loop exiting blocks then it may not safe
120 // to hoist loads from this block.
121 // Tri-state: 0 - false, 1 - true, 2 - unknown
122 unsigned SpeculationState;
125 static char ID; // Pass identification, replacement for typeid
127 MachineFunctionPass(ID), PreRegAlloc(true) {
128 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
131 explicit MachineLICM(bool PreRA) :
132 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
133 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
136 bool runOnMachineFunction(MachineFunction &MF) override;
138 void getAnalysisUsage(AnalysisUsage &AU) const override {
139 AU.addRequired<MachineLoopInfo>();
140 AU.addRequired<MachineDominatorTree>();
141 AU.addRequired<AAResultsWrapperPass>();
142 AU.addPreserved<MachineLoopInfo>();
143 AU.addPreserved<MachineDominatorTree>();
144 MachineFunctionPass::getAnalysisUsage(AU);
147 void releaseMemory() override {
156 /// CandidateInfo - Keep track of information about hoisting candidates.
157 struct CandidateInfo {
161 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
162 : MI(mi), Def(def), FI(fi) {}
165 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
166 /// invariants out to the preheader.
167 void HoistRegionPostRA();
169 /// HoistPostRA - When an instruction is found to only use loop invariant
170 /// operands that is safe to hoist, this instruction is called to do the
172 void HoistPostRA(MachineInstr *MI, unsigned Def);
174 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
175 /// gather register def and frame object update information.
176 void ProcessMI(MachineInstr *MI,
177 BitVector &PhysRegDefs,
178 BitVector &PhysRegClobbers,
179 SmallSet<int, 32> &StoredFIs,
180 SmallVectorImpl<CandidateInfo> &Candidates);
182 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
184 void AddToLiveIns(unsigned Reg);
186 /// IsLICMCandidate - Returns true if the instruction may be a suitable
187 /// candidate for LICM. e.g. If the instruction is a call, then it's
188 /// obviously not safe to hoist it.
189 bool IsLICMCandidate(MachineInstr &I);
191 /// IsLoopInvariantInst - Returns true if the instruction is loop
192 /// invariant. I.e., all virtual register operands are defined outside of
193 /// the loop, physical registers aren't accessed (explicitly or implicitly),
194 /// and the instruction is hoistable.
196 bool IsLoopInvariantInst(MachineInstr &I);
198 /// HasLoopPHIUse - Return true if the specified instruction is used by any
199 /// phi node in the current loop.
200 bool HasLoopPHIUse(const MachineInstr *MI) const;
202 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
203 /// and an use in the current loop, return true if the target considered
205 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
208 bool IsCheapInstruction(MachineInstr &MI) const;
210 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
211 /// check if hoisting an instruction of the given cost matrix can cause high
212 /// register pressure.
213 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
216 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
217 /// the current block and update their register pressures to reflect the
218 /// effect of hoisting MI from the current block to the preheader.
219 void UpdateBackTraceRegPressure(const MachineInstr *MI);
221 /// IsProfitableToHoist - Return true if it is potentially profitable to
222 /// hoist the given loop invariant.
223 bool IsProfitableToHoist(MachineInstr &MI);
225 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
226 /// If not then a load from this mbb may not be safe to hoist.
227 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
229 void EnterScope(MachineBasicBlock *MBB);
231 void ExitScope(MachineBasicBlock *MBB);
233 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
234 /// dominator tree node if its a leaf or all of its children are done. Walk
235 /// up the dominator tree to destroy ancestors which are now done.
236 void ExitScopeIfDone(MachineDomTreeNode *Node,
237 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
238 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
240 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
241 /// blocks dominated by the specified header block, and that are in the
242 /// current loop) in depth first order w.r.t the DominatorTree. This allows
243 /// us to visit definitions before uses, allowing us to hoist a loop body in
244 /// one pass without iteration.
246 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
247 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
249 /// SinkIntoLoop - Sink instructions into loops if profitable. This
250 /// especially tries to prevent register spills caused by register pressure
251 /// if there is little to no overhead moving instructions into loops.
254 /// InitRegPressure - Find all virtual register references that are liveout
255 /// of the preheader to initialize the starting "register pressure". Note
256 /// this does not count live through (livein but not used) registers.
257 void InitRegPressure(MachineBasicBlock *BB);
259 /// calcRegisterCost - Calculate the additional register pressure that the
260 /// registers used in MI cause.
262 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
263 /// figure out which usages are live-ins.
264 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
265 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
267 bool ConsiderUnseenAsDef);
269 /// UpdateRegPressure - Update estimate of register pressure after the
270 /// specified instruction.
271 void UpdateRegPressure(const MachineInstr *MI,
272 bool ConsiderUnseenAsDef = false);
274 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
275 /// the load itself could be hoisted. Return the unfolded and hoistable
276 /// load, or null if the load couldn't be unfolded or if it wouldn't
278 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
280 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
281 /// duplicate of MI. Return this instruction if it's found.
282 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
283 std::vector<const MachineInstr*> &PrevMIs);
285 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
286 /// the preheader that compute the same value. If it's found, do a RAU on
287 /// with the definition of the existing instruction rather than hoisting
288 /// the instruction to the preheader.
289 bool EliminateCSE(MachineInstr *MI,
290 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
292 /// MayCSE - Return true if the given instruction will be CSE'd if it's
293 /// hoisted out of the loop.
294 bool MayCSE(MachineInstr *MI);
296 /// Hoist - When an instruction is found to only use loop invariant operands
297 /// that is safe to hoist, this instruction is called to do the dirty work.
298 /// It returns true if the instruction is hoisted.
299 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
301 /// InitCSEMap - Initialize the CSE map with instructions that are in the
302 /// current loop preheader that may become duplicates of instructions that
303 /// are hoisted out of the loop.
304 void InitCSEMap(MachineBasicBlock *BB);
306 /// getCurPreheader - Get the preheader for the current loop, splitting
307 /// a critical edge if needed.
308 MachineBasicBlock *getCurPreheader();
310 } // end anonymous namespace
312 char MachineLICM::ID = 0;
313 char &llvm::MachineLICMID = MachineLICM::ID;
314 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
315 "Machine Loop Invariant Code Motion", false, false)
316 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
317 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
318 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
319 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
320 "Machine Loop Invariant Code Motion", false, false)
322 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
323 /// loop that has a unique predecessor.
324 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
325 // Check whether this loop even has a unique predecessor.
326 if (!CurLoop->getLoopPredecessor())
328 // Ok, now check to see if any of its outer loops do.
329 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
330 if (L->getLoopPredecessor())
332 // None of them did, so this is the outermost with a unique predecessor.
336 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
337 if (skipOptnoneFunction(*MF.getFunction()))
340 Changed = FirstInLoop = false;
341 const TargetSubtargetInfo &ST = MF.getSubtarget();
342 TII = ST.getInstrInfo();
343 TLI = ST.getTargetLowering();
344 TRI = ST.getRegisterInfo();
345 MFI = MF.getFrameInfo();
346 MRI = &MF.getRegInfo();
347 SchedModel.init(ST.getSchedModel(), &ST, TII);
349 PreRegAlloc = MRI->isSSA();
352 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
354 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
355 DEBUG(dbgs() << MF.getName() << " ********\n");
358 // Estimate register pressure during pre-regalloc pass.
359 unsigned NumRPS = TRI->getNumRegPressureSets();
360 RegPressure.resize(NumRPS);
361 std::fill(RegPressure.begin(), RegPressure.end(), 0);
362 RegLimit.resize(NumRPS);
363 for (unsigned i = 0, e = NumRPS; i != e; ++i)
364 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
367 // Get our Loop information...
368 MLI = &getAnalysis<MachineLoopInfo>();
369 DT = &getAnalysis<MachineDominatorTree>();
370 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
372 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
373 while (!Worklist.empty()) {
374 CurLoop = Worklist.pop_back_val();
375 CurPreheader = nullptr;
378 // If this is done before regalloc, only visit outer-most preheader-sporting
380 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
381 Worklist.append(CurLoop->begin(), CurLoop->end());
385 CurLoop->getExitBlocks(ExitBlocks);
390 // CSEMap is initialized for loop header when the first instruction is
392 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
397 if (SinkInstsToAvoidSpills)
405 /// InstructionStoresToFI - Return true if instruction stores to the
407 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
408 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
409 oe = MI->memoperands_end(); o != oe; ++o) {
410 if (!(*o)->isStore() || !(*o)->getPseudoValue())
412 if (const FixedStackPseudoSourceValue *Value =
413 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
414 if (Value->getFrameIndex() == FI)
421 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
422 /// gather register def and frame object update information.
423 void MachineLICM::ProcessMI(MachineInstr *MI,
424 BitVector &PhysRegDefs,
425 BitVector &PhysRegClobbers,
426 SmallSet<int, 32> &StoredFIs,
427 SmallVectorImpl<CandidateInfo> &Candidates) {
428 bool RuledOut = false;
429 bool HasNonInvariantUse = false;
431 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
432 const MachineOperand &MO = MI->getOperand(i);
434 // Remember if the instruction stores to the frame index.
435 int FI = MO.getIndex();
436 if (!StoredFIs.count(FI) &&
437 MFI->isSpillSlotObjectIndex(FI) &&
438 InstructionStoresToFI(MI, FI))
439 StoredFIs.insert(FI);
440 HasNonInvariantUse = true;
444 // We can't hoist an instruction defining a physreg that is clobbered in
446 if (MO.isRegMask()) {
447 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
453 unsigned Reg = MO.getReg();
456 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
457 "Not expecting virtual register!");
460 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
461 // If it's using a non-loop-invariant register, then it's obviously not
463 HasNonInvariantUse = true;
467 if (MO.isImplicit()) {
468 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
469 PhysRegClobbers.set(*AI);
471 // Non-dead implicit def? This cannot be hoisted.
473 // No need to check if a dead implicit def is also defined by
474 // another instruction.
478 // FIXME: For now, avoid instructions with multiple defs, unless
479 // it's a dead implicit def.
485 // If we have already seen another instruction that defines the same
486 // register, then this is not safe. Two defs is indicated by setting a
487 // PhysRegClobbers bit.
488 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
489 if (PhysRegDefs.test(*AS))
490 PhysRegClobbers.set(*AS);
491 PhysRegDefs.set(*AS);
493 if (PhysRegClobbers.test(Reg))
494 // MI defined register is seen defined by another instruction in
495 // the loop, it cannot be a LICM candidate.
499 // Only consider reloads for now and remats which do not have register
500 // operands. FIXME: Consider unfold load folding instructions.
501 if (Def && !RuledOut) {
503 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
504 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
505 Candidates.push_back(CandidateInfo(MI, Def, FI));
509 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
510 /// invariants out to the preheader.
511 void MachineLICM::HoistRegionPostRA() {
512 MachineBasicBlock *Preheader = getCurPreheader();
516 unsigned NumRegs = TRI->getNumRegs();
517 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
518 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
520 SmallVector<CandidateInfo, 32> Candidates;
521 SmallSet<int, 32> StoredFIs;
523 // Walk the entire region, count number of defs for each register, and
524 // collect potential LICM candidates.
525 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
526 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
527 MachineBasicBlock *BB = Blocks[i];
529 // If the header of the loop containing this basic block is a landing pad,
530 // then don't try to hoist instructions out of this loop.
531 const MachineLoop *ML = MLI->getLoopFor(BB);
532 if (ML && ML->getHeader()->isEHPad()) continue;
534 // Conservatively treat live-in's as an external def.
535 // FIXME: That means a reload that're reused in successor block(s) will not
537 for (const auto &LI : BB->liveins()) {
538 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
539 PhysRegDefs.set(*AI);
542 SpeculationState = SpeculateUnknown;
543 for (MachineBasicBlock::iterator
544 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
545 MachineInstr *MI = &*MII;
546 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
550 // Gather the registers read / clobbered by the terminator.
551 BitVector TermRegs(NumRegs);
552 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
553 if (TI != Preheader->end()) {
554 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
555 const MachineOperand &MO = TI->getOperand(i);
558 unsigned Reg = MO.getReg();
561 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
566 // Now evaluate whether the potential candidates qualify.
567 // 1. Check if the candidate defined register is defined by another
568 // instruction in the loop.
569 // 2. If the candidate is a load from stack slot (always true for now),
570 // check if the slot is stored anywhere in the loop.
571 // 3. Make sure candidate def should not clobber
572 // registers read by the terminator. Similarly its def should not be
573 // clobbered by the terminator.
574 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
575 if (Candidates[i].FI != INT_MIN &&
576 StoredFIs.count(Candidates[i].FI))
579 unsigned Def = Candidates[i].Def;
580 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
582 MachineInstr *MI = Candidates[i].MI;
583 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
584 const MachineOperand &MO = MI->getOperand(j);
585 if (!MO.isReg() || MO.isDef() || !MO.getReg())
587 unsigned Reg = MO.getReg();
588 if (PhysRegDefs.test(Reg) ||
589 PhysRegClobbers.test(Reg)) {
590 // If it's using a non-loop-invariant register, then it's obviously
591 // not safe to hoist.
597 HoistPostRA(MI, Candidates[i].Def);
602 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
603 /// loop, and make sure it is not killed by any instructions in the loop.
604 void MachineLICM::AddToLiveIns(unsigned Reg) {
605 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
606 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
607 MachineBasicBlock *BB = Blocks[i];
608 if (!BB->isLiveIn(Reg))
610 for (MachineBasicBlock::iterator
611 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
612 MachineInstr *MI = &*MII;
613 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
614 MachineOperand &MO = MI->getOperand(i);
615 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
616 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
623 /// HoistPostRA - When an instruction is found to only use loop invariant
624 /// operands that is safe to hoist, this instruction is called to do the
626 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
627 MachineBasicBlock *Preheader = getCurPreheader();
629 // Now move the instructions to the predecessor, inserting it before any
630 // terminator instructions.
631 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
632 << MI->getParent()->getNumber() << ": " << *MI);
634 // Splice the instruction to the preheader.
635 MachineBasicBlock *MBB = MI->getParent();
636 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
638 // Add register to livein list to all the BBs in the current loop since a
639 // loop invariant must be kept live throughout the whole loop. This is
640 // important to ensure later passes do not scavenge the def register.
647 // IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
648 // If not then a load from this mbb may not be safe to hoist.
649 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
650 if (SpeculationState != SpeculateUnknown)
651 return SpeculationState == SpeculateFalse;
653 if (BB != CurLoop->getHeader()) {
654 // Check loop exiting blocks.
655 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
656 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
657 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
658 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
659 SpeculationState = SpeculateTrue;
664 SpeculationState = SpeculateFalse;
668 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
669 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
671 // Remember livein register pressure.
672 BackTrace.push_back(RegPressure);
675 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
676 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
677 BackTrace.pop_back();
680 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
681 /// dominator tree node if its a leaf or all of its children are done. Walk
682 /// up the dominator tree to destroy ancestors which are now done.
683 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
684 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
685 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
686 if (OpenChildren[Node])
690 ExitScope(Node->getBlock());
692 // Now traverse upwards to pop ancestors whose offsprings are all done.
693 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
694 unsigned Left = --OpenChildren[Parent];
697 ExitScope(Parent->getBlock());
702 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
703 /// blocks dominated by the specified header block, and that are in the
704 /// current loop) in depth first order w.r.t the DominatorTree. This allows
705 /// us to visit definitions before uses, allowing us to hoist a loop body in
706 /// one pass without iteration.
708 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
709 MachineBasicBlock *Preheader = getCurPreheader();
713 SmallVector<MachineDomTreeNode*, 32> Scopes;
714 SmallVector<MachineDomTreeNode*, 8> WorkList;
715 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
716 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
718 // Perform a DFS walk to determine the order of visit.
719 WorkList.push_back(HeaderN);
720 while (!WorkList.empty()) {
721 MachineDomTreeNode *Node = WorkList.pop_back_val();
722 assert(Node && "Null dominator tree node?");
723 MachineBasicBlock *BB = Node->getBlock();
725 // If the header of the loop containing this basic block is a landing pad,
726 // then don't try to hoist instructions out of this loop.
727 const MachineLoop *ML = MLI->getLoopFor(BB);
728 if (ML && ML->getHeader()->isEHPad())
731 // If this subregion is not in the top level loop at all, exit.
732 if (!CurLoop->contains(BB))
735 Scopes.push_back(Node);
736 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
737 unsigned NumChildren = Children.size();
739 // Don't hoist things out of a large switch statement. This often causes
740 // code to be hoisted that wasn't going to be executed, and increases
741 // register pressure in a situation where it's likely to matter.
742 if (BB->succ_size() >= 25)
745 OpenChildren[Node] = NumChildren;
746 // Add children in reverse order as then the next popped worklist node is
747 // the first child of this node. This means we ultimately traverse the
748 // DOM tree in exactly the same order as if we'd recursed.
749 for (int i = (int)NumChildren-1; i >= 0; --i) {
750 MachineDomTreeNode *Child = Children[i];
751 ParentMap[Child] = Node;
752 WorkList.push_back(Child);
756 if (Scopes.size() == 0)
759 // Compute registers which are livein into the loop headers.
762 InitRegPressure(Preheader);
765 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
766 MachineDomTreeNode *Node = Scopes[i];
767 MachineBasicBlock *MBB = Node->getBlock();
772 SpeculationState = SpeculateUnknown;
773 for (MachineBasicBlock::iterator
774 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
775 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
776 MachineInstr *MI = &*MII;
777 if (!Hoist(MI, Preheader))
778 UpdateRegPressure(MI);
782 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
783 ExitScopeIfDone(Node, OpenChildren, ParentMap);
787 void MachineLICM::SinkIntoLoop() {
788 MachineBasicBlock *Preheader = getCurPreheader();
792 SmallVector<MachineInstr *, 8> Candidates;
793 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
794 I != Preheader->instr_end(); ++I) {
795 // We need to ensure that we can safely move this instruction into the loop.
796 // As such, it must not have side-effects, e.g. such as a call has.
797 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
798 Candidates.push_back(&*I);
801 for (MachineInstr *I : Candidates) {
802 const MachineOperand &MO = I->getOperand(0);
803 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
805 if (!MRI->hasOneDef(MO.getReg()))
808 MachineBasicBlock *B = nullptr;
809 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
810 // FIXME: Come up with a proper cost model that estimates whether sinking
811 // the instruction (and thus possibly executing it on every loop
812 // iteration) is more expensive than a register.
813 // For now assumes that copies are cheap and thus almost always worth it.
822 B = DT->findNearestCommonDominator(B, MI.getParent());
828 if (!CanSink || !B || B == Preheader)
830 B->splice(B->getFirstNonPHI(), Preheader, I);
834 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
835 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
838 /// InitRegPressure - Find all virtual register references that are liveout of
839 /// the preheader to initialize the starting "register pressure". Note this
840 /// does not count live through (livein but not used) registers.
841 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
842 std::fill(RegPressure.begin(), RegPressure.end(), 0);
844 // If the preheader has only a single predecessor and it ends with a
845 // fallthrough or an unconditional branch, then scan its predecessor for live
846 // defs as well. This happens whenever the preheader is created by splitting
847 // the critical edge from the loop predecessor to the loop header.
848 if (BB->pred_size() == 1) {
849 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
850 SmallVector<MachineOperand, 4> Cond;
851 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
852 InitRegPressure(*BB->pred_begin());
855 for (const MachineInstr &MI : *BB)
856 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
859 /// UpdateRegPressure - Update estimate of register pressure after the
860 /// specified instruction.
861 void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
862 bool ConsiderUnseenAsDef) {
863 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
864 for (const auto &RPIdAndCost : Cost) {
865 unsigned Class = RPIdAndCost.first;
866 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
867 RegPressure[Class] = 0;
869 RegPressure[Class] += RPIdAndCost.second;
873 DenseMap<unsigned, int>
874 MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
875 bool ConsiderUnseenAsDef) {
876 DenseMap<unsigned, int> Cost;
877 if (MI->isImplicitDef())
879 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
880 const MachineOperand &MO = MI->getOperand(i);
881 if (!MO.isReg() || MO.isImplicit())
883 unsigned Reg = MO.getReg();
884 if (!TargetRegisterInfo::isVirtualRegister(Reg))
887 // FIXME: It seems bad to use RegSeen only for some of these calculations.
888 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
889 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
891 RegClassWeight W = TRI->getRegClassWeight(RC);
894 RCCost = W.RegWeight;
896 bool isKill = isOperandKill(MO, MRI);
897 if (isNew && !isKill && ConsiderUnseenAsDef)
898 // Haven't seen this, it must be a livein.
899 RCCost = W.RegWeight;
900 else if (!isNew && isKill)
901 RCCost = -W.RegWeight;
905 const int *PS = TRI->getRegClassPressureSets(RC);
906 for (; *PS != -1; ++PS) {
907 if (Cost.find(*PS) == Cost.end())
916 /// isLoadFromGOTOrConstantPool - Return true if this machine instruction
917 /// loads from global offset table or constant pool.
918 static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
919 assert (MI.mayLoad() && "Expected MI that loads!");
920 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
921 E = MI.memoperands_end(); I != E; ++I) {
922 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
923 if (PSV->isGOT() || PSV->isConstantPool())
930 /// IsLICMCandidate - Returns true if the instruction may be a suitable
931 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
932 /// not safe to hoist it.
933 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
934 // Check if it's safe to move the instruction.
935 bool DontMoveAcrossStore = true;
936 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
939 // If it is load then check if it is guaranteed to execute by making sure that
940 // it dominates all exiting blocks. If it doesn't, then there is a path out of
941 // the loop which does not execute this load, so we can't hoist it. Loads
942 // from constant memory are not safe to speculate all the time, for example
943 // indexed load from a jump table.
944 // Stores and side effects are already checked by isSafeToMove.
945 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
946 !IsGuaranteedToExecute(I.getParent()))
952 /// IsLoopInvariantInst - Returns true if the instruction is loop
953 /// invariant. I.e., all virtual register operands are defined outside of the
954 /// loop, physical registers aren't accessed explicitly, and there are no side
955 /// effects that aren't captured by the operands or other flags.
957 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
958 if (!IsLICMCandidate(I))
961 // The instruction is loop invariant if all of its operands are.
962 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
963 const MachineOperand &MO = I.getOperand(i);
968 unsigned Reg = MO.getReg();
969 if (Reg == 0) continue;
971 // Don't hoist an instruction that uses or defines a physical register.
972 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
974 // If the physreg has no defs anywhere, it's just an ambient register
975 // and we can freely move its uses. Alternatively, if it's allocatable,
976 // it could get allocated to something with a def during allocation.
977 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
979 // Otherwise it's safe to move.
981 } else if (!MO.isDead()) {
982 // A def that isn't dead. We can't move it.
984 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
985 // If the reg is live into the loop, we can't hoist an instruction
986 // which would clobber it.
994 assert(MRI->getVRegDef(Reg) &&
995 "Machine instr not mapped for this vreg?!");
997 // If the loop contains the definition of an operand, then the instruction
998 // isn't loop invariant.
999 if (CurLoop->contains(MRI->getVRegDef(Reg)))
1003 // If we got this far, the instruction is loop invariant!
1008 /// HasLoopPHIUse - Return true if the specified instruction is used by a
1009 /// phi node and hoisting it could cause a copy to be inserted.
1010 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
1011 SmallVector<const MachineInstr*, 8> Work(1, MI);
1013 MI = Work.pop_back_val();
1014 for (const MachineOperand &MO : MI->operands()) {
1015 if (!MO.isReg() || !MO.isDef())
1017 unsigned Reg = MO.getReg();
1018 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1020 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1021 // A PHI may cause a copy to be inserted.
1022 if (UseMI.isPHI()) {
1023 // A PHI inside the loop causes a copy because the live range of Reg is
1024 // extended across the PHI.
1025 if (CurLoop->contains(&UseMI))
1027 // A PHI in an exit block can cause a copy to be inserted if the PHI
1028 // has multiple predecessors in the loop with different values.
1029 // For now, approximate by rejecting all exit blocks.
1030 if (isExitBlock(UseMI.getParent()))
1034 // Look past copies as well.
1035 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1036 Work.push_back(&UseMI);
1039 } while (!Work.empty());
1043 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1044 /// and an use in the current loop, return true if the target considered
1046 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
1047 unsigned DefIdx, unsigned Reg) const {
1048 if (MRI->use_nodbg_empty(Reg))
1051 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1052 if (UseMI.isCopyLike())
1054 if (!CurLoop->contains(UseMI.getParent()))
1056 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1057 const MachineOperand &MO = UseMI.getOperand(i);
1058 if (!MO.isReg() || !MO.isUse())
1060 unsigned MOReg = MO.getReg();
1064 if (TII->hasHighOperandLatency(SchedModel, MRI, &MI, DefIdx, &UseMI, i))
1068 // Only look at the first in loop use.
1075 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1076 /// the operand latency between its def and a use is one or less.
1077 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
1078 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
1081 bool isCheap = false;
1082 unsigned NumDefs = MI.getDesc().getNumDefs();
1083 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1084 MachineOperand &DefMO = MI.getOperand(i);
1085 if (!DefMO.isReg() || !DefMO.isDef())
1088 unsigned Reg = DefMO.getReg();
1089 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1092 if (!TII->hasLowDefLatency(SchedModel, &MI, i))
1100 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
1101 /// if hoisting an instruction of the given cost matrix can cause high
1102 /// register pressure.
1103 bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1105 for (const auto &RPIdAndCost : Cost) {
1106 if (RPIdAndCost.second <= 0)
1109 unsigned Class = RPIdAndCost.first;
1110 int Limit = RegLimit[Class];
1112 // Don't hoist cheap instructions if they would increase register pressure,
1113 // even if we're under the limit.
1114 if (CheapInstr && !HoistCheapInsts)
1117 for (const auto &RP : BackTrace)
1118 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1125 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1126 /// current block and update their register pressures to reflect the effect
1127 /// of hoisting MI from the current block to the preheader.
1128 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1129 // First compute the 'cost' of the instruction, i.e. its contribution
1130 // to register pressure.
1131 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1132 /*ConsiderUnseenAsDef=*/false);
1134 // Update register pressure of blocks from loop header to current block.
1135 for (auto &RP : BackTrace)
1136 for (const auto &RPIdAndCost : Cost)
1137 RP[RPIdAndCost.first] += RPIdAndCost.second;
1140 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1141 /// the given loop invariant.
1142 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1143 if (MI.isImplicitDef())
1146 // Besides removing computation from the loop, hoisting an instruction has
1149 // - The value defined by the instruction becomes live across the entire
1150 // loop. This increases register pressure in the loop.
1152 // - If the value is used by a PHI in the loop, a copy will be required for
1153 // lowering the PHI after extending the live range.
1155 // - When hoisting the last use of a value in the loop, that value no longer
1156 // needs to be live in the loop. This lowers register pressure in the loop.
1158 bool CheapInstr = IsCheapInstruction(MI);
1159 bool CreatesCopy = HasLoopPHIUse(&MI);
1161 // Don't hoist a cheap instruction if it would create a copy in the loop.
1162 if (CheapInstr && CreatesCopy) {
1163 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1167 // Rematerializable instructions should always be hoisted since the register
1168 // allocator can just pull them down again when needed.
1169 if (TII->isTriviallyReMaterializable(&MI, AA))
1172 // FIXME: If there are long latency loop-invariant instructions inside the
1173 // loop at this point, why didn't the optimizer's LICM hoist them?
1174 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1175 const MachineOperand &MO = MI.getOperand(i);
1176 if (!MO.isReg() || MO.isImplicit())
1178 unsigned Reg = MO.getReg();
1179 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1181 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1182 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1188 // Estimate register pressure to determine whether to LICM the instruction.
1189 // In low register pressure situation, we can be more aggressive about
1190 // hoisting. Also, favors hoisting long latency instructions even in
1191 // moderately high pressure situation.
1192 // Cheap instructions will only be hoisted if they don't increase register
1194 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1195 /*ConsiderUnseenAsDef=*/false);
1197 // Visit BBs from header to current BB, if hoisting this doesn't cause
1198 // high register pressure, then it's safe to proceed.
1199 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1200 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1205 // Don't risk increasing register pressure if it would create copies.
1207 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1211 // Do not "speculate" in high register pressure situation. If an
1212 // instruction is not guaranteed to be executed in the loop, it's best to be
1214 if (AvoidSpeculation &&
1215 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1216 DEBUG(dbgs() << "Won't speculate: " << MI);
1220 // High register pressure situation, only hoist if the instruction is going
1222 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1223 !MI.isInvariantLoad(AA)) {
1224 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1231 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1232 // Don't unfold simple loads.
1233 if (MI->canFoldAsLoad())
1236 // If not, we may be able to unfold a load and hoist that.
1237 // First test whether the instruction is loading from an amenable
1239 if (!MI->isInvariantLoad(AA))
1242 // Next determine the register class for a temporary register.
1243 unsigned LoadRegIndex;
1245 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1246 /*UnfoldLoad=*/true,
1247 /*UnfoldStore=*/false,
1249 if (NewOpc == 0) return nullptr;
1250 const MCInstrDesc &MID = TII->get(NewOpc);
1251 if (MID.getNumDefs() != 1) return nullptr;
1252 MachineFunction &MF = *MI->getParent()->getParent();
1253 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1254 // Ok, we're unfolding. Create a temporary register and do the unfold.
1255 unsigned Reg = MRI->createVirtualRegister(RC);
1257 SmallVector<MachineInstr *, 2> NewMIs;
1259 TII->unfoldMemoryOperand(MF, MI, Reg,
1260 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1264 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1266 assert(NewMIs.size() == 2 &&
1267 "Unfolded a load into multiple instructions!");
1268 MachineBasicBlock *MBB = MI->getParent();
1269 MachineBasicBlock::iterator Pos = MI;
1270 MBB->insert(Pos, NewMIs[0]);
1271 MBB->insert(Pos, NewMIs[1]);
1272 // If unfolding produced a load that wasn't loop-invariant or profitable to
1273 // hoist, discard the new instructions and bail.
1274 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1275 NewMIs[0]->eraseFromParent();
1276 NewMIs[1]->eraseFromParent();
1280 // Update register pressure for the unfolded instruction.
1281 UpdateRegPressure(NewMIs[1]);
1283 // Otherwise we successfully unfolded a load that we can hoist.
1284 MI->eraseFromParent();
1288 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1289 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1290 const MachineInstr *MI = &*I;
1291 unsigned Opcode = MI->getOpcode();
1292 CSEMap[Opcode].push_back(MI);
1297 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1298 std::vector<const MachineInstr*> &PrevMIs) {
1299 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1300 const MachineInstr *PrevMI = PrevMIs[i];
1301 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
1307 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1308 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1309 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1310 // the undef property onto uses.
1311 if (CI == CSEMap.end() || MI->isImplicitDef())
1314 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1315 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1317 // Replace virtual registers defined by MI by their counterparts defined
1319 SmallVector<unsigned, 2> Defs;
1320 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1321 const MachineOperand &MO = MI->getOperand(i);
1323 // Physical registers may not differ here.
1324 assert((!MO.isReg() || MO.getReg() == 0 ||
1325 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1326 MO.getReg() == Dup->getOperand(i).getReg()) &&
1327 "Instructions with different phys regs are not identical!");
1329 if (MO.isReg() && MO.isDef() &&
1330 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1334 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1335 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1336 unsigned Idx = Defs[i];
1337 unsigned Reg = MI->getOperand(Idx).getReg();
1338 unsigned DupReg = Dup->getOperand(Idx).getReg();
1339 OrigRCs.push_back(MRI->getRegClass(DupReg));
1341 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1342 // Restore old RCs if more than one defs.
1343 for (unsigned j = 0; j != i; ++j)
1344 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1349 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1350 unsigned Idx = Defs[i];
1351 unsigned Reg = MI->getOperand(Idx).getReg();
1352 unsigned DupReg = Dup->getOperand(Idx).getReg();
1353 MRI->replaceRegWith(Reg, DupReg);
1354 MRI->clearKillFlags(DupReg);
1357 MI->eraseFromParent();
1364 /// MayCSE - Return true if the given instruction will be CSE'd if it's
1365 /// hoisted out of the loop.
1366 bool MachineLICM::MayCSE(MachineInstr *MI) {
1367 unsigned Opcode = MI->getOpcode();
1368 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1369 CI = CSEMap.find(Opcode);
1370 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1371 // the undef property onto uses.
1372 if (CI == CSEMap.end() || MI->isImplicitDef())
1375 return LookForDuplicate(MI, CI->second) != nullptr;
1378 /// Hoist - When an instruction is found to use only loop invariant operands
1379 /// that are safe to hoist, this instruction is called to do the dirty work.
1381 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1382 // First check whether we should hoist this instruction.
1383 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1384 // If not, try unfolding a hoistable load.
1385 MI = ExtractHoistableLoad(MI);
1386 if (!MI) return false;
1389 // Now move the instructions to the predecessor, inserting it before any
1390 // terminator instructions.
1392 dbgs() << "Hoisting " << *MI;
1393 if (Preheader->getBasicBlock())
1394 dbgs() << " to MachineBasicBlock "
1395 << Preheader->getName();
1396 if (MI->getParent()->getBasicBlock())
1397 dbgs() << " from MachineBasicBlock "
1398 << MI->getParent()->getName();
1402 // If this is the first instruction being hoisted to the preheader,
1403 // initialize the CSE map with potential common expressions.
1405 InitCSEMap(Preheader);
1406 FirstInLoop = false;
1409 // Look for opportunity to CSE the hoisted instruction.
1410 unsigned Opcode = MI->getOpcode();
1411 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1412 CI = CSEMap.find(Opcode);
1413 if (!EliminateCSE(MI, CI)) {
1414 // Otherwise, splice the instruction to the preheader.
1415 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1417 // Update register pressure for BBs from header to this block.
1418 UpdateBackTraceRegPressure(MI);
1420 // Clear the kill flags of any register this instruction defines,
1421 // since they may need to be live throughout the entire loop
1422 // rather than just live for part of it.
1423 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1424 MachineOperand &MO = MI->getOperand(i);
1425 if (MO.isReg() && MO.isDef() && !MO.isDead())
1426 MRI->clearKillFlags(MO.getReg());
1429 // Add to the CSE map.
1430 if (CI != CSEMap.end())
1431 CI->second.push_back(MI);
1433 CSEMap[Opcode].push_back(MI);
1442 MachineBasicBlock *MachineLICM::getCurPreheader() {
1443 // Determine the block to which to hoist instructions. If we can't find a
1444 // suitable loop predecessor, we can't do any hoisting.
1446 // If we've tried to get a preheader and failed, don't try again.
1447 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1450 if (!CurPreheader) {
1451 CurPreheader = CurLoop->getLoopPreheader();
1452 if (!CurPreheader) {
1453 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1455 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1459 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1460 if (!CurPreheader) {
1461 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1466 return CurPreheader;