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/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSchedule.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/MC/MCInstrDesc.h"
44 #include "llvm/MC/MCRegisterInfo.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
57 #define DEBUG_TYPE "machinelicm"
60 AvoidSpeculation("avoid-speculation",
61 cl::desc("MachineLICM should avoid speculation"),
62 cl::init(true), cl::Hidden);
65 HoistCheapInsts("hoist-cheap-insts",
66 cl::desc("MachineLICM should hoist even cheap instructions"),
67 cl::init(false), cl::Hidden);
70 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
71 cl::desc("MachineLICM should sink instructions into "
72 "loops to avoid register spills"),
73 cl::init(false), cl::Hidden);
76 "Number of machine instructions hoisted out of loops");
78 "Number of instructions hoisted in low reg pressure situation");
79 STATISTIC(NumHighLatency,
80 "Number of high latency instructions hoisted");
82 "Number of hoisted machine instructions CSEed");
83 STATISTIC(NumPostRAHoisted,
84 "Number of machine instructions hoisted out of loops post regalloc");
88 class MachineLICM : public MachineFunctionPass {
89 const TargetInstrInfo *TII;
90 const TargetLoweringBase *TLI;
91 const TargetRegisterInfo *TRI;
92 const MachineFrameInfo *MFI;
93 MachineRegisterInfo *MRI;
94 TargetSchedModel SchedModel;
95 bool PreRegAlloc = true;
97 // Various analyses that we use...
98 AliasAnalysis *AA; // Alias analysis info.
99 MachineLoopInfo *MLI; // Current MachineLoopInfo
100 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
102 // State that is updated as we process loops
103 bool Changed; // True if a loop is changed.
104 bool FirstInLoop; // True if it's the first LICM in the loop.
105 MachineLoop *CurLoop; // The current loop we are working on.
106 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
108 // Exit blocks for CurLoop.
109 SmallVector<MachineBasicBlock *, 8> ExitBlocks;
111 bool isExitBlock(const MachineBasicBlock *MBB) const {
112 return is_contained(ExitBlocks, MBB);
115 // Track 'estimated' register pressure.
116 SmallSet<unsigned, 32> RegSeen;
117 SmallVector<unsigned, 8> RegPressure;
119 // Register pressure "limit" per register pressure set. If the pressure
120 // is higher than the limit, then it's considered high.
121 SmallVector<unsigned, 8> RegLimit;
123 // Register pressure on path leading from loop preheader to current BB.
124 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
126 // For each opcode, keep a list of potential CSE instructions.
127 DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
135 // If a MBB does not dominate loop exiting blocks then it may not safe
136 // to hoist loads from this block.
137 // Tri-state: 0 - false, 1 - true, 2 - unknown
138 unsigned SpeculationState;
141 static char ID; // Pass identification, replacement for typeid
143 MachineLICM() : MachineFunctionPass(ID) {
144 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
147 explicit MachineLICM(bool PreRA)
148 : MachineFunctionPass(ID), PreRegAlloc(PreRA) {
149 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
152 bool runOnMachineFunction(MachineFunction &MF) override;
154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.addRequired<MachineLoopInfo>();
156 AU.addRequired<MachineDominatorTree>();
157 AU.addRequired<AAResultsWrapperPass>();
158 AU.addPreserved<MachineLoopInfo>();
159 AU.addPreserved<MachineDominatorTree>();
160 MachineFunctionPass::getAnalysisUsage(AU);
163 void releaseMemory() override {
172 /// Keep track of information about hoisting candidates.
173 struct CandidateInfo {
178 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
179 : MI(mi), Def(def), FI(fi) {}
182 void HoistRegionPostRA();
184 void HoistPostRA(MachineInstr *MI, unsigned Def);
186 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
187 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
188 SmallVectorImpl<CandidateInfo> &Candidates);
190 void AddToLiveIns(unsigned Reg);
192 bool IsLICMCandidate(MachineInstr &I);
194 bool IsLoopInvariantInst(MachineInstr &I);
196 bool HasLoopPHIUse(const MachineInstr *MI) const;
198 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
201 bool IsCheapInstruction(MachineInstr &MI) const;
203 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
206 void UpdateBackTraceRegPressure(const MachineInstr *MI);
208 bool IsProfitableToHoist(MachineInstr &MI);
210 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
212 void EnterScope(MachineBasicBlock *MBB);
214 void ExitScope(MachineBasicBlock *MBB);
216 void ExitScopeIfDone(
217 MachineDomTreeNode *Node,
218 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
219 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
221 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
223 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
227 void InitRegPressure(MachineBasicBlock *BB);
229 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
231 bool ConsiderUnseenAsDef);
233 void UpdateRegPressure(const MachineInstr *MI,
234 bool ConsiderUnseenAsDef = false);
236 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
239 LookForDuplicate(const MachineInstr *MI,
240 std::vector<const MachineInstr *> &PrevMIs);
244 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
246 bool MayCSE(MachineInstr *MI);
248 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
250 void InitCSEMap(MachineBasicBlock *BB);
252 MachineBasicBlock *getCurPreheader();
255 } // end anonymous namespace
257 char MachineLICM::ID = 0;
259 char &llvm::MachineLICMID = MachineLICM::ID;
261 INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
262 "Machine Loop Invariant Code Motion", false, false)
263 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
264 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
265 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
266 INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
267 "Machine Loop Invariant Code Motion", false, false)
269 /// Test if the given loop is the outer-most loop that has a unique predecessor.
270 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
271 // Check whether this loop even has a unique predecessor.
272 if (!CurLoop->getLoopPredecessor())
274 // Ok, now check to see if any of its outer loops do.
275 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
276 if (L->getLoopPredecessor())
278 // None of them did, so this is the outermost with a unique predecessor.
282 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
283 if (skipFunction(MF.getFunction()))
286 Changed = FirstInLoop = false;
287 const TargetSubtargetInfo &ST = MF.getSubtarget();
288 TII = ST.getInstrInfo();
289 TLI = ST.getTargetLowering();
290 TRI = ST.getRegisterInfo();
291 MFI = &MF.getFrameInfo();
292 MRI = &MF.getRegInfo();
293 SchedModel.init(ST.getSchedModel(), &ST, TII);
295 PreRegAlloc = MRI->isSSA();
298 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
300 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
301 DEBUG(dbgs() << MF.getName() << " ********\n");
304 // Estimate register pressure during pre-regalloc pass.
305 unsigned NumRPS = TRI->getNumRegPressureSets();
306 RegPressure.resize(NumRPS);
307 std::fill(RegPressure.begin(), RegPressure.end(), 0);
308 RegLimit.resize(NumRPS);
309 for (unsigned i = 0, e = NumRPS; i != e; ++i)
310 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
313 // Get our Loop information...
314 MLI = &getAnalysis<MachineLoopInfo>();
315 DT = &getAnalysis<MachineDominatorTree>();
316 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
318 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
319 while (!Worklist.empty()) {
320 CurLoop = Worklist.pop_back_val();
321 CurPreheader = nullptr;
324 // If this is done before regalloc, only visit outer-most preheader-sporting
326 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
327 Worklist.append(CurLoop->begin(), CurLoop->end());
331 CurLoop->getExitBlocks(ExitBlocks);
336 // CSEMap is initialized for loop header when the first instruction is
338 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
343 if (SinkInstsToAvoidSpills)
351 /// Return true if instruction stores to the specified frame.
352 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
353 // If we lost memory operands, conservatively assume that the instruction
354 // writes to all slots.
355 if (MI->memoperands_empty())
357 for (const MachineMemOperand *MemOp : MI->memoperands()) {
358 if (!MemOp->isStore() || !MemOp->getPseudoValue())
360 if (const FixedStackPseudoSourceValue *Value =
361 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
362 if (Value->getFrameIndex() == FI)
369 /// Examine the instruction for potentai LICM candidate. Also
370 /// gather register def and frame object update information.
371 void MachineLICM::ProcessMI(MachineInstr *MI,
372 BitVector &PhysRegDefs,
373 BitVector &PhysRegClobbers,
374 SmallSet<int, 32> &StoredFIs,
375 SmallVectorImpl<CandidateInfo> &Candidates) {
376 bool RuledOut = false;
377 bool HasNonInvariantUse = false;
379 for (const MachineOperand &MO : MI->operands()) {
381 // Remember if the instruction stores to the frame index.
382 int FI = MO.getIndex();
383 if (!StoredFIs.count(FI) &&
384 MFI->isSpillSlotObjectIndex(FI) &&
385 InstructionStoresToFI(MI, FI))
386 StoredFIs.insert(FI);
387 HasNonInvariantUse = true;
391 // We can't hoist an instruction defining a physreg that is clobbered in
393 if (MO.isRegMask()) {
394 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
400 unsigned Reg = MO.getReg();
403 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
404 "Not expecting virtual register!");
407 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
408 // If it's using a non-loop-invariant register, then it's obviously not
410 HasNonInvariantUse = true;
414 if (MO.isImplicit()) {
415 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
416 PhysRegClobbers.set(*AI);
418 // Non-dead implicit def? This cannot be hoisted.
420 // No need to check if a dead implicit def is also defined by
421 // another instruction.
425 // FIXME: For now, avoid instructions with multiple defs, unless
426 // it's a dead implicit def.
432 // If we have already seen another instruction that defines the same
433 // register, then this is not safe. Two defs is indicated by setting a
434 // PhysRegClobbers bit.
435 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
436 if (PhysRegDefs.test(*AS))
437 PhysRegClobbers.set(*AS);
438 PhysRegDefs.set(*AS);
440 if (PhysRegClobbers.test(Reg))
441 // MI defined register is seen defined by another instruction in
442 // the loop, it cannot be a LICM candidate.
446 // Only consider reloads for now and remats which do not have register
447 // operands. FIXME: Consider unfold load folding instructions.
448 if (Def && !RuledOut) {
449 int FI = std::numeric_limits<int>::min();
450 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
451 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
452 Candidates.push_back(CandidateInfo(MI, Def, FI));
456 /// Walk the specified region of the CFG and hoist loop invariants out to the
458 void MachineLICM::HoistRegionPostRA() {
459 MachineBasicBlock *Preheader = getCurPreheader();
463 unsigned NumRegs = TRI->getNumRegs();
464 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
465 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
467 SmallVector<CandidateInfo, 32> Candidates;
468 SmallSet<int, 32> StoredFIs;
470 // Walk the entire region, count number of defs for each register, and
471 // collect potential LICM candidates.
472 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
473 for (MachineBasicBlock *BB : Blocks) {
474 // If the header of the loop containing this basic block is a landing pad,
475 // then don't try to hoist instructions out of this loop.
476 const MachineLoop *ML = MLI->getLoopFor(BB);
477 if (ML && ML->getHeader()->isEHPad()) continue;
479 // Conservatively treat live-in's as an external def.
480 // FIXME: That means a reload that're reused in successor block(s) will not
482 for (const auto &LI : BB->liveins()) {
483 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
484 PhysRegDefs.set(*AI);
487 SpeculationState = SpeculateUnknown;
488 for (MachineInstr &MI : *BB)
489 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
492 // Gather the registers read / clobbered by the terminator.
493 BitVector TermRegs(NumRegs);
494 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
495 if (TI != Preheader->end()) {
496 for (const MachineOperand &MO : TI->operands()) {
499 unsigned Reg = MO.getReg();
502 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
507 // Now evaluate whether the potential candidates qualify.
508 // 1. Check if the candidate defined register is defined by another
509 // instruction in the loop.
510 // 2. If the candidate is a load from stack slot (always true for now),
511 // check if the slot is stored anywhere in the loop.
512 // 3. Make sure candidate def should not clobber
513 // registers read by the terminator. Similarly its def should not be
514 // clobbered by the terminator.
515 for (CandidateInfo &Candidate : Candidates) {
516 if (Candidate.FI != std::numeric_limits<int>::min() &&
517 StoredFIs.count(Candidate.FI))
520 unsigned Def = Candidate.Def;
521 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
523 MachineInstr *MI = Candidate.MI;
524 for (const MachineOperand &MO : MI->operands()) {
525 if (!MO.isReg() || MO.isDef() || !MO.getReg())
527 unsigned Reg = MO.getReg();
528 if (PhysRegDefs.test(Reg) ||
529 PhysRegClobbers.test(Reg)) {
530 // If it's using a non-loop-invariant register, then it's obviously
531 // not safe to hoist.
537 HoistPostRA(MI, Candidate.Def);
542 /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
543 /// sure it is not killed by any instructions in the loop.
544 void MachineLICM::AddToLiveIns(unsigned Reg) {
545 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
546 for (MachineBasicBlock *BB : Blocks) {
547 if (!BB->isLiveIn(Reg))
549 for (MachineInstr &MI : *BB) {
550 for (MachineOperand &MO : MI.operands()) {
551 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
552 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
559 /// When an instruction is found to only use loop invariant operands that is
560 /// safe to hoist, this instruction is called to do the dirty work.
561 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
562 MachineBasicBlock *Preheader = getCurPreheader();
564 // Now move the instructions to the predecessor, inserting it before any
565 // terminator instructions.
566 DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader) << " from "
567 << printMBBReference(*MI->getParent()) << ": " << *MI);
569 // Splice the instruction to the preheader.
570 MachineBasicBlock *MBB = MI->getParent();
571 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
573 // Add register to livein list to all the BBs in the current loop since a
574 // loop invariant must be kept live throughout the whole loop. This is
575 // important to ensure later passes do not scavenge the def register.
582 /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
583 /// may not be safe to hoist.
584 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
585 if (SpeculationState != SpeculateUnknown)
586 return SpeculationState == SpeculateFalse;
588 if (BB != CurLoop->getHeader()) {
589 // Check loop exiting blocks.
590 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
591 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
592 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
593 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
594 SpeculationState = SpeculateTrue;
599 SpeculationState = SpeculateFalse;
603 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
604 DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
606 // Remember livein register pressure.
607 BackTrace.push_back(RegPressure);
610 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
611 DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
612 BackTrace.pop_back();
615 /// Destroy scope for the MBB that corresponds to the given dominator tree node
616 /// if its a leaf or all of its children are done. Walk up the dominator tree to
617 /// destroy ancestors which are now done.
618 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
619 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
620 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
621 if (OpenChildren[Node])
625 ExitScope(Node->getBlock());
627 // Now traverse upwards to pop ancestors whose offsprings are all done.
628 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
629 unsigned Left = --OpenChildren[Parent];
632 ExitScope(Parent->getBlock());
637 /// Walk the specified loop in the CFG (defined by all blocks dominated by the
638 /// specified header block, and that are in the current loop) in depth first
639 /// order w.r.t the DominatorTree. This allows us to visit definitions before
640 /// uses, allowing us to hoist a loop body in one pass without iteration.
641 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
642 MachineBasicBlock *Preheader = getCurPreheader();
646 SmallVector<MachineDomTreeNode*, 32> Scopes;
647 SmallVector<MachineDomTreeNode*, 8> WorkList;
648 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
649 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
651 // Perform a DFS walk to determine the order of visit.
652 WorkList.push_back(HeaderN);
653 while (!WorkList.empty()) {
654 MachineDomTreeNode *Node = WorkList.pop_back_val();
655 assert(Node && "Null dominator tree node?");
656 MachineBasicBlock *BB = Node->getBlock();
658 // If the header of the loop containing this basic block is a landing pad,
659 // then don't try to hoist instructions out of this loop.
660 const MachineLoop *ML = MLI->getLoopFor(BB);
661 if (ML && ML->getHeader()->isEHPad())
664 // If this subregion is not in the top level loop at all, exit.
665 if (!CurLoop->contains(BB))
668 Scopes.push_back(Node);
669 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
670 unsigned NumChildren = Children.size();
672 // Don't hoist things out of a large switch statement. This often causes
673 // code to be hoisted that wasn't going to be executed, and increases
674 // register pressure in a situation where it's likely to matter.
675 if (BB->succ_size() >= 25)
678 OpenChildren[Node] = NumChildren;
679 // Add children in reverse order as then the next popped worklist node is
680 // the first child of this node. This means we ultimately traverse the
681 // DOM tree in exactly the same order as if we'd recursed.
682 for (int i = (int)NumChildren-1; i >= 0; --i) {
683 MachineDomTreeNode *Child = Children[i];
684 ParentMap[Child] = Node;
685 WorkList.push_back(Child);
689 if (Scopes.size() == 0)
692 // Compute registers which are livein into the loop headers.
695 InitRegPressure(Preheader);
698 for (MachineDomTreeNode *Node : Scopes) {
699 MachineBasicBlock *MBB = Node->getBlock();
704 SpeculationState = SpeculateUnknown;
705 for (MachineBasicBlock::iterator
706 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
707 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
708 MachineInstr *MI = &*MII;
709 if (!Hoist(MI, Preheader))
710 UpdateRegPressure(MI);
714 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
715 ExitScopeIfDone(Node, OpenChildren, ParentMap);
719 /// Sink instructions into loops if profitable. This especially tries to prevent
720 /// register spills caused by register pressure if there is little to no
721 /// overhead moving instructions into loops.
722 void MachineLICM::SinkIntoLoop() {
723 MachineBasicBlock *Preheader = getCurPreheader();
727 SmallVector<MachineInstr *, 8> Candidates;
728 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
729 I != Preheader->instr_end(); ++I) {
730 // We need to ensure that we can safely move this instruction into the loop.
731 // As such, it must not have side-effects, e.g. such as a call has.
732 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
733 Candidates.push_back(&*I);
736 for (MachineInstr *I : Candidates) {
737 const MachineOperand &MO = I->getOperand(0);
738 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
740 if (!MRI->hasOneDef(MO.getReg()))
743 MachineBasicBlock *B = nullptr;
744 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
745 // FIXME: Come up with a proper cost model that estimates whether sinking
746 // the instruction (and thus possibly executing it on every loop
747 // iteration) is more expensive than a register.
748 // For now assumes that copies are cheap and thus almost always worth it.
757 B = DT->findNearestCommonDominator(B, MI.getParent());
763 if (!CanSink || !B || B == Preheader)
765 B->splice(B->getFirstNonPHI(), Preheader, I);
769 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
770 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
773 /// Find all virtual register references that are liveout of the preheader to
774 /// initialize the starting "register pressure". Note this does not count live
775 /// through (livein but not used) registers.
776 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
777 std::fill(RegPressure.begin(), RegPressure.end(), 0);
779 // If the preheader has only a single predecessor and it ends with a
780 // fallthrough or an unconditional branch, then scan its predecessor for live
781 // defs as well. This happens whenever the preheader is created by splitting
782 // the critical edge from the loop predecessor to the loop header.
783 if (BB->pred_size() == 1) {
784 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
785 SmallVector<MachineOperand, 4> Cond;
786 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
787 InitRegPressure(*BB->pred_begin());
790 for (const MachineInstr &MI : *BB)
791 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
794 /// Update estimate of register pressure after the specified instruction.
795 void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
796 bool ConsiderUnseenAsDef) {
797 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
798 for (const auto &RPIdAndCost : Cost) {
799 unsigned Class = RPIdAndCost.first;
800 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
801 RegPressure[Class] = 0;
803 RegPressure[Class] += RPIdAndCost.second;
807 /// Calculate the additional register pressure that the registers used in MI
810 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
811 /// figure out which usages are live-ins.
812 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
813 DenseMap<unsigned, int>
814 MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
815 bool ConsiderUnseenAsDef) {
816 DenseMap<unsigned, int> Cost;
817 if (MI->isImplicitDef())
819 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
820 const MachineOperand &MO = MI->getOperand(i);
821 if (!MO.isReg() || MO.isImplicit())
823 unsigned Reg = MO.getReg();
824 if (!TargetRegisterInfo::isVirtualRegister(Reg))
827 // FIXME: It seems bad to use RegSeen only for some of these calculations.
828 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
829 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
831 RegClassWeight W = TRI->getRegClassWeight(RC);
834 RCCost = W.RegWeight;
836 bool isKill = isOperandKill(MO, MRI);
837 if (isNew && !isKill && ConsiderUnseenAsDef)
838 // Haven't seen this, it must be a livein.
839 RCCost = W.RegWeight;
840 else if (!isNew && isKill)
841 RCCost = -W.RegWeight;
845 const int *PS = TRI->getRegClassPressureSets(RC);
846 for (; *PS != -1; ++PS) {
847 if (Cost.find(*PS) == Cost.end())
856 /// Return true if this machine instruction loads from global offset table or
858 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
859 assert(MI.mayLoad() && "Expected MI that loads!");
861 // If we lost memory operands, conservatively assume that the instruction
862 // reads from everything..
863 if (MI.memoperands_empty())
866 for (MachineMemOperand *MemOp : MI.memoperands())
867 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
868 if (PSV->isGOT() || PSV->isConstantPool())
874 /// Returns true if the instruction may be a suitable candidate for LICM.
875 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
876 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
877 // Check if it's safe to move the instruction.
878 bool DontMoveAcrossStore = true;
879 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
882 // If it is load then check if it is guaranteed to execute by making sure that
883 // it dominates all exiting blocks. If it doesn't, then there is a path out of
884 // the loop which does not execute this load, so we can't hoist it. Loads
885 // from constant memory are not safe to speculate all the time, for example
886 // indexed load from a jump table.
887 // Stores and side effects are already checked by isSafeToMove.
888 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
889 !IsGuaranteedToExecute(I.getParent()))
895 /// Returns true if the instruction is loop invariant.
896 /// I.e., all virtual register operands are defined outside of the loop,
897 /// physical registers aren't accessed explicitly, and there are no side
898 /// effects that aren't captured by the operands or other flags.
899 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
900 if (!IsLICMCandidate(I))
903 // The instruction is loop invariant if all of its operands are.
904 for (const MachineOperand &MO : I.operands()) {
908 unsigned Reg = MO.getReg();
909 if (Reg == 0) continue;
911 // Don't hoist an instruction that uses or defines a physical register.
912 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
914 // If the physreg has no defs anywhere, it's just an ambient register
915 // and we can freely move its uses. Alternatively, if it's allocatable,
916 // it could get allocated to something with a def during allocation.
917 // However, if the physreg is known to always be caller saved/restored
918 // then this use is safe to hoist.
919 if (!MRI->isConstantPhysReg(Reg) &&
920 !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
922 // Otherwise it's safe to move.
924 } else if (!MO.isDead()) {
925 // A def that isn't dead. We can't move it.
927 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
928 // If the reg is live into the loop, we can't hoist an instruction
929 // which would clobber it.
937 assert(MRI->getVRegDef(Reg) &&
938 "Machine instr not mapped for this vreg?!");
940 // If the loop contains the definition of an operand, then the instruction
941 // isn't loop invariant.
942 if (CurLoop->contains(MRI->getVRegDef(Reg)))
946 // If we got this far, the instruction is loop invariant!
950 /// Return true if the specified instruction is used by a phi node and hoisting
951 /// it could cause a copy to be inserted.
952 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
953 SmallVector<const MachineInstr*, 8> Work(1, MI);
955 MI = Work.pop_back_val();
956 for (const MachineOperand &MO : MI->operands()) {
957 if (!MO.isReg() || !MO.isDef())
959 unsigned Reg = MO.getReg();
960 if (!TargetRegisterInfo::isVirtualRegister(Reg))
962 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
963 // A PHI may cause a copy to be inserted.
965 // A PHI inside the loop causes a copy because the live range of Reg is
966 // extended across the PHI.
967 if (CurLoop->contains(&UseMI))
969 // A PHI in an exit block can cause a copy to be inserted if the PHI
970 // has multiple predecessors in the loop with different values.
971 // For now, approximate by rejecting all exit blocks.
972 if (isExitBlock(UseMI.getParent()))
976 // Look past copies as well.
977 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
978 Work.push_back(&UseMI);
981 } while (!Work.empty());
985 /// Compute operand latency between a def of 'Reg' and an use in the current
986 /// loop, return true if the target considered it high.
987 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
988 unsigned DefIdx, unsigned Reg) const {
989 if (MRI->use_nodbg_empty(Reg))
992 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
993 if (UseMI.isCopyLike())
995 if (!CurLoop->contains(UseMI.getParent()))
997 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
998 const MachineOperand &MO = UseMI.getOperand(i);
999 if (!MO.isReg() || !MO.isUse())
1001 unsigned MOReg = MO.getReg();
1005 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
1009 // Only look at the first in loop use.
1016 /// Return true if the instruction is marked "cheap" or the operand latency
1017 /// between its def and a use is one or less.
1018 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
1019 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
1022 bool isCheap = false;
1023 unsigned NumDefs = MI.getDesc().getNumDefs();
1024 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1025 MachineOperand &DefMO = MI.getOperand(i);
1026 if (!DefMO.isReg() || !DefMO.isDef())
1029 unsigned Reg = DefMO.getReg();
1030 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1033 if (!TII->hasLowDefLatency(SchedModel, MI, i))
1041 /// Visit BBs from header to current BB, check if hoisting an instruction of the
1042 /// given cost matrix can cause high register pressure.
1043 bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1045 for (const auto &RPIdAndCost : Cost) {
1046 if (RPIdAndCost.second <= 0)
1049 unsigned Class = RPIdAndCost.first;
1050 int Limit = RegLimit[Class];
1052 // Don't hoist cheap instructions if they would increase register pressure,
1053 // even if we're under the limit.
1054 if (CheapInstr && !HoistCheapInsts)
1057 for (const auto &RP : BackTrace)
1058 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1065 /// Traverse the back trace from header to the current block and update their
1066 /// register pressures to reflect the effect of hoisting MI from the current
1067 /// block to the preheader.
1068 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1069 // First compute the 'cost' of the instruction, i.e. its contribution
1070 // to register pressure.
1071 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1072 /*ConsiderUnseenAsDef=*/false);
1074 // Update register pressure of blocks from loop header to current block.
1075 for (auto &RP : BackTrace)
1076 for (const auto &RPIdAndCost : Cost)
1077 RP[RPIdAndCost.first] += RPIdAndCost.second;
1080 /// Return true if it is potentially profitable to hoist the given loop
1082 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1083 if (MI.isImplicitDef())
1086 // Besides removing computation from the loop, hoisting an instruction has
1089 // - The value defined by the instruction becomes live across the entire
1090 // loop. This increases register pressure in the loop.
1092 // - If the value is used by a PHI in the loop, a copy will be required for
1093 // lowering the PHI after extending the live range.
1095 // - When hoisting the last use of a value in the loop, that value no longer
1096 // needs to be live in the loop. This lowers register pressure in the loop.
1098 bool CheapInstr = IsCheapInstruction(MI);
1099 bool CreatesCopy = HasLoopPHIUse(&MI);
1101 // Don't hoist a cheap instruction if it would create a copy in the loop.
1102 if (CheapInstr && CreatesCopy) {
1103 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1107 // Rematerializable instructions should always be hoisted since the register
1108 // allocator can just pull them down again when needed.
1109 if (TII->isTriviallyReMaterializable(MI, AA))
1112 // FIXME: If there are long latency loop-invariant instructions inside the
1113 // loop at this point, why didn't the optimizer's LICM hoist them?
1114 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1115 const MachineOperand &MO = MI.getOperand(i);
1116 if (!MO.isReg() || MO.isImplicit())
1118 unsigned Reg = MO.getReg();
1119 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1121 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1122 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1128 // Estimate register pressure to determine whether to LICM the instruction.
1129 // In low register pressure situation, we can be more aggressive about
1130 // hoisting. Also, favors hoisting long latency instructions even in
1131 // moderately high pressure situation.
1132 // Cheap instructions will only be hoisted if they don't increase register
1134 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1135 /*ConsiderUnseenAsDef=*/false);
1137 // Visit BBs from header to current BB, if hoisting this doesn't cause
1138 // high register pressure, then it's safe to proceed.
1139 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1140 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1145 // Don't risk increasing register pressure if it would create copies.
1147 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1151 // Do not "speculate" in high register pressure situation. If an
1152 // instruction is not guaranteed to be executed in the loop, it's best to be
1154 if (AvoidSpeculation &&
1155 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1156 DEBUG(dbgs() << "Won't speculate: " << MI);
1160 // High register pressure situation, only hoist if the instruction is going
1162 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1163 !MI.isDereferenceableInvariantLoad(AA)) {
1164 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1171 /// Unfold a load from the given machineinstr if the load itself could be
1172 /// hoisted. Return the unfolded and hoistable load, or null if the load
1173 /// couldn't be unfolded or if it wouldn't be hoistable.
1174 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1175 // Don't unfold simple loads.
1176 if (MI->canFoldAsLoad())
1179 // If not, we may be able to unfold a load and hoist that.
1180 // First test whether the instruction is loading from an amenable
1182 if (!MI->isDereferenceableInvariantLoad(AA))
1185 // Next determine the register class for a temporary register.
1186 unsigned LoadRegIndex;
1188 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1189 /*UnfoldLoad=*/true,
1190 /*UnfoldStore=*/false,
1192 if (NewOpc == 0) return nullptr;
1193 const MCInstrDesc &MID = TII->get(NewOpc);
1194 MachineFunction &MF = *MI->getMF();
1195 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1196 // Ok, we're unfolding. Create a temporary register and do the unfold.
1197 unsigned Reg = MRI->createVirtualRegister(RC);
1199 SmallVector<MachineInstr *, 2> NewMIs;
1200 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1201 /*UnfoldLoad=*/true,
1202 /*UnfoldStore=*/false, NewMIs);
1205 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1207 assert(NewMIs.size() == 2 &&
1208 "Unfolded a load into multiple instructions!");
1209 MachineBasicBlock *MBB = MI->getParent();
1210 MachineBasicBlock::iterator Pos = MI;
1211 MBB->insert(Pos, NewMIs[0]);
1212 MBB->insert(Pos, NewMIs[1]);
1213 // If unfolding produced a load that wasn't loop-invariant or profitable to
1214 // hoist, discard the new instructions and bail.
1215 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1216 NewMIs[0]->eraseFromParent();
1217 NewMIs[1]->eraseFromParent();
1221 // Update register pressure for the unfolded instruction.
1222 UpdateRegPressure(NewMIs[1]);
1224 // Otherwise we successfully unfolded a load that we can hoist.
1225 MI->eraseFromParent();
1229 /// Initialize the CSE map with instructions that are in the current loop
1230 /// preheader that may become duplicates of instructions that are hoisted
1231 /// out of the loop.
1232 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1233 for (MachineInstr &MI : *BB)
1234 CSEMap[MI.getOpcode()].push_back(&MI);
1237 /// Find an instruction amount PrevMIs that is a duplicate of MI.
1238 /// Return this instruction if it's found.
1240 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1241 std::vector<const MachineInstr*> &PrevMIs) {
1242 for (const MachineInstr *PrevMI : PrevMIs)
1243 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1249 /// Given a LICM'ed instruction, look for an instruction on the preheader that
1250 /// computes the same value. If it's found, do a RAU on with the definition of
1251 /// the existing instruction rather than hoisting the instruction to the
1253 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1254 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
1255 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1256 // the undef property onto uses.
1257 if (CI == CSEMap.end() || MI->isImplicitDef())
1260 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1261 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1263 // Replace virtual registers defined by MI by their counterparts defined
1265 SmallVector<unsigned, 2> Defs;
1266 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1267 const MachineOperand &MO = MI->getOperand(i);
1269 // Physical registers may not differ here.
1270 assert((!MO.isReg() || MO.getReg() == 0 ||
1271 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1272 MO.getReg() == Dup->getOperand(i).getReg()) &&
1273 "Instructions with different phys regs are not identical!");
1275 if (MO.isReg() && MO.isDef() &&
1276 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1280 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1281 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1282 unsigned Idx = Defs[i];
1283 unsigned Reg = MI->getOperand(Idx).getReg();
1284 unsigned DupReg = Dup->getOperand(Idx).getReg();
1285 OrigRCs.push_back(MRI->getRegClass(DupReg));
1287 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1288 // Restore old RCs if more than one defs.
1289 for (unsigned j = 0; j != i; ++j)
1290 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1295 for (unsigned Idx : Defs) {
1296 unsigned Reg = MI->getOperand(Idx).getReg();
1297 unsigned DupReg = Dup->getOperand(Idx).getReg();
1298 MRI->replaceRegWith(Reg, DupReg);
1299 MRI->clearKillFlags(DupReg);
1302 MI->eraseFromParent();
1309 /// Return true if the given instruction will be CSE'd if it's hoisted out of
1311 bool MachineLICM::MayCSE(MachineInstr *MI) {
1312 unsigned Opcode = MI->getOpcode();
1313 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
1314 CI = CSEMap.find(Opcode);
1315 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1316 // the undef property onto uses.
1317 if (CI == CSEMap.end() || MI->isImplicitDef())
1320 return LookForDuplicate(MI, CI->second) != nullptr;
1323 /// When an instruction is found to use only loop invariant operands
1324 /// that are safe to hoist, this instruction is called to do the dirty work.
1325 /// It returns true if the instruction is hoisted.
1326 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1327 // First check whether we should hoist this instruction.
1328 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1329 // If not, try unfolding a hoistable load.
1330 MI = ExtractHoistableLoad(MI);
1331 if (!MI) return false;
1334 // Now move the instructions to the predecessor, inserting it before any
1335 // terminator instructions.
1337 dbgs() << "Hoisting " << *MI;
1338 if (MI->getParent()->getBasicBlock())
1339 dbgs() << " from " << printMBBReference(*MI->getParent());
1340 if (Preheader->getBasicBlock())
1341 dbgs() << " to " << printMBBReference(*Preheader);
1345 // If this is the first instruction being hoisted to the preheader,
1346 // initialize the CSE map with potential common expressions.
1348 InitCSEMap(Preheader);
1349 FirstInLoop = false;
1352 // Look for opportunity to CSE the hoisted instruction.
1353 unsigned Opcode = MI->getOpcode();
1354 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
1355 CI = CSEMap.find(Opcode);
1356 if (!EliminateCSE(MI, CI)) {
1357 // Otherwise, splice the instruction to the preheader.
1358 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1360 // Since we are moving the instruction out of its basic block, we do not
1361 // retain its debug location. Doing so would degrade the debugging
1362 // experience and adversely affect the accuracy of profiling information.
1363 MI->setDebugLoc(DebugLoc());
1365 // Update register pressure for BBs from header to this block.
1366 UpdateBackTraceRegPressure(MI);
1368 // Clear the kill flags of any register this instruction defines,
1369 // since they may need to be live throughout the entire loop
1370 // rather than just live for part of it.
1371 for (MachineOperand &MO : MI->operands())
1372 if (MO.isReg() && MO.isDef() && !MO.isDead())
1373 MRI->clearKillFlags(MO.getReg());
1375 // Add to the CSE map.
1376 if (CI != CSEMap.end())
1377 CI->second.push_back(MI);
1379 CSEMap[Opcode].push_back(MI);
1388 /// Get the preheader for the current loop, splitting a critical edge if needed.
1389 MachineBasicBlock *MachineLICM::getCurPreheader() {
1390 // Determine the block to which to hoist instructions. If we can't find a
1391 // suitable loop predecessor, we can't do any hoisting.
1393 // If we've tried to get a preheader and failed, don't try again.
1394 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1397 if (!CurPreheader) {
1398 CurPreheader = CurLoop->getLoopPreheader();
1399 if (!CurPreheader) {
1400 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1402 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1406 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
1407 if (!CurPreheader) {
1408 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1413 return CurPreheader;