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/MC/MCInstrItineraries.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 const InstrItineraryData *InstrItins;
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 class. 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<AliasAnalysis>();
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 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
255 /// index, return the ID and cost of its representative register class by
257 void getRegisterClassIDAndCost(const MachineInstr *MI,
258 unsigned Reg, unsigned OpIdx,
259 unsigned &RCId, unsigned &RCCost) const;
261 /// InitRegPressure - Find all virtual register references that are liveout
262 /// of the preheader to initialize the starting "register pressure". Note
263 /// this does not count live through (livein but not used) registers.
264 void InitRegPressure(MachineBasicBlock *BB);
266 /// calcRegisterCost - Calculate the additional register pressure that the
267 /// registers used in MI cause.
269 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
270 /// figure out which usages are live-ins.
271 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
272 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
274 bool ConsiderUnseenAsDef);
276 /// UpdateRegPressure - Update estimate of register pressure after the
277 /// specified instruction.
278 void UpdateRegPressure(const MachineInstr *MI,
279 bool ConsiderUnseenAsDef = false);
281 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
282 /// the load itself could be hoisted. Return the unfolded and hoistable
283 /// load, or null if the load couldn't be unfolded or if it wouldn't
285 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
287 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
288 /// duplicate of MI. Return this instruction if it's found.
289 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
290 std::vector<const MachineInstr*> &PrevMIs);
292 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
293 /// the preheader that compute the same value. If it's found, do a RAU on
294 /// with the definition of the existing instruction rather than hoisting
295 /// the instruction to the preheader.
296 bool EliminateCSE(MachineInstr *MI,
297 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
299 /// MayCSE - Return true if the given instruction will be CSE'd if it's
300 /// hoisted out of the loop.
301 bool MayCSE(MachineInstr *MI);
303 /// Hoist - When an instruction is found to only use loop invariant operands
304 /// that is safe to hoist, this instruction is called to do the dirty work.
305 /// It returns true if the instruction is hoisted.
306 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
308 /// InitCSEMap - Initialize the CSE map with instructions that are in the
309 /// current loop preheader that may become duplicates of instructions that
310 /// are hoisted out of the loop.
311 void InitCSEMap(MachineBasicBlock *BB);
313 /// getCurPreheader - Get the preheader for the current loop, splitting
314 /// a critical edge if needed.
315 MachineBasicBlock *getCurPreheader();
317 } // end anonymous namespace
319 char MachineLICM::ID = 0;
320 char &llvm::MachineLICMID = MachineLICM::ID;
321 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
322 "Machine Loop Invariant Code Motion", false, false)
323 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
324 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
325 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
326 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
327 "Machine Loop Invariant Code Motion", false, false)
329 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
330 /// loop that has a unique predecessor.
331 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
332 // Check whether this loop even has a unique predecessor.
333 if (!CurLoop->getLoopPredecessor())
335 // Ok, now check to see if any of its outer loops do.
336 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
337 if (L->getLoopPredecessor())
339 // None of them did, so this is the outermost with a unique predecessor.
343 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
344 if (skipOptnoneFunction(*MF.getFunction()))
347 Changed = FirstInLoop = false;
348 TII = MF.getSubtarget().getInstrInfo();
349 TLI = MF.getSubtarget().getTargetLowering();
350 TRI = MF.getSubtarget().getRegisterInfo();
351 MFI = MF.getFrameInfo();
352 MRI = &MF.getRegInfo();
353 InstrItins = MF.getSubtarget().getInstrItineraryData();
355 PreRegAlloc = MRI->isSSA();
358 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
360 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
361 DEBUG(dbgs() << MF.getName() << " ********\n");
364 // Estimate register pressure during pre-regalloc pass.
365 unsigned NumRC = TRI->getNumRegClasses();
366 RegPressure.resize(NumRC);
367 std::fill(RegPressure.begin(), RegPressure.end(), 0);
368 RegLimit.resize(NumRC);
369 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
370 E = TRI->regclass_end(); I != E; ++I)
371 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
374 // Get our Loop information...
375 MLI = &getAnalysis<MachineLoopInfo>();
376 DT = &getAnalysis<MachineDominatorTree>();
377 AA = &getAnalysis<AliasAnalysis>();
379 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
380 while (!Worklist.empty()) {
381 CurLoop = Worklist.pop_back_val();
382 CurPreheader = nullptr;
385 // If this is done before regalloc, only visit outer-most preheader-sporting
387 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
388 Worklist.append(CurLoop->begin(), CurLoop->end());
392 CurLoop->getExitBlocks(ExitBlocks);
397 // CSEMap is initialized for loop header when the first instruction is
399 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
404 if (SinkInstsToAvoidSpills)
412 /// InstructionStoresToFI - Return true if instruction stores to the
414 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
415 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
416 oe = MI->memoperands_end(); o != oe; ++o) {
417 if (!(*o)->isStore() || !(*o)->getPseudoValue())
419 if (const FixedStackPseudoSourceValue *Value =
420 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
421 if (Value->getFrameIndex() == FI)
428 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
429 /// gather register def and frame object update information.
430 void MachineLICM::ProcessMI(MachineInstr *MI,
431 BitVector &PhysRegDefs,
432 BitVector &PhysRegClobbers,
433 SmallSet<int, 32> &StoredFIs,
434 SmallVectorImpl<CandidateInfo> &Candidates) {
435 bool RuledOut = false;
436 bool HasNonInvariantUse = false;
438 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
439 const MachineOperand &MO = MI->getOperand(i);
441 // Remember if the instruction stores to the frame index.
442 int FI = MO.getIndex();
443 if (!StoredFIs.count(FI) &&
444 MFI->isSpillSlotObjectIndex(FI) &&
445 InstructionStoresToFI(MI, FI))
446 StoredFIs.insert(FI);
447 HasNonInvariantUse = true;
451 // We can't hoist an instruction defining a physreg that is clobbered in
453 if (MO.isRegMask()) {
454 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
460 unsigned Reg = MO.getReg();
463 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
464 "Not expecting virtual register!");
467 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
468 // If it's using a non-loop-invariant register, then it's obviously not
470 HasNonInvariantUse = true;
474 if (MO.isImplicit()) {
475 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
476 PhysRegClobbers.set(*AI);
478 // Non-dead implicit def? This cannot be hoisted.
480 // No need to check if a dead implicit def is also defined by
481 // another instruction.
485 // FIXME: For now, avoid instructions with multiple defs, unless
486 // it's a dead implicit def.
492 // If we have already seen another instruction that defines the same
493 // register, then this is not safe. Two defs is indicated by setting a
494 // PhysRegClobbers bit.
495 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
496 if (PhysRegDefs.test(*AS))
497 PhysRegClobbers.set(*AS);
498 PhysRegDefs.set(*AS);
500 if (PhysRegClobbers.test(Reg))
501 // MI defined register is seen defined by another instruction in
502 // the loop, it cannot be a LICM candidate.
506 // Only consider reloads for now and remats which do not have register
507 // operands. FIXME: Consider unfold load folding instructions.
508 if (Def && !RuledOut) {
510 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
511 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
512 Candidates.push_back(CandidateInfo(MI, Def, FI));
516 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
517 /// invariants out to the preheader.
518 void MachineLICM::HoistRegionPostRA() {
519 MachineBasicBlock *Preheader = getCurPreheader();
523 unsigned NumRegs = TRI->getNumRegs();
524 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
525 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
527 SmallVector<CandidateInfo, 32> Candidates;
528 SmallSet<int, 32> StoredFIs;
530 // Walk the entire region, count number of defs for each register, and
531 // collect potential LICM candidates.
532 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
533 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
534 MachineBasicBlock *BB = Blocks[i];
536 // If the header of the loop containing this basic block is a landing pad,
537 // then don't try to hoist instructions out of this loop.
538 const MachineLoop *ML = MLI->getLoopFor(BB);
539 if (ML && ML->getHeader()->isLandingPad()) continue;
541 // Conservatively treat live-in's as an external def.
542 // FIXME: That means a reload that're reused in successor block(s) will not
544 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
545 E = BB->livein_end(); I != E; ++I) {
547 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
548 PhysRegDefs.set(*AI);
551 SpeculationState = SpeculateUnknown;
552 for (MachineBasicBlock::iterator
553 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
554 MachineInstr *MI = &*MII;
555 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
559 // Gather the registers read / clobbered by the terminator.
560 BitVector TermRegs(NumRegs);
561 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
562 if (TI != Preheader->end()) {
563 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
564 const MachineOperand &MO = TI->getOperand(i);
567 unsigned Reg = MO.getReg();
570 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
575 // Now evaluate whether the potential candidates qualify.
576 // 1. Check if the candidate defined register is defined by another
577 // instruction in the loop.
578 // 2. If the candidate is a load from stack slot (always true for now),
579 // check if the slot is stored anywhere in the loop.
580 // 3. Make sure candidate def should not clobber
581 // registers read by the terminator. Similarly its def should not be
582 // clobbered by the terminator.
583 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
584 if (Candidates[i].FI != INT_MIN &&
585 StoredFIs.count(Candidates[i].FI))
588 unsigned Def = Candidates[i].Def;
589 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
591 MachineInstr *MI = Candidates[i].MI;
592 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
593 const MachineOperand &MO = MI->getOperand(j);
594 if (!MO.isReg() || MO.isDef() || !MO.getReg())
596 unsigned Reg = MO.getReg();
597 if (PhysRegDefs.test(Reg) ||
598 PhysRegClobbers.test(Reg)) {
599 // If it's using a non-loop-invariant register, then it's obviously
600 // not safe to hoist.
606 HoistPostRA(MI, Candidates[i].Def);
611 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
612 /// loop, and make sure it is not killed by any instructions in the loop.
613 void MachineLICM::AddToLiveIns(unsigned Reg) {
614 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
615 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
616 MachineBasicBlock *BB = Blocks[i];
617 if (!BB->isLiveIn(Reg))
619 for (MachineBasicBlock::iterator
620 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
621 MachineInstr *MI = &*MII;
622 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
623 MachineOperand &MO = MI->getOperand(i);
624 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
625 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
632 /// HoistPostRA - When an instruction is found to only use loop invariant
633 /// operands that is safe to hoist, this instruction is called to do the
635 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
636 MachineBasicBlock *Preheader = getCurPreheader();
638 // Now move the instructions to the predecessor, inserting it before any
639 // terminator instructions.
640 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
641 << MI->getParent()->getNumber() << ": " << *MI);
643 // Splice the instruction to the preheader.
644 MachineBasicBlock *MBB = MI->getParent();
645 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
647 // Add register to livein list to all the BBs in the current loop since a
648 // loop invariant must be kept live throughout the whole loop. This is
649 // important to ensure later passes do not scavenge the def register.
656 // IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
657 // If not then a load from this mbb may not be safe to hoist.
658 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
659 if (SpeculationState != SpeculateUnknown)
660 return SpeculationState == SpeculateFalse;
662 if (BB != CurLoop->getHeader()) {
663 // Check loop exiting blocks.
664 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
665 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
666 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
667 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
668 SpeculationState = SpeculateTrue;
673 SpeculationState = SpeculateFalse;
677 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
678 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
680 // Remember livein register pressure.
681 BackTrace.push_back(RegPressure);
684 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
685 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
686 BackTrace.pop_back();
689 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
690 /// dominator tree node if its a leaf or all of its children are done. Walk
691 /// up the dominator tree to destroy ancestors which are now done.
692 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
693 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
694 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
695 if (OpenChildren[Node])
699 ExitScope(Node->getBlock());
701 // Now traverse upwards to pop ancestors whose offsprings are all done.
702 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
703 unsigned Left = --OpenChildren[Parent];
706 ExitScope(Parent->getBlock());
711 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
712 /// blocks dominated by the specified header block, and that are in the
713 /// current loop) in depth first order w.r.t the DominatorTree. This allows
714 /// us to visit definitions before uses, allowing us to hoist a loop body in
715 /// one pass without iteration.
717 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
718 MachineBasicBlock *Preheader = getCurPreheader();
722 SmallVector<MachineDomTreeNode*, 32> Scopes;
723 SmallVector<MachineDomTreeNode*, 8> WorkList;
724 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
725 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
727 // Perform a DFS walk to determine the order of visit.
728 WorkList.push_back(HeaderN);
729 while (!WorkList.empty()) {
730 MachineDomTreeNode *Node = WorkList.pop_back_val();
731 assert(Node && "Null dominator tree node?");
732 MachineBasicBlock *BB = Node->getBlock();
734 // If the header of the loop containing this basic block is a landing pad,
735 // then don't try to hoist instructions out of this loop.
736 const MachineLoop *ML = MLI->getLoopFor(BB);
737 if (ML && ML->getHeader()->isLandingPad())
740 // If this subregion is not in the top level loop at all, exit.
741 if (!CurLoop->contains(BB))
744 Scopes.push_back(Node);
745 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
746 unsigned NumChildren = Children.size();
748 // Don't hoist things out of a large switch statement. This often causes
749 // code to be hoisted that wasn't going to be executed, and increases
750 // register pressure in a situation where it's likely to matter.
751 if (BB->succ_size() >= 25)
754 OpenChildren[Node] = NumChildren;
755 // Add children in reverse order as then the next popped worklist node is
756 // the first child of this node. This means we ultimately traverse the
757 // DOM tree in exactly the same order as if we'd recursed.
758 for (int i = (int)NumChildren-1; i >= 0; --i) {
759 MachineDomTreeNode *Child = Children[i];
760 ParentMap[Child] = Node;
761 WorkList.push_back(Child);
765 if (Scopes.size() == 0)
768 // Compute registers which are livein into the loop headers.
771 InitRegPressure(Preheader);
774 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
775 MachineDomTreeNode *Node = Scopes[i];
776 MachineBasicBlock *MBB = Node->getBlock();
781 SpeculationState = SpeculateUnknown;
782 for (MachineBasicBlock::iterator
783 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
784 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
785 MachineInstr *MI = &*MII;
786 if (!Hoist(MI, Preheader))
787 UpdateRegPressure(MI);
791 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
792 ExitScopeIfDone(Node, OpenChildren, ParentMap);
796 void MachineLICM::SinkIntoLoop() {
797 MachineBasicBlock *Preheader = getCurPreheader();
801 SmallVector<MachineInstr *, 8> Candidates;
802 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
803 I != Preheader->instr_end(); ++I) {
804 // We need to ensure that we can safely move this instruction into the loop.
805 // As such, it must not have side-effects, e.g. such as a call has.
806 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(I))
807 Candidates.push_back(I);
810 for (MachineInstr *I : Candidates) {
811 const MachineOperand &MO = I->getOperand(0);
812 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
814 if (!MRI->hasOneDef(MO.getReg()))
817 MachineBasicBlock *B = nullptr;
818 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
819 // FIXME: Come up with a proper cost model that estimates whether sinking
820 // the instruction (and thus possibly executing it on every loop
821 // iteration) is more expensive than a register.
822 // For now assumes that copies are cheap and thus almost always worth it.
831 B = DT->findNearestCommonDominator(B, MI.getParent());
837 if (!CanSink || !B || B == Preheader)
839 B->splice(B->getFirstNonPHI(), Preheader, I);
843 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
844 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
847 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
848 /// index, return the ID and cost of its representative register class.
850 MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
851 unsigned Reg, unsigned OpIdx,
852 unsigned &RCId, unsigned &RCCost) const {
853 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
854 MVT VT = *RC->vt_begin();
855 if (VT == MVT::Untyped) {
859 RCId = TLI->getRepRegClassFor(VT)->getID();
860 RCCost = TLI->getRepRegClassCostFor(VT);
864 /// InitRegPressure - Find all virtual register references that are liveout of
865 /// the preheader to initialize the starting "register pressure". Note this
866 /// does not count live through (livein but not used) registers.
867 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
868 std::fill(RegPressure.begin(), RegPressure.end(), 0);
870 // If the preheader has only a single predecessor and it ends with a
871 // fallthrough or an unconditional branch, then scan its predecessor for live
872 // defs as well. This happens whenever the preheader is created by splitting
873 // the critical edge from the loop predecessor to the loop header.
874 if (BB->pred_size() == 1) {
875 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
876 SmallVector<MachineOperand, 4> Cond;
877 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
878 InitRegPressure(*BB->pred_begin());
881 for (const MachineInstr &MI : *BB)
882 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
885 /// UpdateRegPressure - Update estimate of register pressure after the
886 /// specified instruction.
887 void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
888 bool ConsiderUnseenAsDef) {
889 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
890 for (const auto &ClassAndCost : Cost) {
891 unsigned Class = ClassAndCost.first;
892 if (static_cast<int>(RegPressure[Class]) < -ClassAndCost.second)
893 RegPressure[Class] = 0;
895 RegPressure[Class] += ClassAndCost.second;
899 DenseMap<unsigned, int>
900 MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
901 bool ConsiderUnseenAsDef) {
902 DenseMap<unsigned, int> Cost;
903 if (MI->isImplicitDef())
905 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
906 const MachineOperand &MO = MI->getOperand(i);
907 if (!MO.isReg() || MO.isImplicit())
909 unsigned Reg = MO.getReg();
910 if (!TargetRegisterInfo::isVirtualRegister(Reg))
913 // FIXME: It seems bad to use RegSeen only for some of these calculations.
914 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
915 unsigned RCId, RCCost;
916 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
918 if (Cost.find(RCId) != Cost.end())
919 PriorCost = Cost[RCId];
921 Cost[RCId] = PriorCost + RCCost;
923 bool isKill = isOperandKill(MO, MRI);
924 if (isNew && !isKill && ConsiderUnseenAsDef)
925 // Haven't seen this, it must be a livein.
926 Cost[RCId] = PriorCost + RCCost;
927 else if (!isNew && isKill)
928 Cost[RCId] = PriorCost - RCCost;
934 /// isLoadFromGOTOrConstantPool - Return true if this machine instruction
935 /// loads from global offset table or constant pool.
936 static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
937 assert (MI.mayLoad() && "Expected MI that loads!");
938 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
939 E = MI.memoperands_end(); I != E; ++I) {
940 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
941 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
948 /// IsLICMCandidate - Returns true if the instruction may be a suitable
949 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
950 /// not safe to hoist it.
951 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
952 // Check if it's safe to move the instruction.
953 bool DontMoveAcrossStore = true;
954 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
957 // If it is load then check if it is guaranteed to execute by making sure that
958 // it dominates all exiting blocks. If it doesn't, then there is a path out of
959 // the loop which does not execute this load, so we can't hoist it. Loads
960 // from constant memory are not safe to speculate all the time, for example
961 // indexed load from a jump table.
962 // Stores and side effects are already checked by isSafeToMove.
963 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
964 !IsGuaranteedToExecute(I.getParent()))
970 /// IsLoopInvariantInst - Returns true if the instruction is loop
971 /// invariant. I.e., all virtual register operands are defined outside of the
972 /// loop, physical registers aren't accessed explicitly, and there are no side
973 /// effects that aren't captured by the operands or other flags.
975 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
976 if (!IsLICMCandidate(I))
979 // The instruction is loop invariant if all of its operands are.
980 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
981 const MachineOperand &MO = I.getOperand(i);
986 unsigned Reg = MO.getReg();
987 if (Reg == 0) continue;
989 // Don't hoist an instruction that uses or defines a physical register.
990 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
992 // If the physreg has no defs anywhere, it's just an ambient register
993 // and we can freely move its uses. Alternatively, if it's allocatable,
994 // it could get allocated to something with a def during allocation.
995 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
997 // Otherwise it's safe to move.
999 } else if (!MO.isDead()) {
1000 // A def that isn't dead. We can't move it.
1002 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1003 // If the reg is live into the loop, we can't hoist an instruction
1004 // which would clobber it.
1012 assert(MRI->getVRegDef(Reg) &&
1013 "Machine instr not mapped for this vreg?!");
1015 // If the loop contains the definition of an operand, then the instruction
1016 // isn't loop invariant.
1017 if (CurLoop->contains(MRI->getVRegDef(Reg)))
1021 // If we got this far, the instruction is loop invariant!
1026 /// HasLoopPHIUse - Return true if the specified instruction is used by a
1027 /// phi node and hoisting it could cause a copy to be inserted.
1028 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
1029 SmallVector<const MachineInstr*, 8> Work(1, MI);
1031 MI = Work.pop_back_val();
1032 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1033 if (!MO->isReg() || !MO->isDef())
1035 unsigned Reg = MO->getReg();
1036 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1038 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1039 // A PHI may cause a copy to be inserted.
1040 if (UseMI.isPHI()) {
1041 // A PHI inside the loop causes a copy because the live range of Reg is
1042 // extended across the PHI.
1043 if (CurLoop->contains(&UseMI))
1045 // A PHI in an exit block can cause a copy to be inserted if the PHI
1046 // has multiple predecessors in the loop with different values.
1047 // For now, approximate by rejecting all exit blocks.
1048 if (isExitBlock(UseMI.getParent()))
1052 // Look past copies as well.
1053 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1054 Work.push_back(&UseMI);
1057 } while (!Work.empty());
1061 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1062 /// and an use in the current loop, return true if the target considered
1064 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
1065 unsigned DefIdx, unsigned Reg) const {
1066 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
1069 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1070 if (UseMI.isCopyLike())
1072 if (!CurLoop->contains(UseMI.getParent()))
1074 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1075 const MachineOperand &MO = UseMI.getOperand(i);
1076 if (!MO.isReg() || !MO.isUse())
1078 unsigned MOReg = MO.getReg();
1082 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
1086 // Only look at the first in loop use.
1093 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1094 /// the operand latency between its def and a use is one or less.
1095 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
1096 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
1098 if (!InstrItins || InstrItins->isEmpty())
1101 bool isCheap = false;
1102 unsigned NumDefs = MI.getDesc().getNumDefs();
1103 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1104 MachineOperand &DefMO = MI.getOperand(i);
1105 if (!DefMO.isReg() || !DefMO.isDef())
1108 unsigned Reg = DefMO.getReg();
1109 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1112 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1120 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
1121 /// if hoisting an instruction of the given cost matrix can cause high
1122 /// register pressure.
1123 bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1125 for (const auto &ClassAndCost : Cost) {
1126 if (ClassAndCost.second <= 0)
1129 unsigned Class = ClassAndCost.first;
1130 int Limit = RegLimit[Class];
1132 // Don't hoist cheap instructions if they would increase register pressure,
1133 // even if we're under the limit.
1134 if (CheapInstr && !HoistCheapInsts)
1137 for (const auto &RP : BackTrace)
1138 if (static_cast<int>(RP[Class]) + ClassAndCost.second >= Limit)
1145 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1146 /// current block and update their register pressures to reflect the effect
1147 /// of hoisting MI from the current block to the preheader.
1148 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1149 // First compute the 'cost' of the instruction, i.e. its contribution
1150 // to register pressure.
1151 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1152 /*ConsiderUnseenAsDef=*/false);
1154 // Update register pressure of blocks from loop header to current block.
1155 for (auto &RP : BackTrace)
1156 for (const auto &ClassAndCost : Cost)
1157 RP[ClassAndCost.first] += ClassAndCost.second;
1160 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1161 /// the given loop invariant.
1162 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1163 if (MI.isImplicitDef())
1166 // Besides removing computation from the loop, hoisting an instruction has
1169 // - The value defined by the instruction becomes live across the entire
1170 // loop. This increases register pressure in the loop.
1172 // - If the value is used by a PHI in the loop, a copy will be required for
1173 // lowering the PHI after extending the live range.
1175 // - When hoisting the last use of a value in the loop, that value no longer
1176 // needs to be live in the loop. This lowers register pressure in the loop.
1178 bool CheapInstr = IsCheapInstruction(MI);
1179 bool CreatesCopy = HasLoopPHIUse(&MI);
1181 // Don't hoist a cheap instruction if it would create a copy in the loop.
1182 if (CheapInstr && CreatesCopy) {
1183 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1187 // Rematerializable instructions should always be hoisted since the register
1188 // allocator can just pull them down again when needed.
1189 if (TII->isTriviallyReMaterializable(&MI, AA))
1192 // FIXME: If there are long latency loop-invariant instructions inside the
1193 // loop at this point, why didn't the optimizer's LICM hoist them?
1194 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1195 const MachineOperand &MO = MI.getOperand(i);
1196 if (!MO.isReg() || MO.isImplicit())
1198 unsigned Reg = MO.getReg();
1199 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1201 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1202 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1208 // Estimate register pressure to determine whether to LICM the instruction.
1209 // In low register pressure situation, we can be more aggressive about
1210 // hoisting. Also, favors hoisting long latency instructions even in
1211 // moderately high pressure situation.
1212 // Cheap instructions will only be hoisted if they don't increase register
1214 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1215 /*ConsiderUnseenAsDef=*/false);
1217 // Visit BBs from header to current BB, if hoisting this doesn't cause
1218 // high register pressure, then it's safe to proceed.
1219 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1220 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1225 // Don't risk increasing register pressure if it would create copies.
1227 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1231 // Do not "speculate" in high register pressure situation. If an
1232 // instruction is not guaranteed to be executed in the loop, it's best to be
1234 if (AvoidSpeculation &&
1235 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1236 DEBUG(dbgs() << "Won't speculate: " << MI);
1240 // High register pressure situation, only hoist if the instruction is going
1242 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1243 !MI.isInvariantLoad(AA)) {
1244 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1251 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1252 // Don't unfold simple loads.
1253 if (MI->canFoldAsLoad())
1256 // If not, we may be able to unfold a load and hoist that.
1257 // First test whether the instruction is loading from an amenable
1259 if (!MI->isInvariantLoad(AA))
1262 // Next determine the register class for a temporary register.
1263 unsigned LoadRegIndex;
1265 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1266 /*UnfoldLoad=*/true,
1267 /*UnfoldStore=*/false,
1269 if (NewOpc == 0) return nullptr;
1270 const MCInstrDesc &MID = TII->get(NewOpc);
1271 if (MID.getNumDefs() != 1) return nullptr;
1272 MachineFunction &MF = *MI->getParent()->getParent();
1273 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1274 // Ok, we're unfolding. Create a temporary register and do the unfold.
1275 unsigned Reg = MRI->createVirtualRegister(RC);
1277 SmallVector<MachineInstr *, 2> NewMIs;
1279 TII->unfoldMemoryOperand(MF, MI, Reg,
1280 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1284 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1286 assert(NewMIs.size() == 2 &&
1287 "Unfolded a load into multiple instructions!");
1288 MachineBasicBlock *MBB = MI->getParent();
1289 MachineBasicBlock::iterator Pos = MI;
1290 MBB->insert(Pos, NewMIs[0]);
1291 MBB->insert(Pos, NewMIs[1]);
1292 // If unfolding produced a load that wasn't loop-invariant or profitable to
1293 // hoist, discard the new instructions and bail.
1294 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1295 NewMIs[0]->eraseFromParent();
1296 NewMIs[1]->eraseFromParent();
1300 // Update register pressure for the unfolded instruction.
1301 UpdateRegPressure(NewMIs[1]);
1303 // Otherwise we successfully unfolded a load that we can hoist.
1304 MI->eraseFromParent();
1308 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1309 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1310 const MachineInstr *MI = &*I;
1311 unsigned Opcode = MI->getOpcode();
1312 CSEMap[Opcode].push_back(MI);
1317 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1318 std::vector<const MachineInstr*> &PrevMIs) {
1319 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1320 const MachineInstr *PrevMI = PrevMIs[i];
1321 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
1327 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1328 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1329 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1330 // the undef property onto uses.
1331 if (CI == CSEMap.end() || MI->isImplicitDef())
1334 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1335 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1337 // Replace virtual registers defined by MI by their counterparts defined
1339 SmallVector<unsigned, 2> Defs;
1340 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1341 const MachineOperand &MO = MI->getOperand(i);
1343 // Physical registers may not differ here.
1344 assert((!MO.isReg() || MO.getReg() == 0 ||
1345 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1346 MO.getReg() == Dup->getOperand(i).getReg()) &&
1347 "Instructions with different phys regs are not identical!");
1349 if (MO.isReg() && MO.isDef() &&
1350 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1354 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
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 OrigRCs.push_back(MRI->getRegClass(DupReg));
1361 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1362 // Restore old RCs if more than one defs.
1363 for (unsigned j = 0; j != i; ++j)
1364 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1369 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1370 unsigned Idx = Defs[i];
1371 unsigned Reg = MI->getOperand(Idx).getReg();
1372 unsigned DupReg = Dup->getOperand(Idx).getReg();
1373 MRI->replaceRegWith(Reg, DupReg);
1374 MRI->clearKillFlags(DupReg);
1377 MI->eraseFromParent();
1384 /// MayCSE - Return true if the given instruction will be CSE'd if it's
1385 /// hoisted out of the loop.
1386 bool MachineLICM::MayCSE(MachineInstr *MI) {
1387 unsigned Opcode = MI->getOpcode();
1388 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1389 CI = CSEMap.find(Opcode);
1390 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1391 // the undef property onto uses.
1392 if (CI == CSEMap.end() || MI->isImplicitDef())
1395 return LookForDuplicate(MI, CI->second) != nullptr;
1398 /// Hoist - When an instruction is found to use only loop invariant operands
1399 /// that are safe to hoist, this instruction is called to do the dirty work.
1401 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1402 // First check whether we should hoist this instruction.
1403 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1404 // If not, try unfolding a hoistable load.
1405 MI = ExtractHoistableLoad(MI);
1406 if (!MI) return false;
1409 // Now move the instructions to the predecessor, inserting it before any
1410 // terminator instructions.
1412 dbgs() << "Hoisting " << *MI;
1413 if (Preheader->getBasicBlock())
1414 dbgs() << " to MachineBasicBlock "
1415 << Preheader->getName();
1416 if (MI->getParent()->getBasicBlock())
1417 dbgs() << " from MachineBasicBlock "
1418 << MI->getParent()->getName();
1422 // If this is the first instruction being hoisted to the preheader,
1423 // initialize the CSE map with potential common expressions.
1425 InitCSEMap(Preheader);
1426 FirstInLoop = false;
1429 // Look for opportunity to CSE the hoisted instruction.
1430 unsigned Opcode = MI->getOpcode();
1431 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1432 CI = CSEMap.find(Opcode);
1433 if (!EliminateCSE(MI, CI)) {
1434 // Otherwise, splice the instruction to the preheader.
1435 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1437 // Update register pressure for BBs from header to this block.
1438 UpdateBackTraceRegPressure(MI);
1440 // Clear the kill flags of any register this instruction defines,
1441 // since they may need to be live throughout the entire loop
1442 // rather than just live for part of it.
1443 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1444 MachineOperand &MO = MI->getOperand(i);
1445 if (MO.isReg() && MO.isDef() && !MO.isDead())
1446 MRI->clearKillFlags(MO.getReg());
1449 // Add to the CSE map.
1450 if (CI != CSEMap.end())
1451 CI->second.push_back(MI);
1453 CSEMap[Opcode].push_back(MI);
1462 MachineBasicBlock *MachineLICM::getCurPreheader() {
1463 // Determine the block to which to hoist instructions. If we can't find a
1464 // suitable loop predecessor, we can't do any hoisting.
1466 // If we've tried to get a preheader and failed, don't try again.
1467 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1470 if (!CurPreheader) {
1471 CurPreheader = CurLoop->getLoopPreheader();
1472 if (!CurPreheader) {
1473 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1475 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1479 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1480 if (!CurPreheader) {
1481 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1486 return CurPreheader;