#include "llvm/CodeGen/ScheduleDAGInstrs.h"
#include "llvm/ADT/IntEqClasses.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SparseSet.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/LiveIntervals.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBundle.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/CodeGen/RegisterPressure.h"
#include "llvm/CodeGen/ScheduleDAG.h"
#include "llvm/CodeGen/ScheduleDFS.h"
#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/MC/LaneBitmask.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "machine-scheduler"
static cl::opt<bool>
EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
cl::desc("Enable use of AA during MI DAG construction"));
static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
cl::init(1000), cl::desc("The limit to use while constructing the DAG "
"prior to scheduling, at which point a trade-off "
"is made to avoid excessive compile time."));
static cl::opt<unsigned> ReductionSize(
"dag-maps-reduction-size", cl::Hidden,
cl::desc("A huge scheduling region will have maps reduced by this many "
"nodes at a time. Defaults to HugeRegion / 2."));
static unsigned getReductionSize() {
if (ReductionSize.getNumOccurrences() == 0)
return HugeRegion / 2;
return ReductionSize;
}
static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dbgs() << "{ ";
for (const SUnit *su : L) {
dbgs() << "SU(" << su->NodeNum << ")";
if (su != L.back())
dbgs() << ", ";
}
dbgs() << "}\n";
#endif
}
ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
const MachineLoopInfo *mli,
bool RemoveKillFlags)
: ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
RemoveKillFlags(RemoveKillFlags),
UnknownValue(UndefValue::get(
Type::getVoidTy(mf.getFunction().getContext()))), Topo(SUnits, &ExitSU) {
DbgValues.clear();
const TargetSubtargetInfo &ST = mf.getSubtarget();
SchedModel.init(&ST);
}
static bool getUnderlyingObjectsForInstr(const MachineInstr *MI,
const MachineFrameInfo &MFI,
UnderlyingObjectsVector &Objects,
const DataLayout &DL) {
auto allMMOsOkay = [&]() {
for (const MachineMemOperand *MMO : MI->memoperands()) {
if (MMO->isVolatile() || MMO->isAtomic())
return false;
if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
if (MFI.hasTailCall())
return false;
if (PSV->isAliased(&MFI))
return false;
bool MayAlias = PSV->mayAlias(&MFI);
Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
} else if (const Value *V = MMO->getValue()) {
SmallVector<Value *, 4> Objs;
if (!getUnderlyingObjectsForCodeGen(V, Objs))
return false;
for (Value *V : Objs) {
assert(isIdentifiedObject(V));
Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
}
} else
return false;
}
return true;
};
if (!allMMOsOkay()) {
Objects.clear();
return false;
}
return true;
}
void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
BB = bb;
}
void ScheduleDAGInstrs::finishBlock() {
BB = nullptr;
}
void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
MachineBasicBlock::iterator begin,
MachineBasicBlock::iterator end,
unsigned regioninstrs) {
assert(bb == BB && "startBlock should set BB");
RegionBegin = begin;
RegionEnd = end;
NumRegionInstrs = regioninstrs;
}
void ScheduleDAGInstrs::exitRegion() {
}
void ScheduleDAGInstrs::addSchedBarrierDeps() {
MachineInstr *ExitMI =
RegionEnd != BB->end()
? &*skipDebugInstructionsBackward(RegionEnd, RegionBegin)
: nullptr;
ExitSU.setInstr(ExitMI);
if (ExitMI) {
for (const MachineOperand &MO : ExitMI->operands()) {
if (!MO.isReg() || MO.isDef()) continue;
Register Reg = MO.getReg();
if (Register::isPhysicalRegister(Reg)) {
Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
} else if (Register::isVirtualRegister(Reg) && MO.readsReg()) {
addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
}
}
}
if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
for (const MachineBasicBlock *Succ : BB->successors()) {
for (const auto &LI : Succ->liveins()) {
if (!Uses.contains(LI.PhysReg))
Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
}
}
}
}
void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
assert(MO.isDef() && "expect physreg def");
const TargetSubtargetInfo &ST = MF.getSubtarget();
const MCInstrDesc *DefMIDesc = &SU->getInstr()->getDesc();
bool ImplicitPseudoDef = (OperIdx >= DefMIDesc->getNumOperands() &&
!DefMIDesc->hasImplicitDefOfPhysReg(MO.getReg()));
for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
Alias.isValid(); ++Alias) {
for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
SUnit *UseSU = I->SU;
if (UseSU == SU)
continue;
int UseOp = I->OpIdx;
MachineInstr *RegUse = nullptr;
SDep Dep;
if (UseOp < 0)
Dep = SDep(SU, SDep::Artificial);
else {
SU->hasPhysRegDefs = true;
Dep = SDep(SU, SDep::Data, *Alias);
RegUse = UseSU->getInstr();
}
const MCInstrDesc *UseMIDesc =
(RegUse ? &UseSU->getInstr()->getDesc() : nullptr);
bool ImplicitPseudoUse =
(UseMIDesc && UseOp >= ((int)UseMIDesc->getNumOperands()) &&
!UseMIDesc->hasImplicitUseOfPhysReg(*Alias));
if (!ImplicitPseudoDef && !ImplicitPseudoUse) {
Dep.setLatency(SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
RegUse, UseOp));
} else {
Dep.setLatency(0);
}
ST.adjustSchedDependency(SU, OperIdx, UseSU, UseOp, Dep);
UseSU->addPred(Dep);
}
}
}
void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
MachineInstr *MI = SU->getInstr();
MachineOperand &MO = MI->getOperand(OperIdx);
Register Reg = MO.getReg();
if (MRI.isConstantPhysReg(Reg))
return;
const TargetSubtargetInfo &ST = MF.getSubtarget();
SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
if (!Defs.contains(*Alias))
continue;
for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
SUnit *DefSU = I->SU;
if (DefSU == &ExitSU)
continue;
if (DefSU != SU &&
(Kind != SDep::Output || !MO.isDead() ||
!DefSU->getInstr()->registerDefIsDead(*Alias))) {
SDep Dep(SU, Kind, *Alias);
if (Kind != SDep::Anti)
Dep.setLatency(
SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
ST.adjustSchedDependency(SU, OperIdx, DefSU, I->OpIdx, Dep);
DefSU->addPred(Dep);
}
}
}
if (!MO.isDef()) {
SU->hasPhysRegUses = true;
Uses.insert(PhysRegSUOper(SU, OperIdx, Reg));
if (RemoveKillFlags)
MO.setIsKill(false);
} else {
addPhysRegDataDeps(SU, OperIdx);
for (MCSubRegIterator SubReg(Reg, TRI, true); SubReg.isValid(); ++SubReg) {
if (Uses.contains(*SubReg))
Uses.eraseAll(*SubReg);
if (!MO.isDead())
Defs.eraseAll(*SubReg);
}
if (MO.isDead() && SU->isCall) {
Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
Reg2SUnitsMap::iterator B = P.first;
Reg2SUnitsMap::iterator I = P.second;
for (bool isBegin = I == B; !isBegin; ) {
isBegin = (--I) == B;
if (!I->SU->isCall)
break;
I = Defs.erase(I);
}
}
Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
}
}
LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
{
Register Reg = MO.getReg();
const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
if (!RC.HasDisjunctSubRegs)
return LaneBitmask::getAll();
unsigned SubReg = MO.getSubReg();
if (SubReg == 0)
return RC.getLaneMask();
return TRI->getSubRegIndexLaneMask(SubReg);
}
bool ScheduleDAGInstrs::deadDefHasNoUse(const MachineOperand &MO) {
auto RegUse = CurrentVRegUses.find(MO.getReg());
if (RegUse == CurrentVRegUses.end())
return true;
return (RegUse->LaneMask & getLaneMaskForMO(MO)).none();
}
void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
MachineInstr *MI = SU->getInstr();
MachineOperand &MO = MI->getOperand(OperIdx);
Register Reg = MO.getReg();
LaneBitmask DefLaneMask;
LaneBitmask KillLaneMask;
if (TrackLaneMasks) {
bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
DefLaneMask = getLaneMaskForMO(MO);
KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
if (MO.getSubReg() != 0 && MO.isUndef()) {
for (const MachineOperand &OtherMO :
llvm::drop_begin(MI->operands(), OperIdx + 1))
if (OtherMO.isReg() && OtherMO.isDef() && OtherMO.getReg() == Reg)
KillLaneMask &= ~getLaneMaskForMO(OtherMO);
}
MO.setIsUndef(false);
} else {
DefLaneMask = LaneBitmask::getAll();
KillLaneMask = LaneBitmask::getAll();
}
if (MO.isDead()) {
assert(deadDefHasNoUse(MO) && "Dead defs should have no uses");
} else {
const TargetSubtargetInfo &ST = MF.getSubtarget();
for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
E = CurrentVRegUses.end(); I != E; ) {
LaneBitmask LaneMask = I->LaneMask;
if ((LaneMask & KillLaneMask).none()) {
++I;
continue;
}
if ((LaneMask & DefLaneMask).any()) {
SUnit *UseSU = I->SU;
MachineInstr *Use = UseSU->getInstr();
SDep Dep(SU, SDep::Data, Reg);
Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
I->OperandIndex));
ST.adjustSchedDependency(SU, OperIdx, UseSU, I->OperandIndex, Dep);
UseSU->addPred(Dep);
}
LaneMask &= ~KillLaneMask;
if (LaneMask.any()) {
I->LaneMask = LaneMask;
++I;
} else
I = CurrentVRegUses.erase(I);
}
}
if (MRI.hasOneDef(Reg))
return;
LaneBitmask LaneMask = DefLaneMask;
for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
CurrentVRegDefs.end())) {
if ((V2SU.LaneMask & LaneMask).none())
continue;
SUnit *DefSU = V2SU.SU;
if (DefSU == SU)
continue;
SDep Dep(SU, SDep::Output, Reg);
Dep.setLatency(
SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
DefSU->addPred(Dep);
LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
V2SU.SU = SU;
V2SU.LaneMask = OverlapMask;
if (NonOverlapMask.any())
CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
}
if (LaneMask.any())
CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
}
void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
const MachineInstr *MI = SU->getInstr();
assert(!MI->isDebugOrPseudoInstr());
const MachineOperand &MO = MI->getOperand(OperIdx);
Register Reg = MO.getReg();
LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO)
: LaneBitmask::getAll();
CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
CurrentVRegDefs.end())) {
LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
if ((PrevDefLaneMask & LaneMask).none())
continue;
if (V2SU.SU == SU)
continue;
V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
}
}
static inline bool isGlobalMemoryObject(MachineInstr *MI) {
return MI->isCall() || MI->hasUnmodeledSideEffects() ||
(MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad());
}
void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
unsigned Latency) {
if (SUa->getInstr()->mayAlias(AAForDep, *SUb->getInstr(), UseTBAA)) {
SDep Dep(SUa, SDep::MayAliasMem);
Dep.setLatency(Latency);
SUb->addPred(Dep);
}
}
void ScheduleDAGInstrs::initSUnits() {
SUnits.reserve(NumRegionInstrs);
for (MachineInstr &MI : make_range(RegionBegin, RegionEnd)) {
if (MI.isDebugOrPseudoInstr())
continue;
SUnit *SU = newSUnit(&MI);
MISUnitMap[&MI] = SU;
SU->isCall = MI.isCall();
SU->isCommutable = MI.isCommutable();
SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
if (SchedModel.hasInstrSchedModel()) {
const MCSchedClassDesc *SC = getSchedClass(SU);
for (const MCWriteProcResEntry &PRE :
make_range(SchedModel.getWriteProcResBegin(SC),
SchedModel.getWriteProcResEnd(SC))) {
switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
case 0:
SU->hasReservedResource = true;
break;
case 1:
SU->isUnbuffered = true;
break;
default:
break;
}
}
}
}
}
class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
unsigned NumNodes = 0;
unsigned TrueMemOrderLatency;
public:
Value2SUsMap(unsigned lat = 0) : TrueMemOrderLatency(lat) {}
ValueType &operator[](const SUList &Key) {
llvm_unreachable("Don't use. Use insert() instead."); };
void inline insert(SUnit *SU, ValueType V) {
MapVector::operator[](V).push_back(SU);
NumNodes++;
}
void inline clearList(ValueType V) {
iterator Itr = find(V);
if (Itr != end()) {
assert(NumNodes >= Itr->second.size());
NumNodes -= Itr->second.size();
Itr->second.clear();
}
}
void clear() {
MapVector<ValueType, SUList>::clear();
NumNodes = 0;
}
unsigned inline size() const { return NumNodes; }
void reComputeSize() {
NumNodes = 0;
for (auto &I : *this)
NumNodes += I.second.size();
}
unsigned inline getTrueMemOrderLatency() const {
return TrueMemOrderLatency;
}
void dump();
};
void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
Value2SUsMap &Val2SUsMap) {
for (auto &I : Val2SUsMap)
addChainDependencies(SU, I.second,
Val2SUsMap.getTrueMemOrderLatency());
}
void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
Value2SUsMap &Val2SUsMap,
ValueType V) {
Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
if (Itr != Val2SUsMap.end())
addChainDependencies(SU, Itr->second,
Val2SUsMap.getTrueMemOrderLatency());
}
void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
assert(BarrierChain != nullptr);
for (auto &I : map) {
SUList &sus = I.second;
for (auto *SU : sus)
SU->addPredBarrier(BarrierChain);
}
map.clear();
}
void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
assert(BarrierChain != nullptr);
for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
Value2SUsMap::iterator CurrItr = I++;
SUList &sus = CurrItr->second;
SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
for (; SUItr != SUEE; ++SUItr) {
if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
break;
(*SUItr)->addPredBarrier(BarrierChain);
}
if (SUItr != SUEE && *SUItr == BarrierChain)
SUItr++;
if (SUItr != sus.begin())
sus.erase(sus.begin(), SUItr);
}
map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
return (mapEntry.second.empty()); });
map.reComputeSize();
}
void ScheduleDAGInstrs::buildSchedGraph(AAResults *AA,
RegPressureTracker *RPTracker,
PressureDiffs *PDiffs,
LiveIntervals *LIS,
bool TrackLaneMasks) {
const TargetSubtargetInfo &ST = MF.getSubtarget();
bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
: ST.useAA();
AAForDep = UseAA ? AA : nullptr;
BarrierChain = nullptr;
this->TrackLaneMasks = TrackLaneMasks;
MISUnitMap.clear();
ScheduleDAG::clearDAG();
initSUnits();
if (PDiffs)
PDiffs->init(SUnits.size());
Value2SUsMap Stores, Loads(1 );
Value2SUsMap NonAliasStores, NonAliasLoads(1 );
Value2SUsMap FPExceptions;
DbgValues.clear();
FirstDbgValue = nullptr;
assert(Defs.empty() && Uses.empty() &&
"Only BuildGraph should update Defs/Uses");
Defs.setUniverse(TRI->getNumRegs());
Uses.setUniverse(TRI->getNumRegs());
assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
unsigned NumVirtRegs = MRI.getNumVirtRegs();
CurrentVRegDefs.setUniverse(NumVirtRegs);
CurrentVRegUses.setUniverse(NumVirtRegs);
addSchedBarrierDeps();
MachineInstr *DbgMI = nullptr;
for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
MII != MIE; --MII) {
MachineInstr &MI = *std::prev(MII);
if (DbgMI) {
DbgValues.push_back(std::make_pair(DbgMI, &MI));
DbgMI = nullptr;
}
if (MI.isDebugValue() || MI.isDebugPHI()) {
DbgMI = &MI;
continue;
}
if (MI.isDebugLabel() || MI.isDebugRef() || MI.isPseudoProbe())
continue;
SUnit *SU = MISUnitMap[&MI];
assert(SU && "No SUnit mapped to this MI");
if (RPTracker) {
RegisterOperands RegOpers;
RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
if (TrackLaneMasks) {
SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
}
if (PDiffs != nullptr)
PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
if (RPTracker->getPos() == RegionEnd || &*RPTracker->getPos() != &MI)
RPTracker->recedeSkipDebugValues();
assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
RPTracker->recede(RegOpers);
}
assert(
(CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
"Cannot schedule terminators or labels!");
bool HasVRegDef = false;
for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
const MachineOperand &MO = MI.getOperand(j);
if (!MO.isReg() || !MO.isDef())
continue;
Register Reg = MO.getReg();
if (Register::isPhysicalRegister(Reg)) {
addPhysRegDeps(SU, j);
} else if (Register::isVirtualRegister(Reg)) {
HasVRegDef = true;
addVRegDefDeps(SU, j);
}
}
for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
const MachineOperand &MO = MI.getOperand(j);
if (!MO.isReg() || !MO.isUse())
continue;
Register Reg = MO.getReg();
if (Register::isPhysicalRegister(Reg)) {
addPhysRegDeps(SU, j);
} else if (Register::isVirtualRegister(Reg) && MO.readsReg()) {
addVRegUseDeps(SU, j);
}
}
if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
SDep Dep(SU, SDep::Artificial);
Dep.setLatency(SU->Latency - 1);
ExitSU.addPred(Dep);
}
if (isGlobalMemoryObject(&MI)) {
if (BarrierChain)
BarrierChain->addPredBarrier(SU);
BarrierChain = SU;
LLVM_DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
<< BarrierChain->NodeNum << ").\n";);
addBarrierChain(Stores);
addBarrierChain(Loads);
addBarrierChain(NonAliasStores);
addBarrierChain(NonAliasLoads);
addBarrierChain(FPExceptions);
continue;
}
if (MI.mayRaiseFPException()) {
if (BarrierChain)
BarrierChain->addPredBarrier(SU);
FPExceptions.insert(SU, UnknownValue);
if (FPExceptions.size() >= HugeRegion) {
LLVM_DEBUG(dbgs() << "Reducing FPExceptions map.\n";);
Value2SUsMap empty;
reduceHugeMemNodeMaps(FPExceptions, empty, getReductionSize());
}
}
if (!MI.mayStore() &&
!(MI.mayLoad() && !MI.isDereferenceableInvariantLoad()))
continue;
if (BarrierChain)
BarrierChain->addPredBarrier(SU);
UnderlyingObjectsVector Objs;
bool ObjsFound = getUnderlyingObjectsForInstr(&MI, MFI, Objs,
MF.getDataLayout());
if (MI.mayStore()) {
if (!ObjsFound) {
addChainDependencies(SU, Stores);
addChainDependencies(SU, NonAliasStores);
addChainDependencies(SU, Loads);
addChainDependencies(SU, NonAliasLoads);
Stores.insert(SU, UnknownValue);
} else {
for (const UnderlyingObject &UnderlObj : Objs) {
ValueType V = UnderlObj.getValue();
bool ThisMayAlias = UnderlObj.mayAlias();
addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
}
for (const UnderlyingObject &UnderlObj : Objs) {
ValueType V = UnderlObj.getValue();
bool ThisMayAlias = UnderlObj.mayAlias();
(ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
}
addChainDependencies(SU, Loads, UnknownValue);
addChainDependencies(SU, Stores, UnknownValue);
}
} else { if (!ObjsFound) {
addChainDependencies(SU, Stores);
addChainDependencies(SU, NonAliasStores);
Loads.insert(SU, UnknownValue);
} else {
for (const UnderlyingObject &UnderlObj : Objs) {
ValueType V = UnderlObj.getValue();
bool ThisMayAlias = UnderlObj.mayAlias();
addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
(ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
}
addChainDependencies(SU, Stores, UnknownValue);
}
}
if (Stores.size() + Loads.size() >= HugeRegion) {
LLVM_DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
}
if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
LLVM_DEBUG(
dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
}
}
if (DbgMI)
FirstDbgValue = DbgMI;
Defs.clear();
Uses.clear();
CurrentVRegDefs.clear();
CurrentVRegUses.clear();
Topo.MarkDirty();
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
PSV->printCustom(OS);
return OS;
}
void ScheduleDAGInstrs::Value2SUsMap::dump() {
for (auto &Itr : *this) {
if (Itr.first.is<const Value*>()) {
const Value *V = Itr.first.get<const Value*>();
if (isa<UndefValue>(V))
dbgs() << "Unknown";
else
V->printAsOperand(dbgs());
}
else if (Itr.first.is<const PseudoSourceValue*>())
dbgs() << Itr.first.get<const PseudoSourceValue*>();
else
llvm_unreachable("Unknown Value type.");
dbgs() << " : ";
dumpSUList(Itr.second);
}
}
void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
Value2SUsMap &loads, unsigned N) {
LLVM_DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n"; stores.dump();
dbgs() << "Loading SUnits:\n"; loads.dump());
std::vector<unsigned> NodeNums;
NodeNums.reserve(stores.size() + loads.size());
for (auto &I : stores)
for (auto *SU : I.second)
NodeNums.push_back(SU->NodeNum);
for (auto &I : loads)
for (auto *SU : I.second)
NodeNums.push_back(SU->NodeNum);
llvm::sort(NodeNums);
assert(N <= NodeNums.size());
SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
if (BarrierChain) {
if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
BarrierChain->addPredBarrier(newBarrierChain);
BarrierChain = newBarrierChain;
LLVM_DEBUG(dbgs() << "Inserting new barrier chain: SU("
<< BarrierChain->NodeNum << ").\n";);
}
else
LLVM_DEBUG(dbgs() << "Keeping old barrier chain: SU("
<< BarrierChain->NodeNum << ").\n";);
}
else
BarrierChain = newBarrierChain;
insertBarrierChain(stores);
insertBarrierChain(loads);
LLVM_DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n"; stores.dump();
dbgs() << "Loading SUnits:\n"; loads.dump());
}
static void toggleKills(const MachineRegisterInfo &MRI, LivePhysRegs &LiveRegs,
MachineInstr &MI, bool addToLiveRegs) {
for (MachineOperand &MO : MI.operands()) {
if (!MO.isReg() || !MO.readsReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
bool IsKill = LiveRegs.available(MRI, Reg);
MO.setIsKill(IsKill);
if (addToLiveRegs)
LiveRegs.addReg(Reg);
}
}
void ScheduleDAGInstrs::fixupKills(MachineBasicBlock &MBB) {
LLVM_DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
LiveRegs.init(*TRI);
LiveRegs.addLiveOuts(MBB);
for (MachineInstr &MI : llvm::reverse(MBB)) {
if (MI.isDebugOrPseudoInstr())
continue;
for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
const MachineOperand &MO = *O;
if (MO.isReg()) {
if (!MO.isDef())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
LiveRegs.removeReg(Reg);
} else if (MO.isRegMask()) {
LiveRegs.removeRegsInMask(MO);
}
}
if (!MI.isBundled()) {
toggleKills(MRI, LiveRegs, MI, true);
} else {
MachineBasicBlock::instr_iterator Bundle = MI.getIterator();
if (MI.isBundle())
toggleKills(MRI, LiveRegs, MI, false);
MachineBasicBlock::instr_iterator I = std::next(Bundle);
while (I->isBundledWithSucc())
++I;
do {
if (!I->isDebugOrPseudoInstr())
toggleKills(MRI, LiveRegs, *I, true);
--I;
} while (I != Bundle);
}
}
}
void ScheduleDAGInstrs::dumpNode(const SUnit &SU) const {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dumpNodeName(SU);
dbgs() << ": ";
SU.getInstr()->dump();
#endif
}
void ScheduleDAGInstrs::dump() const {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
if (EntrySU.getInstr() != nullptr)
dumpNodeAll(EntrySU);
for (const SUnit &SU : SUnits)
dumpNodeAll(SU);
if (ExitSU.getInstr() != nullptr)
dumpNodeAll(ExitSU);
#endif
}
std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
std::string s;
raw_string_ostream oss(s);
if (SU == &EntrySU)
oss << "<entry>";
else if (SU == &ExitSU)
oss << "<exit>";
else
SU->getInstr()->print(oss, true);
return oss.str();
}
std::string ScheduleDAGInstrs::getDAGName() const {
return "dag." + BB->getFullName();
}
bool ScheduleDAGInstrs::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
}
bool ScheduleDAGInstrs::addEdge(SUnit *SuccSU, const SDep &PredDep) {
if (SuccSU != &ExitSU) {
if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
return false;
Topo.AddPredQueued(SuccSU, PredDep.getSUnit());
}
SuccSU->addPred(PredDep, !PredDep.isArtificial());
return true;
}
namespace llvm {
class SchedDFSImpl {
SchedDFSResult &R;
IntEqClasses SubtreeClasses;
std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
struct RootData {
unsigned NodeID;
unsigned ParentNodeID; unsigned SubInstrCount = 0;
RootData(unsigned id): NodeID(id),
ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
unsigned getSparseSetIndex() const { return NodeID; }
};
SparseSet<RootData> RootSet;
public:
SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
RootSet.setUniverse(R.DFSNodeData.size());
}
bool isVisited(const SUnit *SU) const {
return R.DFSNodeData[SU->NodeNum].SubtreeID
!= SchedDFSResult::InvalidSubtreeID;
}
void visitPreorder(const SUnit *SU) {
R.DFSNodeData[SU->NodeNum].InstrCount =
SU->getInstr()->isTransient() ? 0 : 1;
}
void visitPostorderNode(const SUnit *SU) {
R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
RootData RData(SU->NodeNum);
RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
for (const SDep &PredDep : SU->Preds) {
if (PredDep.getKind() != SDep::Data)
continue;
unsigned PredNum = PredDep.getSUnit()->NodeNum;
if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
joinPredSubtree(PredDep, SU, false);
if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
RootSet[PredNum].ParentNodeID = SU->NodeNum;
}
else if (RootSet.count(PredNum)) {
RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
RootSet.erase(PredNum);
}
}
RootSet[SU->NodeNum] = RData;
}
void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
R.DFSNodeData[Succ->NodeNum].InstrCount
+= R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
joinPredSubtree(PredDep, Succ);
}
void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
}
void finalize() {
SubtreeClasses.compress();
R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
assert(SubtreeClasses.getNumClasses() == RootSet.size()
&& "number of roots should match trees");
for (const RootData &Root : RootSet) {
unsigned TreeID = SubtreeClasses[Root.NodeID];
if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
}
R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
LLVM_DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
LLVM_DEBUG(dbgs() << " SU(" << Idx << ") in tree "
<< R.DFSNodeData[Idx].SubtreeID << '\n');
}
for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
unsigned PredTree = SubtreeClasses[P.first->NodeNum];
unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
if (PredTree == SuccTree)
continue;
unsigned Depth = P.first->getDepth();
addConnection(PredTree, SuccTree, Depth);
addConnection(SuccTree, PredTree, Depth);
}
}
protected:
bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
bool CheckLimit = true) {
assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
const SUnit *PredSU = PredDep.getSUnit();
unsigned PredNum = PredSU->NodeNum;
if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
return false;
unsigned NumDataSucs = 0;
for (const SDep &SuccDep : PredSU->Succs) {
if (SuccDep.getKind() == SDep::Data) {
if (++NumDataSucs >= 4)
return false;
}
}
if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
return false;
R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
SubtreeClasses.join(Succ->NodeNum, PredNum);
return true;
}
void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
if (!Depth)
return;
do {
SmallVectorImpl<SchedDFSResult::Connection> &Connections =
R.SubtreeConnections[FromTree];
for (SchedDFSResult::Connection &C : Connections) {
if (C.TreeID == ToTree) {
C.Level = std::max(C.Level, Depth);
return;
}
}
Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
FromTree = R.DFSTreeData[FromTree].ParentTreeID;
} while (FromTree != SchedDFSResult::InvalidSubtreeID);
}
};
}
namespace {
class SchedDAGReverseDFS {
std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
public:
bool isComplete() const { return DFSStack.empty(); }
void follow(const SUnit *SU) {
DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
}
void advance() { ++DFSStack.back().second; }
const SDep *backtrack() {
DFSStack.pop_back();
return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
}
const SUnit *getCurr() const { return DFSStack.back().first; }
SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
SUnit::const_pred_iterator getPredEnd() const {
return getCurr()->Preds.end();
}
};
}
static bool hasDataSucc(const SUnit *SU) {
for (const SDep &SuccDep : SU->Succs) {
if (SuccDep.getKind() == SDep::Data &&
!SuccDep.getSUnit()->isBoundaryNode())
return true;
}
return false;
}
void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
if (!IsBottomUp)
llvm_unreachable("Top-down ILP metric is unimplemented");
SchedDFSImpl Impl(*this);
for (const SUnit &SU : SUnits) {
if (Impl.isVisited(&SU) || hasDataSucc(&SU))
continue;
SchedDAGReverseDFS DFS;
Impl.visitPreorder(&SU);
DFS.follow(&SU);
while (true) {
while (DFS.getPred() != DFS.getPredEnd()) {
const SDep &PredDep = *DFS.getPred();
DFS.advance();
if (PredDep.getKind() != SDep::Data
|| PredDep.getSUnit()->isBoundaryNode()) {
continue;
}
if (Impl.isVisited(PredDep.getSUnit())) {
Impl.visitCrossEdge(PredDep, DFS.getCurr());
continue;
}
Impl.visitPreorder(PredDep.getSUnit());
DFS.follow(PredDep.getSUnit());
}
const SUnit *Child = DFS.getCurr();
const SDep *PredDep = DFS.backtrack();
Impl.visitPostorderNode(Child);
if (PredDep)
Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
if (DFS.isComplete())
break;
}
}
Impl.finalize();
}
void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
for (const Connection &C : SubtreeConnections[SubtreeID]) {
SubtreeConnectLevels[C.TreeID] =
std::max(SubtreeConnectLevels[C.TreeID], C.Level);
LLVM_DEBUG(dbgs() << " Tree: " << C.TreeID << " @"
<< SubtreeConnectLevels[C.TreeID] << '\n');
}
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void ILPValue::print(raw_ostream &OS) const {
OS << InstrCount << " / " << Length << " = ";
if (!Length)
OS << "BADILP";
else
OS << format("%g", ((double)InstrCount / Length));
}
LLVM_DUMP_METHOD void ILPValue::dump() const {
dbgs() << *this << '\n';
}
namespace llvm {
LLVM_DUMP_METHOD
raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
Val.print(OS);
return OS;
}
}
#endif