#include "AMDGPU.h"
#include "GCNRegPressure.h"
#include "SIMachineFunctionInfo.h"
#include "llvm/InitializePasses.h"
using namespace llvm;
#define DEBUG_TYPE "si-form-memory-clauses"
static cl::opt<unsigned>
MaxClause("amdgpu-max-memory-clause", cl::Hidden, cl::init(15),
cl::desc("Maximum length of a memory clause, instructions"));
namespace {
class SIFormMemoryClauses : public MachineFunctionPass {
typedef DenseMap<unsigned, std::pair<unsigned, LaneBitmask>> RegUse;
public:
static char ID;
public:
SIFormMemoryClauses() : MachineFunctionPass(ID) {
initializeSIFormMemoryClausesPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
StringRef getPassName() const override {
return "SI Form memory clauses";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<LiveIntervals>();
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
MachineFunctionProperties getClearedProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::IsSSA);
}
private:
bool canBundle(const MachineInstr &MI, const RegUse &Defs,
const RegUse &Uses) const;
bool checkPressure(const MachineInstr &MI, GCNDownwardRPTracker &RPT);
void collectRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses) const;
bool processRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses,
GCNDownwardRPTracker &RPT);
const GCNSubtarget *ST;
const SIRegisterInfo *TRI;
const MachineRegisterInfo *MRI;
SIMachineFunctionInfo *MFI;
unsigned LastRecordedOccupancy;
unsigned MaxVGPRs;
unsigned MaxSGPRs;
};
}
INITIALIZE_PASS_BEGIN(SIFormMemoryClauses, DEBUG_TYPE,
"SI Form memory clauses", false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_END(SIFormMemoryClauses, DEBUG_TYPE,
"SI Form memory clauses", false, false)
char SIFormMemoryClauses::ID = 0;
char &llvm::SIFormMemoryClausesID = SIFormMemoryClauses::ID;
FunctionPass *llvm::createSIFormMemoryClausesPass() {
return new SIFormMemoryClauses();
}
static bool isVMEMClauseInst(const MachineInstr &MI) {
return SIInstrInfo::isFLAT(MI) || SIInstrInfo::isVMEM(MI);
}
static bool isSMEMClauseInst(const MachineInstr &MI) {
return SIInstrInfo::isSMRD(MI);
}
static bool isValidClauseInst(const MachineInstr &MI, bool IsVMEMClause) {
assert(!MI.isDebugInstr() && "debug instructions should not reach here");
if (MI.isBundled())
return false;
if (!MI.mayLoad() || MI.mayStore())
return false;
if (SIInstrInfo::isAtomic(MI))
return false;
if (IsVMEMClause && !isVMEMClauseInst(MI))
return false;
if (!IsVMEMClause && !isSMEMClauseInst(MI))
return false;
for (const MachineOperand &ResMO : MI.defs()) {
Register ResReg = ResMO.getReg();
for (const MachineOperand &MO : MI.uses()) {
if (!MO.isReg() || MO.isDef())
continue;
if (MO.getReg() == ResReg)
return false;
}
break; }
return true;
}
static unsigned getMopState(const MachineOperand &MO) {
unsigned S = 0;
if (MO.isImplicit())
S |= RegState::Implicit;
if (MO.isDead())
S |= RegState::Dead;
if (MO.isUndef())
S |= RegState::Undef;
if (MO.isKill())
S |= RegState::Kill;
if (MO.isEarlyClobber())
S |= RegState::EarlyClobber;
if (MO.getReg().isPhysical() && MO.isRenamable())
S |= RegState::Renamable;
return S;
}
bool SIFormMemoryClauses::canBundle(const MachineInstr &MI, const RegUse &Defs,
const RegUse &Uses) const {
for (const MachineOperand &MO : MI.operands()) {
if (MO.isFI())
return false;
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (MO.isTied())
return false;
const RegUse &Map = MO.isDef() ? Uses : Defs;
auto Conflict = Map.find(Reg);
if (Conflict == Map.end())
continue;
if (Reg.isPhysical())
return false;
LaneBitmask Mask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
if ((Conflict->second.second & Mask).any())
return false;
}
return true;
}
bool SIFormMemoryClauses::checkPressure(const MachineInstr &MI,
GCNDownwardRPTracker &RPT) {
RPT.advanceToNext();
GCNRegPressure MaxPressure = RPT.moveMaxPressure();
unsigned Occupancy = MaxPressure.getOccupancy(*ST);
if (Occupancy >= MFI->getMinAllowedOccupancy() &&
MaxPressure.getVGPRNum(ST->hasGFX90AInsts()) <= MaxVGPRs / 2 &&
MaxPressure.getSGPRNum() <= MaxSGPRs / 2) {
LastRecordedOccupancy = Occupancy;
return true;
}
return false;
}
void SIFormMemoryClauses::collectRegUses(const MachineInstr &MI,
RegUse &Defs, RegUse &Uses) const {
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
LaneBitmask Mask = Reg.isVirtual()
? TRI->getSubRegIndexLaneMask(MO.getSubReg())
: LaneBitmask::getAll();
RegUse &Map = MO.isDef() ? Defs : Uses;
auto Loc = Map.find(Reg);
unsigned State = getMopState(MO);
if (Loc == Map.end()) {
Map[Reg] = std::make_pair(State, Mask);
} else {
Loc->second.first |= State;
Loc->second.second |= Mask;
}
}
}
bool SIFormMemoryClauses::processRegUses(const MachineInstr &MI,
RegUse &Defs, RegUse &Uses,
GCNDownwardRPTracker &RPT) {
if (!canBundle(MI, Defs, Uses))
return false;
if (!checkPressure(MI, RPT))
return false;
collectRegUses(MI, Defs, Uses);
return true;
}
bool SIFormMemoryClauses::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(MF.getFunction()))
return false;
ST = &MF.getSubtarget<GCNSubtarget>();
if (!ST->isXNACKEnabled())
return false;
const SIInstrInfo *TII = ST->getInstrInfo();
TRI = ST->getRegisterInfo();
MRI = &MF.getRegInfo();
MFI = MF.getInfo<SIMachineFunctionInfo>();
LiveIntervals *LIS = &getAnalysis<LiveIntervals>();
SlotIndexes *Ind = LIS->getSlotIndexes();
bool Changed = false;
MaxVGPRs = TRI->getAllocatableSet(MF, &AMDGPU::VGPR_32RegClass).count();
MaxSGPRs = TRI->getAllocatableSet(MF, &AMDGPU::SGPR_32RegClass).count();
unsigned FuncMaxClause = AMDGPU::getIntegerAttribute(
MF.getFunction(), "amdgpu-max-memory-clause", MaxClause);
for (MachineBasicBlock &MBB : MF) {
GCNDownwardRPTracker RPT(*LIS);
MachineBasicBlock::instr_iterator Next;
for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; I = Next) {
MachineInstr &MI = *I;
Next = std::next(I);
if (MI.isMetaInstruction())
continue;
bool IsVMEM = isVMEMClauseInst(MI);
if (!isValidClauseInst(MI, IsVMEM))
continue;
if (!RPT.getNext().isValid())
RPT.reset(MI);
else { RPT.advance(MachineBasicBlock::const_iterator(MI));
RPT.advanceBeforeNext();
}
const GCNRPTracker::LiveRegSet LiveRegsCopy(RPT.getLiveRegs());
RegUse Defs, Uses;
if (!processRegUses(MI, Defs, Uses, RPT)) {
RPT.reset(MI, &LiveRegsCopy);
continue;
}
MachineBasicBlock::iterator LastClauseInst = Next;
unsigned Length = 1;
for ( ; Next != E && Length < FuncMaxClause; ++Next) {
if (Next->isMetaInstruction())
continue;
if (!isValidClauseInst(*Next, IsVMEM))
break;
if (!processRegUses(*Next, Defs, Uses, RPT))
break;
LastClauseInst = Next;
++Length;
}
if (Length < 2) {
RPT.reset(MI, &LiveRegsCopy);
continue;
}
Changed = true;
MFI->limitOccupancy(LastRecordedOccupancy);
assert(!LastClauseInst->isMetaInstruction());
SlotIndex ClauseLiveInIdx = LIS->getInstructionIndex(MI);
SlotIndex ClauseLiveOutIdx =
LIS->getInstructionIndex(*LastClauseInst).getNextIndex();
MachineInstrBuilder Kill;
for (auto &&R : Uses) {
Register Reg = R.first;
if (Reg.isPhysical())
continue;
SmallVector<std::tuple<unsigned, unsigned>> KillOps;
const LiveInterval &LI = LIS->getInterval(R.first);
if (!LI.hasSubRanges()) {
if (!LI.liveAt(ClauseLiveOutIdx)) {
KillOps.emplace_back(R.second.first | RegState::Kill,
AMDGPU::NoSubRegister);
}
} else {
LaneBitmask KilledMask;
for (const LiveInterval::SubRange &SR : LI.subranges()) {
if (SR.liveAt(ClauseLiveInIdx) && !SR.liveAt(ClauseLiveOutIdx))
KilledMask |= SR.LaneMask;
}
if (KilledMask.none())
continue;
SmallVector<unsigned> KilledIndexes;
bool Success = TRI->getCoveringSubRegIndexes(
*MRI, MRI->getRegClass(Reg), KilledMask, KilledIndexes);
(void)Success;
assert(Success && "Failed to find subregister mask to cover lanes");
for (unsigned SubReg : KilledIndexes) {
KillOps.emplace_back(R.second.first | RegState::Kill, SubReg);
}
}
if (KillOps.empty())
continue;
Kill = BuildMI(*MI.getParent(), std::next(LastClauseInst),
DebugLoc(), TII->get(AMDGPU::KILL));
for (auto &Op : KillOps)
Kill.addUse(Reg, std::get<0>(Op), std::get<1>(Op));
Ind->insertMachineInstrInMaps(*Kill);
}
if (!Kill) {
RPT.reset(MI, &LiveRegsCopy);
continue;
}
RPT.reset(*Kill, &LiveRegsCopy);
for (auto &&R : Defs) {
Register Reg = R.first;
Uses.erase(Reg);
if (Reg.isPhysical())
continue;
LIS->removeInterval(Reg);
LIS->createAndComputeVirtRegInterval(Reg);
}
for (auto &&R : Uses) {
Register Reg = R.first;
if (Reg.isPhysical())
continue;
LIS->removeInterval(Reg);
LIS->createAndComputeVirtRegInterval(Reg);
}
}
}
return Changed;
}