#include "CSKY.h"
#include "CSKYConstantPoolValue.h"
#include "CSKYMachineFunctionInfo.h"
#include "CSKYSubtarget.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/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.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 <vector>
using namespace llvm;
#define DEBUG_TYPE "CSKY-constant-islands"
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");
namespace {
using Iter = MachineBasicBlock::iterator;
using ReverseIter = MachineBasicBlock::reverse_iterator;
class CSKYConstantIslands : public MachineFunctionPass {
struct BasicBlockInfo {
unsigned Offset = 0;
unsigned Size = 0;
BasicBlockInfo() = default;
unsigned postOffset() const { return Offset + Size; }
};
std::vector<BasicBlockInfo> BBInfo;
std::vector<MachineBasicBlock *> WaterList;
SmallSet<MachineBasicBlock *, 4> NewWaterList;
using water_iterator = std::vector<MachineBasicBlock *>::iterator;
struct CPUser {
MachineInstr *MI;
MachineInstr *CPEMI;
MachineBasicBlock *HighWaterMark;
private:
unsigned MaxDisp;
public:
bool NegOk;
CPUser(MachineInstr *Mi, MachineInstr *Cpemi, unsigned Maxdisp, bool Neg)
: MI(Mi), CPEMI(Cpemi), MaxDisp(Maxdisp), NegOk(Neg) {
HighWaterMark = CPEMI->getParent();
}
unsigned getMaxDisp() const { return MaxDisp - 16; }
void setMaxDisp(unsigned Val) { MaxDisp = Val; }
};
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;
struct ImmBranch {
MachineInstr *MI;
unsigned MaxDisp : 31;
bool IsCond : 1;
int UncondBr;
ImmBranch(MachineInstr *Mi, unsigned Maxdisp, bool Cond, int Ubr)
: MI(Mi), MaxDisp(Maxdisp), IsCond(Cond), UncondBr(Ubr) {}
};
std::vector<ImmBranch> ImmBranches;
const CSKYSubtarget *STI = nullptr;
const CSKYInstrInfo *TII;
CSKYMachineFunctionInfo *MFI;
MachineFunction *MF = nullptr;
MachineConstantPool *MCP = nullptr;
unsigned PICLabelUId;
void initPICLabelUId(unsigned UId) { PICLabelUId = UId; }
unsigned createPICLabelUId() { return PICLabelUId++; }
public:
static char ID;
CSKYConstantIslands() : MachineFunctionPass(ID) {}
StringRef getPassName() const override { return "CSKY Constant Islands"; }
bool runOnMachineFunction(MachineFunction &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
void doInitialPlacement(std::vector<MachineInstr *> &CPEMIs);
CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Align getCPEAlign(const MachineInstr &CPEMI);
void initializeFunctionInfo(const std::vector<MachineInstr *> &CPEMIs);
unsigned getOffsetOf(MachineInstr *MI) const;
unsigned getUserOffset(CPUser &) const;
void dumpBBs();
bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, unsigned Disp,
bool NegativeOK);
bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
const CPUser &U);
void computeBlockSize(MachineBasicBlock *MBB);
MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
void adjustBBOffsetsAfter(MachineBasicBlock *BB);
bool decrementCPEReferenceCount(unsigned CPI, MachineInstr *CPEMI);
int findInRangeCPEntry(CPUser &U, unsigned UserOffset);
bool findAvailableWater(CPUser &U, unsigned UserOffset,
water_iterator &WaterIter);
void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
MachineBasicBlock *&NewMBB);
bool handleConstantPoolUser(unsigned CPUserIndex);
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 isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
bool fixupImmediateBr(ImmBranch &Br);
bool fixupConditionalBr(ImmBranch &Br);
bool fixupUnconditionalBr(ImmBranch &Br);
};
}
char CSKYConstantIslands::ID = 0;
bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
unsigned TrialOffset,
const CPUser &U) {
return isOffsetInRange(UserOffset, TrialOffset, U.getMaxDisp(), U.NegOk);
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void CSKYConstantIslands::dumpBBs() {
for (unsigned J = 0, E = BBInfo.size(); J != E; ++J) {
const BasicBlockInfo &BBI = BBInfo[J];
dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
<< format(" size=%#x\n", BBInfo[J].Size);
}
}
#endif
bool CSKYConstantIslands::runOnMachineFunction(MachineFunction &Mf) {
MF = &Mf;
MCP = Mf.getConstantPool();
STI = &Mf.getSubtarget<CSKYSubtarget>();
LLVM_DEBUG(dbgs() << "***** CSKYConstantIslands: "
<< MCP->getConstants().size() << " CP entries, aligned to "
<< MCP->getConstantPoolAlign().value() << " bytes *****\n");
TII = STI->getInstrInfo();
MFI = MF->getInfo<CSKYMachineFunctionInfo>();
MF->getRegInfo().invalidateLiveness();
MF->RenumberBlocks();
bool MadeChange = false;
std::vector<MachineInstr *> CPEMIs;
if (!MCP->isEmpty())
doInitialPlacement(CPEMIs);
initPICLabelUId(CPEMIs.size());
initializeFunctionInfo(CPEMIs);
CPEMIs.clear();
LLVM_DEBUG(dumpBBs());
MadeChange |= removeUnusedCPEntries();
unsigned NoCPIters = 0, NoBRIters = 0;
(void)NoBRIters;
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);
if (CPChange && ++NoCPIters > 30)
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;
}
LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
BBInfo.clear();
WaterList.clear();
CPUsers.clear();
CPEntries.clear();
ImmBranches.clear();
return MadeChange;
}
void CSKYConstantIslands::doInitialPlacement(
std::vector<MachineInstr *> &CPEMIs) {
MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
MF->push_back(BB);
const Align MaxAlign = MCP->getConstantPoolAlign();
BB->setAlignment(Align(2));
MF->ensureAlignment(BB->getAlignment());
SmallVector<MachineBasicBlock::iterator, 8> InsPoint(Log2(MaxAlign) + 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);
assert(Size >= 4 && "Too small constant pool entry");
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(CSKY::CONSTPOOL_ENTRY))
.addImm(I)
.addConstantPoolIndex(I)
.addImm(Size);
CPEMIs.push_back(CPEMI);
for (unsigned A = LogAlign + 1; A <= Log2(MaxAlign); ++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());
}
static bool bbHasFallthrough(MachineBasicBlock *MBB) {
MachineFunction::iterator MBBI = MBB->getIterator();
if (std::next(MBBI) == MBB->getParent()->end())
return false;
MachineBasicBlock *NextBB = &*std::next(MBBI);
for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
E = MBB->succ_end();
I != E; ++I)
if (*I == NextBB)
return true;
return false;
}
CSKYConstantIslands::CPEntry *
CSKYConstantIslands::findConstPoolEntry(unsigned CPI,
const MachineInstr *CPEMI) {
std::vector<CPEntry> &CPEs = CPEntries[CPI];
for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
if (CPEs[I].CPEMI == CPEMI)
return &CPEs[I];
}
return nullptr;
}
Align CSKYConstantIslands::getCPEAlign(const MachineInstr &CPEMI) {
assert(CPEMI.getOpcode() == CSKY::CONSTPOOL_ENTRY);
unsigned CPI = CPEMI.getOperand(1).getIndex();
assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
return MCP->getConstants()[CPI].getAlign();
}
void CSKYConstantIslands::initializeFunctionInfo(
const std::vector<MachineInstr *> &CPEMIs) {
BBInfo.clear();
BBInfo.resize(MF->getNumBlockIDs());
for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
computeBlockSize(&*I);
adjustBBOffsetsAfter(&MF->front());
for (MachineBasicBlock &MBB : *MF) {
if (!bbHasFallthrough(&MBB))
WaterList.push_back(&MBB);
for (MachineInstr &MI : MBB) {
if (MI.isDebugInstr())
continue;
int Opc = MI.getOpcode();
if (MI.isBranch() && !MI.isIndirectBranch()) {
bool IsCond = MI.isConditionalBranch();
unsigned Bits = 0;
unsigned Scale = 1;
int UOpc = CSKY::BR32;
switch (MI.getOpcode()) {
case CSKY::BR16:
case CSKY::BF16:
case CSKY::BT16:
Bits = 10;
Scale = 2;
break;
default:
Bits = 16;
Scale = 2;
break;
}
unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
ImmBranches.push_back(ImmBranch(&MI, MaxOffs, IsCond, UOpc));
}
if (Opc == CSKY::CONSTPOOL_ENTRY)
continue;
for (unsigned Op = 0, E = MI.getNumOperands(); Op != E; ++Op)
if (MI.getOperand(Op).isCPI()) {
unsigned Bits = 0;
unsigned Scale = 1;
bool NegOk = false;
switch (Opc) {
default:
llvm_unreachable("Unknown addressing mode for CP reference!");
case CSKY::MOVIH32:
case CSKY::ORI32:
continue;
case CSKY::PseudoTLSLA32:
case CSKY::JSRI32:
case CSKY::JMPI32:
case CSKY::LRW32:
case CSKY::LRW32_Gen:
Bits = 16;
Scale = 4;
break;
case CSKY::f2FLRW_S:
case CSKY::f2FLRW_D:
Bits = 8;
Scale = 4;
break;
case CSKY::GRS32:
Bits = 17;
Scale = 2;
NegOk = true;
break;
}
unsigned CPI = MI.getOperand(Op).getIndex();
MachineInstr *CPEMI = CPEMIs[CPI];
unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk));
CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
assert(CPE && "Cannot find a corresponding CPEntry!");
CPE->RefCount++;
break;
}
}
}
}
void CSKYConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
BBI.Size = 0;
for (const MachineInstr &MI : *MBB)
BBI.Size += TII->getInstSizeInBytes(MI);
}
unsigned CSKYConstantIslands::getOffsetOf(MachineInstr *MI) const {
MachineBasicBlock *MBB = MI->getParent();
unsigned Offset = BBInfo[MBB->getNumber()].Offset;
for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Offset += TII->getInstSizeInBytes(*I);
}
return Offset;
}
static bool compareMbbNumbers(const MachineBasicBlock *LHS,
const MachineBasicBlock *RHS) {
return LHS->getNumber() < RHS->getNumber();
}
void CSKYConstantIslands::updateForInsertedWaterBlock(
MachineBasicBlock *NewBB) {
NewBB->getParent()->RenumberBlocks(NewBB);
BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
water_iterator IP = llvm::lower_bound(WaterList, NewBB, compareMbbNumbers);
WaterList.insert(IP, NewBB);
}
unsigned CSKYConstantIslands::getUserOffset(CPUser &U) const {
unsigned UserOffset = getOffsetOf(U.MI);
UserOffset &= ~3u;
return UserOffset;
}
MachineBasicBlock *
CSKYConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
MachineBasicBlock *OrigBB = MI.getParent();
MachineBasicBlock *NewBB =
MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
MachineFunction::iterator MBBI = ++OrigBB->getIterator();
MF->insert(MBBI, NewBB);
NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
BuildMI(OrigBB, DebugLoc(), TII->get(CSKY::BR32)).addMBB(NewBB);
++NumSplit;
NewBB->transferSuccessors(OrigBB);
OrigBB->addSuccessor(NewBB);
MF->RenumberBlocks(NewBB);
BBInfo.insert(BBInfo.begin() + 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);
computeBlockSize(OrigBB);
computeBlockSize(NewBB);
adjustBBOffsetsAfter(OrigBB);
return NewBB;
}
bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
unsigned TrialOffset,
unsigned MaxDisp, bool NegativeOK) {
if (UserOffset <= TrialOffset) {
if (TrialOffset - UserOffset <= MaxDisp)
return true;
} else if (NegativeOK) {
if (UserOffset - TrialOffset <= MaxDisp)
return true;
}
return false;
}
bool CSKYConstantIslands::isWaterInRange(unsigned UserOffset,
MachineBasicBlock *Water, CPUser &U,
unsigned &Growth) {
unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
unsigned NextBlockOffset;
Align NextBlockAlignment;
MachineFunction::const_iterator NextBlock = ++Water->getIterator();
if (NextBlock == MF->end()) {
NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
NextBlockAlignment = Align(4);
} 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;
} else
Growth = 0;
return isOffsetInRange(UserOffset, CPEOffset, U);
}
bool CSKYConstantIslands::isCPEntryInRange(MachineInstr *MI,
unsigned UserOffset,
MachineInstr *CPEMI,
unsigned MaxDisp, bool NegOk,
bool DoDump) {
unsigned CPEOffset = getOffsetOf(CPEMI);
if (DoDump) {
LLVM_DEBUG({
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() == CSKY::BR32 )
return PredMI->getOperand(0).getMBB() == Succ;
return false;
}
#endif
void CSKYConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
unsigned BBNum = BB->getNumber();
for (unsigned I = BBNum + 1, E = MF->getNumBlockIDs(); I < E; ++I) {
unsigned Offset = BBInfo[I - 1].Offset + BBInfo[I - 1].Size;
BBInfo[I].Offset = Offset;
}
}
bool CSKYConstantIslands::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;
}
int CSKYConstantIslands::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 = CPEMI->getOperand(1).getIndex();
std::vector<CPEntry> &CPEs = CPEntries[CPI];
for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
if (CPEs[I].CPEMI == CPEMI)
continue;
if (CPEs[I].CPEMI == nullptr)
continue;
if (isCPEntryInRange(UserMI, UserOffset, CPEs[I].CPEMI, U.getMaxDisp(),
U.NegOk)) {
LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
<< CPEs[I].CPI << "\n");
U.CPEMI = CPEs[I].CPEMI;
for (unsigned J = 0, E = UserMI->getNumOperands(); J != E; ++J)
if (UserMI->getOperand(J).isCPI()) {
UserMI->getOperand(J).setIndex(CPEs[I].CPI);
break;
}
CPEs[I].RefCount++;
return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
}
}
return 0;
}
static inline unsigned getUnconditionalBrDisp(int Opc) {
unsigned Bits, Scale;
switch (Opc) {
case CSKY::BR16:
Bits = 10;
Scale = 2;
break;
case CSKY::BR32:
Bits = 16;
Scale = 2;
break;
default:
llvm_unreachable("");
}
unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
return MaxOffs;
}
bool CSKYConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
water_iterator &WaterIter) {
if (WaterList.empty())
return false;
unsigned BestGrowth = ~0u;
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)) &&
Growth < BestGrowth) {
BestGrowth = Growth;
WaterIter = IP;
LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
<< " Growth=" << Growth << '\n');
if (BestGrowth == 0)
return true;
}
if (IP == B)
break;
}
return BestGrowth != ~0u;
}
void CSKYConstantIslands::createNewWater(unsigned CPUserIndex,
unsigned UserOffset,
MachineBasicBlock *&NewMBB) {
CPUser &U = CPUsers[CPUserIndex];
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
MachineBasicBlock *UserMBB = UserMI->getParent();
const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
if (bbHasFallthrough(UserMBB)) {
unsigned Delta = 4;
unsigned CPEOffset = UserBBI.postOffset() + 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 = CSKY::BR32;
auto *NewMI = BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
.addMBB(NewMBB)
.getInstr();
unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
ImmBranches.push_back(
ImmBranch(&UserMBB->back(), MaxDisp, false, UncondBr));
BBInfo[UserMBB->getNumber()].Size += TII->getInstSizeInBytes(*NewMI);
adjustBBOffsetsAfter(UserMBB);
return;
}
}
const Align Align = MF->getAlignment();
unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
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) << '\n');
if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
BaseInsertOffset = UserBBI.postOffset() - 8;
LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
}
unsigned EndInsertOffset =
BaseInsertOffset + 4 + CPEMI->getOperand(2).getImm();
MachineBasicBlock::iterator MI = UserMI;
++MI;
unsigned CPUIndex = CPUserIndex + 1;
unsigned NumCPUsers = CPUsers.size();
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++;
}
}
NewMBB = splitBlockBeforeInstr(*--MI);
}
bool CSKYConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
CPUser &U = CPUsers[CPUserIndex];
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
unsigned CPI = CPEMI->getOperand(1).getIndex();
unsigned Size = CPEMI->getOperand(2).getImm();
unsigned UserOffset = getUserOffset(U);
int result = findInRangeCPEntry(U, UserOffset);
if (result == 1)
return false;
if (result == 2)
return true;
MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
MachineBasicBlock *NewMBB;
water_iterator IP;
if (findAvailableWater(U, UserOffset, IP)) {
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 = llvm::find(WaterList, WaterBB);
if (IP != WaterList.end())
NewWaterList.erase(WaterBB);
NewWaterList.insert(NewIsland);
}
if (IP != WaterList.end())
WaterList.erase(IP);
MF->insert(NewMBB->getIterator(), NewIsland);
updateForInsertedWaterBlock(NewIsland);
decrementCPEReferenceCount(CPI, CPEMI);
unsigned ID = createPICLabelUId();
U.HighWaterMark = NewIsland;
U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
.addImm(ID)
.addConstantPoolIndex(CPI)
.addImm(Size);
CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
++NumCPEs;
NewIsland->setAlignment(getCPEAlign(*U.CPEMI));
BBInfo[NewIsland->getNumber()].Size += Size;
adjustBBOffsetsAfter(&*--NewIsland->getIterator());
for (unsigned I = 0, E = UserMI->getNumOperands(); I != E; ++I)
if (UserMI->getOperand(I).isCPI()) {
UserMI->getOperand(I).setIndex(ID);
break;
}
LLVM_DEBUG(
dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
<< format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
return true;
}
void CSKYConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
MachineBasicBlock *CPEBB = CPEMI->getParent();
unsigned Size = CPEMI->getOperand(2).getImm();
CPEMI->eraseFromParent();
BBInfo[CPEBB->getNumber()].Size -= Size;
if (CPEBB->empty()) {
BBInfo[CPEBB->getNumber()].Size = 0;
CPEBB->setAlignment(Align(4));
} else {
CPEBB->setAlignment(getCPEAlign(*CPEBB->begin()));
}
adjustBBOffsetsAfter(CPEBB);
assert(!bbIsJumpedOver(CPEBB) && "How did this happen?");
}
bool CSKYConstantIslands::removeUnusedCPEntries() {
unsigned MadeChange = false;
for (unsigned I = 0, E = CPEntries.size(); I != E; ++I) {
std::vector<CPEntry> &CPEs = CPEntries[I];
for (unsigned J = 0, Ee = CPEs.size(); J != Ee; ++J) {
if (CPEs[J].RefCount == 0 && CPEs[J].CPEMI) {
removeDeadCPEMI(CPEs[J].CPEMI);
CPEs[J].CPEMI = nullptr;
MadeChange = true;
}
}
}
return MadeChange;
}
bool CSKYConstantIslands::isBBInRange(MachineInstr *MI,
MachineBasicBlock *DestBB,
unsigned MaxDisp) {
unsigned BrOffset = getOffsetOf(MI);
unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
<< " from " << printMBBReference(*MI->getParent())
<< " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
<< " to " << DestOffset << " offset "
<< int(DestOffset - BrOffset) << "\t" << *MI);
if (BrOffset <= DestOffset) {
if (DestOffset - BrOffset <= MaxDisp)
return true;
} else {
if (BrOffset - DestOffset <= MaxDisp)
return true;
}
return false;
}
bool CSKYConstantIslands::fixupImmediateBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
if (isBBInRange(MI, DestBB, Br.MaxDisp))
return false;
if (!Br.IsCond)
return fixupUnconditionalBr(Br);
return fixupConditionalBr(Br);
}
bool CSKYConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
MachineBasicBlock *MBB = MI->getParent();
if (!MFI->isLRSpilled())
report_fatal_error("underestimated function size");
Br.MaxDisp = ((1 << (26 - 1)) - 1) * 2;
MI->setDesc(TII->get(CSKY::BSR32_BR));
BBInfo[MBB->getNumber()].Size += 4;
adjustBBOffsetsAfter(MBB);
++NumUBrFixed;
LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
return true;
}
bool CSKYConstantIslands::fixupConditionalBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
SmallVector<MachineOperand, 4> Cond;
Cond.push_back(MachineOperand::CreateImm(MI->getOpcode()));
Cond.push_back(MI->getOperand(0));
TII->reverseBranchCondition(Cond);
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->isUnconditionalBranch()) {
MachineBasicBlock *NewDest = TII->getBranchDestBlock(*BMI);
if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
LLVM_DEBUG(
dbgs() << " Invert Bcc condition and swap its destination with "
<< *BMI);
BMI->getOperand(BMI->getNumExplicitOperands() - 1).setMBB(DestBB);
MI->getOperand(MI->getNumExplicitOperands() - 1).setMBB(NewDest);
MI->setDesc(TII->get(Cond[0].getImm()));
return true;
}
}
}
if (NeedSplit) {
splitBlockBeforeInstr(*MI);
int Delta = TII->getInstSizeInBytes(MBB->back());
BBInfo[MBB->getNumber()].Size -= 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(Cond[0].getImm()))
.addReg(MI->getOperand(0).getReg())
.addMBB(NextBB);
Br.MI = &MBB->back();
BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
MI->eraseFromParent();
adjustBBOffsetsAfter(MBB);
return true;
}
FunctionPass *llvm::createCSKYConstantIslandPass() {
return new CSKYConstantIslands();
}
INITIALIZE_PASS(CSKYConstantIslands, DEBUG_TYPE,
"CSKY constant island placement and branch shortening pass",
false, false)