1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs loop invariant code motion on machine instructions. We
11 // attempt to remove as much code from the body of a loop as possible.
13 // This pass is not intended to be a replacement or a complete alternative
14 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15 // constructs that are not exposed before lowering and instruction selection.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/CodeGen/TargetSchedule.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
41 #define DEBUG_TYPE "machine-licm"
44 AvoidSpeculation("avoid-speculation",
45 cl::desc("MachineLICM should avoid speculation"),
46 cl::init(true), cl::Hidden);
49 HoistCheapInsts("hoist-cheap-insts",
50 cl::desc("MachineLICM should hoist even cheap instructions"),
51 cl::init(false), cl::Hidden);
54 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
55 cl::desc("MachineLICM should sink instructions into "
56 "loops to avoid register spills"),
57 cl::init(false), cl::Hidden);
60 "Number of machine instructions hoisted out of loops");
62 "Number of instructions hoisted in low reg pressure situation");
63 STATISTIC(NumHighLatency,
64 "Number of high latency instructions hoisted");
66 "Number of hoisted machine instructions CSEed");
67 STATISTIC(NumPostRAHoisted,
68 "Number of machine instructions hoisted out of loops post regalloc");
71 class MachineLICM : public MachineFunctionPass {
72 const TargetInstrInfo *TII;
73 const TargetLoweringBase *TLI;
74 const TargetRegisterInfo *TRI;
75 const MachineFrameInfo *MFI;
76 MachineRegisterInfo *MRI;
77 TargetSchedModel SchedModel;
80 // Various analyses that we use...
81 AliasAnalysis *AA; // Alias analysis info.
82 MachineLoopInfo *MLI; // Current MachineLoopInfo
83 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
85 // State that is updated as we process loops
86 bool Changed; // True if a loop is changed.
87 bool FirstInLoop; // True if it's the first LICM in the loop.
88 MachineLoop *CurLoop; // The current loop we are working on.
89 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
91 // Exit blocks for CurLoop.
92 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
94 bool isExitBlock(const MachineBasicBlock *MBB) const {
95 return is_contained(ExitBlocks, MBB);
98 // Track 'estimated' register pressure.
99 SmallSet<unsigned, 32> RegSeen;
100 SmallVector<unsigned, 8> RegPressure;
102 // Register pressure "limit" per register pressure set. If the pressure
103 // is higher than the limit, then it's considered high.
104 SmallVector<unsigned, 8> RegLimit;
106 // Register pressure on path leading from loop preheader to current BB.
107 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
109 // For each opcode, keep a list of potential CSE instructions.
110 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
118 // If a MBB does not dominate loop exiting blocks then it may not safe
119 // to hoist loads from this block.
120 // Tri-state: 0 - false, 1 - true, 2 - unknown
121 unsigned SpeculationState;
124 static char ID; // Pass identification, replacement for typeid
126 MachineFunctionPass(ID), PreRegAlloc(true) {
127 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
130 explicit MachineLICM(bool PreRA) :
131 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
132 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
135 bool runOnMachineFunction(MachineFunction &MF) override;
137 void getAnalysisUsage(AnalysisUsage &AU) const override {
138 AU.addRequired<MachineLoopInfo>();
139 AU.addRequired<MachineDominatorTree>();
140 AU.addRequired<AAResultsWrapperPass>();
141 AU.addPreserved<MachineLoopInfo>();
142 AU.addPreserved<MachineDominatorTree>();
143 MachineFunctionPass::getAnalysisUsage(AU);
146 void releaseMemory() override {
155 /// Keep track of information about hoisting candidates.
156 struct CandidateInfo {
160 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
161 : MI(mi), Def(def), FI(fi) {}
164 void HoistRegionPostRA();
166 void HoistPostRA(MachineInstr *MI, unsigned Def);
168 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
169 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
170 SmallVectorImpl<CandidateInfo> &Candidates);
172 void AddToLiveIns(unsigned Reg);
174 bool IsLICMCandidate(MachineInstr &I);
176 bool IsLoopInvariantInst(MachineInstr &I);
178 bool HasLoopPHIUse(const MachineInstr *MI) const;
180 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
183 bool IsCheapInstruction(MachineInstr &MI) const;
185 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
188 void UpdateBackTraceRegPressure(const MachineInstr *MI);
190 bool IsProfitableToHoist(MachineInstr &MI);
192 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
194 void EnterScope(MachineBasicBlock *MBB);
196 void ExitScope(MachineBasicBlock *MBB);
198 void ExitScopeIfDone(
199 MachineDomTreeNode *Node,
200 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
201 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
203 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
205 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
209 void InitRegPressure(MachineBasicBlock *BB);
211 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
213 bool ConsiderUnseenAsDef);
215 void UpdateRegPressure(const MachineInstr *MI,
216 bool ConsiderUnseenAsDef = false);
218 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
221 LookForDuplicate(const MachineInstr *MI,
222 std::vector<const MachineInstr *> &PrevMIs);
226 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
228 bool MayCSE(MachineInstr *MI);
230 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
232 void InitCSEMap(MachineBasicBlock *BB);
234 MachineBasicBlock *getCurPreheader();
236 } // end anonymous namespace
238 char MachineLICM::ID = 0;
239 char &llvm::MachineLICMID = MachineLICM::ID;
240 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
241 "Machine Loop Invariant Code Motion", false, false)
242 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
243 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
244 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
245 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
246 "Machine Loop Invariant Code Motion", false, false)
248 /// Test if the given loop is the outer-most loop that has a unique predecessor.
249 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
250 // Check whether this loop even has a unique predecessor.
251 if (!CurLoop->getLoopPredecessor())
253 // Ok, now check to see if any of its outer loops do.
254 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
255 if (L->getLoopPredecessor())
257 // None of them did, so this is the outermost with a unique predecessor.
261 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
262 if (skipFunction(*MF.getFunction()))
265 Changed = FirstInLoop = false;
266 const TargetSubtargetInfo &ST = MF.getSubtarget();
267 TII = ST.getInstrInfo();
268 TLI = ST.getTargetLowering();
269 TRI = ST.getRegisterInfo();
270 MFI = &MF.getFrameInfo();
271 MRI = &MF.getRegInfo();
272 SchedModel.init(ST.getSchedModel(), &ST, TII);
274 PreRegAlloc = MRI->isSSA();
277 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
279 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
280 DEBUG(dbgs() << MF.getName() << " ********\n");
283 // Estimate register pressure during pre-regalloc pass.
284 unsigned NumRPS = TRI->getNumRegPressureSets();
285 RegPressure.resize(NumRPS);
286 std::fill(RegPressure.begin(), RegPressure.end(), 0);
287 RegLimit.resize(NumRPS);
288 for (unsigned i = 0, e = NumRPS; i != e; ++i)
289 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
292 // Get our Loop information...
293 MLI = &getAnalysis<MachineLoopInfo>();
294 DT = &getAnalysis<MachineDominatorTree>();
295 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
297 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
298 while (!Worklist.empty()) {
299 CurLoop = Worklist.pop_back_val();
300 CurPreheader = nullptr;
303 // If this is done before regalloc, only visit outer-most preheader-sporting
305 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
306 Worklist.append(CurLoop->begin(), CurLoop->end());
310 CurLoop->getExitBlocks(ExitBlocks);
315 // CSEMap is initialized for loop header when the first instruction is
317 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
322 if (SinkInstsToAvoidSpills)
330 /// Return true if instruction stores to the specified frame.
331 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
332 // If we lost memory operands, conservatively assume that the instruction
333 // writes to all slots.
334 if (MI->memoperands_empty())
336 for (const MachineMemOperand *MemOp : MI->memoperands()) {
337 if (!MemOp->isStore() || !MemOp->getPseudoValue())
339 if (const FixedStackPseudoSourceValue *Value =
340 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
341 if (Value->getFrameIndex() == FI)
348 /// Examine the instruction for potentai LICM candidate. Also
349 /// gather register def and frame object update information.
350 void MachineLICM::ProcessMI(MachineInstr *MI,
351 BitVector &PhysRegDefs,
352 BitVector &PhysRegClobbers,
353 SmallSet<int, 32> &StoredFIs,
354 SmallVectorImpl<CandidateInfo> &Candidates) {
355 bool RuledOut = false;
356 bool HasNonInvariantUse = false;
358 for (const MachineOperand &MO : MI->operands()) {
360 // Remember if the instruction stores to the frame index.
361 int FI = MO.getIndex();
362 if (!StoredFIs.count(FI) &&
363 MFI->isSpillSlotObjectIndex(FI) &&
364 InstructionStoresToFI(MI, FI))
365 StoredFIs.insert(FI);
366 HasNonInvariantUse = true;
370 // We can't hoist an instruction defining a physreg that is clobbered in
372 if (MO.isRegMask()) {
373 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
379 unsigned Reg = MO.getReg();
382 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
383 "Not expecting virtual register!");
386 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
387 // If it's using a non-loop-invariant register, then it's obviously not
389 HasNonInvariantUse = true;
393 if (MO.isImplicit()) {
394 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
395 PhysRegClobbers.set(*AI);
397 // Non-dead implicit def? This cannot be hoisted.
399 // No need to check if a dead implicit def is also defined by
400 // another instruction.
404 // FIXME: For now, avoid instructions with multiple defs, unless
405 // it's a dead implicit def.
411 // If we have already seen another instruction that defines the same
412 // register, then this is not safe. Two defs is indicated by setting a
413 // PhysRegClobbers bit.
414 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
415 if (PhysRegDefs.test(*AS))
416 PhysRegClobbers.set(*AS);
417 PhysRegDefs.set(*AS);
419 if (PhysRegClobbers.test(Reg))
420 // MI defined register is seen defined by another instruction in
421 // the loop, it cannot be a LICM candidate.
425 // Only consider reloads for now and remats which do not have register
426 // operands. FIXME: Consider unfold load folding instructions.
427 if (Def && !RuledOut) {
429 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
430 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
431 Candidates.push_back(CandidateInfo(MI, Def, FI));
435 /// Walk the specified region of the CFG and hoist loop invariants out to the
437 void MachineLICM::HoistRegionPostRA() {
438 MachineBasicBlock *Preheader = getCurPreheader();
442 unsigned NumRegs = TRI->getNumRegs();
443 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
444 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
446 SmallVector<CandidateInfo, 32> Candidates;
447 SmallSet<int, 32> StoredFIs;
449 // Walk the entire region, count number of defs for each register, and
450 // collect potential LICM candidates.
451 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
452 for (MachineBasicBlock *BB : Blocks) {
453 // If the header of the loop containing this basic block is a landing pad,
454 // then don't try to hoist instructions out of this loop.
455 const MachineLoop *ML = MLI->getLoopFor(BB);
456 if (ML && ML->getHeader()->isEHPad()) continue;
458 // Conservatively treat live-in's as an external def.
459 // FIXME: That means a reload that're reused in successor block(s) will not
461 for (const auto &LI : BB->liveins()) {
462 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
463 PhysRegDefs.set(*AI);
466 SpeculationState = SpeculateUnknown;
467 for (MachineInstr &MI : *BB)
468 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
471 // Gather the registers read / clobbered by the terminator.
472 BitVector TermRegs(NumRegs);
473 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
474 if (TI != Preheader->end()) {
475 for (const MachineOperand &MO : TI->operands()) {
478 unsigned Reg = MO.getReg();
481 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
486 // Now evaluate whether the potential candidates qualify.
487 // 1. Check if the candidate defined register is defined by another
488 // instruction in the loop.
489 // 2. If the candidate is a load from stack slot (always true for now),
490 // check if the slot is stored anywhere in the loop.
491 // 3. Make sure candidate def should not clobber
492 // registers read by the terminator. Similarly its def should not be
493 // clobbered by the terminator.
494 for (CandidateInfo &Candidate : Candidates) {
495 if (Candidate.FI != INT_MIN &&
496 StoredFIs.count(Candidate.FI))
499 unsigned Def = Candidate.Def;
500 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
502 MachineInstr *MI = Candidate.MI;
503 for (const MachineOperand &MO : MI->operands()) {
504 if (!MO.isReg() || MO.isDef() || !MO.getReg())
506 unsigned Reg = MO.getReg();
507 if (PhysRegDefs.test(Reg) ||
508 PhysRegClobbers.test(Reg)) {
509 // If it's using a non-loop-invariant register, then it's obviously
510 // not safe to hoist.
516 HoistPostRA(MI, Candidate.Def);
521 /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
522 /// sure it is not killed by any instructions in the loop.
523 void MachineLICM::AddToLiveIns(unsigned Reg) {
524 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
525 for (MachineBasicBlock *BB : Blocks) {
526 if (!BB->isLiveIn(Reg))
528 for (MachineInstr &MI : *BB) {
529 for (MachineOperand &MO : MI.operands()) {
530 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
531 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
538 /// When an instruction is found to only use loop invariant operands that is
539 /// safe to hoist, this instruction is called to do the dirty work.
540 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
541 MachineBasicBlock *Preheader = getCurPreheader();
543 // Now move the instructions to the predecessor, inserting it before any
544 // terminator instructions.
545 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
546 << MI->getParent()->getNumber() << ": " << *MI);
548 // Splice the instruction to the preheader.
549 MachineBasicBlock *MBB = MI->getParent();
550 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
552 // Add register to livein list to all the BBs in the current loop since a
553 // loop invariant must be kept live throughout the whole loop. This is
554 // important to ensure later passes do not scavenge the def register.
561 /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
562 /// may not be safe to hoist.
563 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
564 if (SpeculationState != SpeculateUnknown)
565 return SpeculationState == SpeculateFalse;
567 if (BB != CurLoop->getHeader()) {
568 // Check loop exiting blocks.
569 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
570 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
571 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
572 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
573 SpeculationState = SpeculateTrue;
578 SpeculationState = SpeculateFalse;
582 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
583 DEBUG(dbgs() << "Entering BB#" << MBB->getNumber() << '\n');
585 // Remember livein register pressure.
586 BackTrace.push_back(RegPressure);
589 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
590 DEBUG(dbgs() << "Exiting BB#" << MBB->getNumber() << '\n');
591 BackTrace.pop_back();
594 /// Destroy scope for the MBB that corresponds to the given dominator tree node
595 /// if its a leaf or all of its children are done. Walk up the dominator tree to
596 /// destroy ancestors which are now done.
597 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
598 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
599 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
600 if (OpenChildren[Node])
604 ExitScope(Node->getBlock());
606 // Now traverse upwards to pop ancestors whose offsprings are all done.
607 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
608 unsigned Left = --OpenChildren[Parent];
611 ExitScope(Parent->getBlock());
616 /// Walk the specified loop in the CFG (defined by all blocks dominated by the
617 /// specified header block, and that are in the current loop) in depth first
618 /// order w.r.t the DominatorTree. This allows us to visit definitions before
619 /// uses, allowing us to hoist a loop body in one pass without iteration.
621 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
622 MachineBasicBlock *Preheader = getCurPreheader();
626 SmallVector<MachineDomTreeNode*, 32> Scopes;
627 SmallVector<MachineDomTreeNode*, 8> WorkList;
628 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
629 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
631 // Perform a DFS walk to determine the order of visit.
632 WorkList.push_back(HeaderN);
633 while (!WorkList.empty()) {
634 MachineDomTreeNode *Node = WorkList.pop_back_val();
635 assert(Node && "Null dominator tree node?");
636 MachineBasicBlock *BB = Node->getBlock();
638 // If the header of the loop containing this basic block is a landing pad,
639 // then don't try to hoist instructions out of this loop.
640 const MachineLoop *ML = MLI->getLoopFor(BB);
641 if (ML && ML->getHeader()->isEHPad())
644 // If this subregion is not in the top level loop at all, exit.
645 if (!CurLoop->contains(BB))
648 Scopes.push_back(Node);
649 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
650 unsigned NumChildren = Children.size();
652 // Don't hoist things out of a large switch statement. This often causes
653 // code to be hoisted that wasn't going to be executed, and increases
654 // register pressure in a situation where it's likely to matter.
655 if (BB->succ_size() >= 25)
658 OpenChildren[Node] = NumChildren;
659 // Add children in reverse order as then the next popped worklist node is
660 // the first child of this node. This means we ultimately traverse the
661 // DOM tree in exactly the same order as if we'd recursed.
662 for (int i = (int)NumChildren-1; i >= 0; --i) {
663 MachineDomTreeNode *Child = Children[i];
664 ParentMap[Child] = Node;
665 WorkList.push_back(Child);
669 if (Scopes.size() == 0)
672 // Compute registers which are livein into the loop headers.
675 InitRegPressure(Preheader);
678 for (MachineDomTreeNode *Node : Scopes) {
679 MachineBasicBlock *MBB = Node->getBlock();
684 SpeculationState = SpeculateUnknown;
685 for (MachineBasicBlock::iterator
686 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
687 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
688 MachineInstr *MI = &*MII;
689 if (!Hoist(MI, Preheader))
690 UpdateRegPressure(MI);
694 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
695 ExitScopeIfDone(Node, OpenChildren, ParentMap);
699 /// Sink instructions into loops if profitable. This especially tries to prevent
700 /// register spills caused by register pressure if there is little to no
701 /// overhead moving instructions into loops.
702 void MachineLICM::SinkIntoLoop() {
703 MachineBasicBlock *Preheader = getCurPreheader();
707 SmallVector<MachineInstr *, 8> Candidates;
708 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
709 I != Preheader->instr_end(); ++I) {
710 // We need to ensure that we can safely move this instruction into the loop.
711 // As such, it must not have side-effects, e.g. such as a call has.
712 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
713 Candidates.push_back(&*I);
716 for (MachineInstr *I : Candidates) {
717 const MachineOperand &MO = I->getOperand(0);
718 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
720 if (!MRI->hasOneDef(MO.getReg()))
723 MachineBasicBlock *B = nullptr;
724 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
725 // FIXME: Come up with a proper cost model that estimates whether sinking
726 // the instruction (and thus possibly executing it on every loop
727 // iteration) is more expensive than a register.
728 // For now assumes that copies are cheap and thus almost always worth it.
737 B = DT->findNearestCommonDominator(B, MI.getParent());
743 if (!CanSink || !B || B == Preheader)
745 B->splice(B->getFirstNonPHI(), Preheader, I);
749 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
750 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
753 /// Find all virtual register references that are liveout of the preheader to
754 /// initialize the starting "register pressure". Note this does not count live
755 /// through (livein but not used) registers.
756 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
757 std::fill(RegPressure.begin(), RegPressure.end(), 0);
759 // If the preheader has only a single predecessor and it ends with a
760 // fallthrough or an unconditional branch, then scan its predecessor for live
761 // defs as well. This happens whenever the preheader is created by splitting
762 // the critical edge from the loop predecessor to the loop header.
763 if (BB->pred_size() == 1) {
764 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
765 SmallVector<MachineOperand, 4> Cond;
766 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
767 InitRegPressure(*BB->pred_begin());
770 for (const MachineInstr &MI : *BB)
771 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
774 /// Update estimate of register pressure after the specified instruction.
775 void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
776 bool ConsiderUnseenAsDef) {
777 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
778 for (const auto &RPIdAndCost : Cost) {
779 unsigned Class = RPIdAndCost.first;
780 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
781 RegPressure[Class] = 0;
783 RegPressure[Class] += RPIdAndCost.second;
787 /// Calculate the additional register pressure that the registers used in MI
790 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
791 /// figure out which usages are live-ins.
792 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
793 DenseMap<unsigned, int>
794 MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
795 bool ConsiderUnseenAsDef) {
796 DenseMap<unsigned, int> Cost;
797 if (MI->isImplicitDef())
799 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
800 const MachineOperand &MO = MI->getOperand(i);
801 if (!MO.isReg() || MO.isImplicit())
803 unsigned Reg = MO.getReg();
804 if (!TargetRegisterInfo::isVirtualRegister(Reg))
807 // FIXME: It seems bad to use RegSeen only for some of these calculations.
808 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
809 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
811 RegClassWeight W = TRI->getRegClassWeight(RC);
814 RCCost = W.RegWeight;
816 bool isKill = isOperandKill(MO, MRI);
817 if (isNew && !isKill && ConsiderUnseenAsDef)
818 // Haven't seen this, it must be a livein.
819 RCCost = W.RegWeight;
820 else if (!isNew && isKill)
821 RCCost = -W.RegWeight;
825 const int *PS = TRI->getRegClassPressureSets(RC);
826 for (; *PS != -1; ++PS) {
827 if (Cost.find(*PS) == Cost.end())
836 /// Return true if this machine instruction loads from global offset table or
838 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
839 assert (MI.mayLoad() && "Expected MI that loads!");
841 // If we lost memory operands, conservatively assume that the instruction
842 // reads from everything..
843 if (MI.memoperands_empty())
846 for (MachineMemOperand *MemOp : MI.memoperands())
847 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
848 if (PSV->isGOT() || PSV->isConstantPool())
854 /// Returns true if the instruction may be a suitable candidate for LICM.
855 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
856 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
857 // Check if it's safe to move the instruction.
858 bool DontMoveAcrossStore = true;
859 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
862 // If it is load then check if it is guaranteed to execute by making sure that
863 // it dominates all exiting blocks. If it doesn't, then there is a path out of
864 // the loop which does not execute this load, so we can't hoist it. Loads
865 // from constant memory are not safe to speculate all the time, for example
866 // indexed load from a jump table.
867 // Stores and side effects are already checked by isSafeToMove.
868 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
869 !IsGuaranteedToExecute(I.getParent()))
875 /// Returns true if the instruction is loop invariant.
876 /// I.e., all virtual register operands are defined outside of the loop,
877 /// physical registers aren't accessed explicitly, and there are no side
878 /// effects that aren't captured by the operands or other flags.
880 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
881 if (!IsLICMCandidate(I))
884 // The instruction is loop invariant if all of its operands are.
885 for (const MachineOperand &MO : I.operands()) {
889 unsigned Reg = MO.getReg();
890 if (Reg == 0) continue;
892 // Don't hoist an instruction that uses or defines a physical register.
893 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
895 // If the physreg has no defs anywhere, it's just an ambient register
896 // and we can freely move its uses. Alternatively, if it's allocatable,
897 // it could get allocated to something with a def during allocation.
898 if (!MRI->isConstantPhysReg(Reg))
900 // Otherwise it's safe to move.
902 } else if (!MO.isDead()) {
903 // A def that isn't dead. We can't move it.
905 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
906 // If the reg is live into the loop, we can't hoist an instruction
907 // which would clobber it.
915 assert(MRI->getVRegDef(Reg) &&
916 "Machine instr not mapped for this vreg?!");
918 // If the loop contains the definition of an operand, then the instruction
919 // isn't loop invariant.
920 if (CurLoop->contains(MRI->getVRegDef(Reg)))
924 // If we got this far, the instruction is loop invariant!
929 /// Return true if the specified instruction is used by a phi node and hoisting
930 /// it could cause a copy to be inserted.
931 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
932 SmallVector<const MachineInstr*, 8> Work(1, MI);
934 MI = Work.pop_back_val();
935 for (const MachineOperand &MO : MI->operands()) {
936 if (!MO.isReg() || !MO.isDef())
938 unsigned Reg = MO.getReg();
939 if (!TargetRegisterInfo::isVirtualRegister(Reg))
941 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
942 // A PHI may cause a copy to be inserted.
944 // A PHI inside the loop causes a copy because the live range of Reg is
945 // extended across the PHI.
946 if (CurLoop->contains(&UseMI))
948 // A PHI in an exit block can cause a copy to be inserted if the PHI
949 // has multiple predecessors in the loop with different values.
950 // For now, approximate by rejecting all exit blocks.
951 if (isExitBlock(UseMI.getParent()))
955 // Look past copies as well.
956 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
957 Work.push_back(&UseMI);
960 } while (!Work.empty());
964 /// Compute operand latency between a def of 'Reg' and an use in the current
965 /// loop, return true if the target considered it high.
966 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
967 unsigned DefIdx, unsigned Reg) const {
968 if (MRI->use_nodbg_empty(Reg))
971 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
972 if (UseMI.isCopyLike())
974 if (!CurLoop->contains(UseMI.getParent()))
976 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
977 const MachineOperand &MO = UseMI.getOperand(i);
978 if (!MO.isReg() || !MO.isUse())
980 unsigned MOReg = MO.getReg();
984 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
988 // Only look at the first in loop use.
995 /// Return true if the instruction is marked "cheap" or the operand latency
996 /// between its def and a use is one or less.
997 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
998 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
1001 bool isCheap = false;
1002 unsigned NumDefs = MI.getDesc().getNumDefs();
1003 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1004 MachineOperand &DefMO = MI.getOperand(i);
1005 if (!DefMO.isReg() || !DefMO.isDef())
1008 unsigned Reg = DefMO.getReg();
1009 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1012 if (!TII->hasLowDefLatency(SchedModel, MI, i))
1020 /// Visit BBs from header to current BB, check if hoisting an instruction of the
1021 /// given cost matrix can cause high register pressure.
1022 bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1024 for (const auto &RPIdAndCost : Cost) {
1025 if (RPIdAndCost.second <= 0)
1028 unsigned Class = RPIdAndCost.first;
1029 int Limit = RegLimit[Class];
1031 // Don't hoist cheap instructions if they would increase register pressure,
1032 // even if we're under the limit.
1033 if (CheapInstr && !HoistCheapInsts)
1036 for (const auto &RP : BackTrace)
1037 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1044 /// Traverse the back trace from header to the current block and update their
1045 /// register pressures to reflect the effect of hoisting MI from the current
1046 /// block to the preheader.
1047 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1048 // First compute the 'cost' of the instruction, i.e. its contribution
1049 // to register pressure.
1050 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1051 /*ConsiderUnseenAsDef=*/false);
1053 // Update register pressure of blocks from loop header to current block.
1054 for (auto &RP : BackTrace)
1055 for (const auto &RPIdAndCost : Cost)
1056 RP[RPIdAndCost.first] += RPIdAndCost.second;
1059 /// Return true if it is potentially profitable to hoist the given loop
1061 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1062 if (MI.isImplicitDef())
1065 // Besides removing computation from the loop, hoisting an instruction has
1068 // - The value defined by the instruction becomes live across the entire
1069 // loop. This increases register pressure in the loop.
1071 // - If the value is used by a PHI in the loop, a copy will be required for
1072 // lowering the PHI after extending the live range.
1074 // - When hoisting the last use of a value in the loop, that value no longer
1075 // needs to be live in the loop. This lowers register pressure in the loop.
1077 bool CheapInstr = IsCheapInstruction(MI);
1078 bool CreatesCopy = HasLoopPHIUse(&MI);
1080 // Don't hoist a cheap instruction if it would create a copy in the loop.
1081 if (CheapInstr && CreatesCopy) {
1082 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1086 // Rematerializable instructions should always be hoisted since the register
1087 // allocator can just pull them down again when needed.
1088 if (TII->isTriviallyReMaterializable(MI, AA))
1091 // FIXME: If there are long latency loop-invariant instructions inside the
1092 // loop at this point, why didn't the optimizer's LICM hoist them?
1093 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1094 const MachineOperand &MO = MI.getOperand(i);
1095 if (!MO.isReg() || MO.isImplicit())
1097 unsigned Reg = MO.getReg();
1098 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1100 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1101 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1107 // Estimate register pressure to determine whether to LICM the instruction.
1108 // In low register pressure situation, we can be more aggressive about
1109 // hoisting. Also, favors hoisting long latency instructions even in
1110 // moderately high pressure situation.
1111 // Cheap instructions will only be hoisted if they don't increase register
1113 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1114 /*ConsiderUnseenAsDef=*/false);
1116 // Visit BBs from header to current BB, if hoisting this doesn't cause
1117 // high register pressure, then it's safe to proceed.
1118 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1119 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1124 // Don't risk increasing register pressure if it would create copies.
1126 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1130 // Do not "speculate" in high register pressure situation. If an
1131 // instruction is not guaranteed to be executed in the loop, it's best to be
1133 if (AvoidSpeculation &&
1134 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1135 DEBUG(dbgs() << "Won't speculate: " << MI);
1139 // High register pressure situation, only hoist if the instruction is going
1141 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1142 !MI.isDereferenceableInvariantLoad(AA)) {
1143 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1150 /// Unfold a load from the given machineinstr if the load itself could be
1151 /// hoisted. Return the unfolded and hoistable load, or null if the load
1152 /// couldn't be unfolded or if it wouldn't be hoistable.
1153 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1154 // Don't unfold simple loads.
1155 if (MI->canFoldAsLoad())
1158 // If not, we may be able to unfold a load and hoist that.
1159 // First test whether the instruction is loading from an amenable
1161 if (!MI->isDereferenceableInvariantLoad(AA))
1164 // Next determine the register class for a temporary register.
1165 unsigned LoadRegIndex;
1167 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1168 /*UnfoldLoad=*/true,
1169 /*UnfoldStore=*/false,
1171 if (NewOpc == 0) return nullptr;
1172 const MCInstrDesc &MID = TII->get(NewOpc);
1173 MachineFunction &MF = *MI->getParent()->getParent();
1174 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1175 // Ok, we're unfolding. Create a temporary register and do the unfold.
1176 unsigned Reg = MRI->createVirtualRegister(RC);
1178 SmallVector<MachineInstr *, 2> NewMIs;
1179 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1180 /*UnfoldLoad=*/true,
1181 /*UnfoldStore=*/false, NewMIs);
1184 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1186 assert(NewMIs.size() == 2 &&
1187 "Unfolded a load into multiple instructions!");
1188 MachineBasicBlock *MBB = MI->getParent();
1189 MachineBasicBlock::iterator Pos = MI;
1190 MBB->insert(Pos, NewMIs[0]);
1191 MBB->insert(Pos, NewMIs[1]);
1192 // If unfolding produced a load that wasn't loop-invariant or profitable to
1193 // hoist, discard the new instructions and bail.
1194 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1195 NewMIs[0]->eraseFromParent();
1196 NewMIs[1]->eraseFromParent();
1200 // Update register pressure for the unfolded instruction.
1201 UpdateRegPressure(NewMIs[1]);
1203 // Otherwise we successfully unfolded a load that we can hoist.
1204 MI->eraseFromParent();
1208 /// Initialize the CSE map with instructions that are in the current loop
1209 /// preheader that may become duplicates of instructions that are hoisted
1210 /// out of the loop.
1211 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1212 for (MachineInstr &MI : *BB)
1213 CSEMap[MI.getOpcode()].push_back(&MI);
1216 /// Find an instruction amount PrevMIs that is a duplicate of MI.
1217 /// Return this instruction if it's found.
1219 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1220 std::vector<const MachineInstr*> &PrevMIs) {
1221 for (const MachineInstr *PrevMI : PrevMIs)
1222 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1228 /// Given a LICM'ed instruction, look for an instruction on the preheader that
1229 /// computes the same value. If it's found, do a RAU on with the definition of
1230 /// the existing instruction rather than hoisting the instruction to the
1232 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1233 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1234 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1235 // the undef property onto uses.
1236 if (CI == CSEMap.end() || MI->isImplicitDef())
1239 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1240 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1242 // Replace virtual registers defined by MI by their counterparts defined
1244 SmallVector<unsigned, 2> Defs;
1245 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1246 const MachineOperand &MO = MI->getOperand(i);
1248 // Physical registers may not differ here.
1249 assert((!MO.isReg() || MO.getReg() == 0 ||
1250 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1251 MO.getReg() == Dup->getOperand(i).getReg()) &&
1252 "Instructions with different phys regs are not identical!");
1254 if (MO.isReg() && MO.isDef() &&
1255 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1259 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1260 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1261 unsigned Idx = Defs[i];
1262 unsigned Reg = MI->getOperand(Idx).getReg();
1263 unsigned DupReg = Dup->getOperand(Idx).getReg();
1264 OrigRCs.push_back(MRI->getRegClass(DupReg));
1266 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1267 // Restore old RCs if more than one defs.
1268 for (unsigned j = 0; j != i; ++j)
1269 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1274 for (unsigned Idx : Defs) {
1275 unsigned Reg = MI->getOperand(Idx).getReg();
1276 unsigned DupReg = Dup->getOperand(Idx).getReg();
1277 MRI->replaceRegWith(Reg, DupReg);
1278 MRI->clearKillFlags(DupReg);
1281 MI->eraseFromParent();
1288 /// Return true if the given instruction will be CSE'd if it's hoisted out of
1290 bool MachineLICM::MayCSE(MachineInstr *MI) {
1291 unsigned Opcode = MI->getOpcode();
1292 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1293 CI = CSEMap.find(Opcode);
1294 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1295 // the undef property onto uses.
1296 if (CI == CSEMap.end() || MI->isImplicitDef())
1299 return LookForDuplicate(MI, CI->second) != nullptr;
1302 /// When an instruction is found to use only loop invariant operands
1303 /// that are safe to hoist, this instruction is called to do the dirty work.
1304 /// It returns true if the instruction is hoisted.
1305 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1306 // First check whether we should hoist this instruction.
1307 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1308 // If not, try unfolding a hoistable load.
1309 MI = ExtractHoistableLoad(MI);
1310 if (!MI) return false;
1313 // Now move the instructions to the predecessor, inserting it before any
1314 // terminator instructions.
1316 dbgs() << "Hoisting " << *MI;
1317 if (MI->getParent()->getBasicBlock())
1318 dbgs() << " from BB#" << MI->getParent()->getNumber();
1319 if (Preheader->getBasicBlock())
1320 dbgs() << " to BB#" << Preheader->getNumber();
1324 // If this is the first instruction being hoisted to the preheader,
1325 // initialize the CSE map with potential common expressions.
1327 InitCSEMap(Preheader);
1328 FirstInLoop = false;
1331 // Look for opportunity to CSE the hoisted instruction.
1332 unsigned Opcode = MI->getOpcode();
1333 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1334 CI = CSEMap.find(Opcode);
1335 if (!EliminateCSE(MI, CI)) {
1336 // Otherwise, splice the instruction to the preheader.
1337 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1339 // Since we are moving the instruction out of its basic block, we do not
1340 // retain its debug location. Doing so would degrade the debugging
1341 // experience and adversely affect the accuracy of profiling information.
1342 MI->setDebugLoc(DebugLoc());
1344 // Update register pressure for BBs from header to this block.
1345 UpdateBackTraceRegPressure(MI);
1347 // Clear the kill flags of any register this instruction defines,
1348 // since they may need to be live throughout the entire loop
1349 // rather than just live for part of it.
1350 for (MachineOperand &MO : MI->operands())
1351 if (MO.isReg() && MO.isDef() && !MO.isDead())
1352 MRI->clearKillFlags(MO.getReg());
1354 // Add to the CSE map.
1355 if (CI != CSEMap.end())
1356 CI->second.push_back(MI);
1358 CSEMap[Opcode].push_back(MI);
1367 /// Get the preheader for the current loop, splitting a critical edge if needed.
1368 MachineBasicBlock *MachineLICM::getCurPreheader() {
1369 // Determine the block to which to hoist instructions. If we can't find a
1370 // suitable loop predecessor, we can't do any hoisting.
1372 // If we've tried to get a preheader and failed, don't try again.
1373 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1376 if (!CurPreheader) {
1377 CurPreheader = CurLoop->getLoopPreheader();
1378 if (!CurPreheader) {
1379 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1381 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1385 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
1386 if (!CurPreheader) {
1387 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1392 return CurPreheader;