#include "HexagonInstrInfo.h"
#include "HexagonRegisterInfo.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/LiveInterval.h"
#include "llvm/CodeGen/LiveIntervals.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/InitializePasses.h"
#include "llvm/MC/LaneBitmask.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <iterator>
#include <set>
#include <utility>
#define DEBUG_TYPE "expand-condsets"
using namespace llvm;
static cl::opt<unsigned> OptTfrLimit("expand-condsets-tfr-limit",
cl::init(~0U), cl::Hidden, cl::desc("Max number of mux expansions"));
static cl::opt<unsigned> OptCoaLimit("expand-condsets-coa-limit",
cl::init(~0U), cl::Hidden, cl::desc("Max number of segment coalescings"));
namespace llvm {
void initializeHexagonExpandCondsetsPass(PassRegistry&);
FunctionPass *createHexagonExpandCondsets();
}
namespace {
class HexagonExpandCondsets : public MachineFunctionPass {
public:
static char ID;
HexagonExpandCondsets() : MachineFunctionPass(ID) {
if (OptCoaLimit.getPosition())
CoaLimitActive = true, CoaLimit = OptCoaLimit;
if (OptTfrLimit.getPosition())
TfrLimitActive = true, TfrLimit = OptTfrLimit;
initializeHexagonExpandCondsetsPass(*PassRegistry::getPassRegistry());
}
StringRef getPassName() const override { return "Hexagon Expand Condsets"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<LiveIntervals>();
AU.addPreserved<LiveIntervals>();
AU.addPreserved<SlotIndexes>();
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
private:
const HexagonInstrInfo *HII = nullptr;
const TargetRegisterInfo *TRI = nullptr;
MachineDominatorTree *MDT;
MachineRegisterInfo *MRI = nullptr;
LiveIntervals *LIS = nullptr;
bool CoaLimitActive = false;
bool TfrLimitActive = false;
unsigned CoaLimit;
unsigned TfrLimit;
unsigned CoaCounter = 0;
unsigned TfrCounter = 0;
struct RegisterRef {
RegisterRef(const MachineOperand &Op) : Reg(Op.getReg()),
Sub(Op.getSubReg()) {}
RegisterRef(unsigned R = 0, unsigned S = 0) : Reg(R), Sub(S) {}
bool operator== (RegisterRef RR) const {
return Reg == RR.Reg && Sub == RR.Sub;
}
bool operator!= (RegisterRef RR) const { return !operator==(RR); }
bool operator< (RegisterRef RR) const {
return Reg < RR.Reg || (Reg == RR.Reg && Sub < RR.Sub);
}
Register Reg;
unsigned Sub;
};
using ReferenceMap = DenseMap<unsigned, unsigned>;
enum { Sub_Low = 0x1, Sub_High = 0x2, Sub_None = (Sub_Low | Sub_High) };
enum { Exec_Then = 0x10, Exec_Else = 0x20 };
unsigned getMaskForSub(unsigned Sub);
bool isCondset(const MachineInstr &MI);
LaneBitmask getLaneMask(Register Reg, unsigned Sub);
void addRefToMap(RegisterRef RR, ReferenceMap &Map, unsigned Exec);
bool isRefInMap(RegisterRef, ReferenceMap &Map, unsigned Exec);
void updateDeadsInRange(Register Reg, LaneBitmask LM, LiveRange &Range);
void updateKillFlags(Register Reg);
void updateDeadFlags(Register Reg);
void recalculateLiveInterval(Register Reg);
void removeInstr(MachineInstr &MI);
void updateLiveness(std::set<Register> &RegSet, bool Recalc,
bool UpdateKills, bool UpdateDeads);
unsigned getCondTfrOpcode(const MachineOperand &SO, bool Cond);
MachineInstr *genCondTfrFor(MachineOperand &SrcOp,
MachineBasicBlock::iterator At, unsigned DstR,
unsigned DstSR, const MachineOperand &PredOp, bool PredSense,
bool ReadUndef, bool ImpUse);
bool split(MachineInstr &MI, std::set<Register> &UpdRegs);
bool isPredicable(MachineInstr *MI);
MachineInstr *getReachingDefForPred(RegisterRef RD,
MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond);
bool canMoveOver(MachineInstr &MI, ReferenceMap &Defs, ReferenceMap &Uses);
bool canMoveMemTo(MachineInstr &MI, MachineInstr &ToI, bool IsDown);
void predicateAt(const MachineOperand &DefOp, MachineInstr &MI,
MachineBasicBlock::iterator Where,
const MachineOperand &PredOp, bool Cond,
std::set<Register> &UpdRegs);
void renameInRange(RegisterRef RO, RegisterRef RN, unsigned PredR,
bool Cond, MachineBasicBlock::iterator First,
MachineBasicBlock::iterator Last);
bool predicate(MachineInstr &TfrI, bool Cond, std::set<Register> &UpdRegs);
bool predicateInBlock(MachineBasicBlock &B, std::set<Register> &UpdRegs);
bool isIntReg(RegisterRef RR, unsigned &BW);
bool isIntraBlocks(LiveInterval &LI);
bool coalesceRegisters(RegisterRef R1, RegisterRef R2);
bool coalesceSegments(const SmallVectorImpl<MachineInstr *> &Condsets,
std::set<Register> &UpdRegs);
};
}
char HexagonExpandCondsets::ID = 0;
namespace llvm {
char &HexagonExpandCondsetsID = HexagonExpandCondsets::ID;
}
INITIALIZE_PASS_BEGIN(HexagonExpandCondsets, "expand-condsets",
"Hexagon Expand Condsets", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_END(HexagonExpandCondsets, "expand-condsets",
"Hexagon Expand Condsets", false, false)
unsigned HexagonExpandCondsets::getMaskForSub(unsigned Sub) {
switch (Sub) {
case Hexagon::isub_lo:
case Hexagon::vsub_lo:
return Sub_Low;
case Hexagon::isub_hi:
case Hexagon::vsub_hi:
return Sub_High;
case Hexagon::NoSubRegister:
return Sub_None;
}
llvm_unreachable("Invalid subregister");
}
bool HexagonExpandCondsets::isCondset(const MachineInstr &MI) {
unsigned Opc = MI.getOpcode();
switch (Opc) {
case Hexagon::C2_mux:
case Hexagon::C2_muxii:
case Hexagon::C2_muxir:
case Hexagon::C2_muxri:
case Hexagon::PS_pselect:
return true;
break;
}
return false;
}
LaneBitmask HexagonExpandCondsets::getLaneMask(Register Reg, unsigned Sub) {
assert(Reg.isVirtual());
return Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
: MRI->getMaxLaneMaskForVReg(Reg);
}
void HexagonExpandCondsets::addRefToMap(RegisterRef RR, ReferenceMap &Map,
unsigned Exec) {
unsigned Mask = getMaskForSub(RR.Sub) | Exec;
ReferenceMap::iterator F = Map.find(RR.Reg);
if (F == Map.end())
Map.insert(std::make_pair(RR.Reg, Mask));
else
F->second |= Mask;
}
bool HexagonExpandCondsets::isRefInMap(RegisterRef RR, ReferenceMap &Map,
unsigned Exec) {
ReferenceMap::iterator F = Map.find(RR.Reg);
if (F == Map.end())
return false;
unsigned Mask = getMaskForSub(RR.Sub) | Exec;
if (Mask & F->second)
return true;
return false;
}
void HexagonExpandCondsets::updateKillFlags(Register Reg) {
auto KillAt = [this,Reg] (SlotIndex K, LaneBitmask LM) -> void {
MachineInstr *MI = LIS->getInstructionFromIndex(K);
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
MachineOperand &Op = MI->getOperand(i);
if (!Op.isReg() || !Op.isUse() || Op.getReg() != Reg ||
MI->isRegTiedToDefOperand(i))
continue;
LaneBitmask SLM = getLaneMask(Reg, Op.getSubReg());
if ((SLM & LM) == SLM) {
Op.setIsKill(true);
break;
}
}
};
LiveInterval &LI = LIS->getInterval(Reg);
for (auto I = LI.begin(), E = LI.end(); I != E; ++I) {
if (!I->end.isRegister())
continue;
auto NextI = std::next(I);
if (NextI != E && NextI->start.isRegister()) {
MachineInstr *DefI = LIS->getInstructionFromIndex(NextI->start);
if (HII->isPredicated(*DefI))
continue;
}
bool WholeReg = true;
if (LI.hasSubRanges()) {
auto EndsAtI = [I] (LiveInterval::SubRange &S) -> bool {
LiveRange::iterator F = S.find(I->end);
return F != S.end() && I->end == F->end;
};
for (LiveInterval::SubRange &S : LI.subranges()) {
if (EndsAtI(S))
KillAt(I->end, S.LaneMask);
else
WholeReg = false;
}
}
if (WholeReg)
KillAt(I->end, MRI->getMaxLaneMaskForVReg(Reg));
}
}
void HexagonExpandCondsets::updateDeadsInRange(Register Reg, LaneBitmask LM,
LiveRange &Range) {
assert(Reg.isVirtual());
if (Range.empty())
return;
auto IsRegDef = [this,Reg,LM] (MachineOperand &Op) -> std::pair<bool,bool> {
if (!Op.isReg() || !Op.isDef())
return { false, false };
Register DR = Op.getReg(), DSR = Op.getSubReg();
if (!DR.isVirtual() || DR != Reg)
return { false, false };
LaneBitmask SLM = getLaneMask(DR, DSR);
LaneBitmask A = SLM & LM;
return { A.any(), A == SLM };
};
auto Dominate = [this] (SetVector<MachineBasicBlock*> &Defs,
MachineBasicBlock *Dest) -> bool {
for (MachineBasicBlock *D : Defs)
if (D != Dest && MDT->dominates(D, Dest))
return true;
MachineBasicBlock *Entry = &Dest->getParent()->front();
SetVector<MachineBasicBlock*> Work(Dest->pred_begin(), Dest->pred_end());
for (unsigned i = 0; i < Work.size(); ++i) {
MachineBasicBlock *B = Work[i];
if (Defs.count(B))
continue;
if (B == Entry)
return false;
for (auto *P : B->predecessors())
Work.insert(P);
}
return true;
};
SetVector<MachineBasicBlock*> Defs;
SmallVector<SlotIndex,4> PredDefs;
for (auto &Seg : Range) {
if (!Seg.start.isRegister())
continue;
MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
Defs.insert(DefI->getParent());
if (HII->isPredicated(*DefI))
PredDefs.push_back(Seg.start);
}
SmallVector<SlotIndex,8> Undefs;
LiveInterval &LI = LIS->getInterval(Reg);
LI.computeSubRangeUndefs(Undefs, LM, *MRI, *LIS->getSlotIndexes());
for (auto &SI : PredDefs) {
MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
auto P = Range.extendInBlock(Undefs, LIS->getMBBStartIdx(BB), SI);
if (P.first != nullptr || P.second)
SI = SlotIndex();
}
SmallVector<SlotIndex,4> ExtTo;
for (auto &SI : PredDefs) {
if (!SI.isValid())
continue;
MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
if (BB->pred_empty())
continue;
if (Dominate(Defs, BB))
ExtTo.push_back(SI);
}
if (!ExtTo.empty())
LIS->extendToIndices(Range, ExtTo, Undefs);
std::set<RegisterRef> DefRegs;
for (auto &Seg : Range) {
if (!Seg.start.isRegister())
continue;
MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
for (auto &Op : DefI->operands()) {
auto P = IsRegDef(Op);
if (P.second && Seg.end.isDead()) {
Op.setIsDead(true);
} else if (P.first) {
DefRegs.insert(Op);
Op.setIsDead(false);
}
}
}
for (auto &Seg : Range) {
if (!Seg.start.isRegister() || !Range.liveAt(Seg.start.getPrevSlot()))
continue;
MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
if (!HII->isPredicated(*DefI))
continue;
std::map<RegisterRef,unsigned> ImpUses;
for (unsigned i = 0, e = DefI->getNumOperands(); i != e; ++i) {
MachineOperand &Op = DefI->getOperand(i);
if (!Op.isReg() || !DefRegs.count(Op))
continue;
if (Op.isDef()) {
if (!Op.isTied())
ImpUses.insert({Op, i});
} else {
if (Op.isTied())
ImpUses.erase(Op);
}
}
if (ImpUses.empty())
continue;
MachineFunction &MF = *DefI->getParent()->getParent();
for (std::pair<RegisterRef, unsigned> P : ImpUses) {
RegisterRef R = P.first;
MachineInstrBuilder(MF, DefI).addReg(R.Reg, RegState::Implicit, R.Sub);
DefI->tieOperands(P.second, DefI->getNumOperands()-1);
}
}
}
void HexagonExpandCondsets::updateDeadFlags(Register Reg) {
LiveInterval &LI = LIS->getInterval(Reg);
if (LI.hasSubRanges()) {
for (LiveInterval::SubRange &S : LI.subranges()) {
updateDeadsInRange(Reg, S.LaneMask, S);
LIS->shrinkToUses(S, Reg);
}
LI.clear();
LIS->constructMainRangeFromSubranges(LI);
} else {
updateDeadsInRange(Reg, MRI->getMaxLaneMaskForVReg(Reg), LI);
}
}
void HexagonExpandCondsets::recalculateLiveInterval(Register Reg) {
LIS->removeInterval(Reg);
LIS->createAndComputeVirtRegInterval(Reg);
}
void HexagonExpandCondsets::removeInstr(MachineInstr &MI) {
LIS->RemoveMachineInstrFromMaps(MI);
MI.eraseFromParent();
}
void HexagonExpandCondsets::updateLiveness(std::set<Register> &RegSet,
bool Recalc, bool UpdateKills,
bool UpdateDeads) {
UpdateKills |= UpdateDeads;
for (Register R : RegSet) {
if (!R.isVirtual()) {
assert(R.isPhysical());
assert(MRI->isReserved(R));
continue;
}
if (Recalc)
recalculateLiveInterval(R);
if (UpdateKills)
MRI->clearKillFlags(R);
if (UpdateDeads)
updateDeadFlags(R);
if (UpdateKills)
updateKillFlags(R);
LIS->getInterval(R).verify();
}
}
unsigned HexagonExpandCondsets::getCondTfrOpcode(const MachineOperand &SO,
bool IfTrue) {
using namespace Hexagon;
if (SO.isReg()) {
MCRegister PhysR;
RegisterRef RS = SO;
if (RS.Reg.isVirtual()) {
const TargetRegisterClass *VC = MRI->getRegClass(RS.Reg);
assert(VC->begin() != VC->end() && "Empty register class");
PhysR = *VC->begin();
} else {
PhysR = RS.Reg;
}
MCRegister PhysS = (RS.Sub == 0) ? PhysR : TRI->getSubReg(PhysR, RS.Sub);
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysS);
switch (TRI->getRegSizeInBits(*RC)) {
case 32:
return IfTrue ? A2_tfrt : A2_tfrf;
case 64:
return IfTrue ? A2_tfrpt : A2_tfrpf;
}
llvm_unreachable("Invalid register operand");
}
switch (SO.getType()) {
case MachineOperand::MO_Immediate:
case MachineOperand::MO_FPImmediate:
case MachineOperand::MO_ConstantPoolIndex:
case MachineOperand::MO_TargetIndex:
case MachineOperand::MO_JumpTableIndex:
case MachineOperand::MO_ExternalSymbol:
case MachineOperand::MO_GlobalAddress:
case MachineOperand::MO_BlockAddress:
return IfTrue ? C2_cmoveit : C2_cmoveif;
default:
break;
}
llvm_unreachable("Unexpected source operand");
}
MachineInstr *HexagonExpandCondsets::genCondTfrFor(MachineOperand &SrcOp,
MachineBasicBlock::iterator At,
unsigned DstR, unsigned DstSR, const MachineOperand &PredOp,
bool PredSense, bool ReadUndef, bool ImpUse) {
MachineInstr *MI = SrcOp.getParent();
MachineBasicBlock &B = *At->getParent();
const DebugLoc &DL = MI->getDebugLoc();
unsigned Opc = getCondTfrOpcode(SrcOp, PredSense);
unsigned DstState = RegState::Define | (ReadUndef ? RegState::Undef : 0);
unsigned PredState = getRegState(PredOp) & ~RegState::Kill;
MachineInstrBuilder MIB;
if (SrcOp.isReg()) {
unsigned SrcState = getRegState(SrcOp);
if (RegisterRef(SrcOp) == RegisterRef(DstR, DstSR))
SrcState &= ~RegState::Kill;
MIB = BuildMI(B, At, DL, HII->get(Opc))
.addReg(DstR, DstState, DstSR)
.addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
.addReg(SrcOp.getReg(), SrcState, SrcOp.getSubReg());
} else {
MIB = BuildMI(B, At, DL, HII->get(Opc))
.addReg(DstR, DstState, DstSR)
.addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
.add(SrcOp);
}
LLVM_DEBUG(dbgs() << "created an initial copy: " << *MIB);
return &*MIB;
}
bool HexagonExpandCondsets::split(MachineInstr &MI,
std::set<Register> &UpdRegs) {
if (TfrLimitActive) {
if (TfrCounter >= TfrLimit)
return false;
TfrCounter++;
}
LLVM_DEBUG(dbgs() << "\nsplitting " << printMBBReference(*MI.getParent())
<< ": " << MI);
MachineOperand &MD = MI.getOperand(0); MachineOperand &MP = MI.getOperand(1); assert(MD.isDef());
Register DR = MD.getReg(), DSR = MD.getSubReg();
bool ReadUndef = MD.isUndef();
MachineBasicBlock::iterator At = MI;
auto updateRegs = [&UpdRegs] (const MachineInstr &MI) -> void {
for (auto &Op : MI.operands())
if (Op.isReg())
UpdRegs.insert(Op.getReg());
};
MachineOperand &ST = MI.getOperand(2);
MachineOperand &SF = MI.getOperand(3);
if (ST.isReg() && SF.isReg()) {
RegisterRef RT(ST);
if (RT == RegisterRef(SF)) {
updateRegs(MI);
MI.setDesc(HII->get(TargetOpcode::COPY));
unsigned S = getRegState(ST);
while (MI.getNumOperands() > 1)
MI.removeOperand(MI.getNumOperands()-1);
MachineFunction &MF = *MI.getParent()->getParent();
MachineInstrBuilder(MF, MI).addReg(RT.Reg, S, RT.Sub);
return true;
}
}
MachineInstr *TfrT =
genCondTfrFor(ST, At, DR, DSR, MP, true, ReadUndef, false);
MachineInstr *TfrF =
genCondTfrFor(SF, At, DR, DSR, MP, false, ReadUndef, true);
LIS->InsertMachineInstrInMaps(*TfrT);
LIS->InsertMachineInstrInMaps(*TfrF);
updateRegs(MI);
removeInstr(MI);
return true;
}
bool HexagonExpandCondsets::isPredicable(MachineInstr *MI) {
if (HII->isPredicated(*MI) || !HII->isPredicable(*MI))
return false;
if (MI->hasUnmodeledSideEffects() || MI->mayStore())
return false;
bool HasDef = false;
for (auto &Op : MI->operands()) {
if (!Op.isReg() || !Op.isDef())
continue;
if (HasDef)
return false;
HasDef = true;
}
for (auto &Mo : MI->memoperands())
if (Mo->isVolatile() || Mo->isAtomic())
return false;
return true;
}
MachineInstr *HexagonExpandCondsets::getReachingDefForPred(RegisterRef RD,
MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond) {
MachineBasicBlock &B = *UseIt->getParent();
MachineBasicBlock::iterator I = UseIt, S = B.begin();
if (I == S)
return nullptr;
bool PredValid = true;
do {
--I;
MachineInstr *MI = &*I;
if (PredValid && HII->isPredicated(*MI)) {
if (MI->readsRegister(PredR) && (Cond != HII->isPredicatedTrue(*MI)))
continue;
}
for (auto &Op : MI->operands()) {
if (!Op.isReg() || !Op.isDef())
continue;
RegisterRef RR = Op;
if (RR.Reg == PredR) {
PredValid = false;
continue;
}
if (RR.Reg != RD.Reg)
continue;
if (RR.Sub == RD.Sub)
return MI;
if (RR.Sub == 0 || RD.Sub == 0)
return nullptr;
}
} while (I != S);
return nullptr;
}
bool HexagonExpandCondsets::canMoveOver(MachineInstr &MI, ReferenceMap &Defs,
ReferenceMap &Uses) {
for (auto &Op : MI.operands()) {
if (!Op.isReg())
continue;
RegisterRef RR = Op;
if (!RR.Reg.isVirtual())
return false;
if (isRefInMap(RR, Defs, Exec_Then))
return false;
if (Op.isDef() && isRefInMap(RR, Uses, Exec_Then))
return false;
}
return true;
}
bool HexagonExpandCondsets::canMoveMemTo(MachineInstr &TheI, MachineInstr &ToI,
bool IsDown) {
bool IsLoad = TheI.mayLoad(), IsStore = TheI.mayStore();
if (!IsLoad && !IsStore)
return true;
if (HII->areMemAccessesTriviallyDisjoint(TheI, ToI))
return true;
if (TheI.hasUnmodeledSideEffects())
return false;
MachineBasicBlock::iterator StartI = IsDown ? TheI : ToI;
MachineBasicBlock::iterator EndI = IsDown ? ToI : TheI;
bool Ordered = TheI.hasOrderedMemoryRef();
for (MachineBasicBlock::iterator I = std::next(StartI); I != EndI; ++I) {
MachineInstr *MI = &*I;
if (MI->hasUnmodeledSideEffects())
return false;
bool L = MI->mayLoad(), S = MI->mayStore();
if (!L && !S)
continue;
if (Ordered && MI->hasOrderedMemoryRef())
return false;
bool Conflict = (L && IsStore) || S;
if (Conflict)
return false;
}
return true;
}
void HexagonExpandCondsets::predicateAt(const MachineOperand &DefOp,
MachineInstr &MI,
MachineBasicBlock::iterator Where,
const MachineOperand &PredOp, bool Cond,
std::set<Register> &UpdRegs) {
MachineBasicBlock &B = *MI.getParent();
DebugLoc DL = Where->getDebugLoc(); unsigned Opc = MI.getOpcode();
unsigned PredOpc = HII->getCondOpcode(Opc, !Cond);
MachineInstrBuilder MB = BuildMI(B, Where, DL, HII->get(PredOpc));
unsigned Ox = 0, NP = MI.getNumOperands();
while (Ox < NP) {
MachineOperand &MO = MI.getOperand(Ox);
if (!MO.isReg() || !MO.isDef())
break;
Ox++;
}
MB.addReg(DefOp.getReg(), getRegState(DefOp), DefOp.getSubReg());
MB.addReg(PredOp.getReg(), PredOp.isUndef() ? RegState::Undef : 0,
PredOp.getSubReg());
while (Ox < NP) {
MachineOperand &MO = MI.getOperand(Ox);
if (!MO.isReg() || !MO.isImplicit())
MB.add(MO);
Ox++;
}
MB.cloneMemRefs(MI);
MachineInstr *NewI = MB;
NewI->clearKillInfo();
LIS->InsertMachineInstrInMaps(*NewI);
for (auto &Op : NewI->operands())
if (Op.isReg())
UpdRegs.insert(Op.getReg());
}
void HexagonExpandCondsets::renameInRange(RegisterRef RO, RegisterRef RN,
unsigned PredR, bool Cond, MachineBasicBlock::iterator First,
MachineBasicBlock::iterator Last) {
MachineBasicBlock::iterator End = std::next(Last);
for (MachineBasicBlock::iterator I = First; I != End; ++I) {
MachineInstr *MI = &*I;
if (!HII->isPredicated(*MI))
continue;
if (!MI->readsRegister(PredR) || (Cond != HII->isPredicatedTrue(*MI)))
continue;
for (auto &Op : MI->operands()) {
if (!Op.isReg() || RO != RegisterRef(Op))
continue;
Op.setReg(RN.Reg);
Op.setSubReg(RN.Sub);
assert(!Op.isDef() && "Not expecting a def");
}
}
}
bool HexagonExpandCondsets::predicate(MachineInstr &TfrI, bool Cond,
std::set<Register> &UpdRegs) {
unsigned Opc = TfrI.getOpcode();
(void)Opc;
assert(Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf);
LLVM_DEBUG(dbgs() << "\nattempt to predicate if-" << (Cond ? "true" : "false")
<< ": " << TfrI);
MachineOperand &MD = TfrI.getOperand(0);
MachineOperand &MP = TfrI.getOperand(1);
MachineOperand &MS = TfrI.getOperand(2);
if (!MS.isKill())
return false;
if (MD.getSubReg() && !MRI->shouldTrackSubRegLiveness(MD.getReg()))
return false;
RegisterRef RT(MS);
Register PredR = MP.getReg();
MachineInstr *DefI = getReachingDefForPred(RT, TfrI, PredR, Cond);
if (!DefI || !isPredicable(DefI))
return false;
LLVM_DEBUG(dbgs() << "Source def: " << *DefI);
ReferenceMap Uses, Defs;
MachineBasicBlock::iterator DefIt = DefI, TfrIt = TfrI;
bool PredValid = true;
for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
if (!I->modifiesRegister(PredR, nullptr))
continue;
PredValid = false;
break;
}
for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
MachineInstr *MI = &*I;
unsigned Exec = Exec_Then | Exec_Else;
if (PredValid && HII->isPredicated(*MI) && MI->readsRegister(PredR))
Exec = (Cond == HII->isPredicatedTrue(*MI)) ? Exec_Then : Exec_Else;
for (auto &Op : MI->operands()) {
if (!Op.isReg())
continue;
RegisterRef RR = Op;
if (!RR.Reg.isVirtual())
return false;
ReferenceMap &Map = Op.isDef() ? Defs : Uses;
if (Op.isDef() && Op.isUndef()) {
assert(RR.Sub && "Expecting a subregister on <def,read-undef>");
RR.Sub = 0;
}
addRefToMap(RR, Map, Exec);
}
}
if (isRefInMap(RT, Defs, Exec_Then) || isRefInMap(RT, Uses, Exec_Else))
return false;
RegisterRef RD = MD;
bool CanUp = canMoveOver(TfrI, Defs, Uses);
bool CanDown = canMoveOver(*DefI, Defs, Uses);
if (DefI->mayLoadOrStore())
if (!canMoveMemTo(*DefI, TfrI, true))
CanDown = false;
LLVM_DEBUG(dbgs() << "Can move up: " << (CanUp ? "yes" : "no")
<< ", can move down: " << (CanDown ? "yes\n" : "no\n"));
MachineBasicBlock::iterator PastDefIt = std::next(DefIt);
if (CanUp)
predicateAt(MD, *DefI, PastDefIt, MP, Cond, UpdRegs);
else if (CanDown)
predicateAt(MD, *DefI, TfrIt, MP, Cond, UpdRegs);
else
return false;
if (RT != RD) {
renameInRange(RT, RD, PredR, Cond, PastDefIt, TfrIt);
UpdRegs.insert(RT.Reg);
}
removeInstr(TfrI);
removeInstr(*DefI);
return true;
}
bool HexagonExpandCondsets::predicateInBlock(MachineBasicBlock &B,
std::set<Register> &UpdRegs) {
bool Changed = false;
for (MachineInstr &MI : llvm::make_early_inc_range(B)) {
unsigned Opc = MI.getOpcode();
if (Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf) {
bool Done = predicate(MI, (Opc == Hexagon::A2_tfrt), UpdRegs);
if (!Done) {
if (RegisterRef(MI.getOperand(0)) == RegisterRef(MI.getOperand(2))) {
for (auto &Op : MI.operands())
if (Op.isReg())
UpdRegs.insert(Op.getReg());
removeInstr(MI);
}
}
Changed |= Done;
}
}
return Changed;
}
bool HexagonExpandCondsets::isIntReg(RegisterRef RR, unsigned &BW) {
if (!RR.Reg.isVirtual())
return false;
const TargetRegisterClass *RC = MRI->getRegClass(RR.Reg);
if (RC == &Hexagon::IntRegsRegClass) {
BW = 32;
return true;
}
if (RC == &Hexagon::DoubleRegsRegClass) {
BW = (RR.Sub != 0) ? 32 : 64;
return true;
}
return false;
}
bool HexagonExpandCondsets::isIntraBlocks(LiveInterval &LI) {
for (LiveRange::Segment &LR : LI) {
if (!LR.start.isRegister())
return false;
if (!LR.end.isRegister() && !LR.end.isDead())
return false;
}
return true;
}
bool HexagonExpandCondsets::coalesceRegisters(RegisterRef R1, RegisterRef R2) {
if (CoaLimitActive) {
if (CoaCounter >= CoaLimit)
return false;
CoaCounter++;
}
unsigned BW1, BW2;
if (!isIntReg(R1, BW1) || !isIntReg(R2, BW2) || BW1 != BW2)
return false;
if (MRI->isLiveIn(R1.Reg))
return false;
if (MRI->isLiveIn(R2.Reg))
return false;
LiveInterval &L1 = LIS->getInterval(R1.Reg);
LiveInterval &L2 = LIS->getInterval(R2.Reg);
if (L2.empty())
return false;
if (L1.hasSubRanges() || L2.hasSubRanges())
return false;
bool Overlap = L1.overlaps(L2);
LLVM_DEBUG(dbgs() << "compatible registers: ("
<< (Overlap ? "overlap" : "disjoint") << ")\n "
<< printReg(R1.Reg, TRI, R1.Sub) << " " << L1 << "\n "
<< printReg(R2.Reg, TRI, R2.Sub) << " " << L2 << "\n");
if (R1.Sub || R2.Sub)
return false;
if (Overlap)
return false;
if (!isIntraBlocks(L1) && !isIntraBlocks(L2))
return false;
MRI->replaceRegWith(R2.Reg, R1.Reg);
using ValueInfoMap = DenseMap<VNInfo *, VNInfo *>;
ValueInfoMap VM;
for (LiveRange::Segment &I : L2) {
VNInfo *NewVN, *OldVN = I.valno;
ValueInfoMap::iterator F = VM.find(OldVN);
if (F == VM.end()) {
NewVN = L1.getNextValue(I.valno->def, LIS->getVNInfoAllocator());
VM.insert(std::make_pair(OldVN, NewVN));
} else {
NewVN = F->second;
}
L1.addSegment(LiveRange::Segment(I.start, I.end, NewVN));
}
while (!L2.empty())
L2.removeSegment(*L2.begin());
LIS->removeInterval(R2.Reg);
updateKillFlags(R1.Reg);
LLVM_DEBUG(dbgs() << "coalesced: " << L1 << "\n");
L1.verify();
return true;
}
bool HexagonExpandCondsets::coalesceSegments(
const SmallVectorImpl<MachineInstr *> &Condsets,
std::set<Register> &UpdRegs) {
SmallVector<MachineInstr*,16> TwoRegs;
for (MachineInstr *MI : Condsets) {
MachineOperand &S1 = MI->getOperand(2), &S2 = MI->getOperand(3);
if (!S1.isReg() && !S2.isReg())
continue;
TwoRegs.push_back(MI);
}
bool Changed = false;
for (MachineInstr *CI : TwoRegs) {
RegisterRef RD = CI->getOperand(0);
RegisterRef RP = CI->getOperand(1);
MachineOperand &S1 = CI->getOperand(2), &S2 = CI->getOperand(3);
bool Done = false;
if (S1.isReg()) {
RegisterRef RS = S1;
MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, true);
if (!RDef || !HII->isPredicable(*RDef)) {
Done = coalesceRegisters(RD, RegisterRef(S1));
if (Done) {
UpdRegs.insert(RD.Reg);
UpdRegs.insert(S1.getReg());
}
}
}
if (!Done && S2.isReg()) {
RegisterRef RS = S2;
MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, false);
if (!RDef || !HII->isPredicable(*RDef)) {
Done = coalesceRegisters(RD, RegisterRef(S2));
if (Done) {
UpdRegs.insert(RD.Reg);
UpdRegs.insert(S2.getReg());
}
}
}
Changed |= Done;
}
return Changed;
}
bool HexagonExpandCondsets::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(MF.getFunction()))
return false;
HII = static_cast<const HexagonInstrInfo*>(MF.getSubtarget().getInstrInfo());
TRI = MF.getSubtarget().getRegisterInfo();
MDT = &getAnalysis<MachineDominatorTree>();
LIS = &getAnalysis<LiveIntervals>();
MRI = &MF.getRegInfo();
LLVM_DEBUG(LIS->print(dbgs() << "Before expand-condsets\n",
MF.getFunction().getParent()));
bool Changed = false;
std::set<Register> CoalUpd, PredUpd;
SmallVector<MachineInstr*,16> Condsets;
for (auto &B : MF)
for (auto &I : B)
if (isCondset(I))
Condsets.push_back(&I);
Changed |= coalesceSegments(Condsets, CoalUpd);
std::set<Register> KillUpd;
for (MachineInstr *MI : Condsets)
for (MachineOperand &Op : MI->operands())
if (Op.isReg() && Op.isUse())
if (!CoalUpd.count(Op.getReg()))
KillUpd.insert(Op.getReg());
updateLiveness(KillUpd, false, true, false);
LLVM_DEBUG(
LIS->print(dbgs() << "After coalescing\n", MF.getFunction().getParent()));
for (MachineInstr *MI : Condsets)
Changed |= split(*MI, PredUpd);
Condsets.clear();
LLVM_DEBUG(
LIS->print(dbgs() << "After splitting\n", MF.getFunction().getParent()));
for (auto &B : MF)
Changed |= predicateInBlock(B, PredUpd);
LLVM_DEBUG(LIS->print(dbgs() << "After predicating\n",
MF.getFunction().getParent()));
PredUpd.insert(CoalUpd.begin(), CoalUpd.end());
updateLiveness(PredUpd, true, true, true);
LLVM_DEBUG({
if (Changed)
LIS->print(dbgs() << "After expand-condsets\n",
MF.getFunction().getParent());
});
return Changed;
}
FunctionPass *llvm::createHexagonExpandCondsets() {
return new HexagonExpandCondsets();
}