Path: blob/main/contrib/llvm-project/llvm/lib/Target/CSKY/CSKYConstantIslandPass.cpp
35269 views
//===- CSKYConstantIslandPass.cpp - Emit PC Relative loads ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8//9// Loading constants inline is expensive on CSKY and it's in general better10// to place the constant nearby in code space and then it can be loaded with a11// simple 16/32 bit load instruction like lrw.12//13// The constants can be not just numbers but addresses of functions and labels.14// This can be particularly helpful in static relocation mode for embedded15// non-linux targets.16//17//===----------------------------------------------------------------------===//1819#include "CSKY.h"20#include "CSKYConstantPoolValue.h"21#include "CSKYMachineFunctionInfo.h"22#include "CSKYSubtarget.h"23#include "llvm/ADT/STLExtras.h"24#include "llvm/ADT/SmallSet.h"25#include "llvm/ADT/SmallVector.h"26#include "llvm/ADT/Statistic.h"27#include "llvm/ADT/StringRef.h"28#include "llvm/CodeGen/MachineBasicBlock.h"29#include "llvm/CodeGen/MachineConstantPool.h"30#include "llvm/CodeGen/MachineDominators.h"31#include "llvm/CodeGen/MachineFrameInfo.h"32#include "llvm/CodeGen/MachineFunction.h"33#include "llvm/CodeGen/MachineFunctionPass.h"34#include "llvm/CodeGen/MachineInstr.h"35#include "llvm/CodeGen/MachineInstrBuilder.h"36#include "llvm/CodeGen/MachineOperand.h"37#include "llvm/CodeGen/MachineRegisterInfo.h"38#include "llvm/Config/llvm-config.h"39#include "llvm/IR/Constants.h"40#include "llvm/IR/DataLayout.h"41#include "llvm/IR/DebugLoc.h"42#include "llvm/IR/Function.h"43#include "llvm/IR/Type.h"44#include "llvm/Support/CommandLine.h"45#include "llvm/Support/Compiler.h"46#include "llvm/Support/Debug.h"47#include "llvm/Support/ErrorHandling.h"48#include "llvm/Support/Format.h"49#include "llvm/Support/MathExtras.h"50#include "llvm/Support/raw_ostream.h"51#include <algorithm>52#include <cassert>53#include <cstdint>54#include <iterator>55#include <vector>5657using namespace llvm;5859#define DEBUG_TYPE "CSKY-constant-islands"6061STATISTIC(NumCPEs, "Number of constpool entries");62STATISTIC(NumSplit, "Number of uncond branches inserted");63STATISTIC(NumCBrFixed, "Number of cond branches fixed");64STATISTIC(NumUBrFixed, "Number of uncond branches fixed");6566namespace {6768using Iter = MachineBasicBlock::iterator;69using ReverseIter = MachineBasicBlock::reverse_iterator;7071/// CSKYConstantIslands - Due to limited PC-relative displacements, CSKY72/// requires constant pool entries to be scattered among the instructions73/// inside a function. To do this, it completely ignores the normal LLVM74/// constant pool; instead, it places constants wherever it feels like with75/// special instructions.76///77/// The terminology used in this pass includes:78/// Islands - Clumps of constants placed in the function.79/// Water - Potential places where an island could be formed.80/// CPE - A constant pool entry that has been placed somewhere, which81/// tracks a list of users.8283class CSKYConstantIslands : public MachineFunctionPass {84/// BasicBlockInfo - Information about the offset and size of a single85/// basic block.86struct BasicBlockInfo {87/// Offset - Distance from the beginning of the function to the beginning88/// of this basic block.89///90/// Offsets are computed assuming worst case padding before an aligned91/// block. This means that subtracting basic block offsets always gives a92/// conservative estimate of the real distance which may be smaller.93///94/// Because worst case padding is used, the computed offset of an aligned95/// block may not actually be aligned.96unsigned Offset = 0;9798/// Size - Size of the basic block in bytes. If the block contains99/// inline assembly, this is a worst case estimate.100///101/// The size does not include any alignment padding whether from the102/// beginning of the block, or from an aligned jump table at the end.103unsigned Size = 0;104105BasicBlockInfo() = default;106107unsigned postOffset() const { return Offset + Size; }108};109110std::vector<BasicBlockInfo> BBInfo;111112/// WaterList - A sorted list of basic blocks where islands could be placed113/// (i.e. blocks that don't fall through to the following block, due114/// to a return, unreachable, or unconditional branch).115std::vector<MachineBasicBlock *> WaterList;116117/// NewWaterList - The subset of WaterList that was created since the118/// previous iteration by inserting unconditional branches.119SmallSet<MachineBasicBlock *, 4> NewWaterList;120121using water_iterator = std::vector<MachineBasicBlock *>::iterator;122123/// CPUser - One user of a constant pool, keeping the machine instruction124/// pointer, the constant pool being referenced, and the max displacement125/// allowed from the instruction to the CP. The HighWaterMark records the126/// highest basic block where a new CPEntry can be placed. To ensure this127/// pass terminates, the CP entries are initially placed at the end of the128/// function and then move monotonically to lower addresses. The129/// exception to this rule is when the current CP entry for a particular130/// CPUser is out of range, but there is another CP entry for the same131/// constant value in range. We want to use the existing in-range CP132/// entry, but if it later moves out of range, the search for new water133/// should resume where it left off. The HighWaterMark is used to record134/// that point.135struct CPUser {136MachineInstr *MI;137MachineInstr *CPEMI;138MachineBasicBlock *HighWaterMark;139140private:141unsigned MaxDisp;142143public:144bool NegOk;145146CPUser(MachineInstr *Mi, MachineInstr *Cpemi, unsigned Maxdisp, bool Neg)147: MI(Mi), CPEMI(Cpemi), MaxDisp(Maxdisp), NegOk(Neg) {148HighWaterMark = CPEMI->getParent();149}150151/// getMaxDisp - Returns the maximum displacement supported by MI.152unsigned getMaxDisp() const { return MaxDisp - 16; }153154void setMaxDisp(unsigned Val) { MaxDisp = Val; }155};156157/// CPUsers - Keep track of all of the machine instructions that use various158/// constant pools and their max displacement.159std::vector<CPUser> CPUsers;160161/// CPEntry - One per constant pool entry, keeping the machine instruction162/// pointer, the constpool index, and the number of CPUser's which163/// reference this entry.164struct CPEntry {165MachineInstr *CPEMI;166unsigned CPI;167unsigned RefCount;168169CPEntry(MachineInstr *Cpemi, unsigned Cpi, unsigned Rc = 0)170: CPEMI(Cpemi), CPI(Cpi), RefCount(Rc) {}171};172173/// CPEntries - Keep track of all of the constant pool entry machine174/// instructions. For each original constpool index (i.e. those that175/// existed upon entry to this pass), it keeps a vector of entries.176/// Original elements are cloned as we go along; the clones are177/// put in the vector of the original element, but have distinct CPIs.178std::vector<std::vector<CPEntry>> CPEntries;179180/// ImmBranch - One per immediate branch, keeping the machine instruction181/// pointer, conditional or unconditional, the max displacement,182/// and (if isCond is true) the corresponding unconditional branch183/// opcode.184struct ImmBranch {185MachineInstr *MI;186unsigned MaxDisp : 31;187bool IsCond : 1;188int UncondBr;189190ImmBranch(MachineInstr *Mi, unsigned Maxdisp, bool Cond, int Ubr)191: MI(Mi), MaxDisp(Maxdisp), IsCond(Cond), UncondBr(Ubr) {}192};193194/// ImmBranches - Keep track of all the immediate branch instructions.195///196std::vector<ImmBranch> ImmBranches;197198const CSKYSubtarget *STI = nullptr;199const CSKYInstrInfo *TII;200CSKYMachineFunctionInfo *MFI;201MachineFunction *MF = nullptr;202MachineConstantPool *MCP = nullptr;203204unsigned PICLabelUId;205206void initPICLabelUId(unsigned UId) { PICLabelUId = UId; }207208unsigned createPICLabelUId() { return PICLabelUId++; }209210public:211static char ID;212213CSKYConstantIslands() : MachineFunctionPass(ID) {}214215StringRef getPassName() const override { return "CSKY Constant Islands"; }216217bool runOnMachineFunction(MachineFunction &F) override;218219void getAnalysisUsage(AnalysisUsage &AU) const override {220AU.addRequired<MachineDominatorTreeWrapperPass>();221MachineFunctionPass::getAnalysisUsage(AU);222}223224MachineFunctionProperties getRequiredProperties() const override {225return MachineFunctionProperties().set(226MachineFunctionProperties::Property::NoVRegs);227}228229void doInitialPlacement(std::vector<MachineInstr *> &CPEMIs);230CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);231Align getCPEAlign(const MachineInstr &CPEMI);232void initializeFunctionInfo(const std::vector<MachineInstr *> &CPEMIs);233unsigned getOffsetOf(MachineInstr *MI) const;234unsigned getUserOffset(CPUser &) const;235void dumpBBs();236237bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, unsigned Disp,238bool NegativeOK);239bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,240const CPUser &U);241242void computeBlockSize(MachineBasicBlock *MBB);243MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);244void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);245void adjustBBOffsetsAfter(MachineBasicBlock *BB);246bool decrementCPEReferenceCount(unsigned CPI, MachineInstr *CPEMI);247int findInRangeCPEntry(CPUser &U, unsigned UserOffset);248bool findAvailableWater(CPUser &U, unsigned UserOffset,249water_iterator &WaterIter);250void createNewWater(unsigned CPUserIndex, unsigned UserOffset,251MachineBasicBlock *&NewMBB);252bool handleConstantPoolUser(unsigned CPUserIndex);253void removeDeadCPEMI(MachineInstr *CPEMI);254bool removeUnusedCPEntries();255bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,256MachineInstr *CPEMI, unsigned Disp, bool NegOk,257bool DoDump = false);258bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, CPUser &U,259unsigned &Growth);260bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);261bool fixupImmediateBr(ImmBranch &Br);262bool fixupConditionalBr(ImmBranch &Br);263bool fixupUnconditionalBr(ImmBranch &Br);264};265} // end anonymous namespace266267char CSKYConstantIslands::ID = 0;268269bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,270unsigned TrialOffset,271const CPUser &U) {272return isOffsetInRange(UserOffset, TrialOffset, U.getMaxDisp(), U.NegOk);273}274275#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)276/// print block size and offset information - debugging277LLVM_DUMP_METHOD void CSKYConstantIslands::dumpBBs() {278for (unsigned J = 0, E = BBInfo.size(); J != E; ++J) {279const BasicBlockInfo &BBI = BBInfo[J];280dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)281<< format(" size=%#x\n", BBInfo[J].Size);282}283}284#endif285286bool CSKYConstantIslands::runOnMachineFunction(MachineFunction &Mf) {287MF = &Mf;288MCP = Mf.getConstantPool();289STI = &Mf.getSubtarget<CSKYSubtarget>();290291LLVM_DEBUG(dbgs() << "***** CSKYConstantIslands: "292<< MCP->getConstants().size() << " CP entries, aligned to "293<< MCP->getConstantPoolAlign().value() << " bytes *****\n");294295TII = STI->getInstrInfo();296MFI = MF->getInfo<CSKYMachineFunctionInfo>();297298// This pass invalidates liveness information when it splits basic blocks.299MF->getRegInfo().invalidateLiveness();300301// Renumber all of the machine basic blocks in the function, guaranteeing that302// the numbers agree with the position of the block in the function.303MF->RenumberBlocks();304305bool MadeChange = false;306307// Perform the initial placement of the constant pool entries. To start with,308// we put them all at the end of the function.309std::vector<MachineInstr *> CPEMIs;310if (!MCP->isEmpty())311doInitialPlacement(CPEMIs);312313/// The next UID to take is the first unused one.314initPICLabelUId(CPEMIs.size());315316// Do the initial scan of the function, building up information about the317// sizes of each block, the location of all the water, and finding all of the318// constant pool users.319initializeFunctionInfo(CPEMIs);320CPEMIs.clear();321LLVM_DEBUG(dumpBBs());322323/// Remove dead constant pool entries.324MadeChange |= removeUnusedCPEntries();325326// Iteratively place constant pool entries and fix up branches until there327// is no change.328unsigned NoCPIters = 0, NoBRIters = 0;329(void)NoBRIters;330while (true) {331LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');332bool CPChange = false;333for (unsigned I = 0, E = CPUsers.size(); I != E; ++I)334CPChange |= handleConstantPoolUser(I);335if (CPChange && ++NoCPIters > 30)336report_fatal_error("Constant Island pass failed to converge!");337LLVM_DEBUG(dumpBBs());338339// Clear NewWaterList now. If we split a block for branches, it should340// appear as "new water" for the next iteration of constant pool placement.341NewWaterList.clear();342343LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');344bool BRChange = false;345for (unsigned I = 0, E = ImmBranches.size(); I != E; ++I)346BRChange |= fixupImmediateBr(ImmBranches[I]);347if (BRChange && ++NoBRIters > 30)348report_fatal_error("Branch Fix Up pass failed to converge!");349LLVM_DEBUG(dumpBBs());350if (!CPChange && !BRChange)351break;352MadeChange = true;353}354355LLVM_DEBUG(dbgs() << '\n'; dumpBBs());356357BBInfo.clear();358WaterList.clear();359CPUsers.clear();360CPEntries.clear();361ImmBranches.clear();362return MadeChange;363}364365/// doInitialPlacement - Perform the initial placement of the constant pool366/// entries. To start with, we put them all at the end of the function.367void CSKYConstantIslands::doInitialPlacement(368std::vector<MachineInstr *> &CPEMIs) {369// Create the basic block to hold the CPE's.370MachineBasicBlock *BB = MF->CreateMachineBasicBlock();371MF->push_back(BB);372373// MachineConstantPool measures alignment in bytes. We measure in log2(bytes).374const Align MaxAlign = MCP->getConstantPoolAlign();375376// Mark the basic block as required by the const-pool.377BB->setAlignment(Align(2));378379// The function needs to be as aligned as the basic blocks. The linker may380// move functions around based on their alignment.381MF->ensureAlignment(BB->getAlignment());382383// Order the entries in BB by descending alignment. That ensures correct384// alignment of all entries as long as BB is sufficiently aligned. Keep385// track of the insertion point for each alignment. We are going to bucket386// sort the entries as they are created.387SmallVector<MachineBasicBlock::iterator, 8> InsPoint(Log2(MaxAlign) + 1,388BB->end());389390// Add all of the constants from the constant pool to the end block, use an391// identity mapping of CPI's to CPE's.392const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();393394const DataLayout &TD = MF->getDataLayout();395for (unsigned I = 0, E = CPs.size(); I != E; ++I) {396unsigned Size = CPs[I].getSizeInBytes(TD);397assert(Size >= 4 && "Too small constant pool entry");398Align Alignment = CPs[I].getAlign();399// Verify that all constant pool entries are a multiple of their alignment.400// If not, we would have to pad them out so that instructions stay aligned.401assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");402403// Insert CONSTPOOL_ENTRY before entries with a smaller alignment.404unsigned LogAlign = Log2(Alignment);405MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];406407MachineInstr *CPEMI =408BuildMI(*BB, InsAt, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))409.addImm(I)410.addConstantPoolIndex(I)411.addImm(Size);412413CPEMIs.push_back(CPEMI);414415// Ensure that future entries with higher alignment get inserted before416// CPEMI. This is bucket sort with iterators.417for (unsigned A = LogAlign + 1; A <= Log2(MaxAlign); ++A)418if (InsPoint[A] == InsAt)419InsPoint[A] = CPEMI;420// Add a new CPEntry, but no corresponding CPUser yet.421CPEntries.emplace_back(1, CPEntry(CPEMI, I));422++NumCPEs;423LLVM_DEBUG(dbgs() << "Moved CPI#" << I << " to end of function, size = "424<< Size << ", align = " << Alignment.value() << '\n');425}426LLVM_DEBUG(BB->dump());427}428429/// BBHasFallthrough - Return true if the specified basic block can fallthrough430/// into the block immediately after it.431static bool bbHasFallthrough(MachineBasicBlock *MBB) {432// Get the next machine basic block in the function.433MachineFunction::iterator MBBI = MBB->getIterator();434// Can't fall off end of function.435if (std::next(MBBI) == MBB->getParent()->end())436return false;437438MachineBasicBlock *NextBB = &*std::next(MBBI);439for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),440E = MBB->succ_end();441I != E; ++I)442if (*I == NextBB)443return true;444445return false;446}447448/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,449/// look up the corresponding CPEntry.450CSKYConstantIslands::CPEntry *451CSKYConstantIslands::findConstPoolEntry(unsigned CPI,452const MachineInstr *CPEMI) {453std::vector<CPEntry> &CPEs = CPEntries[CPI];454// Number of entries per constpool index should be small, just do a455// linear search.456for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {457if (CPEs[I].CPEMI == CPEMI)458return &CPEs[I];459}460return nullptr;461}462463/// getCPEAlign - Returns the required alignment of the constant pool entry464/// represented by CPEMI. Alignment is measured in log2(bytes) units.465Align CSKYConstantIslands::getCPEAlign(const MachineInstr &CPEMI) {466assert(CPEMI.getOpcode() == CSKY::CONSTPOOL_ENTRY);467468unsigned CPI = CPEMI.getOperand(1).getIndex();469assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");470return MCP->getConstants()[CPI].getAlign();471}472473/// initializeFunctionInfo - Do the initial scan of the function, building up474/// information about the sizes of each block, the location of all the water,475/// and finding all of the constant pool users.476void CSKYConstantIslands::initializeFunctionInfo(477const std::vector<MachineInstr *> &CPEMIs) {478BBInfo.clear();479BBInfo.resize(MF->getNumBlockIDs());480481// First thing, compute the size of all basic blocks, and see if the function482// has any inline assembly in it. If so, we have to be conservative about483// alignment assumptions, as we don't know for sure the size of any484// instructions in the inline assembly.485for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)486computeBlockSize(&*I);487488// Compute block offsets.489adjustBBOffsetsAfter(&MF->front());490491// Now go back through the instructions and build up our data structures.492for (MachineBasicBlock &MBB : *MF) {493// If this block doesn't fall through into the next MBB, then this is494// 'water' that a constant pool island could be placed.495if (!bbHasFallthrough(&MBB))496WaterList.push_back(&MBB);497for (MachineInstr &MI : MBB) {498if (MI.isDebugInstr())499continue;500501int Opc = MI.getOpcode();502if (MI.isBranch() && !MI.isIndirectBranch()) {503bool IsCond = MI.isConditionalBranch();504unsigned Bits = 0;505unsigned Scale = 1;506int UOpc = CSKY::BR32;507508switch (MI.getOpcode()) {509case CSKY::BR16:510case CSKY::BF16:511case CSKY::BT16:512Bits = 10;513Scale = 2;514break;515default:516Bits = 16;517Scale = 2;518break;519}520521// Record this immediate branch.522unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;523ImmBranches.push_back(ImmBranch(&MI, MaxOffs, IsCond, UOpc));524}525526if (Opc == CSKY::CONSTPOOL_ENTRY)527continue;528529// Scan the instructions for constant pool operands.530for (unsigned Op = 0, E = MI.getNumOperands(); Op != E; ++Op)531if (MI.getOperand(Op).isCPI()) {532// We found one. The addressing mode tells us the max displacement533// from the PC that this instruction permits.534535// Basic size info comes from the TSFlags field.536unsigned Bits = 0;537unsigned Scale = 1;538bool NegOk = false;539540switch (Opc) {541default:542llvm_unreachable("Unknown addressing mode for CP reference!");543case CSKY::MOVIH32:544case CSKY::ORI32:545continue;546case CSKY::PseudoTLSLA32:547case CSKY::JSRI32:548case CSKY::JMPI32:549case CSKY::LRW32:550case CSKY::LRW32_Gen:551Bits = 16;552Scale = 4;553break;554case CSKY::f2FLRW_S:555case CSKY::f2FLRW_D:556Bits = 8;557Scale = 4;558break;559case CSKY::GRS32:560Bits = 17;561Scale = 2;562NegOk = true;563break;564}565// Remember that this is a user of a CP entry.566unsigned CPI = MI.getOperand(Op).getIndex();567MachineInstr *CPEMI = CPEMIs[CPI];568unsigned MaxOffs = ((1 << Bits) - 1) * Scale;569CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk));570571// Increment corresponding CPEntry reference count.572CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);573assert(CPE && "Cannot find a corresponding CPEntry!");574CPE->RefCount++;575}576}577}578}579580/// computeBlockSize - Compute the size and some alignment information for MBB.581/// This function updates BBInfo directly.582void CSKYConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {583BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];584BBI.Size = 0;585586for (const MachineInstr &MI : *MBB)587BBI.Size += TII->getInstSizeInBytes(MI);588}589590/// getOffsetOf - Return the current offset of the specified machine instruction591/// from the start of the function. This offset changes as stuff is moved592/// around inside the function.593unsigned CSKYConstantIslands::getOffsetOf(MachineInstr *MI) const {594MachineBasicBlock *MBB = MI->getParent();595596// The offset is composed of two things: the sum of the sizes of all MBB's597// before this instruction's block, and the offset from the start of the block598// it is in.599unsigned Offset = BBInfo[MBB->getNumber()].Offset;600601// Sum instructions before MI in MBB.602for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {603assert(I != MBB->end() && "Didn't find MI in its own basic block?");604Offset += TII->getInstSizeInBytes(*I);605}606return Offset;607}608609/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB610/// ID.611static bool compareMbbNumbers(const MachineBasicBlock *LHS,612const MachineBasicBlock *RHS) {613return LHS->getNumber() < RHS->getNumber();614}615616/// updateForInsertedWaterBlock - When a block is newly inserted into the617/// machine function, it upsets all of the block numbers. Renumber the blocks618/// and update the arrays that parallel this numbering.619void CSKYConstantIslands::updateForInsertedWaterBlock(620MachineBasicBlock *NewBB) {621// Renumber the MBB's to keep them consecutive.622NewBB->getParent()->RenumberBlocks(NewBB);623624// Insert an entry into BBInfo to align it properly with the (newly625// renumbered) block numbers.626BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());627628// Next, update WaterList. Specifically, we need to add NewMBB as having629// available water after it.630water_iterator IP = llvm::lower_bound(WaterList, NewBB, compareMbbNumbers);631WaterList.insert(IP, NewBB);632}633634unsigned CSKYConstantIslands::getUserOffset(CPUser &U) const {635unsigned UserOffset = getOffsetOf(U.MI);636637UserOffset &= ~3u;638639return UserOffset;640}641642/// Split the basic block containing MI into two blocks, which are joined by643/// an unconditional branch. Update data structures and renumber blocks to644/// account for this change and returns the newly created block.645MachineBasicBlock *646CSKYConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {647MachineBasicBlock *OrigBB = MI.getParent();648649// Create a new MBB for the code after the OrigBB.650MachineBasicBlock *NewBB =651MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());652MachineFunction::iterator MBBI = ++OrigBB->getIterator();653MF->insert(MBBI, NewBB);654655// Splice the instructions starting with MI over to NewBB.656NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());657658// Add an unconditional branch from OrigBB to NewBB.659// Note the new unconditional branch is not being recorded.660// There doesn't seem to be meaningful DebugInfo available; this doesn't661// correspond to anything in the source.662663// TODO: Add support for 16bit instr.664BuildMI(OrigBB, DebugLoc(), TII->get(CSKY::BR32)).addMBB(NewBB);665++NumSplit;666667// Update the CFG. All succs of OrigBB are now succs of NewBB.668NewBB->transferSuccessors(OrigBB);669670// OrigBB branches to NewBB.671OrigBB->addSuccessor(NewBB);672673// Update internal data structures to account for the newly inserted MBB.674// This is almost the same as updateForInsertedWaterBlock, except that675// the Water goes after OrigBB, not NewBB.676MF->RenumberBlocks(NewBB);677678// Insert an entry into BBInfo to align it properly with the (newly679// renumbered) block numbers.680BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());681682// Next, update WaterList. Specifically, we need to add OrigMBB as having683// available water after it (but not if it's already there, which happens684// when splitting before a conditional branch that is followed by an685// unconditional branch - in that case we want to insert NewBB).686water_iterator IP = llvm::lower_bound(WaterList, OrigBB, compareMbbNumbers);687MachineBasicBlock *WaterBB = *IP;688if (WaterBB == OrigBB)689WaterList.insert(std::next(IP), NewBB);690else691WaterList.insert(IP, OrigBB);692NewWaterList.insert(OrigBB);693694// Figure out how large the OrigBB is. As the first half of the original695// block, it cannot contain a tablejump. The size includes696// the new jump we added. (It should be possible to do this without697// recounting everything, but it's very confusing, and this is rarely698// executed.)699computeBlockSize(OrigBB);700701// Figure out how large the NewMBB is. As the second half of the original702// block, it may contain a tablejump.703computeBlockSize(NewBB);704705// All BBOffsets following these blocks must be modified.706adjustBBOffsetsAfter(OrigBB);707708return NewBB;709}710711/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool712/// reference) is within MaxDisp of TrialOffset (a proposed location of a713/// constant pool entry).714bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,715unsigned TrialOffset,716unsigned MaxDisp, bool NegativeOK) {717if (UserOffset <= TrialOffset) {718// User before the Trial.719if (TrialOffset - UserOffset <= MaxDisp)720return true;721} else if (NegativeOK) {722if (UserOffset - TrialOffset <= MaxDisp)723return true;724}725return false;726}727728/// isWaterInRange - Returns true if a CPE placed after the specified729/// Water (a basic block) will be in range for the specific MI.730///731/// Compute how much the function will grow by inserting a CPE after Water.732bool CSKYConstantIslands::isWaterInRange(unsigned UserOffset,733MachineBasicBlock *Water, CPUser &U,734unsigned &Growth) {735unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();736unsigned NextBlockOffset;737Align NextBlockAlignment;738MachineFunction::const_iterator NextBlock = ++Water->getIterator();739if (NextBlock == MF->end()) {740NextBlockOffset = BBInfo[Water->getNumber()].postOffset();741NextBlockAlignment = Align(4);742} else {743NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;744NextBlockAlignment = NextBlock->getAlignment();745}746unsigned Size = U.CPEMI->getOperand(2).getImm();747unsigned CPEEnd = CPEOffset + Size;748749// The CPE may be able to hide in the alignment padding before the next750// block. It may also cause more padding to be required if it is more aligned751// that the next block.752if (CPEEnd > NextBlockOffset) {753Growth = CPEEnd - NextBlockOffset;754// Compute the padding that would go at the end of the CPE to align the next755// block.756Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);757758// If the CPE is to be inserted before the instruction, that will raise759// the offset of the instruction. Also account for unknown alignment padding760// in blocks between CPE and the user.761if (CPEOffset < UserOffset)762UserOffset += Growth;763} else764// CPE fits in existing padding.765Growth = 0;766767return isOffsetInRange(UserOffset, CPEOffset, U);768}769770/// isCPEntryInRange - Returns true if the distance between specific MI and771/// specific ConstPool entry instruction can fit in MI's displacement field.772bool CSKYConstantIslands::isCPEntryInRange(MachineInstr *MI,773unsigned UserOffset,774MachineInstr *CPEMI,775unsigned MaxDisp, bool NegOk,776bool DoDump) {777unsigned CPEOffset = getOffsetOf(CPEMI);778779if (DoDump) {780LLVM_DEBUG({781unsigned Block = MI->getParent()->getNumber();782const BasicBlockInfo &BBI = BBInfo[Block];783dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()784<< " max delta=" << MaxDisp785<< format(" insn address=%#x", UserOffset) << " in "786<< printMBBReference(*MI->getParent()) << ": "787<< format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI788<< format("CPE address=%#x offset=%+d: ", CPEOffset,789int(CPEOffset - UserOffset));790});791}792793return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);794}795796#ifndef NDEBUG797/// BBIsJumpedOver - Return true of the specified basic block's only predecessor798/// unconditionally branches to its only successor.799static bool bbIsJumpedOver(MachineBasicBlock *MBB) {800if (MBB->pred_size() != 1 || MBB->succ_size() != 1)801return false;802MachineBasicBlock *Succ = *MBB->succ_begin();803MachineBasicBlock *Pred = *MBB->pred_begin();804MachineInstr *PredMI = &Pred->back();805if (PredMI->getOpcode() == CSKY::BR32 /*TODO: change to 16bit instr. */)806return PredMI->getOperand(0).getMBB() == Succ;807return false;808}809#endif810811void CSKYConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {812unsigned BBNum = BB->getNumber();813for (unsigned I = BBNum + 1, E = MF->getNumBlockIDs(); I < E; ++I) {814// Get the offset and known bits at the end of the layout predecessor.815// Include the alignment of the current block.816unsigned Offset = BBInfo[I - 1].Offset + BBInfo[I - 1].Size;817BBInfo[I].Offset = Offset;818}819}820821/// decrementCPEReferenceCount - find the constant pool entry with index CPI822/// and instruction CPEMI, and decrement its refcount. If the refcount823/// becomes 0 remove the entry and instruction. Returns true if we removed824/// the entry, false if we didn't.825bool CSKYConstantIslands::decrementCPEReferenceCount(unsigned CPI,826MachineInstr *CPEMI) {827// Find the old entry. Eliminate it if it is no longer used.828CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);829assert(CPE && "Unexpected!");830if (--CPE->RefCount == 0) {831removeDeadCPEMI(CPEMI);832CPE->CPEMI = nullptr;833--NumCPEs;834return true;835}836return false;837}838839/// LookForCPEntryInRange - see if the currently referenced CPE is in range;840/// if not, see if an in-range clone of the CPE is in range, and if so,841/// change the data structures so the user references the clone. Returns:842/// 0 = no existing entry found843/// 1 = entry found, and there were no code insertions or deletions844/// 2 = entry found, and there were code insertions or deletions845int CSKYConstantIslands::findInRangeCPEntry(CPUser &U, unsigned UserOffset) {846MachineInstr *UserMI = U.MI;847MachineInstr *CPEMI = U.CPEMI;848849// Check to see if the CPE is already in-range.850if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,851true)) {852LLVM_DEBUG(dbgs() << "In range\n");853return 1;854}855856// No. Look for previously created clones of the CPE that are in range.857unsigned CPI = CPEMI->getOperand(1).getIndex();858std::vector<CPEntry> &CPEs = CPEntries[CPI];859for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {860// We already tried this one861if (CPEs[I].CPEMI == CPEMI)862continue;863// Removing CPEs can leave empty entries, skip864if (CPEs[I].CPEMI == nullptr)865continue;866if (isCPEntryInRange(UserMI, UserOffset, CPEs[I].CPEMI, U.getMaxDisp(),867U.NegOk)) {868LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"869<< CPEs[I].CPI << "\n");870// Point the CPUser node to the replacement871U.CPEMI = CPEs[I].CPEMI;872// Change the CPI in the instruction operand to refer to the clone.873for (unsigned J = 0, E = UserMI->getNumOperands(); J != E; ++J)874if (UserMI->getOperand(J).isCPI()) {875UserMI->getOperand(J).setIndex(CPEs[I].CPI);876break;877}878// Adjust the refcount of the clone...879CPEs[I].RefCount++;880// ...and the original. If we didn't remove the old entry, none of the881// addresses changed, so we don't need another pass.882return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;883}884}885return 0;886}887888/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in889/// the specific unconditional branch instruction.890static inline unsigned getUnconditionalBrDisp(int Opc) {891unsigned Bits, Scale;892893switch (Opc) {894case CSKY::BR16:895Bits = 10;896Scale = 2;897break;898case CSKY::BR32:899Bits = 16;900Scale = 2;901break;902default:903llvm_unreachable("");904}905906unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;907return MaxOffs;908}909910/// findAvailableWater - Look for an existing entry in the WaterList in which911/// we can place the CPE referenced from U so it's within range of U's MI.912/// Returns true if found, false if not. If it returns true, WaterIter913/// is set to the WaterList entry.914/// To ensure that this pass915/// terminates, the CPE location for a particular CPUser is only allowed to916/// move to a lower address, so search backward from the end of the list and917/// prefer the first water that is in range.918bool CSKYConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,919water_iterator &WaterIter) {920if (WaterList.empty())921return false;922923unsigned BestGrowth = ~0u;924for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;925--IP) {926MachineBasicBlock *WaterBB = *IP;927// Check if water is in range and is either at a lower address than the928// current "high water mark" or a new water block that was created since929// the previous iteration by inserting an unconditional branch. In the930// latter case, we want to allow resetting the high water mark back to931// this new water since we haven't seen it before. Inserting branches932// should be relatively uncommon and when it does happen, we want to be933// sure to take advantage of it for all the CPEs near that block, so that934// we don't insert more branches than necessary.935unsigned Growth;936if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&937(WaterBB->getNumber() < U.HighWaterMark->getNumber() ||938NewWaterList.count(WaterBB)) &&939Growth < BestGrowth) {940// This is the least amount of required padding seen so far.941BestGrowth = Growth;942WaterIter = IP;943LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)944<< " Growth=" << Growth << '\n');945946// Keep looking unless it is perfect.947if (BestGrowth == 0)948return true;949}950if (IP == B)951break;952}953return BestGrowth != ~0u;954}955956/// createNewWater - No existing WaterList entry will work for957/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the958/// block is used if in range, and the conditional branch munged so control959/// flow is correct. Otherwise the block is split to create a hole with an960/// unconditional branch around it. In either case NewMBB is set to a961/// block following which the new island can be inserted (the WaterList962/// is not adjusted).963void CSKYConstantIslands::createNewWater(unsigned CPUserIndex,964unsigned UserOffset,965MachineBasicBlock *&NewMBB) {966CPUser &U = CPUsers[CPUserIndex];967MachineInstr *UserMI = U.MI;968MachineInstr *CPEMI = U.CPEMI;969MachineBasicBlock *UserMBB = UserMI->getParent();970const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];971972// If the block does not end in an unconditional branch already, and if the973// end of the block is within range, make new water there.974if (bbHasFallthrough(UserMBB)) {975// Size of branch to insert.976unsigned Delta = 4;977// Compute the offset where the CPE will begin.978unsigned CPEOffset = UserBBI.postOffset() + Delta;979980if (isOffsetInRange(UserOffset, CPEOffset, U)) {981LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)982<< format(", expected CPE offset %#x\n", CPEOffset));983NewMBB = &*++UserMBB->getIterator();984// Add an unconditional branch from UserMBB to fallthrough block. Record985// it for branch lengthening; this new branch will not get out of range,986// but if the preceding conditional branch is out of range, the targets987// will be exchanged, and the altered branch may be out of range, so the988// machinery has to know about it.989990// TODO: Add support for 16bit instr.991int UncondBr = CSKY::BR32;992auto *NewMI = BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))993.addMBB(NewMBB)994.getInstr();995unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);996ImmBranches.push_back(997ImmBranch(&UserMBB->back(), MaxDisp, false, UncondBr));998BBInfo[UserMBB->getNumber()].Size += TII->getInstSizeInBytes(*NewMI);999adjustBBOffsetsAfter(UserMBB);1000return;1001}1002}10031004// What a big block. Find a place within the block to split it.10051006// Try to split the block so it's fully aligned. Compute the latest split1007// point where we can add a 4-byte branch instruction, and then align to1008// Align which is the largest possible alignment in the function.1009const Align Align = MF->getAlignment();1010unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();1011LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",1012BaseInsertOffset));10131014// The 4 in the following is for the unconditional branch we'll be inserting1015// Alignment of the island is handled1016// inside isOffsetInRange.1017BaseInsertOffset -= 4;10181019LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)1020<< " la=" << Log2(Align) << '\n');10211022// This could point off the end of the block if we've already got constant1023// pool entries following this block; only the last one is in the water list.1024// Back past any possible branches (allow for a conditional and a maximally1025// long unconditional).1026if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {1027BaseInsertOffset = UserBBI.postOffset() - 8;1028LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));1029}1030unsigned EndInsertOffset =1031BaseInsertOffset + 4 + CPEMI->getOperand(2).getImm();1032MachineBasicBlock::iterator MI = UserMI;1033++MI;1034unsigned CPUIndex = CPUserIndex + 1;1035unsigned NumCPUsers = CPUsers.size();1036for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);1037Offset < BaseInsertOffset;1038Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {1039assert(MI != UserMBB->end() && "Fell off end of block");1040if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {1041CPUser &U = CPUsers[CPUIndex];1042if (!isOffsetInRange(Offset, EndInsertOffset, U)) {1043// Shift intertion point by one unit of alignment so it is within reach.1044BaseInsertOffset -= Align.value();1045EndInsertOffset -= Align.value();1046}1047// This is overly conservative, as we don't account for CPEMIs being1048// reused within the block, but it doesn't matter much. Also assume CPEs1049// are added in order with alignment padding. We may eventually be able1050// to pack the aligned CPEs better.1051EndInsertOffset += U.CPEMI->getOperand(2).getImm();1052CPUIndex++;1053}1054}10551056NewMBB = splitBlockBeforeInstr(*--MI);1057}10581059/// handleConstantPoolUser - Analyze the specified user, checking to see if it1060/// is out-of-range. If so, pick up the constant pool value and move it some1061/// place in-range. Return true if we changed any addresses (thus must run1062/// another pass of branch lengthening), false otherwise.1063bool CSKYConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {1064CPUser &U = CPUsers[CPUserIndex];1065MachineInstr *UserMI = U.MI;1066MachineInstr *CPEMI = U.CPEMI;1067unsigned CPI = CPEMI->getOperand(1).getIndex();1068unsigned Size = CPEMI->getOperand(2).getImm();1069// Compute this only once, it's expensive.1070unsigned UserOffset = getUserOffset(U);10711072// See if the current entry is within range, or there is a clone of it1073// in range.1074int result = findInRangeCPEntry(U, UserOffset);1075if (result == 1)1076return false;1077if (result == 2)1078return true;10791080// Look for water where we can place this CPE.1081MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();1082MachineBasicBlock *NewMBB;1083water_iterator IP;1084if (findAvailableWater(U, UserOffset, IP)) {1085LLVM_DEBUG(dbgs() << "Found water in range\n");1086MachineBasicBlock *WaterBB = *IP;10871088// If the original WaterList entry was "new water" on this iteration,1089// propagate that to the new island. This is just keeping NewWaterList1090// updated to match the WaterList, which will be updated below.1091if (NewWaterList.erase(WaterBB))1092NewWaterList.insert(NewIsland);10931094// The new CPE goes before the following block (NewMBB).1095NewMBB = &*++WaterBB->getIterator();1096} else {1097LLVM_DEBUG(dbgs() << "No water found\n");1098createNewWater(CPUserIndex, UserOffset, NewMBB);10991100// splitBlockBeforeInstr adds to WaterList, which is important when it is1101// called while handling branches so that the water will be seen on the1102// next iteration for constant pools, but in this context, we don't want1103// it. Check for this so it will be removed from the WaterList.1104// Also remove any entry from NewWaterList.1105MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();1106IP = llvm::find(WaterList, WaterBB);1107if (IP != WaterList.end())1108NewWaterList.erase(WaterBB);11091110// We are adding new water. Update NewWaterList.1111NewWaterList.insert(NewIsland);1112}11131114// Remove the original WaterList entry; we want subsequent insertions in1115// this vicinity to go after the one we're about to insert. This1116// considerably reduces the number of times we have to move the same CPE1117// more than once and is also important to ensure the algorithm terminates.1118if (IP != WaterList.end())1119WaterList.erase(IP);11201121// Okay, we know we can put an island before NewMBB now, do it!1122MF->insert(NewMBB->getIterator(), NewIsland);11231124// Update internal data structures to account for the newly inserted MBB.1125updateForInsertedWaterBlock(NewIsland);11261127// Decrement the old entry, and remove it if refcount becomes 0.1128decrementCPEReferenceCount(CPI, CPEMI);11291130// No existing clone of this CPE is within range.1131// We will be generating a new clone. Get a UID for it.1132unsigned ID = createPICLabelUId();11331134// Now that we have an island to add the CPE to, clone the original CPE and1135// add it to the island.1136U.HighWaterMark = NewIsland;1137U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))1138.addImm(ID)1139.addConstantPoolIndex(CPI)1140.addImm(Size);1141CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));1142++NumCPEs;11431144// Mark the basic block as aligned as required by the const-pool entry.1145NewIsland->setAlignment(getCPEAlign(*U.CPEMI));11461147// Increase the size of the island block to account for the new entry.1148BBInfo[NewIsland->getNumber()].Size += Size;1149adjustBBOffsetsAfter(&*--NewIsland->getIterator());11501151// Finally, change the CPI in the instruction operand to be ID.1152for (unsigned I = 0, E = UserMI->getNumOperands(); I != E; ++I)1153if (UserMI->getOperand(I).isCPI()) {1154UserMI->getOperand(I).setIndex(ID);1155break;1156}11571158LLVM_DEBUG(1159dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI1160<< format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));11611162return true;1163}11641165/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update1166/// sizes and offsets of impacted basic blocks.1167void CSKYConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {1168MachineBasicBlock *CPEBB = CPEMI->getParent();1169unsigned Size = CPEMI->getOperand(2).getImm();1170CPEMI->eraseFromParent();1171BBInfo[CPEBB->getNumber()].Size -= Size;1172// All succeeding offsets have the current size value added in, fix this.1173if (CPEBB->empty()) {1174BBInfo[CPEBB->getNumber()].Size = 0;11751176// This block no longer needs to be aligned.1177CPEBB->setAlignment(Align(4));1178} else {1179// Entries are sorted by descending alignment, so realign from the front.1180CPEBB->setAlignment(getCPEAlign(*CPEBB->begin()));1181}11821183adjustBBOffsetsAfter(CPEBB);1184// An island has only one predecessor BB and one successor BB. Check if1185// this BB's predecessor jumps directly to this BB's successor. This1186// shouldn't happen currently.1187assert(!bbIsJumpedOver(CPEBB) && "How did this happen?");1188// FIXME: remove the empty blocks after all the work is done?1189}11901191/// removeUnusedCPEntries - Remove constant pool entries whose refcounts1192/// are zero.1193bool CSKYConstantIslands::removeUnusedCPEntries() {1194unsigned MadeChange = false;1195for (unsigned I = 0, E = CPEntries.size(); I != E; ++I) {1196std::vector<CPEntry> &CPEs = CPEntries[I];1197for (unsigned J = 0, Ee = CPEs.size(); J != Ee; ++J) {1198if (CPEs[J].RefCount == 0 && CPEs[J].CPEMI) {1199removeDeadCPEMI(CPEs[J].CPEMI);1200CPEs[J].CPEMI = nullptr;1201MadeChange = true;1202}1203}1204}1205return MadeChange;1206}12071208/// isBBInRange - Returns true if the distance between specific MI and1209/// specific BB can fit in MI's displacement field.1210bool CSKYConstantIslands::isBBInRange(MachineInstr *MI,1211MachineBasicBlock *DestBB,1212unsigned MaxDisp) {1213unsigned BrOffset = getOffsetOf(MI);1214unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;12151216LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)1217<< " from " << printMBBReference(*MI->getParent())1218<< " max delta=" << MaxDisp << " from " << getOffsetOf(MI)1219<< " to " << DestOffset << " offset "1220<< int(DestOffset - BrOffset) << "\t" << *MI);12211222if (BrOffset <= DestOffset) {1223// Branch before the Dest.1224if (DestOffset - BrOffset <= MaxDisp)1225return true;1226} else {1227if (BrOffset - DestOffset <= MaxDisp)1228return true;1229}1230return false;1231}12321233/// fixupImmediateBr - Fix up an immediate branch whose destination is too far1234/// away to fit in its displacement field.1235bool CSKYConstantIslands::fixupImmediateBr(ImmBranch &Br) {1236MachineInstr *MI = Br.MI;1237MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);12381239// Check to see if the DestBB is already in-range.1240if (isBBInRange(MI, DestBB, Br.MaxDisp))1241return false;12421243if (!Br.IsCond)1244return fixupUnconditionalBr(Br);1245return fixupConditionalBr(Br);1246}12471248/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is1249/// too far away to fit in its displacement field. If the LR register has been1250/// spilled in the epilogue, then we can use BSR to implement a far jump.1251/// Otherwise, add an intermediate branch instruction to a branch.1252bool CSKYConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {1253MachineInstr *MI = Br.MI;1254MachineBasicBlock *MBB = MI->getParent();12551256if (!MFI->isLRSpilled())1257report_fatal_error("underestimated function size");12581259// Use BSR to implement far jump.1260Br.MaxDisp = ((1 << (26 - 1)) - 1) * 2;1261MI->setDesc(TII->get(CSKY::BSR32_BR));1262BBInfo[MBB->getNumber()].Size += 4;1263adjustBBOffsetsAfter(MBB);1264++NumUBrFixed;12651266LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);12671268return true;1269}12701271/// fixupConditionalBr - Fix up a conditional branch whose destination is too1272/// far away to fit in its displacement field. It is converted to an inverse1273/// conditional branch + an unconditional branch to the destination.1274bool CSKYConstantIslands::fixupConditionalBr(ImmBranch &Br) {1275MachineInstr *MI = Br.MI;1276MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);12771278SmallVector<MachineOperand, 4> Cond;1279Cond.push_back(MachineOperand::CreateImm(MI->getOpcode()));1280Cond.push_back(MI->getOperand(0));1281TII->reverseBranchCondition(Cond);12821283// Add an unconditional branch to the destination and invert the branch1284// condition to jump over it:1285// bteqz L11286// =>1287// bnez L21288// b L11289// L2:12901291// If the branch is at the end of its MBB and that has a fall-through block,1292// direct the updated conditional branch to the fall-through block. Otherwise,1293// split the MBB before the next instruction.1294MachineBasicBlock *MBB = MI->getParent();1295MachineInstr *BMI = &MBB->back();1296bool NeedSplit = (BMI != MI) || !bbHasFallthrough(MBB);12971298++NumCBrFixed;1299if (BMI != MI) {1300if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&1301BMI->isUnconditionalBranch()) {1302// Last MI in the BB is an unconditional branch. Can we simply invert the1303// condition and swap destinations:1304// beqz L11305// b L21306// =>1307// bnez L21308// b L11309MachineBasicBlock *NewDest = TII->getBranchDestBlock(*BMI);1310if (isBBInRange(MI, NewDest, Br.MaxDisp)) {1311LLVM_DEBUG(1312dbgs() << " Invert Bcc condition and swap its destination with "1313<< *BMI);1314BMI->getOperand(BMI->getNumExplicitOperands() - 1).setMBB(DestBB);1315MI->getOperand(MI->getNumExplicitOperands() - 1).setMBB(NewDest);13161317MI->setDesc(TII->get(Cond[0].getImm()));1318return true;1319}1320}1321}13221323if (NeedSplit) {1324splitBlockBeforeInstr(*MI);1325// No need for the branch to the next block. We're adding an unconditional1326// branch to the destination.1327int Delta = TII->getInstSizeInBytes(MBB->back());1328BBInfo[MBB->getNumber()].Size -= Delta;1329MBB->back().eraseFromParent();1330// BBInfo[SplitBB].Offset is wrong temporarily, fixed below13311332// The conditional successor will be swapped between the BBs after this, so1333// update CFG.1334MBB->addSuccessor(DestBB);1335std::next(MBB->getIterator())->removeSuccessor(DestBB);1336}1337MachineBasicBlock *NextBB = &*++MBB->getIterator();13381339LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)1340<< " also invert condition and change dest. to "1341<< printMBBReference(*NextBB) << "\n");13421343// Insert a new conditional branch and a new unconditional branch.1344// Also update the ImmBranch as well as adding a new entry for the new branch.13451346BuildMI(MBB, DebugLoc(), TII->get(Cond[0].getImm()))1347.addReg(MI->getOperand(0).getReg())1348.addMBB(NextBB);13491350Br.MI = &MBB->back();1351BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());1352BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);1353BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());1354unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);1355ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));13561357// Remove the old conditional branch. It may or may not still be in MBB.1358BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);1359MI->eraseFromParent();1360adjustBBOffsetsAfter(MBB);1361return true;1362}13631364/// Returns a pass that converts branches to long branches.1365FunctionPass *llvm::createCSKYConstantIslandPass() {1366return new CSKYConstantIslands();1367}13681369INITIALIZE_PASS(CSKYConstantIslands, DEBUG_TYPE,1370"CSKY constant island placement and branch shortening pass",1371false, false)137213731374