1 //===- MachineSink.cpp - Sinking for machine instructions -----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass moves instructions into successor blocks when possible, so that
10 // they aren't executed on paths where their results aren't needed.
12 // This pass is not intended to be a replacement or a complete alternative
13 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
14 // constructs that are not exposed before lowering and instruction selection.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.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/TargetInstrInfo.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/BranchProbability.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
55 #define DEBUG_TYPE "machine-sink"
58 SplitEdges("machine-sink-split",
59 cl::desc("Split critical edges during machine sinking"),
60 cl::init(true), cl::Hidden
);
63 UseBlockFreqInfo("machine-sink-bfi",
64 cl::desc("Use block frequency info to find successors to sink"),
65 cl::init(true), cl::Hidden
);
67 static cl::opt
<unsigned> SplitEdgeProbabilityThreshold(
68 "machine-sink-split-probability-threshold",
70 "Percentage threshold for splitting single-instruction critical edge. "
71 "If the branch threshold is higher than this threshold, we allow "
72 "speculative execution of up to 1 instruction to avoid branching to "
73 "splitted critical edge"),
74 cl::init(40), cl::Hidden
);
76 STATISTIC(NumSunk
, "Number of machine instructions sunk");
77 STATISTIC(NumSplit
, "Number of critical edges split");
78 STATISTIC(NumCoalesces
, "Number of copies coalesced");
79 STATISTIC(NumPostRACopySink
, "Number of copies sunk after RA");
83 class MachineSinking
: public MachineFunctionPass
{
84 const TargetInstrInfo
*TII
;
85 const TargetRegisterInfo
*TRI
;
86 MachineRegisterInfo
*MRI
; // Machine register information
87 MachineDominatorTree
*DT
; // Machine dominator tree
88 MachinePostDominatorTree
*PDT
; // Machine post dominator tree
90 const MachineBlockFrequencyInfo
*MBFI
;
91 const MachineBranchProbabilityInfo
*MBPI
;
94 // Remember which edges have been considered for breaking.
95 SmallSet
<std::pair
<MachineBasicBlock
*, MachineBasicBlock
*>, 8>
97 // Remember which edges we are about to split.
98 // This is different from CEBCandidates since those edges
100 SetVector
<std::pair
<MachineBasicBlock
*, MachineBasicBlock
*>> ToSplit
;
102 SparseBitVector
<> RegsToClearKillFlags
;
104 using AllSuccsCache
=
105 std::map
<MachineBasicBlock
*, SmallVector
<MachineBasicBlock
*, 4>>;
108 static char ID
; // Pass identification
110 MachineSinking() : MachineFunctionPass(ID
) {
111 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
114 bool runOnMachineFunction(MachineFunction
&MF
) override
;
116 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
117 AU
.setPreservesCFG();
118 MachineFunctionPass::getAnalysisUsage(AU
);
119 AU
.addRequired
<AAResultsWrapperPass
>();
120 AU
.addRequired
<MachineDominatorTree
>();
121 AU
.addRequired
<MachinePostDominatorTree
>();
122 AU
.addRequired
<MachineLoopInfo
>();
123 AU
.addRequired
<MachineBranchProbabilityInfo
>();
124 AU
.addPreserved
<MachineDominatorTree
>();
125 AU
.addPreserved
<MachinePostDominatorTree
>();
126 AU
.addPreserved
<MachineLoopInfo
>();
127 if (UseBlockFreqInfo
)
128 AU
.addRequired
<MachineBlockFrequencyInfo
>();
131 void releaseMemory() override
{
132 CEBCandidates
.clear();
136 bool ProcessBlock(MachineBasicBlock
&MBB
);
137 bool isWorthBreakingCriticalEdge(MachineInstr
&MI
,
138 MachineBasicBlock
*From
,
139 MachineBasicBlock
*To
);
141 /// Postpone the splitting of the given critical
142 /// edge (\p From, \p To).
144 /// We do not split the edges on the fly. Indeed, this invalidates
145 /// the dominance information and thus triggers a lot of updates
146 /// of that information underneath.
147 /// Instead, we postpone all the splits after each iteration of
148 /// the main loop. That way, the information is at least valid
149 /// for the lifetime of an iteration.
151 /// \return True if the edge is marked as toSplit, false otherwise.
152 /// False can be returned if, for instance, this is not profitable.
153 bool PostponeSplitCriticalEdge(MachineInstr
&MI
,
154 MachineBasicBlock
*From
,
155 MachineBasicBlock
*To
,
157 bool SinkInstruction(MachineInstr
&MI
, bool &SawStore
,
159 AllSuccsCache
&AllSuccessors
);
160 bool AllUsesDominatedByBlock(unsigned Reg
, MachineBasicBlock
*MBB
,
161 MachineBasicBlock
*DefMBB
,
162 bool &BreakPHIEdge
, bool &LocalUse
) const;
163 MachineBasicBlock
*FindSuccToSinkTo(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
164 bool &BreakPHIEdge
, AllSuccsCache
&AllSuccessors
);
165 bool isProfitableToSinkTo(unsigned Reg
, MachineInstr
&MI
,
166 MachineBasicBlock
*MBB
,
167 MachineBasicBlock
*SuccToSinkTo
,
168 AllSuccsCache
&AllSuccessors
);
170 bool PerformTrivialForwardCoalescing(MachineInstr
&MI
,
171 MachineBasicBlock
*MBB
);
173 SmallVector
<MachineBasicBlock
*, 4> &
174 GetAllSortedSuccessors(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
175 AllSuccsCache
&AllSuccessors
) const;
178 } // end anonymous namespace
180 char MachineSinking::ID
= 0;
182 char &llvm::MachineSinkingID
= MachineSinking::ID
;
184 INITIALIZE_PASS_BEGIN(MachineSinking
, DEBUG_TYPE
,
185 "Machine code sinking", false, false)
186 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
187 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
188 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
189 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
190 INITIALIZE_PASS_END(MachineSinking
, DEBUG_TYPE
,
191 "Machine code sinking", false, false)
193 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr
&MI
,
194 MachineBasicBlock
*MBB
) {
198 unsigned SrcReg
= MI
.getOperand(1).getReg();
199 unsigned DstReg
= MI
.getOperand(0).getReg();
200 if (!Register::isVirtualRegister(SrcReg
) ||
201 !Register::isVirtualRegister(DstReg
) || !MRI
->hasOneNonDBGUse(SrcReg
))
204 const TargetRegisterClass
*SRC
= MRI
->getRegClass(SrcReg
);
205 const TargetRegisterClass
*DRC
= MRI
->getRegClass(DstReg
);
209 MachineInstr
*DefMI
= MRI
->getVRegDef(SrcReg
);
210 if (DefMI
->isCopyLike())
212 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI
);
213 LLVM_DEBUG(dbgs() << "*** to: " << MI
);
214 MRI
->replaceRegWith(DstReg
, SrcReg
);
215 MI
.eraseFromParent();
217 // Conservatively, clear any kill flags, since it's possible that they are no
219 MRI
->clearKillFlags(SrcReg
);
225 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
226 /// occur in blocks dominated by the specified block. If any use is in the
227 /// definition block, then return false since it is never legal to move def
230 MachineSinking::AllUsesDominatedByBlock(unsigned Reg
,
231 MachineBasicBlock
*MBB
,
232 MachineBasicBlock
*DefMBB
,
234 bool &LocalUse
) const {
235 assert(Register::isVirtualRegister(Reg
) && "Only makes sense for vregs");
237 // Ignore debug uses because debug info doesn't affect the code.
238 if (MRI
->use_nodbg_empty(Reg
))
241 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
242 // into and they are all PHI nodes. In this case, machine-sink must break
243 // the critical edge first. e.g.
245 // %bb.1: derived from LLVM BB %bb4.preheader
246 // Predecessors according to CFG: %bb.0
248 // %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
250 // JE_4 <%bb.37>, implicit %eflags
251 // Successors according to CFG: %bb.37 %bb.2
253 // %bb.2: derived from LLVM BB %bb.nph
254 // Predecessors according to CFG: %bb.0 %bb.1
255 // %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
257 for (MachineOperand
&MO
: MRI
->use_nodbg_operands(Reg
)) {
258 MachineInstr
*UseInst
= MO
.getParent();
259 unsigned OpNo
= &MO
- &UseInst
->getOperand(0);
260 MachineBasicBlock
*UseBlock
= UseInst
->getParent();
261 if (!(UseBlock
== MBB
&& UseInst
->isPHI() &&
262 UseInst
->getOperand(OpNo
+1).getMBB() == DefMBB
)) {
263 BreakPHIEdge
= false;
270 for (MachineOperand
&MO
: MRI
->use_nodbg_operands(Reg
)) {
271 // Determine the block of the use.
272 MachineInstr
*UseInst
= MO
.getParent();
273 unsigned OpNo
= &MO
- &UseInst
->getOperand(0);
274 MachineBasicBlock
*UseBlock
= UseInst
->getParent();
275 if (UseInst
->isPHI()) {
276 // PHI nodes use the operand in the predecessor block, not the block with
278 UseBlock
= UseInst
->getOperand(OpNo
+1).getMBB();
279 } else if (UseBlock
== DefMBB
) {
284 // Check that it dominates.
285 if (!DT
->dominates(MBB
, UseBlock
))
292 bool MachineSinking::runOnMachineFunction(MachineFunction
&MF
) {
293 if (skipFunction(MF
.getFunction()))
296 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
298 TII
= MF
.getSubtarget().getInstrInfo();
299 TRI
= MF
.getSubtarget().getRegisterInfo();
300 MRI
= &MF
.getRegInfo();
301 DT
= &getAnalysis
<MachineDominatorTree
>();
302 PDT
= &getAnalysis
<MachinePostDominatorTree
>();
303 LI
= &getAnalysis
<MachineLoopInfo
>();
304 MBFI
= UseBlockFreqInfo
? &getAnalysis
<MachineBlockFrequencyInfo
>() : nullptr;
305 MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
306 AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
308 bool EverMadeChange
= false;
311 bool MadeChange
= false;
313 // Process all basic blocks.
314 CEBCandidates
.clear();
317 MadeChange
|= ProcessBlock(MBB
);
319 // If we have anything we marked as toSplit, split it now.
320 for (auto &Pair
: ToSplit
) {
321 auto NewSucc
= Pair
.first
->SplitCriticalEdge(Pair
.second
, *this);
322 if (NewSucc
!= nullptr) {
323 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
324 << printMBBReference(*Pair
.first
) << " -- "
325 << printMBBReference(*NewSucc
) << " -- "
326 << printMBBReference(*Pair
.second
) << '\n');
330 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
332 // If this iteration over the code changed anything, keep iterating.
333 if (!MadeChange
) break;
334 EverMadeChange
= true;
337 // Now clear any kill flags for recorded registers.
338 for (auto I
: RegsToClearKillFlags
)
339 MRI
->clearKillFlags(I
);
340 RegsToClearKillFlags
.clear();
342 return EverMadeChange
;
345 bool MachineSinking::ProcessBlock(MachineBasicBlock
&MBB
) {
346 // Can't sink anything out of a block that has less than two successors.
347 if (MBB
.succ_size() <= 1 || MBB
.empty()) return false;
349 // Don't bother sinking code out of unreachable blocks. In addition to being
350 // unprofitable, it can also lead to infinite looping, because in an
351 // unreachable loop there may be nowhere to stop.
352 if (!DT
->isReachableFromEntry(&MBB
)) return false;
354 bool MadeChange
= false;
356 // Cache all successors, sorted by frequency info and loop depth.
357 AllSuccsCache AllSuccessors
;
359 // Walk the basic block bottom-up. Remember if we saw a store.
360 MachineBasicBlock::iterator I
= MBB
.end();
362 bool ProcessedBegin
, SawStore
= false;
364 MachineInstr
&MI
= *I
; // The instruction to sink.
366 // Predecrement I (if it's not begin) so that it isn't invalidated by
368 ProcessedBegin
= I
== MBB
.begin();
372 if (MI
.isDebugInstr())
375 bool Joined
= PerformTrivialForwardCoalescing(MI
, &MBB
);
381 if (SinkInstruction(MI
, SawStore
, AllSuccessors
)) {
386 // If we just processed the first instruction in the block, we're done.
387 } while (!ProcessedBegin
);
392 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr
&MI
,
393 MachineBasicBlock
*From
,
394 MachineBasicBlock
*To
) {
395 // FIXME: Need much better heuristics.
397 // If the pass has already considered breaking this edge (during this pass
398 // through the function), then let's go ahead and break it. This means
399 // sinking multiple "cheap" instructions into the same block.
400 if (!CEBCandidates
.insert(std::make_pair(From
, To
)).second
)
403 if (!MI
.isCopy() && !TII
->isAsCheapAsAMove(MI
))
406 if (From
->isSuccessor(To
) && MBPI
->getEdgeProbability(From
, To
) <=
407 BranchProbability(SplitEdgeProbabilityThreshold
, 100))
410 // MI is cheap, we probably don't want to break the critical edge for it.
411 // However, if this would allow some definitions of its source operands
412 // to be sunk then it's probably worth it.
413 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
414 const MachineOperand
&MO
= MI
.getOperand(i
);
415 if (!MO
.isReg() || !MO
.isUse())
417 unsigned Reg
= MO
.getReg();
421 // We don't move live definitions of physical registers,
422 // so sinking their uses won't enable any opportunities.
423 if (Register::isPhysicalRegister(Reg
))
426 // If this instruction is the only user of a virtual register,
427 // check if breaking the edge will enable sinking
428 // both this instruction and the defining instruction.
429 if (MRI
->hasOneNonDBGUse(Reg
)) {
430 // If the definition resides in same MBB,
431 // claim it's likely we can sink these together.
432 // If definition resides elsewhere, we aren't
433 // blocking it from being sunk so don't break the edge.
434 MachineInstr
*DefMI
= MRI
->getVRegDef(Reg
);
435 if (DefMI
->getParent() == MI
.getParent())
443 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr
&MI
,
444 MachineBasicBlock
*FromBB
,
445 MachineBasicBlock
*ToBB
,
447 if (!isWorthBreakingCriticalEdge(MI
, FromBB
, ToBB
))
450 // Avoid breaking back edge. From == To means backedge for single BB loop.
451 if (!SplitEdges
|| FromBB
== ToBB
)
454 // Check for backedges of more "complex" loops.
455 if (LI
->getLoopFor(FromBB
) == LI
->getLoopFor(ToBB
) &&
456 LI
->isLoopHeader(ToBB
))
459 // It's not always legal to break critical edges and sink the computation
467 // ... no uses of v1024
473 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
482 // ... no uses of v1024
488 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
489 // flow. We need to ensure the new basic block where the computation is
490 // sunk to dominates all the uses.
491 // It's only legal to break critical edge and sink the computation to the
492 // new block if all the predecessors of "To", except for "From", are
493 // not dominated by "From". Given SSA property, this means these
494 // predecessors are dominated by "To".
496 // There is no need to do this check if all the uses are PHI nodes. PHI
497 // sources are only defined on the specific predecessor edges.
499 for (MachineBasicBlock::pred_iterator PI
= ToBB
->pred_begin(),
500 E
= ToBB
->pred_end(); PI
!= E
; ++PI
) {
503 if (!DT
->dominates(ToBB
, *PI
))
508 ToSplit
.insert(std::make_pair(FromBB
, ToBB
));
513 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
514 bool MachineSinking::isProfitableToSinkTo(unsigned Reg
, MachineInstr
&MI
,
515 MachineBasicBlock
*MBB
,
516 MachineBasicBlock
*SuccToSinkTo
,
517 AllSuccsCache
&AllSuccessors
) {
518 assert (SuccToSinkTo
&& "Invalid SinkTo Candidate BB");
520 if (MBB
== SuccToSinkTo
)
523 // It is profitable if SuccToSinkTo does not post dominate current block.
524 if (!PDT
->dominates(SuccToSinkTo
, MBB
))
527 // It is profitable to sink an instruction from a deeper loop to a shallower
528 // loop, even if the latter post-dominates the former (PR21115).
529 if (LI
->getLoopDepth(MBB
) > LI
->getLoopDepth(SuccToSinkTo
))
532 // Check if only use in post dominated block is PHI instruction.
533 bool NonPHIUse
= false;
534 for (MachineInstr
&UseInst
: MRI
->use_nodbg_instructions(Reg
)) {
535 MachineBasicBlock
*UseBlock
= UseInst
.getParent();
536 if (UseBlock
== SuccToSinkTo
&& !UseInst
.isPHI())
542 // If SuccToSinkTo post dominates then also it may be profitable if MI
543 // can further profitably sinked into another block in next round.
544 bool BreakPHIEdge
= false;
545 // FIXME - If finding successor is compile time expensive then cache results.
546 if (MachineBasicBlock
*MBB2
=
547 FindSuccToSinkTo(MI
, SuccToSinkTo
, BreakPHIEdge
, AllSuccessors
))
548 return isProfitableToSinkTo(Reg
, MI
, SuccToSinkTo
, MBB2
, AllSuccessors
);
550 // If SuccToSinkTo is final destination and it is a post dominator of current
551 // block then it is not profitable to sink MI into SuccToSinkTo block.
555 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
556 /// computing it if it was not already cached.
557 SmallVector
<MachineBasicBlock
*, 4> &
558 MachineSinking::GetAllSortedSuccessors(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
559 AllSuccsCache
&AllSuccessors
) const {
560 // Do we have the sorted successors in cache ?
561 auto Succs
= AllSuccessors
.find(MBB
);
562 if (Succs
!= AllSuccessors
.end())
563 return Succs
->second
;
565 SmallVector
<MachineBasicBlock
*, 4> AllSuccs(MBB
->succ_begin(),
568 // Handle cases where sinking can happen but where the sink point isn't a
569 // successor. For example:
575 const std::vector
<MachineDomTreeNode
*> &Children
=
576 DT
->getNode(MBB
)->getChildren();
577 for (const auto &DTChild
: Children
)
578 // DomTree children of MBB that have MBB as immediate dominator are added.
579 if (DTChild
->getIDom()->getBlock() == MI
.getParent() &&
580 // Skip MBBs already added to the AllSuccs vector above.
581 !MBB
->isSuccessor(DTChild
->getBlock()))
582 AllSuccs
.push_back(DTChild
->getBlock());
584 // Sort Successors according to their loop depth or block frequency info.
586 AllSuccs
, [this](const MachineBasicBlock
*L
, const MachineBasicBlock
*R
) {
587 uint64_t LHSFreq
= MBFI
? MBFI
->getBlockFreq(L
).getFrequency() : 0;
588 uint64_t RHSFreq
= MBFI
? MBFI
->getBlockFreq(R
).getFrequency() : 0;
589 bool HasBlockFreq
= LHSFreq
!= 0 && RHSFreq
!= 0;
590 return HasBlockFreq
? LHSFreq
< RHSFreq
591 : LI
->getLoopDepth(L
) < LI
->getLoopDepth(R
);
594 auto it
= AllSuccessors
.insert(std::make_pair(MBB
, AllSuccs
));
596 return it
.first
->second
;
599 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
601 MachineSinking::FindSuccToSinkTo(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
603 AllSuccsCache
&AllSuccessors
) {
604 assert (MBB
&& "Invalid MachineBasicBlock!");
606 // Loop over all the operands of the specified instruction. If there is
607 // anything we can't handle, bail out.
609 // SuccToSinkTo - This is the successor to sink this instruction to, once we
611 MachineBasicBlock
*SuccToSinkTo
= nullptr;
612 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
613 const MachineOperand
&MO
= MI
.getOperand(i
);
614 if (!MO
.isReg()) continue; // Ignore non-register operands.
616 unsigned Reg
= MO
.getReg();
617 if (Reg
== 0) continue;
619 if (Register::isPhysicalRegister(Reg
)) {
621 // If the physreg has no defs anywhere, it's just an ambient register
622 // and we can freely move its uses. Alternatively, if it's allocatable,
623 // it could get allocated to something with a def during allocation.
624 if (!MRI
->isConstantPhysReg(Reg
))
626 } else if (!MO
.isDead()) {
627 // A def that isn't dead. We can't move it.
631 // Virtual register uses are always safe to sink.
632 if (MO
.isUse()) continue;
634 // If it's not safe to move defs of the register class, then abort.
635 if (!TII
->isSafeToMoveRegClassDefs(MRI
->getRegClass(Reg
)))
638 // Virtual register defs can only be sunk if all their uses are in blocks
639 // dominated by one of the successors.
641 // If a previous operand picked a block to sink to, then this operand
642 // must be sinkable to the same block.
643 bool LocalUse
= false;
644 if (!AllUsesDominatedByBlock(Reg
, SuccToSinkTo
, MBB
,
645 BreakPHIEdge
, LocalUse
))
651 // Otherwise, we should look at all the successors and decide which one
652 // we should sink to. If we have reliable block frequency information
653 // (frequency != 0) available, give successors with smaller frequencies
654 // higher priority, otherwise prioritize smaller loop depths.
655 for (MachineBasicBlock
*SuccBlock
:
656 GetAllSortedSuccessors(MI
, MBB
, AllSuccessors
)) {
657 bool LocalUse
= false;
658 if (AllUsesDominatedByBlock(Reg
, SuccBlock
, MBB
,
659 BreakPHIEdge
, LocalUse
)) {
660 SuccToSinkTo
= SuccBlock
;
664 // Def is used locally, it's never safe to move this def.
668 // If we couldn't find a block to sink to, ignore this instruction.
671 if (!isProfitableToSinkTo(Reg
, MI
, MBB
, SuccToSinkTo
, AllSuccessors
))
676 // It is not possible to sink an instruction into its own block. This can
677 // happen with loops.
678 if (MBB
== SuccToSinkTo
)
681 // It's not safe to sink instructions to EH landing pad. Control flow into
682 // landing pad is implicitly defined.
683 if (SuccToSinkTo
&& SuccToSinkTo
->isEHPad())
689 /// Return true if MI is likely to be usable as a memory operation by the
690 /// implicit null check optimization.
692 /// This is a "best effort" heuristic, and should not be relied upon for
693 /// correctness. This returning true does not guarantee that the implicit null
694 /// check optimization is legal over MI, and this returning false does not
695 /// guarantee MI cannot possibly be used to do a null check.
696 static bool SinkingPreventsImplicitNullCheck(MachineInstr
&MI
,
697 const TargetInstrInfo
*TII
,
698 const TargetRegisterInfo
*TRI
) {
699 using MachineBranchPredicate
= TargetInstrInfo::MachineBranchPredicate
;
701 auto *MBB
= MI
.getParent();
702 if (MBB
->pred_size() != 1)
705 auto *PredMBB
= *MBB
->pred_begin();
706 auto *PredBB
= PredMBB
->getBasicBlock();
708 // Frontends that don't use implicit null checks have no reason to emit
709 // branches with make.implicit metadata, and this function should always
710 // return false for them.
712 !PredBB
->getTerminator()->getMetadata(LLVMContext::MD_make_implicit
))
715 const MachineOperand
*BaseOp
;
717 if (!TII
->getMemOperandWithOffset(MI
, BaseOp
, Offset
, TRI
))
720 if (!BaseOp
->isReg())
723 if (!(MI
.mayLoad() && !MI
.isPredicable()))
726 MachineBranchPredicate MBP
;
727 if (TII
->analyzeBranchPredicate(*PredMBB
, MBP
, false))
730 return MBP
.LHS
.isReg() && MBP
.RHS
.isImm() && MBP
.RHS
.getImm() == 0 &&
731 (MBP
.Predicate
== MachineBranchPredicate::PRED_NE
||
732 MBP
.Predicate
== MachineBranchPredicate::PRED_EQ
) &&
733 MBP
.LHS
.getReg() == BaseOp
->getReg();
736 /// Sink an instruction and its associated debug instructions. If the debug
737 /// instructions to be sunk are already known, they can be provided in DbgVals.
738 static void performSink(MachineInstr
&MI
, MachineBasicBlock
&SuccToSinkTo
,
739 MachineBasicBlock::iterator InsertPos
,
740 SmallVectorImpl
<MachineInstr
*> *DbgVals
= nullptr) {
741 // If debug values are provided use those, otherwise call collectDebugValues.
742 SmallVector
<MachineInstr
*, 2> DbgValuesToSink
;
744 DbgValuesToSink
.insert(DbgValuesToSink
.begin(),
745 DbgVals
->begin(), DbgVals
->end());
747 MI
.collectDebugValues(DbgValuesToSink
);
749 // If we cannot find a location to use (merge with), then we erase the debug
750 // location to prevent debug-info driven tools from potentially reporting
751 // wrong location information.
752 if (!SuccToSinkTo
.empty() && InsertPos
!= SuccToSinkTo
.end())
753 MI
.setDebugLoc(DILocation::getMergedLocation(MI
.getDebugLoc(),
754 InsertPos
->getDebugLoc()));
756 MI
.setDebugLoc(DebugLoc());
758 // Move the instruction.
759 MachineBasicBlock
*ParentBlock
= MI
.getParent();
760 SuccToSinkTo
.splice(InsertPos
, ParentBlock
, MI
,
761 ++MachineBasicBlock::iterator(MI
));
763 // Move previously adjacent debug value instructions to the insert position.
764 for (SmallVectorImpl
<MachineInstr
*>::iterator DBI
= DbgValuesToSink
.begin(),
765 DBE
= DbgValuesToSink
.end();
767 MachineInstr
*DbgMI
= *DBI
;
768 SuccToSinkTo
.splice(InsertPos
, ParentBlock
, DbgMI
,
769 ++MachineBasicBlock::iterator(DbgMI
));
773 /// SinkInstruction - Determine whether it is safe to sink the specified machine
774 /// instruction out of its current block into a successor.
775 bool MachineSinking::SinkInstruction(MachineInstr
&MI
, bool &SawStore
,
776 AllSuccsCache
&AllSuccessors
) {
777 // Don't sink instructions that the target prefers not to sink.
778 if (!TII
->shouldSink(MI
))
781 // Check if it's safe to move the instruction.
782 if (!MI
.isSafeToMove(AA
, SawStore
))
785 // Convergent operations may not be made control-dependent on additional
787 if (MI
.isConvergent())
790 // Don't break implicit null checks. This is a performance heuristic, and not
791 // required for correctness.
792 if (SinkingPreventsImplicitNullCheck(MI
, TII
, TRI
))
795 // FIXME: This should include support for sinking instructions within the
796 // block they are currently in to shorten the live ranges. We often get
797 // instructions sunk into the top of a large block, but it would be better to
798 // also sink them down before their first use in the block. This xform has to
799 // be careful not to *increase* register pressure though, e.g. sinking
800 // "x = y + z" down if it kills y and z would increase the live ranges of y
801 // and z and only shrink the live range of x.
803 bool BreakPHIEdge
= false;
804 MachineBasicBlock
*ParentBlock
= MI
.getParent();
805 MachineBasicBlock
*SuccToSinkTo
=
806 FindSuccToSinkTo(MI
, ParentBlock
, BreakPHIEdge
, AllSuccessors
);
808 // If there are no outputs, it must have side-effects.
812 // If the instruction to move defines a dead physical register which is live
813 // when leaving the basic block, don't move it because it could turn into a
814 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
815 for (unsigned I
= 0, E
= MI
.getNumOperands(); I
!= E
; ++I
) {
816 const MachineOperand
&MO
= MI
.getOperand(I
);
817 if (!MO
.isReg()) continue;
818 unsigned Reg
= MO
.getReg();
819 if (Reg
== 0 || !Register::isPhysicalRegister(Reg
))
821 if (SuccToSinkTo
->isLiveIn(Reg
))
825 LLVM_DEBUG(dbgs() << "Sink instr " << MI
<< "\tinto block " << *SuccToSinkTo
);
827 // If the block has multiple predecessors, this is a critical edge.
828 // Decide if we can sink along it or need to break the edge.
829 if (SuccToSinkTo
->pred_size() > 1) {
830 // We cannot sink a load across a critical edge - there may be stores in
832 bool TryBreak
= false;
834 if (!MI
.isSafeToMove(AA
, store
)) {
835 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
839 // We don't want to sink across a critical edge if we don't dominate the
840 // successor. We could be introducing calculations to new code paths.
841 if (!TryBreak
&& !DT
->dominates(ParentBlock
, SuccToSinkTo
)) {
842 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
846 // Don't sink instructions into a loop.
847 if (!TryBreak
&& LI
->isLoopHeader(SuccToSinkTo
)) {
848 LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
852 // Otherwise we are OK with sinking along a critical edge.
854 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
856 // Mark this edge as to be split.
857 // If the edge can actually be split, the next iteration of the main loop
858 // will sink MI in the newly created block.
860 PostponeSplitCriticalEdge(MI
, ParentBlock
, SuccToSinkTo
, BreakPHIEdge
);
862 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
863 "break critical edge\n");
864 // The instruction will not be sunk this time.
870 // BreakPHIEdge is true if all the uses are in the successor MBB being
871 // sunken into and they are all PHI nodes. In this case, machine-sink must
872 // break the critical edge first.
873 bool Status
= PostponeSplitCriticalEdge(MI
, ParentBlock
,
874 SuccToSinkTo
, BreakPHIEdge
);
876 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
877 "break critical edge\n");
878 // The instruction will not be sunk this time.
882 // Determine where to insert into. Skip phi nodes.
883 MachineBasicBlock::iterator InsertPos
= SuccToSinkTo
->begin();
884 while (InsertPos
!= SuccToSinkTo
->end() && InsertPos
->isPHI())
887 performSink(MI
, *SuccToSinkTo
, InsertPos
);
889 // Conservatively, clear any kill flags, since it's possible that they are no
891 // Note that we have to clear the kill flags for any register this instruction
892 // uses as we may sink over another instruction which currently kills the
894 for (MachineOperand
&MO
: MI
.operands()) {
895 if (MO
.isReg() && MO
.isUse())
896 RegsToClearKillFlags
.set(MO
.getReg()); // Remember to clear kill flags.
902 //===----------------------------------------------------------------------===//
903 // This pass is not intended to be a replacement or a complete alternative
904 // for the pre-ra machine sink pass. It is only designed to sink COPY
905 // instructions which should be handled after RA.
907 // This pass sinks COPY instructions into a successor block, if the COPY is not
908 // used in the current block and the COPY is live-in to a single successor
909 // (i.e., doesn't require the COPY to be duplicated). This avoids executing the
910 // copy on paths where their results aren't needed. This also exposes
911 // additional opportunites for dead copy elimination and shrink wrapping.
913 // These copies were either not handled by or are inserted after the MachineSink
914 // pass. As an example of the former case, the MachineSink pass cannot sink
915 // COPY instructions with allocatable source registers; for AArch64 these type
916 // of copy instructions are frequently used to move function parameters (PhyReg)
917 // into virtual registers in the entry block.
919 // For the machine IR below, this pass will sink %w19 in the entry into its
920 // successor (%bb.1) because %w19 is only live-in in %bb.1.
922 // %wzr = SUBSWri %w1, 1
928 // %w0 = ADDWrr %w0, %w19
933 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
934 // able to see %bb.0 as a candidate.
935 //===----------------------------------------------------------------------===//
938 class PostRAMachineSinking
: public MachineFunctionPass
{
940 bool runOnMachineFunction(MachineFunction
&MF
) override
;
943 PostRAMachineSinking() : MachineFunctionPass(ID
) {}
944 StringRef
getPassName() const override
{ return "PostRA Machine Sink"; }
946 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
947 AU
.setPreservesCFG();
948 MachineFunctionPass::getAnalysisUsage(AU
);
951 MachineFunctionProperties
getRequiredProperties() const override
{
952 return MachineFunctionProperties().set(
953 MachineFunctionProperties::Property::NoVRegs
);
957 /// Track which register units have been modified and used.
958 LiveRegUnits ModifiedRegUnits
, UsedRegUnits
;
960 /// Track DBG_VALUEs of (unmodified) register units.
961 DenseMap
<unsigned, TinyPtrVector
<MachineInstr
*>> SeenDbgInstrs
;
963 /// Sink Copy instructions unused in the same block close to their uses in
965 bool tryToSinkCopy(MachineBasicBlock
&BB
, MachineFunction
&MF
,
966 const TargetRegisterInfo
*TRI
, const TargetInstrInfo
*TII
);
970 char PostRAMachineSinking::ID
= 0;
971 char &llvm::PostRAMachineSinkingID
= PostRAMachineSinking::ID
;
973 INITIALIZE_PASS(PostRAMachineSinking
, "postra-machine-sink",
974 "PostRA Machine Sink", false, false)
976 static bool aliasWithRegsInLiveIn(MachineBasicBlock
&MBB
, unsigned Reg
,
977 const TargetRegisterInfo
*TRI
) {
978 LiveRegUnits
LiveInRegUnits(*TRI
);
979 LiveInRegUnits
.addLiveIns(MBB
);
980 return !LiveInRegUnits
.available(Reg
);
983 static MachineBasicBlock
*
984 getSingleLiveInSuccBB(MachineBasicBlock
&CurBB
,
985 const SmallPtrSetImpl
<MachineBasicBlock
*> &SinkableBBs
,
986 unsigned Reg
, const TargetRegisterInfo
*TRI
) {
987 // Try to find a single sinkable successor in which Reg is live-in.
988 MachineBasicBlock
*BB
= nullptr;
989 for (auto *SI
: SinkableBBs
) {
990 if (aliasWithRegsInLiveIn(*SI
, Reg
, TRI
)) {
991 // If BB is set here, Reg is live-in to at least two sinkable successors,
998 // Reg is not live-in to any sinkable successors.
1002 // Check if any register aliased with Reg is live-in in other successors.
1003 for (auto *SI
: CurBB
.successors()) {
1004 if (!SinkableBBs
.count(SI
) && aliasWithRegsInLiveIn(*SI
, Reg
, TRI
))
1010 static MachineBasicBlock
*
1011 getSingleLiveInSuccBB(MachineBasicBlock
&CurBB
,
1012 const SmallPtrSetImpl
<MachineBasicBlock
*> &SinkableBBs
,
1013 ArrayRef
<unsigned> DefedRegsInCopy
,
1014 const TargetRegisterInfo
*TRI
) {
1015 MachineBasicBlock
*SingleBB
= nullptr;
1016 for (auto DefReg
: DefedRegsInCopy
) {
1017 MachineBasicBlock
*BB
=
1018 getSingleLiveInSuccBB(CurBB
, SinkableBBs
, DefReg
, TRI
);
1019 if (!BB
|| (SingleBB
&& SingleBB
!= BB
))
1026 static void clearKillFlags(MachineInstr
*MI
, MachineBasicBlock
&CurBB
,
1027 SmallVectorImpl
<unsigned> &UsedOpsInCopy
,
1028 LiveRegUnits
&UsedRegUnits
,
1029 const TargetRegisterInfo
*TRI
) {
1030 for (auto U
: UsedOpsInCopy
) {
1031 MachineOperand
&MO
= MI
->getOperand(U
);
1032 unsigned SrcReg
= MO
.getReg();
1033 if (!UsedRegUnits
.available(SrcReg
)) {
1034 MachineBasicBlock::iterator NI
= std::next(MI
->getIterator());
1035 for (MachineInstr
&UI
: make_range(NI
, CurBB
.end())) {
1036 if (UI
.killsRegister(SrcReg
, TRI
)) {
1037 UI
.clearRegisterKills(SrcReg
, TRI
);
1046 static void updateLiveIn(MachineInstr
*MI
, MachineBasicBlock
*SuccBB
,
1047 SmallVectorImpl
<unsigned> &UsedOpsInCopy
,
1048 SmallVectorImpl
<unsigned> &DefedRegsInCopy
) {
1049 MachineFunction
&MF
= *SuccBB
->getParent();
1050 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1051 for (unsigned DefReg
: DefedRegsInCopy
)
1052 for (MCSubRegIterator
S(DefReg
, TRI
, true); S
.isValid(); ++S
)
1053 SuccBB
->removeLiveIn(*S
);
1054 for (auto U
: UsedOpsInCopy
) {
1055 unsigned Reg
= MI
->getOperand(U
).getReg();
1056 if (!SuccBB
->isLiveIn(Reg
))
1057 SuccBB
->addLiveIn(Reg
);
1061 static bool hasRegisterDependency(MachineInstr
*MI
,
1062 SmallVectorImpl
<unsigned> &UsedOpsInCopy
,
1063 SmallVectorImpl
<unsigned> &DefedRegsInCopy
,
1064 LiveRegUnits
&ModifiedRegUnits
,
1065 LiveRegUnits
&UsedRegUnits
) {
1066 bool HasRegDependency
= false;
1067 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
1068 MachineOperand
&MO
= MI
->getOperand(i
);
1071 unsigned Reg
= MO
.getReg();
1075 if (!ModifiedRegUnits
.available(Reg
) || !UsedRegUnits
.available(Reg
)) {
1076 HasRegDependency
= true;
1079 DefedRegsInCopy
.push_back(Reg
);
1081 // FIXME: instead of isUse(), readsReg() would be a better fix here,
1082 // For example, we can ignore modifications in reg with undef. However,
1083 // it's not perfectly clear if skipping the internal read is safe in all
1085 } else if (MO
.isUse()) {
1086 if (!ModifiedRegUnits
.available(Reg
)) {
1087 HasRegDependency
= true;
1090 UsedOpsInCopy
.push_back(i
);
1093 return HasRegDependency
;
1096 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock
&CurBB
,
1097 MachineFunction
&MF
,
1098 const TargetRegisterInfo
*TRI
,
1099 const TargetInstrInfo
*TII
) {
1100 SmallPtrSet
<MachineBasicBlock
*, 2> SinkableBBs
;
1101 // FIXME: For now, we sink only to a successor which has a single predecessor
1102 // so that we can directly sink COPY instructions to the successor without
1103 // adding any new block or branch instruction.
1104 for (MachineBasicBlock
*SI
: CurBB
.successors())
1105 if (!SI
->livein_empty() && SI
->pred_size() == 1)
1106 SinkableBBs
.insert(SI
);
1108 if (SinkableBBs
.empty())
1111 bool Changed
= false;
1113 // Track which registers have been modified and used between the end of the
1114 // block and the current instruction.
1115 ModifiedRegUnits
.clear();
1116 UsedRegUnits
.clear();
1117 SeenDbgInstrs
.clear();
1119 for (auto I
= CurBB
.rbegin(), E
= CurBB
.rend(); I
!= E
;) {
1120 MachineInstr
*MI
= &*I
;
1123 // Track the operand index for use in Copy.
1124 SmallVector
<unsigned, 2> UsedOpsInCopy
;
1125 // Track the register number defed in Copy.
1126 SmallVector
<unsigned, 2> DefedRegsInCopy
;
1128 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1129 // for DBG_VALUEs later, record them when they're encountered.
1130 if (MI
->isDebugValue()) {
1131 auto &MO
= MI
->getOperand(0);
1132 if (MO
.isReg() && Register::isPhysicalRegister(MO
.getReg())) {
1133 // Bail if we can already tell the sink would be rejected, rather
1134 // than needlessly accumulating lots of DBG_VALUEs.
1135 if (hasRegisterDependency(MI
, UsedOpsInCopy
, DefedRegsInCopy
,
1136 ModifiedRegUnits
, UsedRegUnits
))
1139 // Record debug use of this register.
1140 SeenDbgInstrs
[MO
.getReg()].push_back(MI
);
1145 if (MI
->isDebugInstr())
1148 // Do not move any instruction across function call.
1152 if (!MI
->isCopy() || !MI
->getOperand(0).isRenamable()) {
1153 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1158 // Don't sink the COPY if it would violate a register dependency.
1159 if (hasRegisterDependency(MI
, UsedOpsInCopy
, DefedRegsInCopy
,
1160 ModifiedRegUnits
, UsedRegUnits
)) {
1161 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1165 assert((!UsedOpsInCopy
.empty() && !DefedRegsInCopy
.empty()) &&
1166 "Unexpect SrcReg or DefReg");
1167 MachineBasicBlock
*SuccBB
=
1168 getSingleLiveInSuccBB(CurBB
, SinkableBBs
, DefedRegsInCopy
, TRI
);
1169 // Don't sink if we cannot find a single sinkable successor in which Reg
1172 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1176 assert((SuccBB
->pred_size() == 1 && *SuccBB
->pred_begin() == &CurBB
) &&
1177 "Unexpected predecessor");
1179 // Collect DBG_VALUEs that must sink with this copy.
1180 SmallVector
<MachineInstr
*, 4> DbgValsToSink
;
1181 for (auto &MO
: MI
->operands()) {
1182 if (!MO
.isReg() || !MO
.isDef())
1184 unsigned reg
= MO
.getReg();
1185 for (auto *MI
: SeenDbgInstrs
.lookup(reg
))
1186 DbgValsToSink
.push_back(MI
);
1189 // Clear the kill flag if SrcReg is killed between MI and the end of the
1191 clearKillFlags(MI
, CurBB
, UsedOpsInCopy
, UsedRegUnits
, TRI
);
1192 MachineBasicBlock::iterator InsertPos
= SuccBB
->getFirstNonPHI();
1193 performSink(*MI
, *SuccBB
, InsertPos
, &DbgValsToSink
);
1194 updateLiveIn(MI
, SuccBB
, UsedOpsInCopy
, DefedRegsInCopy
);
1197 ++NumPostRACopySink
;
1202 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction
&MF
) {
1203 if (skipFunction(MF
.getFunction()))
1206 bool Changed
= false;
1207 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1208 const TargetInstrInfo
*TII
= MF
.getSubtarget().getInstrInfo();
1210 ModifiedRegUnits
.init(*TRI
);
1211 UsedRegUnits
.init(*TRI
);
1213 Changed
|= tryToSinkCopy(BB
, MF
, TRI
, TII
);