51#define DEBUG_TYPE "regalloc"
55STATISTIC(NumCoalesced,
"Number of copies coalesced");
68class InstrPosIndexes {
70 void unsetInitialized() { IsInitialized =
false; }
72 void init(
const MachineBasicBlock &
MBB) {
74 Instr2PosIndex.
clear();
76 for (
const MachineInstr &
MI :
MBB) {
77 LastIndex += InstrDist;
78 Instr2PosIndex[&
MI] = LastIndex;
85 bool getIndex(
const MachineInstr &
MI,
uint64_t &Index) {
93 assert(
MI.getParent() == CurMBB &&
"MI is not in CurMBB");
94 auto It = Instr2PosIndex.find(&
MI);
95 if (It != Instr2PosIndex.end()) {
109 unsigned Distance = 1;
111 End = std::next(Start);
112 while (Start != CurMBB->begin() &&
113 !Instr2PosIndex.count(&*std::prev(Start))) {
117 while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
125 Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
127 if (End == CurMBB->end())
128 Step =
static_cast<uint64_t>(InstrDist);
131 uint64_t EndIndex = Instr2PosIndex.at(&*End);
132 assert(EndIndex > LastIndex &&
"Index must be ascending order");
133 unsigned NumAvailableIndexes = EndIndex - LastIndex - 1;
152 Step = (NumAvailableIndexes + 1) / (Distance + 1);
157 if (
LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
159 Index = Instr2PosIndex.at(&
MI);
163 for (
auto I = Start;
I != End; ++
I) {
165 Instr2PosIndex[&*
I] = LastIndex;
167 Index = Instr2PosIndex.at(&
MI);
172 bool IsInitialized =
false;
173 enum { InstrDist = 1024 };
174 const MachineBasicBlock *CurMBB =
nullptr;
175 DenseMap<const MachineInstr *, uint64_t> Instr2PosIndex;
178class RegAllocFastImpl {
181 bool ClearVirtRegs_ =
true)
182 : ShouldAllocateRegisterImpl(
F), StackSlotForVirtReg(-1),
183 ClearVirtRegs(ClearVirtRegs_) {}
186 MachineFrameInfo *MFI =
nullptr;
187 MachineRegisterInfo *MRI =
nullptr;
188 const TargetRegisterInfo *TRI =
nullptr;
189 const TargetInstrInfo *TII =
nullptr;
190 RegisterClassInfo RegClassInfo;
194 MachineBasicBlock *MBB =
nullptr;
197 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
201 MachineInstr *LastUse =
nullptr;
204 bool LiveOut =
false;
205 bool Reloaded =
false;
208 explicit LiveReg(
Register VirtReg) : VirtReg(VirtReg) {}
209 explicit LiveReg() =
default;
211 unsigned getSparseSetIndex()
const {
return VirtReg.virtRegIndex(); }
214 using LiveRegMap = SparseSet<LiveReg, unsigned, identity, uint16_t>;
217 LiveRegMap LiveVirtRegs;
220 DenseMap<Register, LiveReg> BundleVirtRegsMap;
222 DenseMap<Register, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
225 DenseMap<Register, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
229 BitVector MayLiveAcrossBlocks;
251 std::vector<unsigned> RegUnitStates;
269 SmallVector<unsigned, 0> UsedInInstr;
271 SmallVector<unsigned, 8> DefOperandIndexes;
276 InstrPosIndexes PosIndexes;
278 void setRegUnitState(MCRegUnit Unit,
unsigned NewState);
279 unsigned getRegUnitState(MCRegUnit Unit)
const;
281 void setPhysRegState(MCRegister PhysReg,
unsigned NewState);
282 bool isPhysRegFree(MCRegister PhysReg)
const;
285 void markRegUsedInInstr(MCRegister PhysReg) {
286 for (MCRegUnit Unit : TRI->regunits(PhysReg))
287 UsedInInstr[
static_cast<unsigned>(
Unit)] = InstrGen | 1;
291 bool isClobberedByRegMasks(MCRegister PhysReg)
const {
292 return llvm::any_of(RegMasks, [PhysReg](
const uint32_t *Mask) {
298 bool isRegUsedInInstr(MCRegister PhysReg,
bool LookAtPhysRegUses)
const {
299 if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
301 for (MCRegUnit Unit : TRI->regunits(PhysReg))
302 if (UsedInInstr[
static_cast<unsigned>(Unit)] >=
303 (InstrGen | !LookAtPhysRegUses))
310 void markPhysRegUsedInInstr(MCRegister PhysReg) {
311 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
312 assert(UsedInInstr[
static_cast<unsigned>(Unit)] <= InstrGen &&
313 "non-phys use before phys use?");
314 UsedInInstr[
static_cast<unsigned>(
Unit)] = InstrGen;
319 void unmarkRegUsedInInstr(MCRegister PhysReg) {
320 for (MCRegUnit Unit : TRI->regunits(PhysReg))
321 UsedInInstr[
static_cast<unsigned>(
Unit)] = 0;
328 spillImpossible = ~0
u
337 void allocateBasicBlock(MachineBasicBlock &MBB);
342 void findAndSortDefOperandIndexes(
const MachineInstr &
MI);
344 void allocateInstruction(MachineInstr &
MI);
345 void handleDebugValue(MachineInstr &
MI);
346 void handleBundle(MachineInstr &
MI);
348 bool usePhysReg(MachineInstr &
MI, MCRegister PhysReg);
349 bool definePhysReg(MachineInstr &
MI, MCRegister PhysReg);
350 bool displacePhysReg(MachineInstr &
MI, MCRegister PhysReg);
351 void freePhysReg(MCRegister PhysReg);
353 unsigned calcSpillCost(
MCPhysReg PhysReg)
const;
363 void assignVirtToPhysReg(MachineInstr &
MI, LiveReg &, MCRegister PhysReg);
364 void allocVirtReg(MachineInstr &
MI, LiveReg &LR,
Register Hint,
365 bool LookAtPhysRegUses =
false);
366 void allocVirtRegUndef(MachineOperand &MO);
367 void assignDanglingDebugValues(MachineInstr &Def,
Register VirtReg,
369 bool defineLiveThroughVirtReg(MachineInstr &
MI,
unsigned OpNum,
371 bool defineVirtReg(MachineInstr &
MI,
unsigned OpNum,
Register VirtReg,
372 bool LookAtPhysRegUses =
false);
373 bool useVirtReg(MachineInstr &
MI, MachineOperand &MO,
Register VirtReg);
375 MCPhysReg getErrorAssignment(
const LiveReg &LR, MachineInstr &
MI,
379 getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
380 SmallSet<Register, 2> &PrologLiveIns)
const;
382 void reloadAtBegin(MachineBasicBlock &MBB);
383 bool setPhysReg(MachineInstr &
MI, MachineOperand &MO,
384 const LiveReg &Assignment);
389 bool shouldAllocateRegister(
const Register Reg)
const;
390 int getStackSpaceFor(
Register VirtReg);
392 MCRegister AssignedReg,
bool Kill,
bool LiveOut);
399 bool mayBeSpillFromInlineAsmBr(
const MachineInstr &
MI)
const;
401 void dumpState()
const;
405 RegAllocFastImpl Impl;
411 : MachineFunctionPass(ID), Impl(
F, ClearVirtRegs_) {}
414 return Impl.runOnMachineFunction(MF);
417 StringRef getPassName()
const override {
return "Fast Register Allocator"; }
419 void getAnalysisUsage(AnalysisUsage &AU)
const override {
424 MachineFunctionProperties getRequiredProperties()
const override {
425 return MachineFunctionProperties().setNoPHIs();
428 MachineFunctionProperties getSetProperties()
const override {
429 if (Impl.ClearVirtRegs) {
430 return MachineFunctionProperties().setNoVRegs();
433 return MachineFunctionProperties();
436 MachineFunctionProperties getClearedProperties()
const override {
437 return MachineFunctionProperties().setIsSSA();
443char RegAllocFast::ID = 0;
450 if (!ShouldAllocateRegisterImpl)
453 return ShouldAllocateRegisterImpl(*
TRI, *MRI,
Reg);
456void RegAllocFastImpl::setRegUnitState(MCRegUnit Unit,
unsigned NewState) {
457 RegUnitStates[
static_cast<unsigned>(
Unit)] = NewState;
460unsigned RegAllocFastImpl::getRegUnitState(MCRegUnit Unit)
const {
461 return RegUnitStates[
static_cast<unsigned>(
Unit)];
464void RegAllocFastImpl::setPhysRegState(MCRegister PhysReg,
unsigned NewState) {
465 for (MCRegUnit Unit :
TRI->regunits(PhysReg))
466 setRegUnitState(Unit, NewState);
469bool RegAllocFastImpl::isPhysRegFree(MCRegister PhysReg)
const {
470 for (MCRegUnit Unit :
TRI->regunits(PhysReg)) {
471 if (getRegUnitState(Unit) != regFree)
479int RegAllocFastImpl::getStackSpaceFor(
Register VirtReg) {
481 int SS = StackSlotForVirtReg[VirtReg];
488 unsigned Size =
TRI->getSpillSize(RC);
493 Align CurrentAlign =
ST.getFrameLowering()->getStackAlign();
494 if (Alignment > CurrentAlign && !
TRI->canRealignStack(MF))
501 StackSlotForVirtReg[VirtReg] = FrameIdx;
508 PosIndexes.getIndex(
A, IndexA);
510 PosIndexes.getIndex(
A, IndexA);
511 return IndexA < IndexB;
518bool RegAllocFastImpl::mayBeSpillFromInlineAsmBr(
const MachineInstr &
MI)
const {
523 for (
const auto &
Op :
MI.operands())
530bool RegAllocFastImpl::mayLiveOut(
Register VirtReg) {
536 const MachineInstr *SelfLoopDef =
nullptr;
543 if (DefInst.getParent() !=
MBB) {
547 if (!SelfLoopDef ||
dominates(PosIndexes, DefInst, *SelfLoopDef))
548 SelfLoopDef = &DefInst;
559 static const unsigned Limit = 8;
562 if (UseInst.getParent() !=
MBB || ++
C >= Limit) {
571 if (SelfLoopDef == &UseInst ||
572 !
dominates(PosIndexes, *SelfLoopDef, UseInst)) {
583bool RegAllocFastImpl::mayLiveIn(
Register VirtReg) {
588 static const unsigned Limit = 8;
591 if (DefInst.getParent() !=
MBB || ++
C >= Limit) {
603 Register VirtReg, MCRegister AssignedReg,
604 bool Kill,
bool LiveOut) {
607 int FI = getStackSpaceFor(VirtReg);
619 SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
620 SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
622 for (MachineOperand *MO : LRIDbgOperands)
623 SpilledOperandsMap[MO->getParent()].push_back(MO);
624 for (
const auto &MISpilledOperands : SpilledOperandsMap) {
625 MachineInstr &
DBG = *MISpilledOperands.first;
627 if (
DBG.isDebugValueList())
630 *
MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
633 LLVM_DEBUG(
dbgs() <<
"Inserting debug info due to spill:\n" << *NewDV);
640 MachineInstr *ClonedDV =
MBB->
getParent()->CloneMachineInstr(NewDV);
642 LLVM_DEBUG(
dbgs() <<
"Cloning debug info due to live out spill\n");
648 if (
DBG.isNonListDebugValue()) {
649 MachineOperand &MO =
DBG.getDebugOperand(0);
658 LRIDbgOperands.
clear();
663 Register VirtReg, MCRegister PhysReg) {
666 int FI = getStackSpaceFor(VirtReg);
677 MachineBasicBlock &
MBB, SmallSet<Register, 2> &PrologLiveIns)
const {
686 if (!
TII->isBasicBlockPrologue(*
I) && !mayBeSpillFromInlineAsmBr(*
I))
691 for (MachineOperand &MO :
I->operands()) {
703void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &
MBB) {
704 if (LiveVirtRegs.empty())
707 for (MachineBasicBlock::RegisterMaskPair
P :
MBB.
liveins()) {
708 MCRegister
Reg =
P.PhysReg;
711 setPhysRegState(
Reg, regLiveIn);
714 SmallSet<Register, 2> PrologLiveIns;
719 getMBBBeginInsertionPoint(
MBB, PrologLiveIns);
720 for (
const LiveReg &LR : LiveVirtRegs) {
721 MCRegister PhysReg = LR.PhysReg;
722 if (!PhysReg || LR.Error)
725 MCRegUnit FirstUnit = *
TRI->regunits(PhysReg).begin();
726 if (getRegUnitState(FirstUnit) == regLiveIn)
730 "no reload in start block. Missing vreg def?");
732 if (PrologLiveIns.
count(PhysReg)) {
736 reload(
MBB.
begin(), LR.VirtReg, PhysReg);
738 reload(InsertBefore, LR.VirtReg, PhysReg);
740 LiveVirtRegs.clear();
746bool RegAllocFastImpl::usePhysReg(MachineInstr &
MI, MCRegister
Reg) {
748 bool displacedAny = displacePhysReg(
MI,
Reg);
749 setPhysRegState(
Reg, regPreAssigned);
750 markRegUsedInInstr(
Reg);
754bool RegAllocFastImpl::definePhysReg(MachineInstr &
MI, MCRegister
Reg) {
755 bool displacedAny = displacePhysReg(
MI,
Reg);
756 setPhysRegState(
Reg, regPreAssigned);
763bool RegAllocFastImpl::displacePhysReg(MachineInstr &
MI, MCRegister PhysReg) {
764 bool displacedAny =
false;
766 for (MCRegUnit Unit :
TRI->regunits(PhysReg)) {
767 switch (
unsigned VirtReg = getRegUnitState(Unit)) {
769 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
770 assert(LRI != LiveVirtRegs.end() &&
"datastructures in sync");
773 while (mayBeSpillFromInlineAsmBr(*ReloadBefore))
775 reload(ReloadBefore, VirtReg, LRI->PhysReg);
777 setPhysRegState(LRI->PhysReg, regFree);
778 LRI->PhysReg = MCRegister();
779 LRI->Reloaded =
true;
784 setRegUnitState(Unit, regFree);
794void RegAllocFastImpl::freePhysReg(MCRegister PhysReg) {
797 MCRegUnit FirstUnit = *
TRI->regunits(PhysReg).begin();
798 switch (
unsigned VirtReg = getRegUnitState(FirstUnit)) {
804 setPhysRegState(PhysReg, regFree);
807 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
808 assert(LRI != LiveVirtRegs.end());
810 setPhysRegState(LRI->PhysReg, regFree);
811 LRI->PhysReg = MCRegister();
821unsigned RegAllocFastImpl::calcSpillCost(
MCPhysReg PhysReg)
const {
822 for (MCRegUnit Unit :
TRI->regunits(PhysReg)) {
823 switch (
unsigned VirtReg = getRegUnitState(Unit)) {
829 return spillImpossible;
831 bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
832 findLiveVirtReg(VirtReg)->LiveOut;
833 return SureSpill ? spillClean : spillDirty;
840void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
843 auto UDBGValIter = DanglingDbgValues.
find(VirtReg);
844 if (UDBGValIter == DanglingDbgValues.
end())
847 SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
848 for (MachineInstr *DbgValue : Dangling) {
849 assert(DbgValue->isDebugValue());
850 if (!DbgValue->hasDebugOperandForReg(VirtReg))
854 MCRegister SetToReg =
Reg;
857 E = DbgValue->getIterator();
859 if (
I->modifiesRegister(
Reg,
TRI) || --Limit == 0) {
862 SetToReg = MCRegister();
866 for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
878void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
879 MCRegister PhysReg) {
883 assert(!LR.PhysReg &&
"Already assigned a physreg");
884 assert(PhysReg &&
"Trying to assign no register");
885 LR.PhysReg = PhysReg;
886 setPhysRegState(PhysReg, VirtReg.
id());
888 assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
894 static const unsigned ChainLengthLimit = 3;
895 for (
unsigned C = 0;
C <= ChainLengthLimit; ++
C) {
906 Reg =
Def->getOperand(1).getReg();
915 static const unsigned DefLimit = 3;
920 Reg = traceCopyChain(
Reg);
932void RegAllocFastImpl::allocVirtReg(MachineInstr &
MI, LiveReg &LR,
933 Register Hint0,
bool LookAtPhysRegUses) {
934 const Register VirtReg = LR.VirtReg;
939 <<
" in class " <<
TRI->getRegClassName(&RC)
944 !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
946 if (isPhysRegFree(Hint0)) {
949 assignVirtToPhysReg(
MI, LR, Hint0);
960 Register Hint1 = traceCopies(VirtReg);
962 !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
964 if (isPhysRegFree(Hint1)) {
967 assignVirtToPhysReg(
MI, LR, Hint1);
978 unsigned BestCost = spillImpossible;
980 for (
MCPhysReg PhysReg : AllocationOrder) {
982 if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
987 unsigned Cost = calcSpillCost(PhysReg);
991 assignVirtToPhysReg(
MI, LR, PhysReg);
995 if (PhysReg == Hint0 || PhysReg == Hint1)
996 Cost -= spillPrefBonus;
998 if (
Cost < BestCost) {
1007 LR.PhysReg = getErrorAssignment(LR,
MI, RC);
1012 displacePhysReg(
MI, BestReg);
1013 assignVirtToPhysReg(
MI, LR, BestReg);
1016void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
1020 if (!shouldAllocateRegister(VirtReg))
1023 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1025 bool IsRenamable =
true;
1026 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1027 PhysReg = LRI->PhysReg;
1031 if (AllocationOrder.
empty()) {
1037 PhysReg = getErrorAssignment(*LRI, *MO.
getParent(), RC);
1039 IsRenamable =
false;
1041 PhysReg = AllocationOrder.
front();
1045 if (SubRegIdx != 0) {
1046 PhysReg =
TRI->getSubReg(PhysReg, SubRegIdx);
1056bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &
MI,
1059 if (!shouldAllocateRegister(VirtReg))
1061 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1062 if (LRI != LiveVirtRegs.end()) {
1063 MCRegister PrevReg = LRI->PhysReg;
1064 if (PrevReg && isRegUsedInInstr(PrevReg,
true)) {
1066 <<
" (tied/earlyclobber resolution)\n");
1067 freePhysReg(PrevReg);
1068 LRI->PhysReg = MCRegister();
1075 TII->get(TargetOpcode::COPY), PrevReg)
1078 MachineOperand &MO =
MI.getOperand(OpNum);
1083 return defineVirtReg(
MI, OpNum, VirtReg,
true);
1093bool RegAllocFastImpl::defineVirtReg(MachineInstr &
MI,
unsigned OpNum,
1094 Register VirtReg,
bool LookAtPhysRegUses) {
1096 if (!shouldAllocateRegister(VirtReg))
1098 MachineOperand &MO =
MI.getOperand(OpNum);
1099 LiveRegMap::iterator LRI;
1101 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1104 if (mayLiveOut(VirtReg)) {
1105 LRI->LiveOut =
true;
1112 if (!LRI->PhysReg) {
1113 allocVirtReg(
MI, *LRI,
Register(), LookAtPhysRegUses);
1115 assert((!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) || LRI->Error) &&
1116 "TODO: preassign mismatch");
1118 <<
" use existing assignment to "
1122 MCRegister PhysReg = LRI->PhysReg;
1123 if (LRI->Reloaded || LRI->LiveOut) {
1124 if (!
MI.isImplicitDef()) {
1128 <<
" RL: " << LRI->Reloaded <<
'\n');
1129 bool Kill = LRI->LastUse ==
nullptr;
1130 spill(SpillBefore, VirtReg, PhysReg,
Kill, LRI->LiveOut);
1134 if (
MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1135 int FI = StackSlotForVirtReg[VirtReg];
1137 for (MachineOperand &MO :
MI.operands()) {
1139 MachineBasicBlock *Succ = MO.
getMBB();
1148 LRI->LastUse =
nullptr;
1150 LRI->LiveOut =
false;
1151 LRI->Reloaded =
false;
1153 if (
MI.getOpcode() == TargetOpcode::BUNDLE) {
1154 BundleVirtRegsMap[VirtReg] = *LRI;
1156 markRegUsedInInstr(PhysReg);
1157 return setPhysReg(
MI, MO, *LRI);
1162bool RegAllocFastImpl::useVirtReg(MachineInstr &
MI, MachineOperand &MO,
1165 if (!shouldAllocateRegister(VirtReg))
1167 LiveRegMap::iterator LRI;
1169 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1172 if (mayLiveOut(VirtReg)) {
1173 LRI->LiveOut =
true;
1180 assert((!MO.
isKill() || LRI->LastUse == &
MI) &&
"Invalid kill flag");
1184 if (!LRI->PhysReg) {
1187 if (
MI.isCopy() &&
MI.getOperand(1).getSubReg() == 0) {
1188 Hint =
MI.getOperand(0).getReg();
1189 if (
Hint.isVirtual()) {
1190 assert(!shouldAllocateRegister(Hint));
1194 "Copy destination should already be assigned");
1197 allocVirtReg(
MI, *LRI, Hint,
false);
1202 if (
MI.getOpcode() == TargetOpcode::BUNDLE) {
1203 BundleVirtRegsMap[VirtReg] = *LRI;
1205 markRegUsedInInstr(LRI->PhysReg);
1206 return setPhysReg(
MI, MO, *LRI);
1212MCPhysReg RegAllocFastImpl::getErrorAssignment(
const LiveReg &LR,
1226 if (AllocationOrder.
empty()) {
1230 "no registers from class available to allocate", Fn,
1235 assert(!RawRegs.
empty() &&
"register classes cannot have no registers");
1236 return RawRegs.
front();
1239 if (!LR.Error && EmitError) {
1242 if (
MI.isInlineAsm()) {
1243 MI.emitInlineAsmError(
1244 "inline assembly requires more registers than available");
1248 "ran out of registers during register allocation", Fn,
1253 return AllocationOrder.
front();
1258bool RegAllocFastImpl::setPhysReg(MachineInstr &
MI, MachineOperand &MO,
1259 const LiveReg &Assignment) {
1260 MCRegister PhysReg = Assignment.PhysReg;
1261 assert(PhysReg &&
"assignments should always be to a valid physreg");
1289 MI.addRegisterKilled(PhysReg,
TRI,
true);
1298 MI.addRegisterDead(PhysReg,
TRI,
true);
1300 MI.addRegisterDefined(PhysReg,
TRI);
1309void RegAllocFastImpl::dumpState()
const {
1310 for (MCRegUnit Unit :
TRI->regunits()) {
1311 switch (
unsigned VirtReg = getRegUnitState(Unit)) {
1314 case regPreAssigned:
1321 LiveRegMap::const_iterator
I = findLiveVirtReg(VirtReg);
1322 assert(
I != LiveVirtRegs.end() &&
"have LiveVirtRegs entry");
1323 if (
I->LiveOut ||
I->Reloaded) {
1331 assert(
TRI->hasRegUnit(
I->PhysReg, Unit) &&
"inverse mapping present");
1338 for (
const LiveReg &LR : LiveVirtRegs) {
1341 MCRegister PhysReg = LR.PhysReg;
1344 for (MCRegUnit Unit :
TRI->regunits(PhysReg)) {
1345 assert(getRegUnitState(Unit) == VirtReg &&
"inverse map valid");
1353void RegAllocFastImpl::addRegClassDefCounts(
1355 assert(RegClassDefCounts.
size() ==
TRI->getNumRegClasses());
1358 if (!shouldAllocateRegister(
Reg))
1361 for (
unsigned RCIdx = 0, RCIdxEnd =
TRI->getNumRegClasses();
1362 RCIdx != RCIdxEnd; ++RCIdx) {
1366 ++RegClassDefCounts[RCIdx];
1372 for (
unsigned RCIdx = 0, RCIdxEnd =
TRI->getNumRegClasses();
1373 RCIdx != RCIdxEnd; ++RCIdx) {
1375 for (MCRegAliasIterator Alias(
Reg,
TRI,
true); Alias.isValid(); ++Alias) {
1377 ++RegClassDefCounts[RCIdx];
1387void RegAllocFastImpl::findAndSortDefOperandIndexes(
const MachineInstr &
MI) {
1388 DefOperandIndexes.
clear();
1391 for (
unsigned I = 0,
E =
MI.getNumOperands();
I <
E; ++
I) {
1392 const MachineOperand &MO =
MI.getOperand(
I);
1399 markPhysRegUsedInInstr(
Reg);
1409 if (DefOperandIndexes.
size() <= 1)
1417 SmallVector<unsigned> RegClassDefCounts(
TRI->getNumRegClasses(), 0);
1419 for (
const MachineOperand &MO :
MI.all_defs())
1420 addRegClassDefCounts(RegClassDefCounts, MO.
getReg());
1422 llvm::sort(DefOperandIndexes, [&](
unsigned I0,
unsigned I1) {
1423 const MachineOperand &MO0 =
MI.getOperand(I0);
1424 const MachineOperand &MO1 =
MI.getOperand(I1);
1432 unsigned ClassSize0 = RegClassInfo.
getOrder(&RC0).size();
1433 unsigned ClassSize1 = RegClassInfo.
getOrder(&RC1).size();
1435 bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.
getID()];
1436 bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.
getID()];
1437 if (SmallClass0 > SmallClass1)
1439 if (SmallClass0 < SmallClass1)
1447 if (Livethrough0 > Livethrough1)
1449 if (Livethrough0 < Livethrough1)
1462 unsigned TiedIdx =
MI.findTiedOperandIdx(
MI.getOperandNo(&MO));
1467void RegAllocFastImpl::allocateInstruction(MachineInstr &
MI) {
1487 BundleVirtRegsMap.
clear();
1490 bool HasPhysRegUse =
false;
1491 bool HasRegMask =
false;
1492 bool HasVRegDef =
false;
1493 bool HasDef =
false;
1494 bool HasEarlyClobber =
false;
1495 bool NeedToAssignLiveThroughs =
false;
1496 for (MachineOperand &MO :
MI.operands()) {
1500 if (!shouldAllocateRegister(
Reg))
1506 HasEarlyClobber =
true;
1507 NeedToAssignLiveThroughs =
true;
1511 NeedToAssignLiveThroughs =
true;
1517 bool displacedAny = definePhysReg(
MI,
Reg);
1519 HasEarlyClobber =
true;
1524 HasPhysRegUse =
true;
1538 bool ReArrangedImplicitOps =
true;
1546 if (NeedToAssignLiveThroughs) {
1547 while (ReArrangedImplicitOps) {
1548 ReArrangedImplicitOps =
false;
1549 findAndSortDefOperandIndexes(
MI);
1550 for (
unsigned OpIdx : DefOperandIndexes) {
1551 MachineOperand &MO =
MI.getOperand(OpIdx);
1556 ReArrangedImplicitOps = defineLiveThroughVirtReg(
MI, OpIdx,
Reg);
1558 ReArrangedImplicitOps = defineVirtReg(
MI, OpIdx,
Reg);
1562 if (ReArrangedImplicitOps)
1568 while (ReArrangedImplicitOps) {
1569 ReArrangedImplicitOps =
false;
1570 for (MachineOperand &MO :
MI.all_defs()) {
1573 ReArrangedImplicitOps =
1574 defineVirtReg(
MI,
MI.getOperandNo(&MO),
Reg);
1575 if (ReArrangedImplicitOps)
1586 for (MachineOperand &MO :
reverse(
MI.all_defs())) {
1597 "tied def assigned to clobbered register");
1612 unmarkRegUsedInInstr(
Reg);
1620 for (
const auto *RM : RegMasks)
1624 for (
const LiveReg &LR : LiveVirtRegs) {
1625 MCRegister PhysReg = LR.PhysReg;
1626 if (PhysReg && isClobberedByRegMasks(PhysReg))
1627 displacePhysReg(
MI, PhysReg);
1632 if (HasPhysRegUse) {
1633 for (MachineOperand &MO :
MI.operands()) {
1641 if (!usePhysReg(
MI,
Reg))
1649 bool HasUndefUse =
false;
1650 bool ReArrangedImplicitMOs =
true;
1651 while (ReArrangedImplicitMOs) {
1652 ReArrangedImplicitMOs =
false;
1653 for (MachineOperand &MO :
MI.operands()) {
1671 ReArrangedImplicitMOs = useVirtReg(
MI, MO,
Reg);
1672 if (ReArrangedImplicitMOs)
1681 for (MachineOperand &MO :
MI.all_uses()) {
1686 assert(MO.
isUndef() &&
"Should only have undef virtreg uses left");
1687 allocVirtRegUndef(MO);
1692 if (HasEarlyClobber) {
1693 for (MachineOperand &MO :
reverse(
MI.all_defs())) {
1696 assert(!MO.
getSubReg() &&
"should be already handled in def processing");
1722 (
MI.getOperand(0).getReg() ==
MI.getOperand(1).getReg() ||
1723 MI.getOperand(0).isDead()) &&
1724 MI.getNumOperands() == 2) {
1730void RegAllocFastImpl::handleDebugValue(MachineInstr &
MI) {
1733 assert(
MI.isDebugValue() &&
"not a DBG_VALUE*");
1734 for (
const auto &MO :
MI.debug_operands()) {
1740 if (!shouldAllocateRegister(
Reg))
1744 int SS = StackSlotForVirtReg[
Reg];
1754 LiveRegMap::iterator LRI = findLiveVirtReg(
Reg);
1758 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1760 for (
auto &RegMO : DbgOps)
1761 setPhysReg(
MI, *RegMO, *LRI);
1763 DanglingDbgValues[
Reg].push_back(&
MI);
1768 LiveDbgValueMap[
Reg].append(DbgOps.begin(), DbgOps.end());
1772void RegAllocFastImpl::handleBundle(MachineInstr &
MI) {
1775 while (BundledMI->isBundledWithPred()) {
1776 for (MachineOperand &MO : BundledMI->operands()) {
1784 auto DI = BundleVirtRegsMap.
find(
Reg);
1785 assert(DI != BundleVirtRegsMap.
end() &&
"Unassigned virtual register");
1787 setPhysReg(
MI, MO, DI->second);
1794void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &
MBB) {
1798 PosIndexes.unsetInitialized();
1799 RegUnitStates.assign(
TRI->getNumRegUnits(), regFree);
1800 assert(LiveVirtRegs.empty() &&
"Mapping not cleared from last block?");
1803 setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1813 if (
MI.isDebugValue()) {
1814 handleDebugValue(
MI);
1818 allocateInstruction(
MI);
1822 if (
MI.getOpcode() == TargetOpcode::BUNDLE) {
1830 LLVM_DEBUG(
dbgs() <<
"Loading live registers at begin of block.\n");
1835 for (MachineInstr *
MI : Coalesced)
1837 NumCoalesced += Coalesced.size();
1839 for (
auto &UDBGPair : DanglingDbgValues) {
1840 for (MachineInstr *DbgValue : UDBGPair.second) {
1845 LLVM_DEBUG(
dbgs() <<
"Register did not survive for " << *DbgValue
1850 DanglingDbgValues.clear();
1856 LLVM_DEBUG(
dbgs() <<
"********** FAST REGISTER ALLOCATION **********\n"
1857 <<
"********** Function: " << MF.
getName() <<
'\n');
1865 unsigned NumRegUnits =
TRI->getNumRegUnits();
1867 UsedInInstr.
assign(NumRegUnits, 0);
1872 StackSlotForVirtReg.
resize(NumVirtRegs);
1873 LiveVirtRegs.setUniverse(NumVirtRegs);
1874 MayLiveAcrossBlocks.
clear();
1875 MayLiveAcrossBlocks.
resize(NumVirtRegs);
1878 for (MachineBasicBlock &
MBB : MF)
1879 allocateBasicBlock(
MBB);
1881 if (ClearVirtRegs) {
1887 StackSlotForVirtReg.
clear();
1888 LiveDbgValueMap.
clear();
1895 RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
1896 bool Changed = Impl.runOnMachineFunction(MF);
1906 bool PrintFilterName = Opts.FilterName !=
"all";
1907 bool PrintNoClearVRegs = !Opts.ClearVRegs;
1908 bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
1910 OS <<
"regallocfast";
1911 if (PrintFilterName || PrintNoClearVRegs) {
1913 if (PrintFilterName)
1914 OS <<
"filter=" << Opts.FilterName;
1917 if (PrintNoClearVRegs)
1918 OS <<
"no-clear-vregs";
1926 bool ClearVirtRegs) {
1927 return new RegAllocFast(Ftor, ClearVirtRegs);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
This file defines the DenseMap class.
const HexagonInstrInfo * TII
This file implements an indexed map.
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool isCoalescable(const MachineInstr &MI)
static cl::opt< bool > IgnoreMissingDefs("rafast-ignore-missing-defs", cl::Hidden)
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator)
static bool isTiedToNotUndef(const MachineInstr &MI, const MachineOperand &MO)
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
const T & front() const
Get the first element.
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
void clear()
Removes all bits from the bitvector.
BitVector & set()
Set all bits in the bitvector.
Represents analyses that only rely on functions' control flow.
iterator find(const_arg_type_t< KeyT > Val)
FunctionPass class - This class is used to implement most global optimizations.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Store the specified register of the given register class to the specified stack frame index.
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Load the specified register of the given register class from the specified stack frame index.
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
void resize(typename StorageT::size_type S)
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
unsigned getID() const
getID() - Return the register class ID number.
ArrayRef< MCPhysReg > getRegisters() const
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
iterator_range< liveout_iterator > liveouts() const
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator_range< livein_iterator > liveins() const
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void dump() const
Instructions::iterator instr_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
bool hasDebugOperandForReg(Register Reg) const
Returns whether this debug value has at least one debug operand with the register Reg.
void setDebugValueUndef()
Sets all register debug operands in this debug value instruction to be undef.
const MachineBasicBlock * getParent() const
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineBasicBlock * getMBB() const
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
bool isInternalRead() const
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
MachineOperand * getOneDef(Register Reg) const
Returns the defining operand if there is exactly one operand defining the specified register,...
LLVM_ABI void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
const MachineFunction & getMF() const
void addPhysRegsUsedFromRegMask(const uint32_t *RegMask)
addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI void runOnMachineFunction(const MachineFunction &MF, bool Rev=false)
runOnFunction - Prepare to answer questions about MF.
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
unsigned virtRegIndex() const
Convert a virtual register number to a 0-based index.
constexpr bool isValid() const
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
constexpr unsigned id() const
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void assign(size_type NumElts, ValueParamT Elt)
void push_back(const T &Elt)
typename DenseT::const_iterator const_iterator
typename DenseT::iterator iterator
Represent a constant reference to a string, i.e.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
LLVM_ABI void updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex, Register Reg)
Update a DBG_VALUE whose value has been spilled to FrameIndex.
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI MachineInstr * buildDbgValueForSpill(MachineBasicBlock &BB, MachineBasicBlock::iterator I, const MachineInstr &Orig, int FrameIndex, Register SpillReg)
Clone a DBG_VALUE whose value has been spilled to FrameIndex.
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass