#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
#include "llvm/CodeGen/MachineCycleAnalysis.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachinePostDominators.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegisterClassInfo.h"
#include "llvm/CodeGen/RegisterPressure.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/InitializePasses.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/BranchProbability.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <map>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "machine-sink"
static cl::opt<bool>
SplitEdges("machine-sink-split",
cl::desc("Split critical edges during machine sinking"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
UseBlockFreqInfo("machine-sink-bfi",
cl::desc("Use block frequency info to find successors to sink"),
cl::init(true), cl::Hidden);
static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
"machine-sink-split-probability-threshold",
cl::desc(
"Percentage threshold for splitting single-instruction critical edge. "
"If the branch threshold is higher than this threshold, we allow "
"speculative execution of up to 1 instruction to avoid branching to "
"splitted critical edge"),
cl::init(40), cl::Hidden);
static cl::opt<unsigned> SinkLoadInstsPerBlockThreshold(
"machine-sink-load-instrs-threshold",
cl::desc("Do not try to find alias store for a load if there is a in-path "
"block whose instruction number is higher than this threshold."),
cl::init(2000), cl::Hidden);
static cl::opt<unsigned> SinkLoadBlocksThreshold(
"machine-sink-load-blocks-threshold",
cl::desc("Do not try to find alias store for a load if the block number in "
"the straight line is higher than this threshold."),
cl::init(20), cl::Hidden);
static cl::opt<bool>
SinkInstsIntoCycle("sink-insts-to-avoid-spills",
cl::desc("Sink instructions into cycles to avoid "
"register spills"),
cl::init(false), cl::Hidden);
static cl::opt<unsigned> SinkIntoCycleLimit(
"machine-sink-cycle-limit",
cl::desc("The maximum number of instructions considered for cycle sinking."),
cl::init(50), cl::Hidden);
STATISTIC(NumSunk, "Number of machine instructions sunk");
STATISTIC(NumCycleSunk, "Number of machine instructions sunk into a cycle");
STATISTIC(NumSplit, "Number of critical edges split");
STATISTIC(NumCoalesces, "Number of copies coalesced");
STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
namespace {
class MachineSinking : public MachineFunctionPass {
const TargetInstrInfo *TII;
const TargetRegisterInfo *TRI;
MachineRegisterInfo *MRI; MachineDominatorTree *DT; MachinePostDominatorTree *PDT; MachineCycleInfo *CI;
MachineBlockFrequencyInfo *MBFI;
const MachineBranchProbabilityInfo *MBPI;
AliasAnalysis *AA;
RegisterClassInfo RegClassInfo;
SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
CEBCandidates;
SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
DenseSet<Register> RegsToClearKillFlags;
using AllSuccsCache =
std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers;
DenseSet<DebugVariable> SeenDbgVars;
std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>, bool>
HasStoreCache;
std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>,
std::vector<MachineInstr *>>
StoreInstrCache;
std::map<MachineBasicBlock *, std::vector<unsigned>> CachedRegisterPressure;
public:
static char ID;
MachineSinking() : MachineFunctionPass(ID) {
initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
MachineFunctionPass::getAnalysisUsage(AU);
AU.addRequired<AAResultsWrapperPass>();
AU.addRequired<MachineDominatorTree>();
AU.addRequired<MachinePostDominatorTree>();
AU.addRequired<MachineCycleInfoWrapperPass>();
AU.addRequired<MachineBranchProbabilityInfo>();
AU.addPreserved<MachineCycleInfoWrapperPass>();
AU.addPreserved<MachineLoopInfo>();
if (UseBlockFreqInfo)
AU.addRequired<MachineBlockFrequencyInfo>();
}
void releaseMemory() override {
CEBCandidates.clear();
}
private:
bool ProcessBlock(MachineBasicBlock &MBB);
void ProcessDbgInst(MachineInstr &MI);
bool isWorthBreakingCriticalEdge(MachineInstr &MI,
MachineBasicBlock *From,
MachineBasicBlock *To);
bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
MachineInstr &MI);
bool PostponeSplitCriticalEdge(MachineInstr &MI,
MachineBasicBlock *From,
MachineBasicBlock *To,
bool BreakPHIEdge);
bool SinkInstruction(MachineInstr &MI, bool &SawStore,
AllSuccsCache &AllSuccessors);
void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
MachineBasicBlock *TargetBlock);
bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
bool &LocalUse) const;
MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
void FindCycleSinkCandidates(MachineCycle *Cycle, MachineBasicBlock *BB,
SmallVectorImpl<MachineInstr *> &Candidates);
bool SinkIntoCycle(MachineCycle *Cycle, MachineInstr &I);
bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
MachineBasicBlock *MBB,
MachineBasicBlock *SuccToSinkTo,
AllSuccsCache &AllSuccessors);
bool PerformTrivialForwardCoalescing(MachineInstr &MI,
MachineBasicBlock *MBB);
SmallVector<MachineBasicBlock *, 4> &
GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
AllSuccsCache &AllSuccessors) const;
std::vector<unsigned> &getBBRegisterPressure(MachineBasicBlock &MBB);
};
}
char MachineSinking::ID = 0;
char &llvm::MachineSinkingID = MachineSinking::ID;
INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
"Machine code sinking", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(MachineCycleInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
"Machine code sinking", false, false)
bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
MachineBasicBlock *MBB) {
if (!MI.isCopy())
return false;
Register SrcReg = MI.getOperand(1).getReg();
Register DstReg = MI.getOperand(0).getReg();
if (!Register::isVirtualRegister(SrcReg) ||
!Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg))
return false;
const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
if (SRC != DRC)
return false;
MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
if (DefMI->isCopyLike())
return false;
LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
LLVM_DEBUG(dbgs() << "*** to: " << MI);
MRI->replaceRegWith(DstReg, SrcReg);
MI.eraseFromParent();
MRI->clearKillFlags(SrcReg);
++NumCoalesces;
return true;
}
bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
MachineBasicBlock *MBB,
MachineBasicBlock *DefMBB,
bool &BreakPHIEdge,
bool &LocalUse) const {
assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs");
if (MRI->use_nodbg_empty(Reg))
return true;
if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
MachineInstr *UseInst = MO.getParent();
unsigned OpNo = UseInst->getOperandNo(&MO);
MachineBasicBlock *UseBlock = UseInst->getParent();
return UseBlock == MBB && UseInst->isPHI() &&
UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
})) {
BreakPHIEdge = true;
return true;
}
for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
MachineInstr *UseInst = MO.getParent();
unsigned OpNo = &MO - &UseInst->getOperand(0);
MachineBasicBlock *UseBlock = UseInst->getParent();
if (UseInst->isPHI()) {
UseBlock = UseInst->getOperand(OpNo+1).getMBB();
} else if (UseBlock == DefMBB) {
LocalUse = true;
return false;
}
if (!DT->dominates(MBB, UseBlock))
return false;
}
return true;
}
static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
assert(MI.mayLoad() && "Expected MI that loads!");
if (MI.memoperands_empty())
return true;
for (MachineMemOperand *MemOp : MI.memoperands())
if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
if (PSV->isGOT() || PSV->isConstantPool())
return true;
return false;
}
void MachineSinking::FindCycleSinkCandidates(
MachineCycle *Cycle, MachineBasicBlock *BB,
SmallVectorImpl<MachineInstr *> &Candidates) {
for (auto &MI : *BB) {
LLVM_DEBUG(dbgs() << "CycleSink: Analysing candidate: " << MI);
if (!TII->shouldSink(MI)) {
LLVM_DEBUG(dbgs() << "CycleSink: Instruction not a candidate for this "
"target\n");
continue;
}
if (!isCycleInvariant(Cycle, MI)) {
LLVM_DEBUG(dbgs() << "CycleSink: Instruction is not cycle invariant\n");
continue;
}
bool DontMoveAcrossStore = true;
if (!MI.isSafeToMove(AA, DontMoveAcrossStore)) {
LLVM_DEBUG(dbgs() << "CycleSink: Instruction not safe to move.\n");
continue;
}
if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) {
LLVM_DEBUG(dbgs() << "CycleSink: Dont sink GOT or constant pool loads\n");
continue;
}
if (MI.isConvergent())
continue;
const MachineOperand &MO = MI.getOperand(0);
if (!MO.isReg() || !MO.getReg() || !MO.isDef())
continue;
if (!MRI->hasOneDef(MO.getReg()))
continue;
LLVM_DEBUG(dbgs() << "CycleSink: Instruction added as candidate.\n");
Candidates.push_back(&MI);
}
}
bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(MF.getFunction()))
return false;
LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
TII = MF.getSubtarget().getInstrInfo();
TRI = MF.getSubtarget().getRegisterInfo();
MRI = &MF.getRegInfo();
DT = &getAnalysis<MachineDominatorTree>();
PDT = &getAnalysis<MachinePostDominatorTree>();
CI = &getAnalysis<MachineCycleInfoWrapperPass>().getCycleInfo();
MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
RegClassInfo.runOnMachineFunction(MF);
bool EverMadeChange = false;
while (true) {
bool MadeChange = false;
CEBCandidates.clear();
ToSplit.clear();
for (auto &MBB: MF)
MadeChange |= ProcessBlock(MBB);
for (const auto &Pair : ToSplit) {
auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
if (NewSucc != nullptr) {
LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
<< printMBBReference(*Pair.first) << " -- "
<< printMBBReference(*NewSucc) << " -- "
<< printMBBReference(*Pair.second) << '\n');
if (MBFI)
MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
MadeChange = true;
++NumSplit;
} else
LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
}
if (!MadeChange) break;
EverMadeChange = true;
}
if (SinkInstsIntoCycle) {
SmallVector<MachineCycle *, 8> Cycles(CI->toplevel_begin(),
CI->toplevel_end());
for (auto *Cycle : Cycles) {
MachineBasicBlock *Preheader = Cycle->getCyclePreheader();
if (!Preheader) {
LLVM_DEBUG(dbgs() << "CycleSink: Can't find preheader\n");
continue;
}
SmallVector<MachineInstr *, 8> Candidates;
FindCycleSinkCandidates(Cycle, Preheader, Candidates);
unsigned i = 0;
for (MachineInstr *I : llvm::reverse(Candidates)) {
if (i++ == SinkIntoCycleLimit) {
LLVM_DEBUG(dbgs() << "CycleSink: Limit reached of instructions to "
"be analysed.");
break;
}
if (!SinkIntoCycle(Cycle, *I))
break;
EverMadeChange = true;
++NumCycleSunk;
}
}
}
HasStoreCache.clear();
StoreInstrCache.clear();
for (auto I : RegsToClearKillFlags)
MRI->clearKillFlags(I);
RegsToClearKillFlags.clear();
return EverMadeChange;
}
bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
if (MBB.succ_size() <= 1 || MBB.empty()) return false;
if (!DT->isReachableFromEntry(&MBB)) return false;
bool MadeChange = false;
AllSuccsCache AllSuccessors;
MachineBasicBlock::iterator I = MBB.end();
--I;
bool ProcessedBegin, SawStore = false;
do {
MachineInstr &MI = *I;
ProcessedBegin = I == MBB.begin();
if (!ProcessedBegin)
--I;
if (MI.isDebugOrPseudoInstr()) {
if (MI.isDebugValue())
ProcessDbgInst(MI);
continue;
}
bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
if (Joined) {
MadeChange = true;
continue;
}
if (SinkInstruction(MI, SawStore, AllSuccessors)) {
++NumSunk;
MadeChange = true;
}
} while (!ProcessedBegin);
SeenDbgUsers.clear();
SeenDbgVars.clear();
CachedRegisterPressure.clear();
return MadeChange;
}
void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
MI.getDebugLoc()->getInlinedAt());
bool SeenBefore = SeenDbgVars.contains(Var);
for (MachineOperand &MO : MI.debug_operands()) {
if (MO.isReg() && MO.getReg().isVirtual())
SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
}
SeenDbgVars.insert(Var);
}
bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
MachineBasicBlock *From,
MachineBasicBlock *To) {
if (!CEBCandidates.insert(std::make_pair(From, To)).second)
return true;
if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
return true;
if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
BranchProbability(SplitEdgeProbabilityThreshold, 100))
return true;
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg() || !MO.isUse())
continue;
Register Reg = MO.getReg();
if (Reg == 0)
continue;
if (Register::isPhysicalRegister(Reg))
continue;
if (MRI->hasOneNonDBGUse(Reg)) {
MachineInstr *DefMI = MRI->getVRegDef(Reg);
if (DefMI->getParent() == MI.getParent())
return true;
}
}
return false;
}
bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
MachineBasicBlock *FromBB,
MachineBasicBlock *ToBB,
bool BreakPHIEdge) {
if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
return false;
if (!SplitEdges || FromBB == ToBB)
return false;
MachineCycle *FromCycle = CI->getCycle(FromBB);
MachineCycle *ToCycle = CI->getCycle(ToBB);
if (FromCycle == ToCycle && FromCycle &&
(!FromCycle->isReducible() || FromCycle->getHeader() == ToBB))
return false;
if (!BreakPHIEdge) {
for (MachineBasicBlock *Pred : ToBB->predecessors())
if (Pred != FromBB && !DT->dominates(ToBB, Pred))
return false;
}
ToSplit.insert(std::make_pair(FromBB, ToBB));
return true;
}
std::vector<unsigned> &
MachineSinking::getBBRegisterPressure(MachineBasicBlock &MBB) {
auto RP = CachedRegisterPressure.find(&MBB);
if (RP != CachedRegisterPressure.end())
return RP->second;
RegionPressure Pressure;
RegPressureTracker RPTracker(Pressure);
RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(),
false, true);
for (MachineBasicBlock::iterator MII = MBB.instr_end(),
MIE = MBB.instr_begin();
MII != MIE; --MII) {
MachineInstr &MI = *std::prev(MII);
if (MI.isDebugInstr() || MI.isPseudoProbe())
continue;
RegisterOperands RegOpers;
RegOpers.collect(MI, *TRI, *MRI, false, false);
RPTracker.recedeSkipDebugValues();
assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
RPTracker.recede(RegOpers);
}
RPTracker.closeRegion();
auto It = CachedRegisterPressure.insert(
std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
return It.first->second;
}
bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
MachineBasicBlock *MBB,
MachineBasicBlock *SuccToSinkTo,
AllSuccsCache &AllSuccessors) {
assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
if (MBB == SuccToSinkTo)
return false;
if (!PDT->dominates(SuccToSinkTo, MBB))
return true;
if (CI->getCycleDepth(MBB) > CI->getCycleDepth(SuccToSinkTo))
return true;
bool NonPHIUse = false;
for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
MachineBasicBlock *UseBlock = UseInst.getParent();
if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
NonPHIUse = true;
}
if (!NonPHIUse)
return true;
bool BreakPHIEdge = false;
if (MachineBasicBlock *MBB2 =
FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
MachineCycle *MCycle = CI->getCycle(MBB);
if (!MCycle)
return false;
auto isRegisterPressureSetExceedLimit = [&](const TargetRegisterClass *RC) {
unsigned Weight = TRI->getRegClassWeight(RC).RegWeight;
const int *PS = TRI->getRegClassPressureSets(RC);
std::vector<unsigned> BBRegisterPressure =
getBBRegisterPressure(*SuccToSinkTo);
for (; *PS != -1; PS++)
if (Weight + BBRegisterPressure[*PS] >=
TRI->getRegPressureSetLimit(*MBB->getParent(), *PS))
return true;
return false;
};
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (Reg == 0)
continue;
if (Register::isPhysicalRegister(Reg)) {
if (MO.isUse() &&
(MRI->isConstantPhysReg(Reg) || TII->isIgnorableUse(MO)))
continue;
return false;
}
if (MO.isDef()) {
bool LocalUse = false;
if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
LocalUse))
return false;
} else {
MachineInstr *DefMI = MRI->getVRegDef(Reg);
if (!DefMI)
continue;
MachineCycle *Cycle = CI->getCycle(DefMI->getParent());
if (Cycle != MCycle || (DefMI->isPHI() && Cycle && Cycle->isReducible() &&
Cycle->getHeader() == DefMI->getParent()))
continue;
if (isRegisterPressureSetExceedLimit(MRI->getRegClass(Reg))) {
LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
return false;
}
}
}
return true;
}
SmallVector<MachineBasicBlock *, 4> &
MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
AllSuccsCache &AllSuccessors) const {
auto Succs = AllSuccessors.find(MBB);
if (Succs != AllSuccessors.end())
return Succs->second;
SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
if (DTChild->getIDom()->getBlock() == MI.getParent() &&
!MBB->isSuccessor(DTChild->getBlock()))
AllSuccs.push_back(DTChild->getBlock());
}
llvm::stable_sort(
AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
return HasBlockFreq ? LHSFreq < RHSFreq
: CI->getCycleDepth(L) < CI->getCycleDepth(R);
});
auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
return it.first->second;
}
MachineBasicBlock *
MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
bool &BreakPHIEdge,
AllSuccsCache &AllSuccessors) {
assert (MBB && "Invalid MachineBasicBlock!");
MachineBasicBlock *SuccToSinkTo = nullptr;
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg()) continue;
Register Reg = MO.getReg();
if (Reg == 0) continue;
if (Register::isPhysicalRegister(Reg)) {
if (MO.isUse()) {
if (!MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
return nullptr;
} else if (!MO.isDead()) {
return nullptr;
}
} else {
if (MO.isUse()) continue;
if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
return nullptr;
if (SuccToSinkTo) {
bool LocalUse = false;
if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
BreakPHIEdge, LocalUse))
return nullptr;
continue;
}
for (MachineBasicBlock *SuccBlock :
GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
bool LocalUse = false;
if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
BreakPHIEdge, LocalUse)) {
SuccToSinkTo = SuccBlock;
break;
}
if (LocalUse)
return nullptr;
}
if (!SuccToSinkTo)
return nullptr;
if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
return nullptr;
}
}
if (MBB == SuccToSinkTo)
return nullptr;
if (SuccToSinkTo && SuccToSinkTo->isEHPad())
return nullptr;
if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
return nullptr;
return SuccToSinkTo;
}
static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
const TargetInstrInfo *TII,
const TargetRegisterInfo *TRI) {
using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
auto *MBB = MI.getParent();
if (MBB->pred_size() != 1)
return false;
auto *PredMBB = *MBB->pred_begin();
auto *PredBB = PredMBB->getBasicBlock();
if (!PredBB ||
!PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
return false;
const MachineOperand *BaseOp;
int64_t Offset;
bool OffsetIsScalable;
if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
return false;
if (!BaseOp->isReg())
return false;
if (!(MI.mayLoad() && !MI.isPredicable()))
return false;
MachineBranchPredicate MBP;
if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
return false;
return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
(MBP.Predicate == MachineBranchPredicate::PRED_NE ||
MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
MBP.LHS.getReg() == BaseOp->getReg();
}
static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
Register Reg) {
const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
auto CopyOperands = TII.isCopyInstr(SinkInst);
if (!CopyOperands)
return false;
SrcMO = CopyOperands->Source;
DstMO = CopyOperands->Destination;
bool PostRA = MRI.getNumVirtRegs() == 0;
if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
return false;
bool arePhysRegs = !Reg.isVirtual();
if (arePhysRegs != PostRA)
return false;
if (!PostRA)
for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
DbgMO.getSubReg() != DstMO->getSubReg())
return false;
if (PostRA && Reg != DstMO->getReg())
return false;
for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
DbgMO.setReg(SrcMO->getReg());
DbgMO.setSubReg(SrcMO->getSubReg());
}
return true;
}
using MIRegs = std::pair<MachineInstr *, SmallVector<unsigned, 2>>;
static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
MachineBasicBlock::iterator InsertPos,
ArrayRef<MIRegs> DbgValuesToSink) {
if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
InsertPos->getDebugLoc()));
else
MI.setDebugLoc(DebugLoc());
MachineBasicBlock *ParentBlock = MI.getParent();
SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
++MachineBasicBlock::iterator(MI));
for (const auto &DbgValueToSink : DbgValuesToSink) {
MachineInstr *DbgMI = DbgValueToSink.first;
MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
SuccToSinkTo.insert(InsertPos, NewDbgMI);
bool PropagatedAllSunkOps = true;
for (unsigned Reg : DbgValueToSink.second) {
if (DbgMI->hasDebugOperandForReg(Reg)) {
if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
PropagatedAllSunkOps = false;
break;
}
}
}
if (!PropagatedAllSunkOps)
DbgMI->setDebugValueUndef();
}
}
bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
MachineBasicBlock *To, MachineInstr &MI) {
if (!DT->dominates(From, To) || !PDT->dominates(To, From))
return true;
auto BlockPair = std::make_pair(From, To);
if (HasStoreCache.find(BlockPair) != HasStoreCache.end())
return HasStoreCache[BlockPair];
if (StoreInstrCache.find(BlockPair) != StoreInstrCache.end())
return llvm::any_of(StoreInstrCache[BlockPair], [&](MachineInstr *I) {
return I->mayAlias(AA, MI, false);
});
bool SawStore = false;
bool HasAliasedStore = false;
DenseSet<MachineBasicBlock *> HandledBlocks;
DenseSet<MachineBasicBlock *> HandledDomBlocks;
for (MachineBasicBlock *BB : depth_first(From)) {
if (BB == To || BB == From)
continue;
if (HandledBlocks.count(BB))
continue;
HandledBlocks.insert(BB);
if (PDT->dominates(To, BB)) {
if (!HandledDomBlocks.count(BB))
HandledDomBlocks.insert(BB);
if (BB->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold) ||
HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
for (auto *DomBB : HandledDomBlocks) {
if (DomBB != BB && DT->dominates(DomBB, BB))
HasStoreCache[std::make_pair(DomBB, To)] = true;
else if(DomBB != BB && DT->dominates(BB, DomBB))
HasStoreCache[std::make_pair(From, DomBB)] = true;
}
HasStoreCache[BlockPair] = true;
return true;
}
for (MachineInstr &I : *BB) {
if (I.isCall() || I.hasOrderedMemoryRef()) {
for (auto *DomBB : HandledDomBlocks) {
if (DomBB != BB && DT->dominates(DomBB, BB))
HasStoreCache[std::make_pair(DomBB, To)] = true;
else if(DomBB != BB && DT->dominates(BB, DomBB))
HasStoreCache[std::make_pair(From, DomBB)] = true;
}
HasStoreCache[BlockPair] = true;
return true;
}
if (I.mayStore()) {
SawStore = true;
if (I.mayAlias(AA, MI, false))
HasAliasedStore = true;
StoreInstrCache[BlockPair].push_back(&I);
}
}
}
}
if (!SawStore)
HasStoreCache[BlockPair] = false;
return HasAliasedStore;
}
bool MachineSinking::SinkIntoCycle(MachineCycle *Cycle, MachineInstr &I) {
LLVM_DEBUG(dbgs() << "CycleSink: Finding sink block for: " << I);
MachineBasicBlock *Preheader = Cycle->getCyclePreheader();
assert(Preheader && "Cycle sink needs a preheader block");
MachineBasicBlock *SinkBlock = nullptr;
bool CanSink = true;
const MachineOperand &MO = I.getOperand(0);
for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
LLVM_DEBUG(dbgs() << "CycleSink: Analysing use: " << MI);
if (!Cycle->contains(MI.getParent())) {
LLVM_DEBUG(dbgs() << "CycleSink: Use not in cycle, can't sink.\n");
CanSink = false;
break;
}
if (!MI.isCopy()) {
LLVM_DEBUG(dbgs() << "CycleSink: Use is not a copy\n");
CanSink = false;
break;
}
if (!SinkBlock) {
SinkBlock = MI.getParent();
LLVM_DEBUG(dbgs() << "CycleSink: Setting sink block to: "
<< printMBBReference(*SinkBlock) << "\n");
continue;
}
SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
if (!SinkBlock) {
LLVM_DEBUG(dbgs() << "CycleSink: Can't find nearest dominator\n");
CanSink = false;
break;
}
LLVM_DEBUG(dbgs() << "CycleSink: Setting nearest common dom block: " <<
printMBBReference(*SinkBlock) << "\n");
}
if (!CanSink) {
LLVM_DEBUG(dbgs() << "CycleSink: Can't sink instruction.\n");
return false;
}
if (!SinkBlock) {
LLVM_DEBUG(dbgs() << "CycleSink: Not sinking, can't find sink block.\n");
return false;
}
if (SinkBlock == Preheader) {
LLVM_DEBUG(
dbgs() << "CycleSink: Not sinking, sink block is the preheader\n");
return false;
}
if (SinkBlock->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold)) {
LLVM_DEBUG(
dbgs() << "CycleSink: Not Sinking, block too large to analyse.\n");
return false;
}
LLVM_DEBUG(dbgs() << "CycleSink: Sinking instruction!\n");
SinkBlock->splice(SinkBlock->SkipPHIsAndLabels(SinkBlock->begin()), Preheader,
I);
for (MachineOperand &MO : I.operands()) {
if (MO.isReg() && MO.readsReg())
RegsToClearKillFlags.insert(MO.getReg());
}
assert(!I.isDebugInstr() && "Should not sink debug inst");
I.setDebugLoc(DebugLoc());
return true;
}
static bool blockPrologueInterferes(MachineBasicBlock *BB,
MachineBasicBlock::iterator End,
MachineInstr &MI,
const TargetRegisterInfo *TRI,
const TargetInstrInfo *TII,
const MachineRegisterInfo *MRI) {
if (BB->begin() == End)
return false; for (MachineBasicBlock::iterator PI = BB->getFirstNonPHI(); PI != End; ++PI) {
if (!TII->isBasicBlockPrologue(*PI))
continue;
for (auto &MO : MI.operands()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
if (MO.isUse()) {
if (Register::isPhysicalRegister(Reg) &&
(TII->isIgnorableUse(MO) || (MRI && MRI->isConstantPhysReg(Reg))))
continue;
if (PI->modifiesRegister(Reg, TRI))
return true;
} else {
if (PI->readsRegister(Reg, TRI))
return true;
auto *DefOp = PI->findRegisterDefOperand(Reg, false, true, TRI);
if (DefOp && !DefOp->isDead())
return true;
}
}
}
return false;
}
bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
AllSuccsCache &AllSuccessors) {
if (!TII->shouldSink(MI))
return false;
if (!MI.isSafeToMove(AA, SawStore))
return false;
if (MI.isConvergent())
return false;
if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
return false;
bool BreakPHIEdge = false;
MachineBasicBlock *ParentBlock = MI.getParent();
MachineBasicBlock *SuccToSinkTo =
FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
if (!SuccToSinkTo)
return false;
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg() || MO.isUse())
continue;
Register Reg = MO.getReg();
if (Reg == 0 || !Register::isPhysicalRegister(Reg))
continue;
if (SuccToSinkTo->isLiveIn(Reg))
return false;
}
LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
if (SuccToSinkTo->pred_size() > 1) {
bool TryBreak = false;
bool Store =
MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
if (!MI.isSafeToMove(AA, Store)) {
LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
TryBreak = true;
}
if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
TryBreak = true;
}
if (!TryBreak && CI->getCycle(SuccToSinkTo) &&
(!CI->getCycle(SuccToSinkTo)->isReducible() ||
CI->getCycle(SuccToSinkTo)->getHeader() == SuccToSinkTo)) {
LLVM_DEBUG(dbgs() << " *** NOTE: cycle header found\n");
TryBreak = true;
}
if (!TryBreak)
LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
else {
bool Status =
PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
if (!Status)
LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
"break critical edge\n");
return false;
}
}
if (BreakPHIEdge) {
bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
SuccToSinkTo, BreakPHIEdge);
if (!Status)
LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
"break critical edge\n");
return false;
}
MachineBasicBlock::iterator InsertPos =
SuccToSinkTo->SkipPHIsAndLabels(SuccToSinkTo->begin());
if (blockPrologueInterferes(SuccToSinkTo, InsertPos, MI, TRI, TII, MRI)) {
LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
return false;
}
SmallVector<MIRegs, 4> DbgUsersToSink;
for (auto &MO : MI.operands()) {
if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
continue;
if (!SeenDbgUsers.count(MO.getReg()))
continue;
auto &Users = SeenDbgUsers[MO.getReg()];
for (auto &User : Users) {
MachineInstr *DbgMI = User.getPointer();
if (User.getInt()) {
if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
DbgMI->setDebugValueUndef();
} else {
DbgUsersToSink.push_back(
{DbgMI, SmallVector<unsigned, 2>(1, MO.getReg())});
}
}
}
if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
for (MachineOperand &MO : MI.operands()) {
if (MO.isReg() && MO.isUse())
RegsToClearKillFlags.insert(MO.getReg()); }
return true;
}
void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
MachineInstr &MI, MachineBasicBlock *TargetBlock) {
assert(MI.isCopy());
assert(MI.getOperand(1).isReg());
SmallVector<MachineInstr *, 4> DbgDefUsers;
SmallVector<Register, 4> DbgUseRegs;
const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
for (auto &MO : MI.operands()) {
if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
continue;
DbgUseRegs.push_back(MO.getReg());
for (auto &User : MRI.use_instructions(MO.getReg())) {
if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
continue;
if (User.getParent() == MI.getParent())
continue;
assert(User.hasDebugOperandForReg(MO.getReg()) &&
"DBG_VALUE user of vreg, but has no operand for it?");
DbgDefUsers.push_back(&User);
}
}
for (auto *User : DbgDefUsers) {
for (auto &Reg : DbgUseRegs) {
for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
DbgOp.setReg(MI.getOperand(1).getReg());
DbgOp.setSubReg(MI.getOperand(1).getSubReg());
}
}
}
}
namespace {
class PostRAMachineSinking : public MachineFunctionPass {
public:
bool runOnMachineFunction(MachineFunction &MF) override;
static char ID;
PostRAMachineSinking() : MachineFunctionPass(ID) {}
StringRef getPassName() const override { return "PostRA Machine Sink"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
private:
LiveRegUnits ModifiedRegUnits, UsedRegUnits;
DenseMap<unsigned, SmallVector<MIRegs, 2>> SeenDbgInstrs;
bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
};
}
char PostRAMachineSinking::ID = 0;
char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
"PostRA Machine Sink", false, false)
static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
const TargetRegisterInfo *TRI) {
LiveRegUnits LiveInRegUnits(*TRI);
LiveInRegUnits.addLiveIns(MBB);
return !LiveInRegUnits.available(Reg);
}
static MachineBasicBlock *
getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
unsigned Reg, const TargetRegisterInfo *TRI) {
MachineBasicBlock *BB = nullptr;
for (auto *SI : SinkableBBs) {
if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
if (BB)
return nullptr;
BB = SI;
}
}
if (!BB)
return nullptr;
for (auto *SI : CurBB.successors()) {
if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
return nullptr;
}
return BB;
}
static MachineBasicBlock *
getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
ArrayRef<unsigned> DefedRegsInCopy,
const TargetRegisterInfo *TRI) {
MachineBasicBlock *SingleBB = nullptr;
for (auto DefReg : DefedRegsInCopy) {
MachineBasicBlock *BB =
getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
if (!BB || (SingleBB && SingleBB != BB))
return nullptr;
SingleBB = BB;
}
return SingleBB;
}
static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
SmallVectorImpl<unsigned> &UsedOpsInCopy,
LiveRegUnits &UsedRegUnits,
const TargetRegisterInfo *TRI) {
for (auto U : UsedOpsInCopy) {
MachineOperand &MO = MI->getOperand(U);
Register SrcReg = MO.getReg();
if (!UsedRegUnits.available(SrcReg)) {
MachineBasicBlock::iterator NI = std::next(MI->getIterator());
for (MachineInstr &UI : make_range(NI, CurBB.end())) {
if (UI.killsRegister(SrcReg, TRI)) {
UI.clearRegisterKills(SrcReg, TRI);
MO.setIsKill(true);
break;
}
}
}
}
}
static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
SmallVectorImpl<unsigned> &UsedOpsInCopy,
SmallVectorImpl<unsigned> &DefedRegsInCopy) {
MachineFunction &MF = *SuccBB->getParent();
const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
for (unsigned DefReg : DefedRegsInCopy)
for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
SuccBB->removeLiveIn(*S);
for (auto U : UsedOpsInCopy) {
Register SrcReg = MI->getOperand(U).getReg();
LaneBitmask Mask;
for (MCRegUnitMaskIterator S(SrcReg, TRI); S.isValid(); ++S) {
Mask |= (*S).second;
}
SuccBB->addLiveIn(SrcReg, Mask.any() ? Mask : LaneBitmask::getAll());
}
SuccBB->sortUniqueLiveIns();
}
static bool hasRegisterDependency(MachineInstr *MI,
SmallVectorImpl<unsigned> &UsedOpsInCopy,
SmallVectorImpl<unsigned> &DefedRegsInCopy,
LiveRegUnits &ModifiedRegUnits,
LiveRegUnits &UsedRegUnits) {
bool HasRegDependency = false;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
MachineOperand &MO = MI->getOperand(i);
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
if (MO.isDef()) {
if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
HasRegDependency = true;
break;
}
DefedRegsInCopy.push_back(Reg);
} else if (MO.isUse()) {
if (!ModifiedRegUnits.available(Reg)) {
HasRegDependency = true;
break;
}
UsedOpsInCopy.push_back(i);
}
}
return HasRegDependency;
}
bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
MachineFunction &MF,
const TargetRegisterInfo *TRI,
const TargetInstrInfo *TII) {
SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
for (MachineBasicBlock *SI : CurBB.successors())
if (!SI->livein_empty() && SI->pred_size() == 1)
SinkableBBs.insert(SI);
if (SinkableBBs.empty())
return false;
bool Changed = false;
ModifiedRegUnits.clear();
UsedRegUnits.clear();
SeenDbgInstrs.clear();
for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
SmallVector<unsigned, 2> UsedOpsInCopy;
SmallVector<unsigned, 2> DefedRegsInCopy;
if (MI.isDebugValue()) {
SmallDenseMap<MCRegister, SmallVector<unsigned, 2>, 4> MIUnits;
bool IsValid = true;
for (MachineOperand &MO : MI.debug_operands()) {
if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) {
if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
ModifiedRegUnits, UsedRegUnits)) {
IsValid = false;
break;
}
for (auto RI = MCRegUnitIterator(MO.getReg(), TRI); RI.isValid();
++RI)
MIUnits[*RI].push_back(MO.getReg());
}
}
if (IsValid) {
for (auto &RegOps : MIUnits)
SeenDbgInstrs[RegOps.first].emplace_back(&MI,
std::move(RegOps.second));
}
continue;
}
if (MI.isDebugOrPseudoInstr())
continue;
if (MI.isCall())
return false;
if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
TRI);
continue;
}
if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
ModifiedRegUnits, UsedRegUnits)) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
TRI);
continue;
}
assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
"Unexpect SrcReg or DefReg");
MachineBasicBlock *SuccBB =
getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
if (!SuccBB) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
TRI);
continue;
}
assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
"Unexpected predecessor");
MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
for (auto &MO : MI.operands()) {
if (!MO.isReg() || !MO.isDef())
continue;
for (auto RI = MCRegUnitIterator(MO.getReg(), TRI); RI.isValid(); ++RI) {
for (const auto &MIRegs : SeenDbgInstrs.lookup(*RI)) {
auto &Regs = DbgValsToSinkMap[MIRegs.first];
for (unsigned Reg : MIRegs.second)
Regs.push_back(Reg);
}
}
}
auto DbgValsToSink = DbgValsToSinkMap.takeVector();
LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccBB);
MachineBasicBlock::iterator InsertPos =
SuccBB->SkipPHIsAndLabels(SuccBB->begin());
if (blockPrologueInterferes(SuccBB, InsertPos, MI, TRI, TII, nullptr)) {
LLVM_DEBUG(
dbgs() << " *** Not sinking: prologue interference\n");
continue;
}
clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
Changed = true;
++NumPostRACopySink;
}
return Changed;
}
bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(MF.getFunction()))
return false;
bool Changed = false;
const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
ModifiedRegUnits.init(*TRI);
UsedRegUnits.init(*TRI);
for (auto &BB : MF)
Changed |= tryToSinkCopy(BB, MF, TRI, TII);
return Changed;
}