#include "ARM.h"
#include "ARMBaseInstrInfo.h"
#include "ARMBasicBlockInfo.h"
#include "ARMMachineFunctionInfo.h"
#include "ARMSubtarget.h"
#include "MCTargetDesc/ARMBaseInfo.h"
#include "MVETailPredUtils.h"
#include "Thumb2InstrInfo.h"
#include "Utils/ARMBaseInfo.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/Pass.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/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "arm-cp-islands"
#define ARM_CP_ISLANDS_OPT_NAME \
"ARM constant island placement and branch shortening pass"
STATISTIC(NumCPEs, "Number of constpool entries");
STATISTIC(NumSplit, "Number of uncond branches inserted");
STATISTIC(NumCBrFixed, "Number of cond branches fixed");
STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
STATISTIC(NumTBs, "Number of table branches generated");
STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
STATISTIC(NumLEInserted, "Number of LE backwards branches inserted");
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]"));
static cl::opt<unsigned>
CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
cl::desc("The max number of iteration for converge"));
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"));
namespace {
class ARMConstantIslands : public MachineFunctionPass {
std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
std::vector<MachineBasicBlock*> WaterList;
SmallSet<MachineBasicBlock*, 4> NewWaterList;
using water_iterator = std::vector<MachineBasicBlock *>::iterator;
struct CPUser {
MachineInstr *MI;
MachineInstr *CPEMI;
MachineBasicBlock *HighWaterMark;
unsigned MaxDisp;
bool NegOk;
bool IsSoImm;
bool KnownAlignment = false;
CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
bool neg, bool soimm)
: MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
HighWaterMark = CPEMI->getParent();
}
unsigned getMaxDisp() const {
return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
}
};
std::vector<CPUser> CPUsers;
struct CPEntry {
MachineInstr *CPEMI;
unsigned CPI;
unsigned RefCount;
CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
: CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
};
std::vector<std::vector<CPEntry>> CPEntries;
DenseMap<int, int> JumpTableEntryIndices;
DenseMap<int, int> JumpTableUserIndices;
DenseMap<const MachineBasicBlock *, int> BlockJumpTableRefCount;
struct ImmBranch {
MachineInstr *MI;
unsigned MaxDisp : 31;
bool isCond : 1;
unsigned UncondBr;
ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
: MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
};
std::vector<ImmBranch> ImmBranches;
SmallVector<MachineInstr*, 4> PushPopMIs;
SmallVector<MachineInstr*, 4> T2JumpTables;
MachineFunction *MF;
MachineConstantPool *MCP;
const ARMBaseInstrInfo *TII;
const ARMSubtarget *STI;
ARMFunctionInfo *AFI;
MachineDominatorTree *DT = nullptr;
bool isThumb;
bool isThumb1;
bool isThumb2;
bool isPositionIndependentOrROPI;
public:
static char ID;
ARMConstantIslands() : MachineFunctionPass(ID) {}
bool runOnMachineFunction(MachineFunction &MF) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
StringRef getPassName() const override {
return ARM_CP_ISLANDS_OPT_NAME;
}
private:
void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
bool BBHasFallthrough(MachineBasicBlock *MBB);
CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Align getCPEAlign(const MachineInstr *CPEMI);
void scanFunctionJumpTables();
void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
unsigned getCombinedIndex(const MachineInstr *CPEMI);
int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
bool findAvailableWater(CPUser&U, unsigned UserOffset,
water_iterator &WaterIter, bool CloserWater);
void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
MachineBasicBlock *&NewMBB);
bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
void removeDeadCPEMI(MachineInstr *CPEMI);
bool removeUnusedCPEntries();
bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
MachineInstr *CPEMI, unsigned Disp, bool NegOk,
bool DoDump = false);
bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
CPUser &U, unsigned &Growth);
bool fixupImmediateBr(ImmBranch &Br);
bool fixupConditionalBr(ImmBranch &Br);
bool fixupUnconditionalBr(ImmBranch &Br);
bool optimizeThumb2Instructions();
bool optimizeThumb2Branches();
bool reorderThumb2JumpTables();
bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
unsigned &DeadSize, bool &CanDeleteLEA,
bool &BaseRegKill);
bool optimizeThumb2JumpTables();
void fixupBTI(unsigned JTI, MachineBasicBlock &OldBB,
MachineBasicBlock &NewBB);
MachineBasicBlock *adjustJTTargetBlockForward(unsigned JTI,
MachineBasicBlock *BB,
MachineBasicBlock *JTBB);
unsigned getUserOffset(CPUser&) const;
void dumpBBs();
void verify();
bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
unsigned Disp, bool NegativeOK, bool IsSoImm = false);
bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
const CPUser &U) {
return isOffsetInRange(UserOffset, TrialOffset,
U.getMaxDisp(), U.NegOk, U.IsSoImm);
}
};
}
char ARMConstantIslands::ID = 0;
void ARMConstantIslands::verify() {
#ifndef NDEBUG
BBInfoVector &BBInfo = BBUtils->getBBInfo();
assert(is_sorted(*MF, [&BBInfo](const MachineBasicBlock &LHS,
const MachineBasicBlock &RHS) {
return BBInfo[LHS.getNumber()].postOffset() <
BBInfo[RHS.getNumber()].postOffset();
}));
LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
for (CPUser &U : CPUsers) {
unsigned UserOffset = getUserOffset(U);
if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
true)) {
LLVM_DEBUG(dbgs() << "OK\n");
continue;
}
LLVM_DEBUG(dbgs() << "Out of range.\n");
dumpBBs();
LLVM_DEBUG(MF->dump());
llvm_unreachable("Constant pool entry out of range!");
}
#endif
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
LLVM_DEBUG({
BBInfoVector &BBInfo = BBUtils->getBBInfo();
for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
const BasicBlockInfo &BBI = BBInfo[J];
dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
<< " kb=" << unsigned(BBI.KnownBits)
<< " ua=" << unsigned(BBI.Unalign) << " pa=" << Log2(BBI.PostAlign)
<< format(" size=%#x\n", BBInfo[J].Size);
}
});
}
#endif
static bool AlignBlocks(MachineFunction *MF, const ARMSubtarget *STI) {
if (MF->getTarget().getOptLevel() != CodeGenOpt::Aggressive ||
MF->getFunction().hasOptSize())
return false;
auto *TLI = STI->getTargetLowering();
const Align Alignment = TLI->getPrefLoopAlignment();
if (Alignment < 4)
return false;
bool Changed = false;
bool PrevCanFallthough = true;
for (auto &MBB : *MF) {
if (!PrevCanFallthough) {
Changed = true;
MBB.setAlignment(Alignment);
}
PrevCanFallthough = MBB.canFallThrough();
if (STI->hasLOB()) {
for (const auto &MI : reverse(MBB.terminators())) {
if (MI.getOpcode() == ARM::t2B &&
MI.getOperand(0).getMBB() == MBB.getNextNode())
continue;
if (isLoopStart(MI) || MI.getOpcode() == ARM::t2LoopEnd ||
MI.getOpcode() == ARM::t2LoopEndDec) {
PrevCanFallthough = true;
break;
}
break;
}
}
}
return Changed;
}
bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
MF = &mf;
MCP = mf.getConstantPool();
BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(mf));
LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
<< MCP->getConstants().size() << " CP entries, aligned to "
<< MCP->getConstantPoolAlign().value() << " bytes *****\n");
STI = &MF->getSubtarget<ARMSubtarget>();
TII = STI->getInstrInfo();
isPositionIndependentOrROPI =
STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
AFI = MF->getInfo<ARMFunctionInfo>();
DT = &getAnalysis<MachineDominatorTree>();
isThumb = AFI->isThumbFunction();
isThumb1 = AFI->isThumb1OnlyFunction();
isThumb2 = AFI->isThumb2Function();
bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
if (STI->hardenSlsRetBr())
GenerateTBB = false;
MF->RenumberBlocks();
bool MadeChange = false;
if (GenerateTBB && AdjustJumpTableBlocks) {
scanFunctionJumpTables();
MadeChange |= reorderThumb2JumpTables();
T2JumpTables.clear();
MF->RenumberBlocks();
}
MadeChange |= AlignBlocks(MF, STI);
std::vector<MachineInstr*> CPEMIs;
if (!MCP->isEmpty())
doInitialConstPlacement(CPEMIs);
if (MF->getJumpTableInfo())
doInitialJumpTablePlacement(CPEMIs);
AFI->initPICLabelUId(CPEMIs.size());
initializeFunctionInfo(CPEMIs);
CPEMIs.clear();
LLVM_DEBUG(dumpBBs());
if (!T2JumpTables.empty())
MF->ensureAlignment(Align(4));
MadeChange |= removeUnusedCPEntries();
unsigned NoCPIters = 0, NoBRIters = 0;
while (true) {
LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
bool CPChange = false;
for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
if (CPChange && ++NoCPIters > CPMaxIteration)
report_fatal_error("Constant Island pass failed to converge!");
LLVM_DEBUG(dumpBBs());
NewWaterList.clear();
LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
bool BRChange = false;
for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
BRChange |= fixupImmediateBr(ImmBranches[i]);
if (BRChange && ++NoBRIters > 30)
report_fatal_error("Branch Fix Up pass failed to converge!");
LLVM_DEBUG(dumpBBs());
if (!CPChange && !BRChange)
break;
MadeChange = true;
}
if (isThumb2 && !STI->prefers32BitThumb())
MadeChange |= optimizeThumb2Instructions();
if (isThumb && STI->hasV8MBaselineOps())
MadeChange |= optimizeThumb2Branches();
if (GenerateTBB && !STI->genExecuteOnly())
MadeChange |= optimizeThumb2JumpTables();
verify();
for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
const CPEntry & CPE = CPEntries[i][j];
if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
AFI->recordCPEClone(i, CPE.CPI);
}
}
LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
BBUtils->clear();
WaterList.clear();
CPUsers.clear();
CPEntries.clear();
JumpTableEntryIndices.clear();
JumpTableUserIndices.clear();
BlockJumpTableRefCount.clear();
ImmBranches.clear();
PushPopMIs.clear();
T2JumpTables.clear();
return MadeChange;
}
void
ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
MF->push_back(BB);
const Align MaxAlign = MCP->getConstantPoolAlign();
const unsigned MaxLogAlign = Log2(MaxAlign);
BB->setAlignment(MaxAlign);
Align FuncAlign = MaxAlign;
if (MaxAlign == 2)
FuncAlign = Align(4);
MF->ensureAlignment(FuncAlign);
SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1,
BB->end());
const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
const DataLayout &TD = MF->getDataLayout();
for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
unsigned Size = CPs[i].getSizeInBytes(TD);
Align Alignment = CPs[i].getAlign();
assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");
unsigned LogAlign = Log2(Alignment);
MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
MachineInstr *CPEMI =
BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
.addImm(i).addConstantPoolIndex(i).addImm(Size);
CPEMIs.push_back(CPEMI);
for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a)
if (InsPoint[a] == InsAt)
InsPoint[a] = CPEMI;
CPEntries.emplace_back(1, CPEntry(CPEMI, i));
++NumCPEs;
LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
<< Size << ", align = " << Alignment.value() << '\n');
}
LLVM_DEBUG(BB->dump());
}
void ARMConstantIslands::doInitialJumpTablePlacement(
std::vector<MachineInstr *> &CPEMIs) {
unsigned i = CPEntries.size();
auto MJTI = MF->getJumpTableInfo();
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
for (MachineBasicBlock &MBB : *MF) {
auto MI = MBB.getLastNonDebugInstr();
while (MI != MBB.end() &&
(isSpeculationBarrierEndBBOpcode(MI->getOpcode()) ||
MI->isDebugInstr()))
--MI;
if (MI == MBB.end())
continue;
unsigned JTOpcode;
switch (MI->getOpcode()) {
default:
continue;
case ARM::BR_JTadd:
case ARM::BR_JTr:
case ARM::tBR_JTr:
case ARM::BR_JTm_i12:
case ARM::BR_JTm_rs:
JTOpcode = ARM::JUMPTABLE_ADDRS;
break;
case ARM::t2BR_JT:
JTOpcode = ARM::JUMPTABLE_INSTS;
break;
case ARM::tTBB_JT:
case ARM::t2TBB_JT:
JTOpcode = ARM::JUMPTABLE_TBB;
break;
case ARM::tTBH_JT:
case ARM::t2TBH_JT:
JTOpcode = ARM::JUMPTABLE_TBH;
break;
}
unsigned NumOps = MI->getDesc().getNumOperands();
MachineOperand JTOp =
MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
unsigned JTI = JTOp.getIndex();
unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
DebugLoc(), TII->get(JTOpcode))
.addImm(i++)
.addJumpTableIndex(JTI)
.addImm(Size);
CPEMIs.push_back(CPEMI);
CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
if (!LastCorrectlyNumberedBB)
LastCorrectlyNumberedBB = &MBB;
}
if (LastCorrectlyNumberedBB)
MF->RenumberBlocks(LastCorrectlyNumberedBB);
}
bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
MachineFunction::iterator MBBI = MBB->getIterator();
if (std::next(MBBI) == MBB->getParent()->end())
return false;
MachineBasicBlock *NextBB = &*std::next(MBBI);
if (!MBB->isSuccessor(NextBB))
return false;
MachineBasicBlock *TBB, *FBB;
SmallVector<MachineOperand, 4> Cond;
bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
return TooDifficult || FBB == nullptr;
}
ARMConstantIslands::CPEntry *
ARMConstantIslands::findConstPoolEntry(unsigned CPI,
const MachineInstr *CPEMI) {
std::vector<CPEntry> &CPEs = CPEntries[CPI];
for (CPEntry &CPE : CPEs)
if (CPE.CPEMI == CPEMI)
return &CPE;
return nullptr;
}
Align ARMConstantIslands::getCPEAlign(const MachineInstr *CPEMI) {
switch (CPEMI->getOpcode()) {
case ARM::CONSTPOOL_ENTRY:
break;
case ARM::JUMPTABLE_TBB:
return isThumb1 ? Align(4) : Align(1);
case ARM::JUMPTABLE_TBH:
return isThumb1 ? Align(4) : Align(2);
case ARM::JUMPTABLE_INSTS:
return Align(2);
case ARM::JUMPTABLE_ADDRS:
return Align(4);
default:
llvm_unreachable("unknown constpool entry kind");
}
unsigned CPI = getCombinedIndex(CPEMI);
assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
return MCP->getConstants()[CPI].getAlign();
}
static bool isAlwaysIndirectTarget(const MachineBasicBlock &MBB) {
return MBB.isEHPad() || MBB.hasAddressTaken() ||
&MBB == &MBB.getParent()->front();
}
void ARMConstantIslands::scanFunctionJumpTables() {
for (MachineBasicBlock &MBB : *MF) {
for (MachineInstr &I : MBB)
if (I.isBranch() &&
(I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
T2JumpTables.push_back(&I);
}
if (!MF->getInfo<ARMFunctionInfo>()->branchTargetEnforcement())
return;
if (const MachineJumpTableInfo *JTI = MF->getJumpTableInfo())
for (const MachineJumpTableEntry &JTE : JTI->getJumpTables())
for (const MachineBasicBlock *MBB : JTE.MBBs) {
if (isAlwaysIndirectTarget(*MBB))
BlockJumpTableRefCount[MBB] = std::numeric_limits<int>::max();
else
++BlockJumpTableRefCount[MBB];
}
}
void ARMConstantIslands::
initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
BBUtils->computeAllBlockSizes();
BBInfoVector &BBInfo = BBUtils->getBBInfo();
BBInfo.front().KnownBits = Log2(MF->getAlignment());
BBUtils->adjustBBOffsetsAfter(&MF->front());
for (MachineBasicBlock &MBB : *MF) {
if (!BBHasFallthrough(&MBB))
WaterList.push_back(&MBB);
for (MachineInstr &I : MBB) {
if (I.isDebugInstr())
continue;
unsigned Opc = I.getOpcode();
if (I.isBranch()) {
bool isCond = false;
unsigned Bits = 0;
unsigned Scale = 1;
int UOpc = Opc;
switch (Opc) {
default:
continue; case ARM::t2BR_JT:
case ARM::tBR_JTr:
T2JumpTables.push_back(&I);
continue; case ARM::Bcc:
isCond = true;
UOpc = ARM::B;
LLVM_FALLTHROUGH;
case ARM::B:
Bits = 24;
Scale = 4;
break;
case ARM::tBcc:
isCond = true;
UOpc = ARM::tB;
Bits = 8;
Scale = 2;
break;
case ARM::tB:
Bits = 11;
Scale = 2;
break;
case ARM::t2Bcc:
isCond = true;
UOpc = ARM::t2B;
Bits = 20;
Scale = 2;
break;
case ARM::t2B:
Bits = 24;
Scale = 2;
break;
}
unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
}
if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
PushPopMIs.push_back(&I);
if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
Opc == ARM::JUMPTABLE_TBH)
continue;
for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
unsigned Bits = 0;
unsigned Scale = 1;
bool NegOk = false;
bool IsSoImm = false;
switch (Opc) {
default:
llvm_unreachable("Unknown addressing mode for CP reference!");
case ARM::LEApcrel:
case ARM::LEApcrelJT: {
Bits = 8;
NegOk = true;
IsSoImm = true;
unsigned CPI = I.getOperand(op).getIndex();
assert(CPI < CPEMIs.size());
MachineInstr *CPEMI = CPEMIs[CPI];
const Align CPEAlign = getCPEAlign(CPEMI);
const unsigned LogCPEAlign = Log2(CPEAlign);
if (LogCPEAlign >= 2)
Scale = 4;
else
Scale = 1;
}
break;
case ARM::t2LEApcrel:
case ARM::t2LEApcrelJT:
Bits = 12;
NegOk = true;
break;
case ARM::tLEApcrel:
case ARM::tLEApcrelJT:
Bits = 8;
Scale = 4;
break;
case ARM::LDRBi12:
case ARM::LDRi12:
case ARM::LDRcp:
case ARM::t2LDRpci:
case ARM::t2LDRHpci:
case ARM::t2LDRSHpci:
case ARM::t2LDRBpci:
case ARM::t2LDRSBpci:
Bits = 12; NegOk = true;
break;
case ARM::tLDRpci:
Bits = 8;
Scale = 4; break;
case ARM::VLDRD:
case ARM::VLDRS:
Bits = 8;
Scale = 4; NegOk = true;
break;
case ARM::VLDRH:
Bits = 8;
Scale = 2; NegOk = true;
break;
}
unsigned CPI = I.getOperand(op).getIndex();
if (I.getOperand(op).isJTI()) {
JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
CPI = JumpTableEntryIndices[CPI];
}
MachineInstr *CPEMI = CPEMIs[CPI];
unsigned MaxOffs = ((1 << Bits)-1) * Scale;
CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
assert(CPE && "Cannot find a corresponding CPEntry!");
CPE->RefCount++;
break;
}
}
}
}
static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
const MachineBasicBlock *RHS) {
return LHS->getNumber() < RHS->getNumber();
}
void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
NewBB->getParent()->RenumberBlocks(NewBB);
BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
WaterList.insert(IP, NewBB);
}
MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
MachineBasicBlock *OrigBB = MI->getParent();
LivePhysRegs LRs(*MF->getSubtarget().getRegisterInfo());
LRs.addLiveOuts(*OrigBB);
auto LivenessEnd = ++MachineBasicBlock::iterator(MI).getReverse();
for (MachineInstr &LiveMI : make_range(OrigBB->rbegin(), LivenessEnd))
LRs.stepBackward(LiveMI);
MachineBasicBlock *NewBB =
MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
MachineFunction::iterator MBBI = ++OrigBB->getIterator();
MF->insert(MBBI, NewBB);
NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
if (!isThumb)
BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
else
BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
.addMBB(NewBB)
.add(predOps(ARMCC::AL));
++NumSplit;
NewBB->transferSuccessors(OrigBB);
OrigBB->addSuccessor(NewBB);
MachineRegisterInfo &MRI = MF->getRegInfo();
for (MCPhysReg L : LRs)
if (!MRI.isReserved(L))
NewBB->addLiveIn(L);
MF->RenumberBlocks(NewBB);
BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
MachineBasicBlock* WaterBB = *IP;
if (WaterBB == OrigBB)
WaterList.insert(std::next(IP), NewBB);
else
WaterList.insert(IP, OrigBB);
NewWaterList.insert(OrigBB);
BBUtils->computeBlockSize(OrigBB);
BBUtils->computeBlockSize(NewBB);
BBUtils->adjustBBOffsetsAfter(OrigBB);
return NewBB;
}
unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
unsigned UserOffset = BBUtils->getOffsetOf(U.MI);
SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo();
const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
unsigned KnownBits = BBI.internalKnownBits();
UserOffset += (isThumb ? 4 : 8);
U.KnownAlignment = (KnownBits >= 2);
if (isThumb && U.KnownAlignment)
UserOffset &= ~3u;
return UserOffset;
}
bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
unsigned TrialOffset, unsigned MaxDisp,
bool NegativeOK, bool IsSoImm) {
if (UserOffset <= TrialOffset) {
if (TrialOffset - UserOffset <= MaxDisp)
return true;
} else if (NegativeOK) {
if (UserOffset - TrialOffset <= MaxDisp)
return true;
}
return false;
}
bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
MachineBasicBlock* Water, CPUser &U,
unsigned &Growth) {
BBInfoVector &BBInfo = BBUtils->getBBInfo();
const Align CPEAlign = getCPEAlign(U.CPEMI);
const unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPEAlign);
unsigned NextBlockOffset;
Align NextBlockAlignment;
MachineFunction::const_iterator NextBlock = Water->getIterator();
if (++NextBlock == MF->end()) {
NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
} else {
NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
NextBlockAlignment = NextBlock->getAlignment();
}
unsigned Size = U.CPEMI->getOperand(2).getImm();
unsigned CPEEnd = CPEOffset + Size;
if (CPEEnd > NextBlockOffset) {
Growth = CPEEnd - NextBlockOffset;
Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
if (CPEOffset < UserOffset)
UserOffset += Growth + UnknownPadding(MF->getAlignment(), Log2(CPEAlign));
} else
Growth = 0;
return isOffsetInRange(UserOffset, CPEOffset, U);
}
bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
MachineInstr *CPEMI, unsigned MaxDisp,
bool NegOk, bool DoDump) {
unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI);
if (DoDump) {
LLVM_DEBUG({
BBInfoVector &BBInfo = BBUtils->getBBInfo();
unsigned Block = MI->getParent()->getNumber();
const BasicBlockInfo &BBI = BBInfo[Block];
dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
<< " max delta=" << MaxDisp
<< format(" insn address=%#x", UserOffset) << " in "
<< printMBBReference(*MI->getParent()) << ": "
<< format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
<< format("CPE address=%#x offset=%+d: ", CPEOffset,
int(CPEOffset - UserOffset));
});
}
return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
}
#ifndef NDEBUG
static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
return false;
MachineBasicBlock *Succ = *MBB->succ_begin();
MachineBasicBlock *Pred = *MBB->pred_begin();
MachineInstr *PredMI = &Pred->back();
if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
|| PredMI->getOpcode() == ARM::t2B)
return PredMI->getOperand(0).getMBB() == Succ;
return false;
}
#endif
bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
MachineInstr *CPEMI) {
CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
assert(CPE && "Unexpected!");
if (--CPE->RefCount == 0) {
removeDeadCPEMI(CPEMI);
CPE->CPEMI = nullptr;
--NumCPEs;
return true;
}
return false;
}
unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
if (CPEMI->getOperand(1).isCPI())
return CPEMI->getOperand(1).getIndex();
return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
}
int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
true)) {
LLVM_DEBUG(dbgs() << "In range\n");
return 1;
}
unsigned CPI = getCombinedIndex(CPEMI);
std::vector<CPEntry> &CPEs = CPEntries[CPI];
for (CPEntry &CPE : CPEs) {
if (CPE.CPEMI == CPEMI)
continue;
if (CPE.CPEMI == nullptr)
continue;
if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, U.getMaxDisp(),
U.NegOk)) {
LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI
<< "\n");
U.CPEMI = CPE.CPEMI;
for (MachineOperand &MO : UserMI->operands())
if (MO.isCPI()) {
MO.setIndex(CPE.CPI);
break;
}
CPE.RefCount++;
return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
}
}
return 0;
}
static inline unsigned getUnconditionalBrDisp(int Opc) {
switch (Opc) {
case ARM::tB:
return ((1<<10)-1)*2;
case ARM::t2B:
return ((1<<23)-1)*2;
default:
break;
}
return ((1<<23)-1)*4;
}
bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
water_iterator &WaterIter,
bool CloserWater) {
if (WaterList.empty())
return false;
unsigned BestGrowth = ~0u;
MachineBasicBlock *UserBB = U.MI->getParent();
BBInfoVector &BBInfo = BBUtils->getBBInfo();
const Align CPEAlign = getCPEAlign(U.CPEMI);
unsigned MinNoSplitDisp = BBInfo[UserBB->getNumber()].postOffset(CPEAlign);
if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
return false;
for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
--IP) {
MachineBasicBlock* WaterBB = *IP;
unsigned Growth;
if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
(WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
Growth < BestGrowth) {
BestGrowth = Growth;
WaterIter = IP;
LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
<< " Growth=" << Growth << '\n');
if (CloserWater && WaterBB == U.MI->getParent())
return true;
if (!CloserWater && BestGrowth == 0)
return true;
}
if (IP == B)
break;
}
return BestGrowth != ~0u;
}
void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
unsigned UserOffset,
MachineBasicBlock *&NewMBB) {
CPUser &U = CPUsers[CPUserIndex];
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
const Align CPEAlign = getCPEAlign(CPEMI);
MachineBasicBlock *UserMBB = UserMI->getParent();
BBInfoVector &BBInfo = BBUtils->getBBInfo();
const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
if (BBHasFallthrough(UserMBB)) {
unsigned Delta = isThumb1 ? 2 : 4;
unsigned CPEOffset = UserBBI.postOffset(CPEAlign) + Delta;
if (isOffsetInRange(UserOffset, CPEOffset, U)) {
LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
<< format(", expected CPE offset %#x\n", CPEOffset));
NewMBB = &*++UserMBB->getIterator();
int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
if (!isThumb)
BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
else
BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
.addMBB(NewMBB)
.add(predOps(ARMCC::AL));
unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
ImmBranches.push_back(ImmBranch(&UserMBB->back(),
MaxDisp, false, UncondBr));
BBUtils->computeBlockSize(UserMBB);
BBUtils->adjustBBOffsetsAfter(UserMBB);
return;
}
}
const Align Align = MF->getAlignment();
assert(Align >= CPEAlign && "Over-aligned constant pool entry");
unsigned KnownBits = UserBBI.internalKnownBits();
unsigned UPad = UnknownPadding(Align, KnownBits);
unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
BaseInsertOffset));
BaseInsertOffset -= 4;
LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
<< " la=" << Log2(Align) << " kb=" << KnownBits
<< " up=" << UPad << '\n');
if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
BaseInsertOffset =
std::max(UserBBI.postOffset() - UPad - 8,
UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
MachineBasicBlock::iterator I = UserMI;
++I;
Register PredReg;
for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
I->getOpcode() != ARM::t2IT &&
getITInstrPredicate(*I, PredReg) != ARMCC::AL;
Offset += TII->getInstSizeInBytes(*I), I = std::next(I)) {
BaseInsertOffset =
std::max(BaseInsertOffset, Offset + TII->getInstSizeInBytes(*I) + 1);
assert(I != UserMBB->end() && "Fell off end of block");
}
LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
}
unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
CPEMI->getOperand(2).getImm();
MachineBasicBlock::iterator MI = UserMI;
++MI;
unsigned CPUIndex = CPUserIndex+1;
unsigned NumCPUsers = CPUsers.size();
MachineInstr *LastIT = nullptr;
for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Offset < BaseInsertOffset;
Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
assert(MI != UserMBB->end() && "Fell off end of block");
if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
CPUser &U = CPUsers[CPUIndex];
if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
BaseInsertOffset -= Align.value();
EndInsertOffset -= Align.value();
}
EndInsertOffset += U.CPEMI->getOperand(2).getImm();
CPUIndex++;
}
if (MI->getOpcode() == ARM::t2IT)
LastIT = &*MI;
}
--MI;
if (LastIT) {
Register PredReg;
ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
if (CC != ARMCC::AL)
MI = LastIT;
}
if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
(MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
ARMII::MO_HI16) {
--MI;
assert(MI->getOpcode() == ARM::t2MOVi16 &&
(MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
ARMII::MO_LO16);
}
#ifndef NDEBUG
Register PredReg;
assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL);
#endif
NewMBB = splitBlockBeforeInstr(&*MI);
}
bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
bool CloserWater) {
CPUser &U = CPUsers[CPUserIndex];
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
unsigned CPI = getCombinedIndex(CPEMI);
unsigned Size = CPEMI->getOperand(2).getImm();
unsigned UserOffset = getUserOffset(U);
int result = findInRangeCPEntry(U, UserOffset);
if (result==1) return false;
else if (result==2) return true;
unsigned ID = AFI->createPICLabelUId();
MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
MachineBasicBlock *NewMBB;
water_iterator IP;
if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
LLVM_DEBUG(dbgs() << "Found water in range\n");
MachineBasicBlock *WaterBB = *IP;
if (NewWaterList.erase(WaterBB))
NewWaterList.insert(NewIsland);
NewMBB = &*++WaterBB->getIterator();
} else {
LLVM_DEBUG(dbgs() << "No water found\n");
createNewWater(CPUserIndex, UserOffset, NewMBB);
MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
IP = find(WaterList, WaterBB);
if (IP != WaterList.end())
NewWaterList.erase(WaterBB);
NewWaterList.insert(NewIsland);
}
const Align Alignment = isThumb ? Align(2) : Align(4);
if (NewMBB->getAlignment() < Alignment)
NewMBB->setAlignment(Alignment);
if (IP != WaterList.end())
WaterList.erase(IP);
MF->insert(NewMBB->getIterator(), NewIsland);
updateForInsertedWaterBlock(NewIsland);
U.HighWaterMark = NewIsland;
U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
.addImm(ID)
.add(CPEMI->getOperand(1))
.addImm(Size);
CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
++NumCPEs;
decrementCPEReferenceCount(CPI, CPEMI);
NewIsland->setAlignment(getCPEAlign(U.CPEMI));
BBUtils->adjustBBSize(NewIsland, Size);
BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator());
for (MachineOperand &MO : UserMI->operands())
if (MO.isCPI()) {
MO.setIndex(ID);
break;
}
LLVM_DEBUG(
dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
<< format(" offset=%#x\n",
BBUtils->getBBInfo()[NewIsland->getNumber()].Offset));
return true;
}
void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
MachineBasicBlock *CPEBB = CPEMI->getParent();
unsigned Size = CPEMI->getOperand(2).getImm();
CPEMI->eraseFromParent();
BBInfoVector &BBInfo = BBUtils->getBBInfo();
BBUtils->adjustBBSize(CPEBB, -Size);
if (CPEBB->empty()) {
BBInfo[CPEBB->getNumber()].Size = 0;
CPEBB->setAlignment(Align(1));
} else {
CPEBB->setAlignment(getCPEAlign(&*CPEBB->begin()));
}
BBUtils->adjustBBOffsetsAfter(CPEBB);
assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
}
bool ARMConstantIslands::removeUnusedCPEntries() {
unsigned MadeChange = false;
for (std::vector<CPEntry> &CPEs : CPEntries) {
for (CPEntry &CPE : CPEs) {
if (CPE.RefCount == 0 && CPE.CPEMI) {
removeDeadCPEMI(CPE.CPEMI);
CPE.CPEMI = nullptr;
MadeChange = true;
}
}
}
return MadeChange;
}
bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp))
return false;
if (!Br.isCond)
return fixupUnconditionalBr(Br);
return fixupConditionalBr(Br);
}
bool
ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
MachineBasicBlock *MBB = MI->getParent();
if (!isThumb1)
llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
if (!AFI->isLRSpilled())
report_fatal_error("underestimated function size");
Br.MaxDisp = (1 << 21) * 2;
MI->setDesc(TII->get(ARM::tBfar));
BBInfoVector &BBInfo = BBUtils->getBBInfo();
BBInfo[MBB->getNumber()].Size += 2;
BBUtils->adjustBBOffsetsAfter(MBB);
++NumUBrFixed;
LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
return true;
}
bool
ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
CC = ARMCC::getOppositeCondition(CC);
Register CCReg = MI->getOperand(2).getReg();
MachineBasicBlock *MBB = MI->getParent();
MachineInstr *BMI = &MBB->back();
bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
++NumCBrFixed;
if (BMI != MI) {
if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
BMI->getOpcode() == Br.UncondBr) {
MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) {
LLVM_DEBUG(
dbgs() << " Invert Bcc condition and swap its destination with "
<< *BMI);
BMI->getOperand(0).setMBB(DestBB);
MI->getOperand(0).setMBB(NewDest);
MI->getOperand(1).setImm(CC);
return true;
}
}
}
if (NeedSplit) {
splitBlockBeforeInstr(MI);
int delta = TII->getInstSizeInBytes(MBB->back());
BBUtils->adjustBBSize(MBB, -delta);
MBB->back().eraseFromParent();
MBB->addSuccessor(DestBB);
std::next(MBB->getIterator())->removeSuccessor(DestBB);
}
MachineBasicBlock *NextBB = &*++MBB->getIterator();
LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
<< " also invert condition and change dest. to "
<< printMBBReference(*NextBB) << "\n");
BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
.addMBB(NextBB).addImm(CC).addReg(CCReg);
Br.MI = &MBB->back();
BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
if (isThumb)
BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
.addMBB(DestBB)
.add(predOps(ARMCC::AL));
else
BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI));
MI->eraseFromParent();
BBUtils->adjustBBOffsetsAfter(MBB);
return true;
}
bool ARMConstantIslands::optimizeThumb2Instructions() {
bool MadeChange = false;
for (CPUser &U : CPUsers) {
unsigned Opcode = U.MI->getOpcode();
unsigned NewOpc = 0;
unsigned Scale = 1;
unsigned Bits = 0;
switch (Opcode) {
default: break;
case ARM::t2LEApcrel:
if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
NewOpc = ARM::tLEApcrel;
Bits = 8;
Scale = 4;
}
break;
case ARM::t2LDRpci:
if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
NewOpc = ARM::tLDRpci;
Bits = 8;
Scale = 4;
}
break;
}
if (!NewOpc)
continue;
unsigned UserOffset = getUserOffset(U);
unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
if (!U.KnownAlignment)
MaxOffs -= 2;
if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
U.MI->setDesc(TII->get(NewOpc));
MachineBasicBlock *MBB = U.MI->getParent();
BBUtils->adjustBBSize(MBB, -2);
BBUtils->adjustBBOffsetsAfter(MBB);
++NumT2CPShrunk;
MadeChange = true;
}
}
return MadeChange;
}
bool ARMConstantIslands::optimizeThumb2Branches() {
auto TryShrinkBranch = [this](ImmBranch &Br) {
unsigned Opcode = Br.MI->getOpcode();
unsigned NewOpc = 0;
unsigned Scale = 1;
unsigned Bits = 0;
switch (Opcode) {
default: break;
case ARM::t2B:
NewOpc = ARM::tB;
Bits = 11;
Scale = 2;
break;
case ARM::t2Bcc:
NewOpc = ARM::tBcc;
Bits = 8;
Scale = 2;
break;
}
if (NewOpc) {
unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) {
LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Br.MI->setDesc(TII->get(NewOpc));
MachineBasicBlock *MBB = Br.MI->getParent();
BBUtils->adjustBBSize(MBB, -2);
BBUtils->adjustBBOffsetsAfter(MBB);
++NumT2BrShrunk;
return true;
}
}
return false;
};
struct ImmCompare {
MachineInstr* MI = nullptr;
unsigned NewOpc = 0;
};
auto FindCmpForCBZ = [this](ImmBranch &Br, ImmCompare &ImmCmp,
MachineBasicBlock *DestBB) {
ImmCmp.MI = nullptr;
ImmCmp.NewOpc = 0;
if (!Br.MI->killsRegister(ARM::CPSR))
return false;
Register PredReg;
unsigned NewOpc = 0;
ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
if (Pred == ARMCC::EQ)
NewOpc = ARM::tCBZ;
else if (Pred == ARMCC::NE)
NewOpc = ARM::tCBNZ;
else
return false;
unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2;
BBInfoVector &BBInfo = BBUtils->getBBInfo();
unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)
return false;
auto *TRI = STI->getRegisterInfo();
MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);
if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)
return false;
ImmCmp.MI = CmpMI;
ImmCmp.NewOpc = NewOpc;
return true;
};
auto TryConvertToLE = [this](ImmBranch &Br, ImmCompare &Cmp) {
if (Br.MI->getOpcode() != ARM::t2Bcc || !STI->hasLOB() ||
STI->hasMinSize())
return false;
MachineBasicBlock *MBB = Br.MI->getParent();
MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
if (BBUtils->getOffsetOf(MBB) < BBUtils->getOffsetOf(DestBB) ||
!BBUtils->isBBInRange(Br.MI, DestBB, 4094))
return false;
if (!DT->dominates(DestBB, MBB))
return false;
Cmp.NewOpc = Cmp.NewOpc == ARM::tCBZ ? ARM::tCBNZ : ARM::tCBZ;
MachineInstrBuilder MIB = BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(),
TII->get(ARM::t2LE));
MIB.add(Br.MI->getOperand(0));
Br.MI->eraseFromParent();
Br.MI = MIB;
++NumLEInserted;
return true;
};
bool MadeChange = false;
for (ImmBranch &Br : reverse(ImmBranches)) {
MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
MachineBasicBlock *MBB = Br.MI->getParent();
MachineBasicBlock *ExitBB = &MBB->back() == Br.MI ?
MBB->getFallThrough() :
MBB->back().getOperand(0).getMBB();
ImmCompare Cmp;
if (FindCmpForCBZ(Br, Cmp, ExitBB) && TryConvertToLE(Br, Cmp)) {
DestBB = ExitBB;
MadeChange = true;
} else {
FindCmpForCBZ(Br, Cmp, DestBB);
MadeChange |= TryShrinkBranch(Br);
}
unsigned Opcode = Br.MI->getOpcode();
if ((Opcode != ARM::tBcc && Opcode != ARM::t2LE) || !Cmp.NewOpc)
continue;
Register Reg = Cmp.MI->getOperand(0).getReg();
auto *TRI = STI->getRegisterInfo();
MachineBasicBlock::iterator KillMI = Br.MI;
bool RegKilled = false;
do {
--KillMI;
if (KillMI->killsRegister(Reg, TRI)) {
KillMI->clearRegisterKills(Reg, TRI);
RegKilled = true;
break;
}
} while (KillMI != Cmp.MI);
LLVM_DEBUG(dbgs() << "Fold: " << *Cmp.MI << " and: " << *Br.MI);
MachineInstr *NewBR =
BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(Cmp.NewOpc))
.addReg(Reg, getKillRegState(RegKilled) |
getRegState(Cmp.MI->getOperand(0)))
.addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
Cmp.MI->eraseFromParent();
if (Br.MI->getOpcode() == ARM::tBcc) {
Br.MI->eraseFromParent();
Br.MI = NewBR;
BBUtils->adjustBBSize(MBB, -2);
} else if (MBB->back().getOpcode() != ARM::t2LE) {
MachineInstr *LastMI = &MBB->back();
BBUtils->adjustBBSize(MBB, -LastMI->getDesc().getSize());
LastMI->eraseFromParent();
}
BBUtils->adjustBBOffsetsAfter(MBB);
++NumCBZ;
MadeChange = true;
}
return MadeChange;
}
static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
unsigned BaseReg) {
if (I.getOpcode() != ARM::t2ADDrs)
return false;
if (I.getOperand(0).getReg() != EntryReg)
return false;
if (I.getOperand(1).getReg() != BaseReg)
return false;
return true;
}
bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
MachineInstr *LEAMI,
unsigned &DeadSize,
bool &CanDeleteLEA,
bool &BaseRegKill) {
if (JumpMI->getParent() != LEAMI->getParent())
return false;
Register EntryReg = JumpMI->getOperand(0).getReg();
Register BaseReg = LEAMI->getOperand(0).getReg();
CanDeleteLEA = true;
BaseRegKill = false;
MachineInstr *RemovableAdd = nullptr;
MachineBasicBlock::iterator I(LEAMI);
for (++I; &*I != JumpMI; ++I) {
if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
RemovableAdd = &*I;
break;
}
for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
const MachineOperand &MO = I->getOperand(K);
if (!MO.isReg() || !MO.getReg())
continue;
if (MO.isDef() && MO.getReg() == BaseReg)
return false;
if (MO.isUse() && MO.getReg() == BaseReg) {
BaseRegKill = BaseRegKill || MO.isKill();
CanDeleteLEA = false;
}
}
}
if (!RemovableAdd)
return true;
for (++I; &*I != JumpMI; ++I) {
for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
const MachineOperand &MO = I->getOperand(K);
if (!MO.isReg() || !MO.getReg())
continue;
if (MO.isDef() && MO.getReg() == BaseReg)
return false;
if (MO.isUse() && MO.getReg() == EntryReg)
RemovableAdd = nullptr;
}
}
if (RemovableAdd) {
RemovableAdd->eraseFromParent();
DeadSize += isThumb2 ? 4 : 2;
} else if (BaseReg == EntryReg) {
return false;
}
return true;
}
static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
MachineFunction *MF = MBB->getParent();
++MBB;
return MBB != MF->end() && !MBB->empty() && &*MBB->begin() == CPEMI;
}
static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
MachineInstr *JumpMI,
unsigned &DeadSize) {
MachineInstr *RemovableAdd = nullptr;
Register EntryReg = JumpMI->getOperand(0).getReg();
MachineBasicBlock::iterator I(LEAMI);
for (++I; &*I != JumpMI; ++I) {
if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
RemovableAdd = &*I;
}
if (!RemovableAdd)
return;
MachineBasicBlock::iterator J(RemovableAdd);
for (++J; &*J != JumpMI; ++J) {
for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
const MachineOperand &MO = J->getOperand(K);
if (!MO.isReg() || !MO.getReg())
continue;
if (MO.isDef() && MO.getReg() == EntryReg)
return;
if (MO.isUse() && MO.getReg() == EntryReg)
return;
}
}
LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
RemovableAdd->eraseFromParent();
DeadSize += 4;
}
bool ARMConstantIslands::optimizeThumb2JumpTables() {
bool MadeChange = false;
MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
if (!MJTI) return false;
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
MachineInstr *MI = T2JumpTables[i];
const MCInstrDesc &MCID = MI->getDesc();
unsigned NumOps = MCID.getNumOperands();
unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
MachineOperand JTOP = MI->getOperand(JTOpIdx);
unsigned JTI = JTOP.getIndex();
assert(JTI < JT.size());
bool ByteOk = true;
bool HalfWordOk = true;
unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4;
const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
BBInfoVector &BBInfo = BBUtils->getBBInfo();
for (MachineBasicBlock *MBB : JTBBs) {
unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
ByteOk = false;
unsigned TBHLimit = ((1<<16)-1)*2;
if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
HalfWordOk = false;
if (!ByteOk && !HalfWordOk)
break;
}
if (!ByteOk && !HalfWordOk)
continue;
CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
MachineBasicBlock *MBB = MI->getParent();
if (!MI->getOperand(0).isKill()) continue;
unsigned DeadSize = 0;
bool CanDeleteLEA = false;
bool BaseRegKill = false;
unsigned IdxReg = ~0U;
bool IdxRegKill = true;
if (isThumb2) {
IdxReg = MI->getOperand(1).getReg();
IdxRegKill = MI->getOperand(1).isKill();
bool PreservedBaseReg =
preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
continue;
} else {
Register BaseReg = User.MI->getOperand(0).getReg();
if (User.MI->getIterator() == User.MI->getParent()->begin())
continue;
MachineInstr *Shift = User.MI->getPrevNode();
if (Shift->getOpcode() != ARM::tLSLri ||
Shift->getOperand(3).getImm() != 2 ||
!Shift->getOperand(2).isKill())
continue;
IdxReg = Shift->getOperand(2).getReg();
Register ShiftedIdxReg = Shift->getOperand(0).getReg();
if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
continue;
MachineInstr *Load = User.MI->getNextNode();
if (Load->getOpcode() != ARM::tLDRr)
continue;
if (Load->getOperand(1).getReg() != BaseReg ||
Load->getOperand(2).getReg() != ShiftedIdxReg ||
!Load->getOperand(2).isKill())
continue;
auto *TRI = STI->getRegisterInfo();
if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
continue;
if (isPositionIndependentOrROPI) {
MachineInstr *Add = Load->getNextNode();
if (Add->getOpcode() != ARM::tADDrr ||
Add->getOperand(2).getReg() != BaseReg ||
Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
!Add->getOperand(3).isKill())
continue;
if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
continue;
if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
continue;
Add->eraseFromParent();
DeadSize += 2;
} else {
if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
continue;
if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
continue;
}
CanDeleteLEA = true;
Shift->eraseFromParent();
Load->eraseFromParent();
DeadSize += 4;
}
LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
MachineInstr *CPEMI = User.CPEMI;
unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
if (!isThumb2)
Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
MachineBasicBlock::iterator MI_JT = MI;
MachineInstr *NewJTMI =
BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
.addReg(User.MI->getOperand(0).getReg(),
getKillRegState(BaseRegKill))
.addReg(IdxReg, getKillRegState(IdxRegKill))
.addJumpTableIndex(JTI, JTOP.getTargetFlags())
.addImm(CPEMI->getOperand(0).getImm());
LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
CPEMI->setDesc(TII->get(JTOpc));
if (jumpTableFollowsTB(MI, User.CPEMI)) {
NewJTMI->getOperand(0).setReg(ARM::PC);
NewJTMI->getOperand(0).setIsKill(false);
if (CanDeleteLEA) {
if (isThumb2)
RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
User.MI->eraseFromParent();
DeadSize += isThumb2 ? 4 : 2;
User.MI = NewJTMI;
User.MaxDisp = 4;
User.NegOk = false;
User.IsSoImm = false;
User.KnownAlignment = false;
} else {
int CPEntryIdx = JumpTableEntryIndices[JTI];
auto &CPEs = CPEntries[CPEntryIdx];
auto Entry =
find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
++Entry->RefCount;
CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
}
}
unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
unsigned OrigSize = TII->getInstSizeInBytes(*MI);
MI->eraseFromParent();
int Delta = OrigSize - NewSize + DeadSize;
BBInfo[MBB->getNumber()].Size -= Delta;
BBUtils->adjustBBOffsetsAfter(MBB);
++NumTBs;
MadeChange = true;
}
return MadeChange;
}
bool ARMConstantIslands::reorderThumb2JumpTables() {
bool MadeChange = false;
MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
if (!MJTI) return false;
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
MachineInstr *MI = T2JumpTables[i];
const MCInstrDesc &MCID = MI->getDesc();
unsigned NumOps = MCID.getNumOperands();
unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
MachineOperand JTOP = MI->getOperand(JTOpIdx);
unsigned JTI = JTOP.getIndex();
assert(JTI < JT.size());
int JTNumber = MI->getParent()->getNumber();
const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
for (MachineBasicBlock *MBB : JTBBs) {
int DTNumber = MBB->getNumber();
if (DTNumber < JTNumber) {
MachineBasicBlock *NewBB =
adjustJTTargetBlockForward(JTI, MBB, MI->getParent());
if (NewBB)
MJTI->ReplaceMBBInJumpTable(JTI, MBB, NewBB);
MadeChange = true;
}
}
}
return MadeChange;
}
void ARMConstantIslands::fixupBTI(unsigned JTI, MachineBasicBlock &OldBB,
MachineBasicBlock &NewBB) {
assert(isThumb2 && "BTI in Thumb1?");
BuildMI(NewBB, NewBB.begin(), DebugLoc(), TII->get(ARM::t2BTI));
const MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
const MachineJumpTableEntry &JTE = MJTI.getJumpTables()[JTI];
for (const MachineBasicBlock *MBB : JTE.MBBs) {
if (MBB != &OldBB)
continue;
--BlockJumpTableRefCount[MBB];
++BlockJumpTableRefCount[&NewBB];
}
if (BlockJumpTableRefCount[&OldBB] > 0)
return;
auto BTIPos = llvm::find_if_not(OldBB.instrs(), [](const MachineInstr &MI) {
return MI.isMetaInstruction();
});
assert(BTIPos->getOpcode() == ARM::t2BTI &&
"BasicBlock is mentioned in a jump table but does start with BTI");
if (BTIPos->getOpcode() == ARM::t2BTI)
BTIPos->eraseFromParent();
}
MachineBasicBlock *ARMConstantIslands::adjustJTTargetBlockForward(
unsigned JTI, MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
SmallVector<MachineOperand, 4> Cond;
SmallVector<MachineOperand, 4> CondPrior;
MachineFunction::iterator BBi = BB->getIterator();
MachineFunction::iterator OldPrior = std::prev(BBi);
MachineFunction::iterator OldNext = std::next(BBi);
bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
if (!B && Cond.empty() && BB != &MF->front() &&
!TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
BB->moveAfter(JTBB);
OldPrior->updateTerminator(BB);
BB->updateTerminator(OldNext != MF->end() ? &*OldNext : nullptr);
MF->RenumberBlocks();
++NumJTMoved;
return nullptr;
}
MachineBasicBlock *NewBB =
MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
MachineFunction::iterator MBBI = ++JTBB->getIterator();
MF->insert(MBBI, NewBB);
for (const MachineBasicBlock::RegisterMaskPair &RegMaskPair : BB->liveins())
NewBB->addLiveIn(RegMaskPair);
if (isThumb2)
BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
.addMBB(BB)
.add(predOps(ARMCC::AL));
else
BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
.addMBB(BB)
.add(predOps(ARMCC::AL));
MF->RenumberBlocks(NewBB);
NewBB->addSuccessor(BB);
JTBB->replaceSuccessor(BB, NewBB);
if (MF->getInfo<ARMFunctionInfo>()->branchTargetEnforcement())
fixupBTI(JTI, *BB, *NewBB);
++NumJTInserted;
return NewBB;
}
FunctionPass *llvm::createARMConstantIslandPass() {
return new ARMConstantIslands();
}
INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
false, false)