57 #define DEBUG_TYPE "arm-cp-islands"
59 #define ARM_CP_ISLANDS_OPT_NAME \
60 "ARM constant island placement and branch shortening pass"
61 STATISTIC(NumCPEs,
"Number of constpool entries");
62 STATISTIC(NumSplit,
"Number of uncond branches inserted");
63 STATISTIC(NumCBrFixed,
"Number of cond branches fixed");
64 STATISTIC(NumUBrFixed,
"Number of uncond branches fixed");
65 STATISTIC(NumTBs,
"Number of table branches generated");
66 STATISTIC(NumT2CPShrunk,
"Number of Thumb2 constantpool instructions shrunk");
67 STATISTIC(NumT2BrShrunk,
"Number of Thumb2 immediate branches shrunk");
68 STATISTIC(NumCBZ,
"Number of CBZ / CBNZ formed");
69 STATISTIC(NumJTMoved,
"Number of jump table destination blocks moved");
70 STATISTIC(NumJTInserted,
"Number of jump table intermediate blocks inserted");
74 cl::desc(
"Adjust basic block layout to better use TB[BH]"));
78 cl::desc(
"The max number of iteration for converge"));
82 cl::desc(
"Use compressed jump tables in Thumb-1 by synthesizing an "
83 "equivalent to the TBB/TBH instructions"));
99 std::vector<BasicBlockInfo> BBInfo;
104 std::vector<MachineBasicBlock*> WaterList;
110 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
134 bool neg,
bool soimm)
135 :
MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
136 KnownAlignment(
false) {
137 HighWaterMark = CPEMI->getParent();
143 unsigned getMaxDisp()
const {
144 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
150 std::vector<CPUser> CPUsers;
161 : CPEMI(cpemi), CPI(cpi), RefCount(
rc) {}
173 std::vector<std::vector<CPEntry>> CPEntries;
189 unsigned MaxDisp : 31;
193 ImmBranch(
MachineInstr *mi,
unsigned maxdisp,
bool cond,
unsigned ubr)
194 :
MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
199 std::vector<ImmBranch> ImmBranches;
220 bool isPositionIndependentOrROPI;
239 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
240 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
242 CPEntry *findConstPoolEntry(
unsigned CPI,
const MachineInstr *CPEMI);
244 void scanFunctionJumpTables();
245 void initializeFunctionInfo(
const std::vector<MachineInstr*> &CPEMIs);
249 bool decrementCPEReferenceCount(
unsigned CPI,
MachineInstr* CPEMI);
251 int findInRangeCPEntry(CPUser& U,
unsigned UserOffset);
252 bool findAvailableWater(CPUser&U,
unsigned UserOffset,
253 water_iterator &WaterIter,
bool CloserWater);
254 void createNewWater(
unsigned CPUserIndex,
unsigned UserOffset,
256 bool handleConstantPoolUser(
unsigned CPUserIndex,
bool CloserWater);
258 bool removeUnusedCPEntries();
261 bool DoDump =
false);
263 CPUser &U,
unsigned &Growth);
265 bool fixupImmediateBr(ImmBranch &Br);
266 bool fixupConditionalBr(ImmBranch &Br);
267 bool fixupUnconditionalBr(ImmBranch &Br);
268 bool undoLRSpillRestore();
269 bool optimizeThumb2Instructions();
270 bool optimizeThumb2Branches();
271 bool reorderThumb2JumpTables();
273 unsigned &DeadSize,
bool &CanDeleteLEA,
275 bool optimizeThumb2JumpTables();
280 unsigned getUserOffset(CPUser&)
const;
284 bool isOffsetInRange(
unsigned UserOffset,
unsigned TrialOffset,
285 unsigned Disp,
bool NegativeOK,
bool IsSoImm =
false);
286 bool isOffsetInRange(
unsigned UserOffset,
unsigned TrialOffset,
288 return isOffsetInRange(UserOffset, TrialOffset,
289 U.getMaxDisp(), U.NegOk, U.IsSoImm);
300 assert(std::is_sorted(MF->begin(), MF->end(),
303 return BBInfo[LHS.
getNumber()].postOffset() <
304 BBInfo[RHS.getNumber()].postOffset();
306 DEBUG(
dbgs() <<
"Verifying " << CPUsers.size() <<
" CP users.\n");
307 for (
unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
308 CPUser &U = CPUsers[i];
309 unsigned UserOffset = getUserOffset(U);
312 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
325 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
329 for (
unsigned J = 0,
E = BBInfo.size(); J !=
E; ++J) {
345 DEBUG(
dbgs() <<
"***** ARMConstantIslands: "
346 << MCP->getConstants().size() <<
" CP entries, aligned to "
347 << MCP->getConstantPoolAlignment() <<
" bytes *****\n");
349 STI = &
static_cast<const ARMSubtarget &
>(MF->getSubtarget());
350 TII = STI->getInstrInfo();
351 isPositionIndependentOrROPI =
352 STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
355 isThumb = AFI->isThumbFunction();
356 isThumb1 = AFI->isThumb1OnlyFunction();
357 isThumb2 = AFI->isThumb2Function();
363 MF->getRegInfo().invalidateLiveness();
367 MF->RenumberBlocks();
371 bool MadeChange =
false;
373 scanFunctionJumpTables();
374 MadeChange |= reorderThumb2JumpTables();
376 T2JumpTables.clear();
378 MF->RenumberBlocks();
383 std::vector<MachineInstr*> CPEMIs;
385 doInitialConstPlacement(CPEMIs);
387 if (MF->getJumpTableInfo())
388 doInitialJumpTablePlacement(CPEMIs);
391 AFI->initPICLabelUId(CPEMIs.size());
396 initializeFunctionInfo(CPEMIs);
402 if (!T2JumpTables.empty())
403 MF->ensureAlignment(2);
406 MadeChange |= removeUnusedCPEntries();
410 unsigned NoCPIters = 0, NoBRIters = 0;
412 DEBUG(
dbgs() <<
"Beginning CP iteration #" << NoCPIters <<
'\n');
413 bool CPChange =
false;
414 for (
unsigned i = 0, e = CPUsers.size(); i != e; ++i)
418 CPChange |= handleConstantPoolUser(i, NoCPIters >=
CPMaxIteration / 2);
425 NewWaterList.clear();
427 DEBUG(
dbgs() <<
"Beginning BR iteration #" << NoBRIters <<
'\n');
428 bool BRChange =
false;
429 for (
unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
430 BRChange |= fixupImmediateBr(ImmBranches[i]);
431 if (BRChange && ++NoBRIters > 30)
435 if (!CPChange && !BRChange)
441 if (isThumb2 && !STI->prefers32BitThumb())
442 MadeChange |= optimizeThumb2Instructions();
445 if (isThumb && STI->hasV8MBaselineOps())
446 MadeChange |= optimizeThumb2Branches();
449 if (GenerateTBB && !STI->genExecuteOnly())
450 MadeChange |= optimizeThumb2JumpTables();
458 MadeChange |= undoLRSpillRestore();
461 for (
unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
462 for (
unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
463 const CPEntry & CPE = CPEntries[i][j];
464 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
465 AFI->recordCPEClone(i, CPE.CPI);
475 JumpTableEntryIndices.clear();
476 JumpTableUserIndices.clear();
479 T2JumpTables.clear();
487 ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
493 unsigned MaxAlign =
Log2_32(MCP->getConstantPoolAlignment());
510 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
513 for (
unsigned i = 0, e = CPs.
size(); i != e; ++i) {
515 assert(Size >= 4 &&
"Too small constant pool entry");
516 unsigned Align = CPs[i].getAlignment();
520 assert((Size % Align) == 0 &&
"CP Entry not multiple of 4 bytes!");
523 unsigned LogAlign =
Log2_32(Align);
528 CPEMIs.push_back(CPEMI);
532 for (
unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
533 if (InsPoint[a] == InsAt)
537 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
539 DEBUG(
dbgs() <<
"Moved CPI#" << i <<
" to end of function, size = "
540 << Size <<
", align = " << Align <<
'\n');
550 void ARMConstantIslands::doInitialJumpTablePlacement(
551 std::vector<MachineInstr *> &CPEMIs) {
552 unsigned i = CPEntries.size();
553 auto MJTI = MF->getJumpTableInfo();
554 const std::vector<MachineJumpTableEntry> &
JT = MJTI->getJumpTables();
558 auto MI = MBB.getLastNonDebugInstr();
563 switch (
MI->getOpcode()) {
570 JTOpcode = ARM::JUMPTABLE_ADDRS;
573 JTOpcode = ARM::JUMPTABLE_INSTS;
577 JTOpcode = ARM::JUMPTABLE_TBB;
581 JTOpcode = ARM::JUMPTABLE_TBH;
585 unsigned NumOps =
MI->getDesc().getNumOperands();
587 MI->getOperand(NumOps - (
MI->isPredicable() ? 2 : 1));
589 unsigned Size = JT[JTI].MBBs.size() *
sizeof(
uint32_t);
597 CPEMIs.push_back(CPEMI);
598 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
599 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
600 if (!LastCorrectlyNumberedBB)
601 LastCorrectlyNumberedBB = &MBB;
605 if (LastCorrectlyNumberedBB)
606 MF->RenumberBlocks(LastCorrectlyNumberedBB);
627 return TooDifficult || FBB ==
nullptr;
632 ARMConstantIslands::CPEntry
633 *ARMConstantIslands::findConstPoolEntry(
unsigned CPI,
635 std::vector<CPEntry> &CPEs = CPEntries[CPI];
638 for (
unsigned i = 0, e = CPEs.size(); i != e; ++i) {
639 if (CPEs[i].CPEMI == CPEMI)
647 unsigned ARMConstantIslands::getCPELogAlign(
const MachineInstr *CPEMI) {
649 case ARM::CONSTPOOL_ENTRY:
651 case ARM::JUMPTABLE_TBB:
652 return isThumb1 ? 2 : 0;
653 case ARM::JUMPTABLE_TBH:
654 return isThumb1 ? 2 : 1;
655 case ARM::JUMPTABLE_INSTS:
657 case ARM::JUMPTABLE_ADDRS:
663 unsigned CPI = getCombinedIndex(CPEMI);
664 assert(CPI < MCP->getConstants().size() &&
"Invalid constant pool index.");
665 unsigned Align = MCP->getConstants()[CPI].getAlignment();
673 void ARMConstantIslands::scanFunctionJumpTables() {
677 (
I.getOpcode() == ARM::t2BR_JT ||
I.getOpcode() == ARM::tBR_JTr))
678 T2JumpTables.push_back(&
I);
685 void ARMConstantIslands::
686 initializeFunctionInfo(
const std::vector<MachineInstr*> &CPEMIs) {
692 BBInfo.front().KnownBits = MF->getAlignment();
695 adjustBBOffsetsAfter(&MF->front());
702 WaterList.push_back(&MBB);
705 if (
I.isDebugValue())
708 unsigned Opc =
I.getOpcode();
719 T2JumpTables.push_back(&
I);
752 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
753 ImmBranches.push_back(ImmBranch(&
I, MaxOffs, isCond, UOpc));
756 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
757 PushPopMIs.push_back(&
I);
759 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
760 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
761 Opc == ARM::JUMPTABLE_TBH)
765 for (
unsigned op = 0, e =
I.getNumOperands();
op != e; ++
op)
766 if (
I.getOperand(
op).isCPI() ||
I.getOperand(
op).isJTI()) {
774 bool IsSoImm =
false;
782 case ARM::LEApcrelJT:
792 case ARM::t2LEApcrel:
793 case ARM::t2LEApcrelJT:
798 case ARM::tLEApcrelJT:
832 unsigned CPI =
I.getOperand(
op).getIndex();
833 if (
I.getOperand(
op).isJTI()) {
834 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
835 CPI = JumpTableEntryIndices[CPI];
839 unsigned MaxOffs = ((1 <<
Bits)-1) * Scale;
840 CPUsers.push_back(CPUser(&
I, CPEMI, MaxOffs, NegOk, IsSoImm));
843 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
844 assert(CPE &&
"Cannot find a corresponding CPEntry!");
858 unsigned ARMConstantIslands::getOffsetOf(
MachineInstr *
MI)
const {
868 assert(
I != MBB->
end() &&
"Didn't find MI in its own basic block?");
869 Offset +=
TII->getInstSizeInBytes(*
I);
895 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
897 WaterList.insert(IP, NewBB);
910 MF->insert(MBBI, NewBB);
919 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) :
ARM::B;
937 MF->RenumberBlocks(NewBB);
948 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
951 if (WaterBB == OrigBB)
952 WaterList.
insert(std::next(IP), NewBB);
954 WaterList.insert(IP, OrigBB);
955 NewWaterList.insert(OrigBB);
969 adjustBBOffsetsAfter(OrigBB);
977 unsigned ARMConstantIslands::getUserOffset(CPUser &U)
const {
978 unsigned UserOffset = getOffsetOf(U.MI);
979 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
983 UserOffset += (isThumb ? 4 : 8);
987 U.KnownAlignment = (KnownBits >= 2);
992 if (isThumb && U.KnownAlignment)
1004 bool ARMConstantIslands::isOffsetInRange(
unsigned UserOffset,
1005 unsigned TrialOffset,
unsigned MaxDisp,
1006 bool NegativeOK,
bool IsSoImm) {
1007 if (UserOffset <= TrialOffset) {
1009 if (TrialOffset - UserOffset <= MaxDisp)
1012 }
else if (NegativeOK) {
1013 if (UserOffset - TrialOffset <= MaxDisp)
1024 bool ARMConstantIslands::isWaterInRange(
unsigned UserOffset,
1027 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1028 unsigned CPEOffset = BBInfo[Water->
getNumber()].postOffset(CPELogAlign);
1029 unsigned NextBlockOffset, NextBlockAlignment;
1031 if (++NextBlock == MF->end()) {
1032 NextBlockOffset = BBInfo[Water->
getNumber()].postOffset();
1033 NextBlockAlignment = 0;
1035 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1036 NextBlockAlignment = NextBlock->getAlignment();
1038 unsigned Size = U.CPEMI->getOperand(2).getImm();
1039 unsigned CPEEnd = CPEOffset +
Size;
1044 if (CPEEnd > NextBlockOffset) {
1045 Growth = CPEEnd - NextBlockOffset;
1053 if (CPEOffset < UserOffset)
1054 UserOffset += Growth +
UnknownPadding(MF->getAlignment(), CPELogAlign);
1059 return isOffsetInRange(UserOffset, CPEOffset, U);
1064 bool ARMConstantIslands::isCPEntryInRange(
MachineInstr *MI,
unsigned UserOffset,
1066 bool NegOk,
bool DoDump) {
1067 unsigned CPEOffset = getOffsetOf(CPEMI);
1074 <<
" max delta=" << MaxDisp
1075 <<
format(
" insn address=%#x", UserOffset)
1076 <<
" in BB#" << Block <<
": "
1078 <<
format(
"CPE address=%#x offset=%+d: ", CPEOffset,
1079 int(CPEOffset-UserOffset));
1083 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1105 for(
unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1108 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1109 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1110 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1115 if (i > BBNum + 2 &&
1116 BBInfo[i].Offset == Offset &&
1117 BBInfo[i].KnownBits == KnownBits)
1120 BBInfo[i].Offset =
Offset;
1121 BBInfo[i].KnownBits = KnownBits;
1130 bool ARMConstantIslands::decrementCPEReferenceCount(
unsigned CPI,
1133 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1134 assert(CPE &&
"Unexpected!");
1135 if (--CPE->RefCount == 0) {
1136 removeDeadCPEMI(CPEMI);
1137 CPE->CPEMI =
nullptr;
1144 unsigned ARMConstantIslands::getCombinedIndex(
const MachineInstr *CPEMI) {
1157 int ARMConstantIslands::findInRangeCPEntry(CPUser& U,
unsigned UserOffset)
1163 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1170 unsigned CPI = getCombinedIndex(CPEMI);
1171 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1172 for (
unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1174 if (CPEs[i].CPEMI == CPEMI)
1177 if (CPEs[i].CPEMI ==
nullptr)
1179 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1181 DEBUG(
dbgs() <<
"Replacing CPE#" << CPI <<
" with CPE#"
1182 << CPEs[i].CPI <<
"\n");
1184 U.CPEMI = CPEs[i].CPEMI;
1195 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1206 return ((1<<10)-1)*2;
1208 return ((1<<23)-1)*2;
1213 return ((1<<23)-1)*4;
1224 bool ARMConstantIslands::findAvailableWater(CPUser &U,
unsigned UserOffset,
1225 water_iterator &WaterIter,
1227 if (WaterList.empty())
1230 unsigned BestGrowth = ~0u;
1242 unsigned MinNoSplitDisp =
1243 BBInfo[UserBB->
getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1244 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1246 for (water_iterator IP = std::prev(WaterList.end()),
B = WaterList.begin();;
1260 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1261 (WaterBB->
getNumber() < U.HighWaterMark->getNumber() ||
1262 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1263 Growth < BestGrowth) {
1265 BestGrowth = Growth;
1268 <<
" Growth=" << Growth <<
'\n');
1270 if (CloserWater && WaterBB == U.MI->getParent())
1274 if (!CloserWater && BestGrowth == 0)
1280 return BestGrowth != ~0u;
1290 void ARMConstantIslands::createNewWater(
unsigned CPUserIndex,
1291 unsigned UserOffset,
1293 CPUser &U = CPUsers[CPUserIndex];
1296 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1306 unsigned Delta = isThumb1 ? 2 : 4;
1308 unsigned CPEOffset = UserBBI.
postOffset(CPELogAlign) + Delta;
1310 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1312 <<
format(
", expected CPE offset %#x\n", CPEOffset));
1319 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) :
ARM::
B;
1327 ImmBranches.push_back(ImmBranch(&UserMBB->
back(),
1328 MaxDisp,
false, UncondBr));
1330 adjustBBOffsetsAfter(UserMBB);
1350 unsigned LogAlign = MF->getAlignment();
1351 assert(LogAlign >= CPELogAlign &&
"Over-aligned constant pool entry");
1354 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1361 BaseInsertOffset -= 4;
1364 <<
" la=" << LogAlign
1365 <<
" kb=" << KnownBits
1366 <<
" up=" << UPad <<
'\n');
1372 if (BaseInsertOffset + 8 >= UserBBI.
postOffset()) {
1378 UserOffset +
TII->getInstSizeInBytes(*UserMI) + 1);
1379 DEBUG(
dbgs() <<
format(
"Move inside block: %#x\n", BaseInsertOffset));
1381 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1385 unsigned CPUIndex = CPUserIndex+1;
1386 unsigned NumCPUsers = CPUsers.size();
1388 for (
unsigned Offset = UserOffset +
TII->getInstSizeInBytes(*UserMI);
1389 Offset < BaseInsertOffset;
1390 Offset +=
TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1391 assert(MI != UserMBB->
end() &&
"Fell off end of block");
1392 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
1393 CPUser &U = CPUsers[CPUIndex];
1394 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1396 BaseInsertOffset -= 1u << LogAlign;
1397 EndInsertOffset -= 1u << LogAlign;
1403 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1408 if (MI->getOpcode() == ARM::t2IT)
1416 unsigned PredReg = 0;
1423 DEBUG(
unsigned PredReg;
1426 NewMBB = splitBlockBeforeInstr(&*MI);
1433 bool ARMConstantIslands::handleConstantPoolUser(
unsigned CPUserIndex,
1435 CPUser &U = CPUsers[CPUserIndex];
1438 unsigned CPI = getCombinedIndex(CPEMI);
1441 unsigned UserOffset = getUserOffset(U);
1445 int result = findInRangeCPEntry(U, UserOffset);
1446 if (result==1)
return false;
1447 else if (result==2)
return true;
1451 unsigned ID = AFI->createPICLabelUId();
1457 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
1458 DEBUG(
dbgs() <<
"Found water in range\n");
1464 if (NewWaterList.erase(WaterBB))
1465 NewWaterList.
insert(NewIsland);
1472 createNewWater(CPUserIndex, UserOffset, NewMBB);
1480 IP =
find(WaterList, WaterBB);
1481 if (IP != WaterList.end())
1482 NewWaterList.erase(WaterBB);
1485 NewWaterList.insert(NewIsland);
1492 if (IP != WaterList.end())
1493 WaterList.erase(IP);
1499 updateForInsertedWaterBlock(NewIsland);
1503 U.HighWaterMark = NewIsland;
1508 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1512 decrementCPEReferenceCount(CPI, CPEMI);
1519 adjustBBOffsetsAfter(&*--NewIsland->
getIterator());
1528 DEBUG(
dbgs() <<
" Moved CPE to #" << ID <<
" CPI=" << CPI
1536 void ARMConstantIslands::removeDeadCPEMI(
MachineInstr *CPEMI) {
1542 if (CPEBB->
empty()) {
1551 adjustBBOffsetsAfter(CPEBB);
1561 bool ARMConstantIslands::removeUnusedCPEntries() {
1562 unsigned MadeChange =
false;
1563 for (
unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1564 std::vector<CPEntry> &CPEs = CPEntries[i];
1565 for (
unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1566 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1567 removeDeadCPEMI(CPEs[j].CPEMI);
1568 CPEs[j].CPEMI =
nullptr;
1580 unsigned PCAdj = isThumb ? 4 : 8;
1581 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1582 unsigned DestOffset = BBInfo[DestBB->
getNumber()].Offset;
1586 <<
" max delta=" << MaxDisp
1587 <<
" from " << getOffsetOf(MI) <<
" to " << DestOffset
1588 <<
" offset " << int(DestOffset-BrOffset) <<
"\t" << *
MI);
1590 if (BrOffset <= DestOffset) {
1592 if (DestOffset-BrOffset <= MaxDisp)
1595 if (BrOffset-DestOffset <= MaxDisp)
1603 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1608 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1612 return fixupUnconditionalBr(Br);
1613 return fixupConditionalBr(Br);
1621 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1628 Br.MaxDisp = (1 << 21) * 2;
1631 adjustBBOffsetsAfter(MBB);
1635 DEBUG(
dbgs() <<
" Changed B to long jump " << *MI);
1644 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1678 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1679 DEBUG(
dbgs() <<
" Invert Bcc condition and swap its destination with "
1690 splitBlockBeforeInstr(MI);
1693 int delta =
TII->getInstSizeInBytes(MBB->
back());
1701 <<
" also invert condition and change dest. to BB#"
1708 Br.MI = &MBB->
back();
1718 ImmBranches.push_back(ImmBranch(&MBB->
back(), MaxDisp,
false, Br.UncondBr));
1723 adjustBBOffsetsAfter(MBB);
1730 bool ARMConstantIslands::undoLRSpillRestore() {
1731 bool MadeChange =
false;
1732 for (
unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1744 }
else if (MI->
getOpcode() == ARM::tPUSH &&
1755 bool ARMConstantIslands::optimizeThumb2Instructions() {
1756 bool MadeChange =
false;
1759 for (
unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1760 CPUser &U = CPUsers[i];
1761 unsigned Opcode = U.MI->getOpcode();
1762 unsigned NewOpc = 0;
1767 case ARM::t2LEApcrel:
1769 NewOpc = ARM::tLEApcrel;
1776 NewOpc = ARM::tLDRpci;
1786 unsigned UserOffset = getUserOffset(U);
1787 unsigned MaxOffs = ((1 <<
Bits) - 1) * Scale;
1790 if (!U.KnownAlignment)
1794 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs,
false,
true)) {
1796 U.MI->setDesc(
TII->get(NewOpc));
1799 adjustBBOffsetsAfter(MBB);
1808 bool ARMConstantIslands::optimizeThumb2Branches() {
1809 bool MadeChange =
false;
1816 for (
unsigned i = ImmBranches.size(); i != 0; --i) {
1817 ImmBranch &Br = ImmBranches[i-1];
1818 unsigned Opcode = Br.MI->getOpcode();
1819 unsigned NewOpc = 0;
1836 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1838 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1839 DEBUG(
dbgs() <<
"Shrink branch: " << *Br.MI);
1840 Br.MI->setDesc(
TII->get(NewOpc));
1843 adjustBBOffsetsAfter(MBB);
1849 Opcode = Br.MI->getOpcode();
1850 if (Opcode != ARM::tBcc)
1855 if (!Br.MI->killsRegister(ARM::CPSR))
1859 unsigned PredReg = 0;
1864 NewOpc = ARM::tCBNZ;
1870 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1871 unsigned DestOffset = BBInfo[DestBB->
getNumber()].Offset;
1872 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1874 if (CmpMI != Br.MI->getParent()->begin()) {
1876 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1877 unsigned Reg = CmpMI->getOperand(0).getReg();
1880 CmpMI->getOperand(1).getImm() == 0 &&
1883 DEBUG(
dbgs() <<
"Fold: " << *CmpMI <<
" and: " << *Br.MI);
1885 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(),
TII->get(NewOpc))
1886 .addReg(Reg).
addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1887 CmpMI->eraseFromParent();
1888 Br.MI->eraseFromParent();
1891 adjustBBOffsetsAfter(MBB);
1924 bool ARMConstantIslands::preserveBaseRegister(
MachineInstr *JumpMI,
1928 bool &BaseRegKill) {
1951 CanDeleteLEA =
true;
1952 BaseRegKill =
false;
1955 for (++
I; &*
I != JumpMI; ++
I) {
1961 for (
unsigned K = 0,
E =
I->getNumOperands(); K !=
E; ++K) {
1968 BaseRegKill = BaseRegKill || MO.
isKill();
1969 CanDeleteLEA =
false;
1979 for (++
I; &*
I != JumpMI; ++
I) {
1980 for (
unsigned K = 0,
E =
I->getNumOperands(); K !=
E; ++K) {
1987 RemovableAdd =
nullptr;
1993 DeadSize += isThumb2 ? 4 : 2;
1994 }
else if (BaseReg == EntryReg) {
2015 return MBB != MF->
end() && MBB->begin() != MBB->end() &&
2016 &*MBB->begin() == CPEMI;
2021 unsigned &DeadSize) {
2030 for (++I; &*I != JumpMI; ++
I) {
2031 if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2040 for (++J; &*J != JumpMI; ++J) {
2041 for (
unsigned K = 0,
E = J->getNumOperands(); K !=
E; ++K) {
2052 DEBUG(
dbgs() <<
"Removing Dead Add: " << *RemovableAdd);
2061 for (
auto I = From;
I != To; ++
I)
2062 if (
I->modifiesRegister(Reg, TRI))
2069 bool ARMConstantIslands::optimizeThumb2JumpTables() {
2070 bool MadeChange =
false;
2075 if (!MJTI)
return false;
2077 const std::vector<MachineJumpTableEntry> &JT = MJTI->
getJumpTables();
2078 for (
unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2082 unsigned JTOpIdx = NumOps - (MI->
isPredicable() ? 2 : 1);
2084 unsigned JTI = JTOP.getIndex();
2088 bool HalfWordOk =
true;
2089 unsigned JTOffset = getOffsetOf(MI) + 4;
2090 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2091 for (
unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2093 unsigned DstOffset = BBInfo[MBB->
getNumber()].Offset;
2096 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
2098 unsigned TBHLimit = ((1<<16)-1)*2;
2099 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
2101 if (!ByteOk && !HalfWordOk)
2105 if (!ByteOk && !HalfWordOk)
2108 CPUser &
User = CPUsers[JumpTableUserIndices[JTI]];
2113 unsigned DeadSize = 0;
2114 bool CanDeleteLEA =
false;
2115 bool BaseRegKill =
false;
2117 unsigned IdxReg = ~0U;
2118 bool IdxRegKill =
true;
2123 bool PreservedBaseReg =
2124 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2132 unsigned BaseReg = User.MI->getOperand(0).getReg();
2134 if (User.MI->getIterator() == User.MI->getParent()->begin())
2137 if (Shift->
getOpcode() != ARM::tLSLri ||
2159 auto *TRI = STI->getRegisterInfo();
2169 if (isPositionIndependentOrROPI) {
2192 CanDeleteLEA =
true;
2200 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2202 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2207 .addReg(User.MI->getOperand(0).getReg(),
2210 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2214 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2225 User.MI->eraseFromParent();
2226 DeadSize += isThumb2 ? 4 : 2;
2233 User.IsSoImm =
false;
2234 User.KnownAlignment =
false;
2238 int CPEntryIdx = JumpTableEntryIndices[JTI];
2239 auto &CPEs = CPEntries[CPEntryIdx];
2241 find_if(CPEs, [&](CPEntry &
E) {
return E.CPEMI == User.CPEMI; });
2243 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4,
false,
false));
2247 unsigned NewSize =
TII->getInstSizeInBytes(*NewJTMI);
2248 unsigned OrigSize =
TII->getInstSizeInBytes(*MI);
2251 int Delta = OrigSize - NewSize + DeadSize;
2253 adjustBBOffsetsAfter(MBB);
2264 bool ARMConstantIslands::reorderThumb2JumpTables() {
2265 bool MadeChange =
false;
2268 if (!MJTI)
return false;
2270 const std::vector<MachineJumpTableEntry> &JT = MJTI->
getJumpTables();
2271 for (
unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2275 unsigned JTOpIdx = NumOps - (MI->
isPredicable() ? 2 : 1);
2277 unsigned JTI = JTOP.getIndex();
2284 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2285 for (
unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2289 if (DTNumber < JTNumber) {
2293 adjustJTTargetBlockForward(MBB, MI->
getParent());
2322 if (!B && Cond.
empty() && BB != &MF->
front() &&
2325 OldPrior->updateTerminator();
2328 MF->RenumberBlocks();
2337 MF->insert(MBBI, NewBB);
2352 MF->RenumberBlocks(NewBB);
2365 return new ARMConstantIslands();
unsigned succ_size() const
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
A parsed version of the target data layout string in and methods for querying it. ...
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
STATISTIC(NumFunctions,"Total number of functions")
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
MachineBasicBlock * getMBB() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
Describe properties that are true of each instruction in the target description file.
const MachineInstrBuilder & add(const MachineOperand &MO) const
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
bool isPredicable(QueryType Type=AllInBundle) const
Return true if this instruction has a predicate operand that controls execution.
unsigned Offset
Offset - Distance from the beginning of the function to the beginning of this basic block...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
void moveAfter(MachineBasicBlock *NewBefore)
void computeBlockSize(MachineFunction *MF, MachineBasicBlock *MBB, BasicBlockInfo &BBI)
static bool isThumb(const MCSubtargetInfo &STI)
void setAlignment(unsigned Align)
Set alignment of the basic block.
bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTable - If Old is a target of the jump tables, update the jump table to branch to New...
BasicBlockInfo - Information about the offset and size of a single basic block.
bool isLRSpilledForFarJump() const
static bool CompareMBBNumbers(const MachineBasicBlock *LHS, const MachineBasicBlock *RHS)
CompareMBBNumbers - Little predicate function to sort the WaterList by MBB ID.
static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg, unsigned BaseReg)
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
const std::vector< MachineJumpTableEntry > & getJumpTables() const
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Reg
All possible values of the reg field in the ModR/M byte.
#define ARM_CP_ISLANDS_OPT_NAME
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
LLVM_NODISCARD bool empty() const
unsigned getNumOperands() const
Access to explicit operands of the instruction.
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
FunctionPass * createARMConstantIslandPass()
createARMConstantIslandPass - returns an instance of the constpool island pass.
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
unsigned getKillRegState(bool B)
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
Function Alias Analysis false
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
initializer< Ty > init(const Ty &Val)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
const MachineOperand & getOperand(unsigned i) const
static bool registerDefinedBetween(unsigned Reg, MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, const TargetRegisterInfo *TRI)
static cl::opt< bool > SynthesizeThumb1TBB("arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true), cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an ""equivalent to the TBB/TBH instructions"))
void setMBB(MachineBasicBlock *MBB)
unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
static bool BBIsJumpedOver(MachineBasicBlock *MBB)
BBIsJumpedOver - Return true of the specified basic block's only predecessor unconditionally branches...
void setImm(int64_t immVal)
FunctionPass class - This class is used to implement most global optimizations.
self_iterator getIterator()
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
succ_iterator succ_begin()
ARMCC::CondCodes getInstrPredicate(const MachineInstr &MI, unsigned &PredReg)
getInstrPredicate - If instruction is predicated, returns its predicate condition, otherwise returns AL.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
pred_iterator pred_begin()
static wasm::ValType getType(const TargetRegisterClass *RC)
void setIsKill(bool Val=true)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Iterator for intrusive lists based on ilist_node.
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void setDesc(const MCInstrDesc &tid)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one...
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
ARMCC::CondCodes getITInstrPredicate(const MachineInstr &MI, unsigned &PredReg)
getITInstrPredicate - Valid only in Thumb2 mode.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits)
UnknownPadding - Return the worst case padding that could result from unknown offset bits...
const MachineInstrBuilder & addJumpTableIndex(unsigned Idx, unsigned char TargetFlags=0) const
MachineOperand class - Representation of each machine instruction operand.
void updateTerminator()
Update the terminator instructions in block to account for changes to the layout. ...
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
APFloat neg(APFloat X)
Returns the negated value of the argument.
static cl::opt< bool > AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true), cl::desc("Adjust basic block layout to better use TB[BH]"))
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
MachineFunctionProperties & set(Property P)
static bool isARMLowRegister(unsigned Reg)
isARMLowRegister - Returns true if the register is a low register (r0-r7).
Representation of each machine instruction.
static CondCodes getOppositeCondition(CondCodes CC)
uint8_t Unalign
Unalign - When non-zero, the block contains instructions (inline asm) of unknown size.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
static bool BBHasFallthrough(MachineBasicBlock *MBB)
BBHasFallthrough - Return true if the specified basic block can fallthrough into the block immediatel...
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
void setReg(unsigned Reg)
Change the register this operand corresponds to.
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned char TargetFlags=0) const
void push_back(MachineInstr *MI)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint8_t KnownBits
KnownBits - The number of low bits in Offset that are known to be exact.
unsigned internalKnownBits() const
Compute the number of known offset bits internally to this block.
static unsigned getUnconditionalBrDisp(int Opc)
getUnconditionalBrDisp - Returns the maximum displacement that can fit in the specific unconditional ...
unsigned getReg() const
getReg - Returns the register number.
static cl::opt< unsigned > CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30), cl::desc("The max number of iteration for converge"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI)
Returns whether CPEMI is the first instruction in the block immediately following JTMI (assumed to be...
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
StringRef - Represent a constant reference to a string, i.e.
static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI, MachineInstr *JumpMI, unsigned &DeadSize)
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
unsigned pred_size() const
uint8_t PostAlign
PostAlign - When non-zero, the block terminator contains a .align directive, so the end of the block ...
Properties which a MachineFunction may have at a given point in time.
unsigned postOffset(unsigned LogAlign=0) const
Compute the offset immediately following this block.
std::vector< BasicBlockInfo > computeAllBlockSizes(MachineFunction *MF)
unsigned getAlignment() const
Return alignment of the basic block.