1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
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 moves instructions into successor blocks when possible, so that
11 // they aren't executed on paths where their results aren't needed.
13 // This pass is not intended to be a replacement or a complete alternative
14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
15 // constructs that are not exposed before lowering and instruction selection.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SparseBitVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachinePostDominators.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
52 #define DEBUG_TYPE "machine-sink"
55 SplitEdges("machine-sink-split",
56 cl::desc("Split critical edges during machine sinking"),
57 cl::init(true), cl::Hidden);
60 UseBlockFreqInfo("machine-sink-bfi",
61 cl::desc("Use block frequency info to find successors to sink"),
62 cl::init(true), cl::Hidden);
64 static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
65 "machine-sink-split-probability-threshold",
67 "Percentage threshold for splitting single-instruction critical edge. "
68 "If the branch threshold is higher than this threshold, we allow "
69 "speculative execution of up to 1 instruction to avoid branching to "
70 "splitted critical edge"),
71 cl::init(40), cl::Hidden);
73 STATISTIC(NumSunk, "Number of machine instructions sunk");
74 STATISTIC(NumSplit, "Number of critical edges split");
75 STATISTIC(NumCoalesces, "Number of copies coalesced");
79 class MachineSinking : public MachineFunctionPass {
80 const TargetInstrInfo *TII;
81 const TargetRegisterInfo *TRI;
82 MachineRegisterInfo *MRI; // Machine register information
83 MachineDominatorTree *DT; // Machine dominator tree
84 MachinePostDominatorTree *PDT; // Machine post dominator tree
86 const MachineBlockFrequencyInfo *MBFI;
87 const MachineBranchProbabilityInfo *MBPI;
90 // Remember which edges have been considered for breaking.
91 SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
93 // Remember which edges we are about to split.
94 // This is different from CEBCandidates since those edges
96 SetVector<std::pair<MachineBasicBlock*, MachineBasicBlock*> > ToSplit;
98 SparseBitVector<> RegsToClearKillFlags;
100 typedef std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>
104 static char ID; // Pass identification
106 MachineSinking() : MachineFunctionPass(ID) {
107 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
110 bool runOnMachineFunction(MachineFunction &MF) override;
112 void getAnalysisUsage(AnalysisUsage &AU) const override {
113 AU.setPreservesCFG();
114 MachineFunctionPass::getAnalysisUsage(AU);
115 AU.addRequired<AAResultsWrapperPass>();
116 AU.addRequired<MachineDominatorTree>();
117 AU.addRequired<MachinePostDominatorTree>();
118 AU.addRequired<MachineLoopInfo>();
119 AU.addRequired<MachineBranchProbabilityInfo>();
120 AU.addPreserved<MachineDominatorTree>();
121 AU.addPreserved<MachinePostDominatorTree>();
122 AU.addPreserved<MachineLoopInfo>();
123 if (UseBlockFreqInfo)
124 AU.addRequired<MachineBlockFrequencyInfo>();
127 void releaseMemory() override {
128 CEBCandidates.clear();
132 bool ProcessBlock(MachineBasicBlock &MBB);
133 bool isWorthBreakingCriticalEdge(MachineInstr &MI,
134 MachineBasicBlock *From,
135 MachineBasicBlock *To);
136 /// \brief Postpone the splitting of the given critical
137 /// edge (\p From, \p To).
139 /// We do not split the edges on the fly. Indeed, this invalidates
140 /// the dominance information and thus triggers a lot of updates
141 /// of that information underneath.
142 /// Instead, we postpone all the splits after each iteration of
143 /// the main loop. That way, the information is at least valid
144 /// for the lifetime of an iteration.
146 /// \return True if the edge is marked as toSplit, false otherwise.
147 /// False can be returned if, for instance, this is not profitable.
148 bool PostponeSplitCriticalEdge(MachineInstr &MI,
149 MachineBasicBlock *From,
150 MachineBasicBlock *To,
152 bool SinkInstruction(MachineInstr &MI, bool &SawStore,
153 AllSuccsCache &AllSuccessors);
154 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
155 MachineBasicBlock *DefMBB,
156 bool &BreakPHIEdge, bool &LocalUse) const;
157 MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
158 bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
159 bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
160 MachineBasicBlock *MBB,
161 MachineBasicBlock *SuccToSinkTo,
162 AllSuccsCache &AllSuccessors);
164 bool PerformTrivialForwardCoalescing(MachineInstr &MI,
165 MachineBasicBlock *MBB);
167 SmallVector<MachineBasicBlock *, 4> &
168 GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
169 AllSuccsCache &AllSuccessors) const;
172 } // end anonymous namespace
174 char MachineSinking::ID = 0;
175 char &llvm::MachineSinkingID = MachineSinking::ID;
176 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
177 "Machine code sinking", false, false)
178 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
179 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
180 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
181 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
182 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
183 "Machine code sinking", false, false)
185 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
186 MachineBasicBlock *MBB) {
190 unsigned SrcReg = MI.getOperand(1).getReg();
191 unsigned DstReg = MI.getOperand(0).getReg();
192 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
193 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
194 !MRI->hasOneNonDBGUse(SrcReg))
197 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
198 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
202 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
203 if (DefMI->isCopyLike())
205 DEBUG(dbgs() << "Coalescing: " << *DefMI);
206 DEBUG(dbgs() << "*** to: " << MI);
207 MRI->replaceRegWith(DstReg, SrcReg);
208 MI.eraseFromParent();
210 // Conservatively, clear any kill flags, since it's possible that they are no
212 MRI->clearKillFlags(SrcReg);
218 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
219 /// occur in blocks dominated by the specified block. If any use is in the
220 /// definition block, then return false since it is never legal to move def
223 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
224 MachineBasicBlock *MBB,
225 MachineBasicBlock *DefMBB,
227 bool &LocalUse) const {
228 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
229 "Only makes sense for vregs");
231 // Ignore debug uses because debug info doesn't affect the code.
232 if (MRI->use_nodbg_empty(Reg))
235 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
236 // into and they are all PHI nodes. In this case, machine-sink must break
237 // the critical edge first. e.g.
239 // BB#1: derived from LLVM BB %bb4.preheader
240 // Predecessors according to CFG: BB#0
242 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
244 // JE_4 <BB#37>, %EFLAGS<imp-use>
245 // Successors according to CFG: BB#37 BB#2
247 // BB#2: derived from LLVM BB %bb.nph
248 // Predecessors according to CFG: BB#0 BB#1
249 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
251 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
252 MachineInstr *UseInst = MO.getParent();
253 unsigned OpNo = &MO - &UseInst->getOperand(0);
254 MachineBasicBlock *UseBlock = UseInst->getParent();
255 if (!(UseBlock == MBB && UseInst->isPHI() &&
256 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
257 BreakPHIEdge = false;
264 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
265 // Determine the block of the use.
266 MachineInstr *UseInst = MO.getParent();
267 unsigned OpNo = &MO - &UseInst->getOperand(0);
268 MachineBasicBlock *UseBlock = UseInst->getParent();
269 if (UseInst->isPHI()) {
270 // PHI nodes use the operand in the predecessor block, not the block with
272 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
273 } else if (UseBlock == DefMBB) {
278 // Check that it dominates.
279 if (!DT->dominates(MBB, UseBlock))
286 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
287 if (skipFunction(*MF.getFunction()))
290 DEBUG(dbgs() << "******** Machine Sinking ********\n");
292 TII = MF.getSubtarget().getInstrInfo();
293 TRI = MF.getSubtarget().getRegisterInfo();
294 MRI = &MF.getRegInfo();
295 DT = &getAnalysis<MachineDominatorTree>();
296 PDT = &getAnalysis<MachinePostDominatorTree>();
297 LI = &getAnalysis<MachineLoopInfo>();
298 MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
299 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
300 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
302 bool EverMadeChange = false;
305 bool MadeChange = false;
307 // Process all basic blocks.
308 CEBCandidates.clear();
311 MadeChange |= ProcessBlock(MBB);
313 // If we have anything we marked as toSplit, split it now.
314 for (auto &Pair : ToSplit) {
315 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
316 if (NewSucc != nullptr) {
317 DEBUG(dbgs() << " *** Splitting critical edge:"
318 " BB#" << Pair.first->getNumber()
319 << " -- BB#" << NewSucc->getNumber()
320 << " -- BB#" << Pair.second->getNumber() << '\n');
324 DEBUG(dbgs() << " *** Not legal to break critical edge\n");
326 // If this iteration over the code changed anything, keep iterating.
327 if (!MadeChange) break;
328 EverMadeChange = true;
331 // Now clear any kill flags for recorded registers.
332 for (auto I : RegsToClearKillFlags)
333 MRI->clearKillFlags(I);
334 RegsToClearKillFlags.clear();
336 return EverMadeChange;
339 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
340 // Can't sink anything out of a block that has less than two successors.
341 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
343 // Don't bother sinking code out of unreachable blocks. In addition to being
344 // unprofitable, it can also lead to infinite looping, because in an
345 // unreachable loop there may be nowhere to stop.
346 if (!DT->isReachableFromEntry(&MBB)) return false;
348 bool MadeChange = false;
350 // Cache all successors, sorted by frequency info and loop depth.
351 AllSuccsCache AllSuccessors;
353 // Walk the basic block bottom-up. Remember if we saw a store.
354 MachineBasicBlock::iterator I = MBB.end();
356 bool ProcessedBegin, SawStore = false;
358 MachineInstr &MI = *I; // The instruction to sink.
360 // Predecrement I (if it's not begin) so that it isn't invalidated by
362 ProcessedBegin = I == MBB.begin();
366 if (MI.isDebugValue())
369 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
375 if (SinkInstruction(MI, SawStore, AllSuccessors)) {
380 // If we just processed the first instruction in the block, we're done.
381 } while (!ProcessedBegin);
386 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
387 MachineBasicBlock *From,
388 MachineBasicBlock *To) {
389 // FIXME: Need much better heuristics.
391 // If the pass has already considered breaking this edge (during this pass
392 // through the function), then let's go ahead and break it. This means
393 // sinking multiple "cheap" instructions into the same block.
394 if (!CEBCandidates.insert(std::make_pair(From, To)).second)
397 if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
400 if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
401 BranchProbability(SplitEdgeProbabilityThreshold, 100))
404 // MI is cheap, we probably don't want to break the critical edge for it.
405 // However, if this would allow some definitions of its source operands
406 // to be sunk then it's probably worth it.
407 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
408 const MachineOperand &MO = MI.getOperand(i);
409 if (!MO.isReg() || !MO.isUse())
411 unsigned Reg = MO.getReg();
415 // We don't move live definitions of physical registers,
416 // so sinking their uses won't enable any opportunities.
417 if (TargetRegisterInfo::isPhysicalRegister(Reg))
420 // If this instruction is the only user of a virtual register,
421 // check if breaking the edge will enable sinking
422 // both this instruction and the defining instruction.
423 if (MRI->hasOneNonDBGUse(Reg)) {
424 // If the definition resides in same MBB,
425 // claim it's likely we can sink these together.
426 // If definition resides elsewhere, we aren't
427 // blocking it from being sunk so don't break the edge.
428 MachineInstr *DefMI = MRI->getVRegDef(Reg);
429 if (DefMI->getParent() == MI.getParent())
437 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
438 MachineBasicBlock *FromBB,
439 MachineBasicBlock *ToBB,
441 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
444 // Avoid breaking back edge. From == To means backedge for single BB loop.
445 if (!SplitEdges || FromBB == ToBB)
448 // Check for backedges of more "complex" loops.
449 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
450 LI->isLoopHeader(ToBB))
453 // It's not always legal to break critical edges and sink the computation
461 // ... no uses of v1024
467 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
476 // ... no uses of v1024
482 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
483 // flow. We need to ensure the new basic block where the computation is
484 // sunk to dominates all the uses.
485 // It's only legal to break critical edge and sink the computation to the
486 // new block if all the predecessors of "To", except for "From", are
487 // not dominated by "From". Given SSA property, this means these
488 // predecessors are dominated by "To".
490 // There is no need to do this check if all the uses are PHI nodes. PHI
491 // sources are only defined on the specific predecessor edges.
493 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
494 E = ToBB->pred_end(); PI != E; ++PI) {
497 if (!DT->dominates(ToBB, *PI))
502 ToSplit.insert(std::make_pair(FromBB, ToBB));
507 /// collectDebgValues - Scan instructions following MI and collect any
508 /// matching DBG_VALUEs.
509 static void collectDebugValues(MachineInstr &MI,
510 SmallVectorImpl<MachineInstr *> &DbgValues) {
512 if (!MI.getOperand(0).isReg())
515 MachineBasicBlock::iterator DI = MI; ++DI;
516 for (MachineBasicBlock::iterator DE = MI.getParent()->end();
518 if (!DI->isDebugValue())
520 if (DI->getOperand(0).isReg() &&
521 DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
522 DbgValues.push_back(&*DI);
526 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
527 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
528 MachineBasicBlock *MBB,
529 MachineBasicBlock *SuccToSinkTo,
530 AllSuccsCache &AllSuccessors) {
531 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
533 if (MBB == SuccToSinkTo)
536 // It is profitable if SuccToSinkTo does not post dominate current block.
537 if (!PDT->dominates(SuccToSinkTo, MBB))
540 // It is profitable to sink an instruction from a deeper loop to a shallower
541 // loop, even if the latter post-dominates the former (PR21115).
542 if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
545 // Check if only use in post dominated block is PHI instruction.
546 bool NonPHIUse = false;
547 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
548 MachineBasicBlock *UseBlock = UseInst.getParent();
549 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
555 // If SuccToSinkTo post dominates then also it may be profitable if MI
556 // can further profitably sinked into another block in next round.
557 bool BreakPHIEdge = false;
558 // FIXME - If finding successor is compile time expensive then cache results.
559 if (MachineBasicBlock *MBB2 =
560 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
561 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
563 // If SuccToSinkTo is final destination and it is a post dominator of current
564 // block then it is not profitable to sink MI into SuccToSinkTo block.
568 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
569 /// computing it if it was not already cached.
570 SmallVector<MachineBasicBlock *, 4> &
571 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
572 AllSuccsCache &AllSuccessors) const {
574 // Do we have the sorted successors in cache ?
575 auto Succs = AllSuccessors.find(MBB);
576 if (Succs != AllSuccessors.end())
577 return Succs->second;
579 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
582 // Handle cases where sinking can happen but where the sink point isn't a
583 // successor. For example:
589 const std::vector<MachineDomTreeNode *> &Children =
590 DT->getNode(MBB)->getChildren();
591 for (const auto &DTChild : Children)
592 // DomTree children of MBB that have MBB as immediate dominator are added.
593 if (DTChild->getIDom()->getBlock() == MI.getParent() &&
594 // Skip MBBs already added to the AllSuccs vector above.
595 !MBB->isSuccessor(DTChild->getBlock()))
596 AllSuccs.push_back(DTChild->getBlock());
598 // Sort Successors according to their loop depth or block frequency info.
600 AllSuccs.begin(), AllSuccs.end(),
601 [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
602 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
603 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
604 bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
605 return HasBlockFreq ? LHSFreq < RHSFreq
606 : LI->getLoopDepth(L) < LI->getLoopDepth(R);
609 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
611 return it.first->second;
614 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
616 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
618 AllSuccsCache &AllSuccessors) {
619 assert (MBB && "Invalid MachineBasicBlock!");
621 // Loop over all the operands of the specified instruction. If there is
622 // anything we can't handle, bail out.
624 // SuccToSinkTo - This is the successor to sink this instruction to, once we
626 MachineBasicBlock *SuccToSinkTo = nullptr;
627 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
628 const MachineOperand &MO = MI.getOperand(i);
629 if (!MO.isReg()) continue; // Ignore non-register operands.
631 unsigned Reg = MO.getReg();
632 if (Reg == 0) continue;
634 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
636 // If the physreg has no defs anywhere, it's just an ambient register
637 // and we can freely move its uses. Alternatively, if it's allocatable,
638 // it could get allocated to something with a def during allocation.
639 if (!MRI->isConstantPhysReg(Reg))
641 } else if (!MO.isDead()) {
642 // A def that isn't dead. We can't move it.
646 // Virtual register uses are always safe to sink.
647 if (MO.isUse()) continue;
649 // If it's not safe to move defs of the register class, then abort.
650 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
653 // Virtual register defs can only be sunk if all their uses are in blocks
654 // dominated by one of the successors.
656 // If a previous operand picked a block to sink to, then this operand
657 // must be sinkable to the same block.
658 bool LocalUse = false;
659 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
660 BreakPHIEdge, LocalUse))
666 // Otherwise, we should look at all the successors and decide which one
667 // we should sink to. If we have reliable block frequency information
668 // (frequency != 0) available, give successors with smaller frequencies
669 // higher priority, otherwise prioritize smaller loop depths.
670 for (MachineBasicBlock *SuccBlock :
671 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
672 bool LocalUse = false;
673 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
674 BreakPHIEdge, LocalUse)) {
675 SuccToSinkTo = SuccBlock;
679 // Def is used locally, it's never safe to move this def.
683 // If we couldn't find a block to sink to, ignore this instruction.
686 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
691 // It is not possible to sink an instruction into its own block. This can
692 // happen with loops.
693 if (MBB == SuccToSinkTo)
696 // It's not safe to sink instructions to EH landing pad. Control flow into
697 // landing pad is implicitly defined.
698 if (SuccToSinkTo && SuccToSinkTo->isEHPad())
704 /// \brief Return true if MI is likely to be usable as a memory operation by the
705 /// implicit null check optimization.
707 /// This is a "best effort" heuristic, and should not be relied upon for
708 /// correctness. This returning true does not guarantee that the implicit null
709 /// check optimization is legal over MI, and this returning false does not
710 /// guarantee MI cannot possibly be used to do a null check.
711 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
712 const TargetInstrInfo *TII,
713 const TargetRegisterInfo *TRI) {
714 typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
716 auto *MBB = MI.getParent();
717 if (MBB->pred_size() != 1)
720 auto *PredMBB = *MBB->pred_begin();
721 auto *PredBB = PredMBB->getBasicBlock();
723 // Frontends that don't use implicit null checks have no reason to emit
724 // branches with make.implicit metadata, and this function should always
725 // return false for them.
727 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
732 if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
735 if (!(MI.mayLoad() && !MI.isPredicable()))
738 MachineBranchPredicate MBP;
739 if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
742 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
743 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
744 MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
745 MBP.LHS.getReg() == BaseReg;
748 /// SinkInstruction - Determine whether it is safe to sink the specified machine
749 /// instruction out of its current block into a successor.
750 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
751 AllSuccsCache &AllSuccessors) {
752 // Don't sink instructions that the target prefers not to sink.
753 if (!TII->shouldSink(MI))
756 // Check if it's safe to move the instruction.
757 if (!MI.isSafeToMove(AA, SawStore))
760 // Convergent operations may not be made control-dependent on additional
762 if (MI.isConvergent())
765 // Don't break implicit null checks. This is a performance heuristic, and not
766 // required for correctness.
767 if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
770 // FIXME: This should include support for sinking instructions within the
771 // block they are currently in to shorten the live ranges. We often get
772 // instructions sunk into the top of a large block, but it would be better to
773 // also sink them down before their first use in the block. This xform has to
774 // be careful not to *increase* register pressure though, e.g. sinking
775 // "x = y + z" down if it kills y and z would increase the live ranges of y
776 // and z and only shrink the live range of x.
778 bool BreakPHIEdge = false;
779 MachineBasicBlock *ParentBlock = MI.getParent();
780 MachineBasicBlock *SuccToSinkTo =
781 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
783 // If there are no outputs, it must have side-effects.
788 // If the instruction to move defines a dead physical register which is live
789 // when leaving the basic block, don't move it because it could turn into a
790 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
791 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
792 const MachineOperand &MO = MI.getOperand(I);
793 if (!MO.isReg()) continue;
794 unsigned Reg = MO.getReg();
795 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
796 if (SuccToSinkTo->isLiveIn(Reg))
800 DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
802 // If the block has multiple predecessors, this is a critical edge.
803 // Decide if we can sink along it or need to break the edge.
804 if (SuccToSinkTo->pred_size() > 1) {
805 // We cannot sink a load across a critical edge - there may be stores in
807 bool TryBreak = false;
809 if (!MI.isSafeToMove(AA, store)) {
810 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
814 // We don't want to sink across a critical edge if we don't dominate the
815 // successor. We could be introducing calculations to new code paths.
816 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
817 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
821 // Don't sink instructions into a loop.
822 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
823 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
827 // Otherwise we are OK with sinking along a critical edge.
829 DEBUG(dbgs() << "Sinking along critical edge.\n");
831 // Mark this edge as to be split.
832 // If the edge can actually be split, the next iteration of the main loop
833 // will sink MI in the newly created block.
835 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
837 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
838 "break critical edge\n");
839 // The instruction will not be sunk this time.
845 // BreakPHIEdge is true if all the uses are in the successor MBB being
846 // sunken into and they are all PHI nodes. In this case, machine-sink must
847 // break the critical edge first.
848 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
849 SuccToSinkTo, BreakPHIEdge);
851 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
852 "break critical edge\n");
853 // The instruction will not be sunk this time.
857 // Determine where to insert into. Skip phi nodes.
858 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
859 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
862 // collect matching debug values.
863 SmallVector<MachineInstr *, 2> DbgValuesToSink;
864 collectDebugValues(MI, DbgValuesToSink);
866 // Move the instruction.
867 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
868 ++MachineBasicBlock::iterator(MI));
870 // Move debug values.
871 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
872 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
873 MachineInstr *DbgMI = *DBI;
874 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
875 ++MachineBasicBlock::iterator(DbgMI));
878 // Conservatively, clear any kill flags, since it's possible that they are no
880 // Note that we have to clear the kill flags for any register this instruction
881 // uses as we may sink over another instruction which currently kills the
883 for (MachineOperand &MO : MI.operands()) {
884 if (MO.isReg() && MO.isUse())
885 RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.