LLVM API Documentation

MipsConstantIslandPass.cpp
Go to the documentation of this file.
00001 //===-- MipsConstantIslandPass.cpp - Emit Pc Relative loads----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //
00011 // This pass is used to make Pc relative loads of constants.
00012 // For now, only Mips16 will use this. 
00013 //
00014 // Loading constants inline is expensive on Mips16 and it's in general better
00015 // to place the constant nearby in code space and then it can be loaded with a
00016 // simple 16 bit load instruction.
00017 //
00018 // The constants can be not just numbers but addresses of functions and labels.
00019 // This can be particularly helpful in static relocation mode for embedded
00020 // non-linux targets.
00021 //
00022 //
00023 
00024 #include "Mips.h"
00025 #include "MCTargetDesc/MipsBaseInfo.h"
00026 #include "Mips16InstrInfo.h"
00027 #include "MipsMachineFunction.h"
00028 #include "MipsTargetMachine.h"
00029 #include "llvm/ADT/Statistic.h"
00030 #include "llvm/CodeGen/MachineBasicBlock.h"
00031 #include "llvm/CodeGen/MachineConstantPool.h"
00032 #include "llvm/CodeGen/MachineFunctionPass.h"
00033 #include "llvm/CodeGen/MachineInstrBuilder.h"
00034 #include "llvm/CodeGen/MachineRegisterInfo.h"
00035 #include "llvm/IR/Function.h"
00036 #include "llvm/IR/InstIterator.h"
00037 #include "llvm/Support/CommandLine.h"
00038 #include "llvm/Support/Debug.h"
00039 #include "llvm/Support/Format.h"
00040 #include "llvm/Support/MathExtras.h"
00041 #include "llvm/Support/raw_ostream.h"
00042 #include "llvm/Target/TargetInstrInfo.h"
00043 #include "llvm/Target/TargetMachine.h"
00044 #include "llvm/Target/TargetRegisterInfo.h"
00045 #include <algorithm>
00046 
00047 using namespace llvm;
00048 
00049 #define DEBUG_TYPE "mips-constant-islands"
00050 
00051 STATISTIC(NumCPEs,       "Number of constpool entries");
00052 STATISTIC(NumSplit,      "Number of uncond branches inserted");
00053 STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
00054 STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
00055 
00056 // FIXME: This option should be removed once it has received sufficient testing.
00057 static cl::opt<bool>
00058 AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
00059           cl::desc("Align constant islands in code"));
00060 
00061 
00062 // Rather than do make check tests with huge amounts of code, we force
00063 // the test to use this amount.
00064 //
00065 static cl::opt<int> ConstantIslandsSmallOffset(
00066   "mips-constant-islands-small-offset",
00067   cl::init(0),
00068   cl::desc("Make small offsets be this amount for testing purposes"),
00069   cl::Hidden);
00070 
00071 //
00072 // For testing purposes we tell it to not use relaxed load forms so that it
00073 // will split blocks.
00074 //
00075 static cl::opt<bool> NoLoadRelaxation(
00076   "mips-constant-islands-no-load-relaxation",
00077   cl::init(false),
00078   cl::desc("Don't relax loads to long loads - for testing purposes"),
00079   cl::Hidden);
00080 
00081 static unsigned int branchTargetOperand(MachineInstr *MI) {
00082   switch (MI->getOpcode()) {
00083   case Mips::Bimm16:
00084   case Mips::BimmX16:
00085   case Mips::Bteqz16:
00086   case Mips::BteqzX16:
00087   case Mips::Btnez16:
00088   case Mips::BtnezX16:
00089   case Mips::JalB16:
00090     return 0;
00091   case Mips::BeqzRxImm16:
00092   case Mips::BeqzRxImmX16:
00093   case Mips::BnezRxImm16:
00094   case Mips::BnezRxImmX16:
00095     return 1;
00096   }
00097   llvm_unreachable("Unknown branch type");
00098 }
00099 
00100 static bool isUnconditionalBranch(unsigned int Opcode) {
00101   switch (Opcode) {
00102   default: return false;
00103   case Mips::Bimm16:
00104   case Mips::BimmX16:
00105   case Mips::JalB16:
00106     return true;
00107   }
00108 }
00109 
00110 static unsigned int longformBranchOpcode(unsigned int Opcode) {
00111   switch (Opcode) {
00112   case Mips::Bimm16:
00113   case Mips::BimmX16:
00114     return Mips::BimmX16;
00115   case Mips::Bteqz16:
00116   case Mips::BteqzX16:
00117     return Mips::BteqzX16;
00118   case Mips::Btnez16:
00119   case Mips::BtnezX16:
00120     return Mips::BtnezX16;
00121   case Mips::JalB16:
00122     return Mips::JalB16;
00123   case Mips::BeqzRxImm16:
00124   case Mips::BeqzRxImmX16:
00125     return Mips::BeqzRxImmX16;
00126   case Mips::BnezRxImm16:
00127   case Mips::BnezRxImmX16:
00128     return Mips::BnezRxImmX16;
00129   }
00130   llvm_unreachable("Unknown branch type");
00131 }
00132 
00133 //
00134 // FIXME: need to go through this whole constant islands port and check the math
00135 // for branch ranges and clean this up and make some functions to calculate things
00136 // that are done many times identically.
00137 // Need to refactor some of the code to call this routine.
00138 //
00139 static unsigned int branchMaxOffsets(unsigned int Opcode) {
00140   unsigned Bits, Scale;
00141   switch (Opcode) {
00142     case Mips::Bimm16:
00143       Bits = 11;
00144       Scale = 2;
00145       break;
00146     case Mips::BimmX16:
00147       Bits = 16;
00148       Scale = 2;
00149       break;
00150     case Mips::BeqzRxImm16:
00151       Bits = 8;
00152       Scale = 2;
00153       break;
00154     case Mips::BeqzRxImmX16:
00155       Bits = 16;
00156       Scale = 2;
00157       break;
00158     case Mips::BnezRxImm16:
00159       Bits = 8;
00160       Scale = 2;
00161       break;
00162     case Mips::BnezRxImmX16:
00163       Bits = 16;
00164       Scale = 2;
00165       break;
00166     case Mips::Bteqz16:
00167       Bits = 8;
00168       Scale = 2;
00169       break;
00170     case Mips::BteqzX16:
00171       Bits = 16;
00172       Scale = 2;
00173       break;
00174     case Mips::Btnez16:
00175       Bits = 8;
00176       Scale = 2;
00177       break;
00178     case Mips::BtnezX16:
00179       Bits = 16;
00180       Scale = 2;
00181       break;
00182     default:
00183       llvm_unreachable("Unknown branch type");
00184   }
00185   unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
00186   return MaxOffs;
00187 }
00188 
00189 namespace {
00190 
00191 
00192   typedef MachineBasicBlock::iterator Iter;
00193   typedef MachineBasicBlock::reverse_iterator ReverseIter;
00194 
00195   /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
00196   /// requires constant pool entries to be scattered among the instructions
00197   /// inside a function.  To do this, it completely ignores the normal LLVM
00198   /// constant pool; instead, it places constants wherever it feels like with
00199   /// special instructions.
00200   ///
00201   /// The terminology used in this pass includes:
00202   ///   Islands - Clumps of constants placed in the function.
00203   ///   Water   - Potential places where an island could be formed.
00204   ///   CPE     - A constant pool entry that has been placed somewhere, which
00205   ///             tracks a list of users.
00206 
00207   class MipsConstantIslands : public MachineFunctionPass {
00208 
00209     /// BasicBlockInfo - Information about the offset and size of a single
00210     /// basic block.
00211     struct BasicBlockInfo {
00212       /// Offset - Distance from the beginning of the function to the beginning
00213       /// of this basic block.
00214       ///
00215       /// Offsets are computed assuming worst case padding before an aligned
00216       /// block. This means that subtracting basic block offsets always gives a
00217       /// conservative estimate of the real distance which may be smaller.
00218       ///
00219       /// Because worst case padding is used, the computed offset of an aligned
00220       /// block may not actually be aligned.
00221       unsigned Offset;
00222 
00223       /// Size - Size of the basic block in bytes.  If the block contains
00224       /// inline assembly, this is a worst case estimate.
00225       ///
00226       /// The size does not include any alignment padding whether from the
00227       /// beginning of the block, or from an aligned jump table at the end.
00228       unsigned Size;
00229 
00230       // FIXME: ignore LogAlign for this patch
00231       //
00232       unsigned postOffset(unsigned LogAlign = 0) const {
00233         unsigned PO = Offset + Size;
00234         return PO;
00235       }
00236 
00237       BasicBlockInfo() : Offset(0), Size(0) {}
00238 
00239     };
00240 
00241     std::vector<BasicBlockInfo> BBInfo;
00242 
00243     /// WaterList - A sorted list of basic blocks where islands could be placed
00244     /// (i.e. blocks that don't fall through to the following block, due
00245     /// to a return, unreachable, or unconditional branch).
00246     std::vector<MachineBasicBlock*> WaterList;
00247 
00248     /// NewWaterList - The subset of WaterList that was created since the
00249     /// previous iteration by inserting unconditional branches.
00250     SmallSet<MachineBasicBlock*, 4> NewWaterList;
00251 
00252     typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
00253 
00254     /// CPUser - One user of a constant pool, keeping the machine instruction
00255     /// pointer, the constant pool being referenced, and the max displacement
00256     /// allowed from the instruction to the CP.  The HighWaterMark records the
00257     /// highest basic block where a new CPEntry can be placed.  To ensure this
00258     /// pass terminates, the CP entries are initially placed at the end of the
00259     /// function and then move monotonically to lower addresses.  The
00260     /// exception to this rule is when the current CP entry for a particular
00261     /// CPUser is out of range, but there is another CP entry for the same
00262     /// constant value in range.  We want to use the existing in-range CP
00263     /// entry, but if it later moves out of range, the search for new water
00264     /// should resume where it left off.  The HighWaterMark is used to record
00265     /// that point.
00266     struct CPUser {
00267       MachineInstr *MI;
00268       MachineInstr *CPEMI;
00269       MachineBasicBlock *HighWaterMark;
00270     private:
00271       unsigned MaxDisp;
00272       unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
00273                                 // with different displacements
00274       unsigned LongFormOpcode;
00275     public:
00276       bool NegOk;
00277       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
00278              bool neg,
00279              unsigned longformmaxdisp, unsigned longformopcode)
00280         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
00281           LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
00282           NegOk(neg){
00283         HighWaterMark = CPEMI->getParent();
00284       }
00285       /// getMaxDisp - Returns the maximum displacement supported by MI.
00286       unsigned getMaxDisp() const {
00287         unsigned xMaxDisp = ConstantIslandsSmallOffset?
00288                             ConstantIslandsSmallOffset: MaxDisp;
00289         return xMaxDisp;
00290       }
00291       void setMaxDisp(unsigned val) {
00292         MaxDisp = val;
00293       }
00294       unsigned getLongFormMaxDisp() const {
00295         return LongFormMaxDisp;
00296       }
00297       unsigned getLongFormOpcode() const {
00298           return LongFormOpcode;
00299       }
00300     };
00301 
00302     /// CPUsers - Keep track of all of the machine instructions that use various
00303     /// constant pools and their max displacement.
00304     std::vector<CPUser> CPUsers;
00305 
00306   /// CPEntry - One per constant pool entry, keeping the machine instruction
00307   /// pointer, the constpool index, and the number of CPUser's which
00308   /// reference this entry.
00309   struct CPEntry {
00310     MachineInstr *CPEMI;
00311     unsigned CPI;
00312     unsigned RefCount;
00313     CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
00314       : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
00315   };
00316 
00317   /// CPEntries - Keep track of all of the constant pool entry machine
00318   /// instructions. For each original constpool index (i.e. those that
00319   /// existed upon entry to this pass), it keeps a vector of entries.
00320   /// Original elements are cloned as we go along; the clones are
00321   /// put in the vector of the original element, but have distinct CPIs.
00322   std::vector<std::vector<CPEntry> > CPEntries;
00323 
00324   /// ImmBranch - One per immediate branch, keeping the machine instruction
00325   /// pointer, conditional or unconditional, the max displacement,
00326   /// and (if isCond is true) the corresponding unconditional branch
00327   /// opcode.
00328   struct ImmBranch {
00329     MachineInstr *MI;
00330     unsigned MaxDisp : 31;
00331     bool isCond : 1;
00332     int UncondBr;
00333     ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
00334       : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
00335   };
00336 
00337   /// ImmBranches - Keep track of all the immediate branch instructions.
00338   ///
00339   std::vector<ImmBranch> ImmBranches;
00340 
00341   /// HasFarJump - True if any far jump instruction has been emitted during
00342   /// the branch fix up pass.
00343   bool HasFarJump;
00344 
00345   const TargetMachine &TM;
00346   bool IsPIC;
00347   unsigned ABI;
00348   const MipsSubtarget *STI;
00349   const Mips16InstrInfo *TII;
00350   MipsFunctionInfo *MFI;
00351   MachineFunction *MF;
00352   MachineConstantPool *MCP;
00353 
00354   unsigned PICLabelUId;
00355   bool PrescannedForConstants;
00356 
00357   void initPICLabelUId(unsigned UId) {
00358     PICLabelUId = UId;
00359   }
00360 
00361 
00362   unsigned createPICLabelUId() {
00363     return PICLabelUId++;
00364   }
00365 
00366   public:
00367     static char ID;
00368     MipsConstantIslands(TargetMachine &tm)
00369         : MachineFunctionPass(ID), TM(tm),
00370           IsPIC(TM.getRelocationModel() == Reloc::PIC_),
00371           ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()), STI(nullptr),
00372           MF(nullptr), MCP(nullptr), PrescannedForConstants(false) {}
00373 
00374     const char *getPassName() const override {
00375       return "Mips Constant Islands";
00376     }
00377 
00378     bool runOnMachineFunction(MachineFunction &F) override;
00379 
00380     void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
00381     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
00382     unsigned getCPELogAlign(const MachineInstr *CPEMI);
00383     void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
00384     unsigned getOffsetOf(MachineInstr *MI) const;
00385     unsigned getUserOffset(CPUser&) const;
00386     void dumpBBs();
00387 
00388     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
00389                          unsigned Disp, bool NegativeOK);
00390     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
00391                          const CPUser &U);
00392 
00393     void computeBlockSize(MachineBasicBlock *MBB);
00394     MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
00395     void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
00396     void adjustBBOffsetsAfter(MachineBasicBlock *BB);
00397     bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
00398     int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
00399     int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
00400     bool findAvailableWater(CPUser&U, unsigned UserOffset,
00401                             water_iterator &WaterIter);
00402     void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
00403                         MachineBasicBlock *&NewMBB);
00404     bool handleConstantPoolUser(unsigned CPUserIndex);
00405     void removeDeadCPEMI(MachineInstr *CPEMI);
00406     bool removeUnusedCPEntries();
00407     bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
00408                           MachineInstr *CPEMI, unsigned Disp, bool NegOk,
00409                           bool DoDump = false);
00410     bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
00411                         CPUser &U, unsigned &Growth);
00412     bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
00413     bool fixupImmediateBr(ImmBranch &Br);
00414     bool fixupConditionalBr(ImmBranch &Br);
00415     bool fixupUnconditionalBr(ImmBranch &Br);
00416 
00417     void prescanForConstants();
00418 
00419   private:
00420 
00421   };
00422 
00423   char MipsConstantIslands::ID = 0;
00424 } // end of anonymous namespace
00425 
00426 bool MipsConstantIslands::isOffsetInRange
00427   (unsigned UserOffset, unsigned TrialOffset,
00428    const CPUser &U) {
00429   return isOffsetInRange(UserOffset, TrialOffset,
00430                          U.getMaxDisp(), U.NegOk);
00431 }
00432 /// print block size and offset information - debugging
00433 void MipsConstantIslands::dumpBBs() {
00434   DEBUG({
00435     for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
00436       const BasicBlockInfo &BBI = BBInfo[J];
00437       dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
00438              << format(" size=%#x\n", BBInfo[J].Size);
00439     }
00440   });
00441 }
00442 /// createMipsLongBranchPass - Returns a pass that converts branches to long
00443 /// branches.
00444 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
00445   return new MipsConstantIslands(tm);
00446 }
00447 
00448 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
00449   // The intention is for this to be a mips16 only pass for now
00450   // FIXME:
00451   MF = &mf;
00452   MCP = mf.getConstantPool();
00453   STI = &mf.getTarget().getSubtarget<MipsSubtarget>();
00454   DEBUG(dbgs() << "constant island machine function " << "\n");
00455   if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
00456     return false;
00457   }
00458   TII = (const Mips16InstrInfo *)MF->getTarget()
00459             .getSubtargetImpl()
00460             ->getInstrInfo();
00461   MFI = MF->getInfo<MipsFunctionInfo>();
00462   DEBUG(dbgs() << "constant island processing " << "\n");
00463   //
00464   // will need to make predermination if there is any constants we need to
00465   // put in constant islands. TBD.
00466   //
00467   if (!PrescannedForConstants) prescanForConstants();
00468 
00469   HasFarJump = false;
00470   // This pass invalidates liveness information when it splits basic blocks.
00471   MF->getRegInfo().invalidateLiveness();
00472 
00473   // Renumber all of the machine basic blocks in the function, guaranteeing that
00474   // the numbers agree with the position of the block in the function.
00475   MF->RenumberBlocks();
00476 
00477   bool MadeChange = false;
00478 
00479   // Perform the initial placement of the constant pool entries.  To start with,
00480   // we put them all at the end of the function.
00481   std::vector<MachineInstr*> CPEMIs;
00482   if (!MCP->isEmpty())
00483     doInitialPlacement(CPEMIs);
00484 
00485   /// The next UID to take is the first unused one.
00486   initPICLabelUId(CPEMIs.size());
00487 
00488   // Do the initial scan of the function, building up information about the
00489   // sizes of each block, the location of all the water, and finding all of the
00490   // constant pool users.
00491   initializeFunctionInfo(CPEMIs);
00492   CPEMIs.clear();
00493   DEBUG(dumpBBs());
00494 
00495   /// Remove dead constant pool entries.
00496   MadeChange |= removeUnusedCPEntries();
00497 
00498   // Iteratively place constant pool entries and fix up branches until there
00499   // is no change.
00500   unsigned NoCPIters = 0, NoBRIters = 0;
00501   (void)NoBRIters;
00502   while (true) {
00503     DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
00504     bool CPChange = false;
00505     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
00506       CPChange |= handleConstantPoolUser(i);
00507     if (CPChange && ++NoCPIters > 30)
00508       report_fatal_error("Constant Island pass failed to converge!");
00509     DEBUG(dumpBBs());
00510 
00511     // Clear NewWaterList now.  If we split a block for branches, it should
00512     // appear as "new water" for the next iteration of constant pool placement.
00513     NewWaterList.clear();
00514 
00515     DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
00516     bool BRChange = false;
00517     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
00518       BRChange |= fixupImmediateBr(ImmBranches[i]);
00519     if (BRChange && ++NoBRIters > 30)
00520       report_fatal_error("Branch Fix Up pass failed to converge!");
00521     DEBUG(dumpBBs());
00522     if (!CPChange && !BRChange)
00523       break;
00524     MadeChange = true;
00525   }
00526 
00527   DEBUG(dbgs() << '\n'; dumpBBs());
00528 
00529   BBInfo.clear();
00530   WaterList.clear();
00531   CPUsers.clear();
00532   CPEntries.clear();
00533   ImmBranches.clear();
00534   return MadeChange;
00535 }
00536 
00537 /// doInitialPlacement - Perform the initial placement of the constant pool
00538 /// entries.  To start with, we put them all at the end of the function.
00539 void
00540 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
00541   // Create the basic block to hold the CPE's.
00542   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
00543   MF->push_back(BB);
00544 
00545 
00546   // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
00547   unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
00548 
00549   // Mark the basic block as required by the const-pool.
00550   // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
00551   BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
00552 
00553   // The function needs to be as aligned as the basic blocks. The linker may
00554   // move functions around based on their alignment.
00555   MF->ensureAlignment(BB->getAlignment());
00556 
00557   // Order the entries in BB by descending alignment.  That ensures correct
00558   // alignment of all entries as long as BB is sufficiently aligned.  Keep
00559   // track of the insertion point for each alignment.  We are going to bucket
00560   // sort the entries as they are created.
00561   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
00562 
00563   // Add all of the constants from the constant pool to the end block, use an
00564   // identity mapping of CPI's to CPE's.
00565   const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
00566 
00567   const DataLayout &TD = *MF->getSubtarget().getDataLayout();
00568   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
00569     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
00570     assert(Size >= 4 && "Too small constant pool entry");
00571     unsigned Align = CPs[i].getAlignment();
00572     assert(isPowerOf2_32(Align) && "Invalid alignment");
00573     // Verify that all constant pool entries are a multiple of their alignment.
00574     // If not, we would have to pad them out so that instructions stay aligned.
00575     assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
00576 
00577     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
00578     unsigned LogAlign = Log2_32(Align);
00579     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
00580 
00581     MachineInstr *CPEMI =
00582       BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
00583         .addImm(i).addConstantPoolIndex(i).addImm(Size);
00584 
00585     CPEMIs.push_back(CPEMI);
00586 
00587     // Ensure that future entries with higher alignment get inserted before
00588     // CPEMI. This is bucket sort with iterators.
00589     for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
00590       if (InsPoint[a] == InsAt)
00591         InsPoint[a] = CPEMI;
00592     // Add a new CPEntry, but no corresponding CPUser yet.
00593     std::vector<CPEntry> CPEs;
00594     CPEs.push_back(CPEntry(CPEMI, i));
00595     CPEntries.push_back(CPEs);
00596     ++NumCPEs;
00597     DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
00598                  << Size << ", align = " << Align <<'\n');
00599   }
00600   DEBUG(BB->dump());
00601 }
00602 
00603 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
00604 /// into the block immediately after it.
00605 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
00606   // Get the next machine basic block in the function.
00607   MachineFunction::iterator MBBI = MBB;
00608   // Can't fall off end of function.
00609   if (std::next(MBBI) == MBB->getParent()->end())
00610     return false;
00611 
00612   MachineBasicBlock *NextBB = std::next(MBBI);
00613   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
00614        E = MBB->succ_end(); I != E; ++I)
00615     if (*I == NextBB)
00616       return true;
00617 
00618   return false;
00619 }
00620 
00621 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
00622 /// look up the corresponding CPEntry.
00623 MipsConstantIslands::CPEntry
00624 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
00625                                         const MachineInstr *CPEMI) {
00626   std::vector<CPEntry> &CPEs = CPEntries[CPI];
00627   // Number of entries per constpool index should be small, just do a
00628   // linear search.
00629   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
00630     if (CPEs[i].CPEMI == CPEMI)
00631       return &CPEs[i];
00632   }
00633   return nullptr;
00634 }
00635 
00636 /// getCPELogAlign - Returns the required alignment of the constant pool entry
00637 /// represented by CPEMI.  Alignment is measured in log2(bytes) units.
00638 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
00639   assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
00640 
00641   // Everything is 4-byte aligned unless AlignConstantIslands is set.
00642   if (!AlignConstantIslands)
00643     return 2;
00644 
00645   unsigned CPI = CPEMI->getOperand(1).getIndex();
00646   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
00647   unsigned Align = MCP->getConstants()[CPI].getAlignment();
00648   assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
00649   return Log2_32(Align);
00650 }
00651 
00652 /// initializeFunctionInfo - Do the initial scan of the function, building up
00653 /// information about the sizes of each block, the location of all the water,
00654 /// and finding all of the constant pool users.
00655 void MipsConstantIslands::
00656 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
00657   BBInfo.clear();
00658   BBInfo.resize(MF->getNumBlockIDs());
00659 
00660   // First thing, compute the size of all basic blocks, and see if the function
00661   // has any inline assembly in it. If so, we have to be conservative about
00662   // alignment assumptions, as we don't know for sure the size of any
00663   // instructions in the inline assembly.
00664   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
00665     computeBlockSize(I);
00666 
00667 
00668   // Compute block offsets.
00669   adjustBBOffsetsAfter(MF->begin());
00670 
00671   // Now go back through the instructions and build up our data structures.
00672   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
00673        MBBI != E; ++MBBI) {
00674     MachineBasicBlock &MBB = *MBBI;
00675 
00676     // If this block doesn't fall through into the next MBB, then this is
00677     // 'water' that a constant pool island could be placed.
00678     if (!BBHasFallthrough(&MBB))
00679       WaterList.push_back(&MBB);
00680     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
00681          I != E; ++I) {
00682       if (I->isDebugValue())
00683         continue;
00684 
00685       int Opc = I->getOpcode();
00686       if (I->isBranch()) {
00687         bool isCond = false;
00688         unsigned Bits = 0;
00689         unsigned Scale = 1;
00690         int UOpc = Opc;
00691         switch (Opc) {
00692         default:
00693           continue;  // Ignore other branches for now
00694         case Mips::Bimm16:
00695           Bits = 11;
00696           Scale = 2;
00697           isCond = false;
00698           break;
00699         case Mips::BimmX16:
00700           Bits = 16;
00701           Scale = 2;
00702           isCond = false;
00703           break;
00704         case Mips::BeqzRxImm16:
00705           UOpc=Mips::Bimm16;
00706           Bits = 8;
00707           Scale = 2;
00708           isCond = true;
00709           break;
00710         case Mips::BeqzRxImmX16:
00711           UOpc=Mips::Bimm16;
00712           Bits = 16;
00713           Scale = 2;
00714           isCond = true;
00715           break;
00716         case Mips::BnezRxImm16:
00717           UOpc=Mips::Bimm16;
00718           Bits = 8;
00719           Scale = 2;
00720           isCond = true;
00721           break;
00722         case Mips::BnezRxImmX16:
00723           UOpc=Mips::Bimm16;
00724           Bits = 16;
00725           Scale = 2;
00726           isCond = true;
00727           break;
00728         case Mips::Bteqz16:
00729           UOpc=Mips::Bimm16;
00730           Bits = 8;
00731           Scale = 2;
00732           isCond = true;
00733           break;
00734         case Mips::BteqzX16:
00735           UOpc=Mips::Bimm16;
00736           Bits = 16;
00737           Scale = 2;
00738           isCond = true;
00739           break;
00740         case Mips::Btnez16:
00741           UOpc=Mips::Bimm16;
00742           Bits = 8;
00743           Scale = 2;
00744           isCond = true;
00745           break;
00746         case Mips::BtnezX16:
00747           UOpc=Mips::Bimm16;
00748           Bits = 16;
00749           Scale = 2;
00750           isCond = true;
00751           break;
00752         }
00753         // Record this immediate branch.
00754         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
00755         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
00756       }
00757 
00758       if (Opc == Mips::CONSTPOOL_ENTRY)
00759         continue;
00760 
00761 
00762       // Scan the instructions for constant pool operands.
00763       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
00764         if (I->getOperand(op).isCPI()) {
00765 
00766           // We found one.  The addressing mode tells us the max displacement
00767           // from the PC that this instruction permits.
00768 
00769           // Basic size info comes from the TSFlags field.
00770           unsigned Bits = 0;
00771           unsigned Scale = 1;
00772           bool NegOk = false;
00773           unsigned LongFormBits = 0;
00774           unsigned LongFormScale = 0;
00775           unsigned LongFormOpcode = 0;
00776           switch (Opc) {
00777           default:
00778             llvm_unreachable("Unknown addressing mode for CP reference!");
00779           case Mips::LwRxPcTcp16:
00780             Bits = 8;
00781             Scale = 4;
00782             LongFormOpcode = Mips::LwRxPcTcpX16;
00783             LongFormBits = 14;
00784             LongFormScale = 1;
00785             break;
00786           case Mips::LwRxPcTcpX16:
00787             Bits = 14;
00788             Scale = 1;
00789             NegOk = true;
00790             break;
00791           }
00792           // Remember that this is a user of a CP entry.
00793           unsigned CPI = I->getOperand(op).getIndex();
00794           MachineInstr *CPEMI = CPEMIs[CPI];
00795           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
00796           unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
00797           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
00798                                    LongFormMaxOffs, LongFormOpcode));
00799 
00800           // Increment corresponding CPEntry reference count.
00801           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
00802           assert(CPE && "Cannot find a corresponding CPEntry!");
00803           CPE->RefCount++;
00804 
00805           // Instructions can only use one CP entry, don't bother scanning the
00806           // rest of the operands.
00807           break;
00808 
00809         }
00810 
00811     }
00812   }
00813 
00814 }
00815 
00816 /// computeBlockSize - Compute the size and some alignment information for MBB.
00817 /// This function updates BBInfo directly.
00818 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
00819   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
00820   BBI.Size = 0;
00821 
00822   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
00823        ++I)
00824     BBI.Size += TII->GetInstSizeInBytes(I);
00825 
00826 }
00827 
00828 /// getOffsetOf - Return the current offset of the specified machine instruction
00829 /// from the start of the function.  This offset changes as stuff is moved
00830 /// around inside the function.
00831 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
00832   MachineBasicBlock *MBB = MI->getParent();
00833 
00834   // The offset is composed of two things: the sum of the sizes of all MBB's
00835   // before this instruction's block, and the offset from the start of the block
00836   // it is in.
00837   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
00838 
00839   // Sum instructions before MI in MBB.
00840   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
00841     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
00842     Offset += TII->GetInstSizeInBytes(I);
00843   }
00844   return Offset;
00845 }
00846 
00847 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
00848 /// ID.
00849 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
00850                               const MachineBasicBlock *RHS) {
00851   return LHS->getNumber() < RHS->getNumber();
00852 }
00853 
00854 /// updateForInsertedWaterBlock - When a block is newly inserted into the
00855 /// machine function, it upsets all of the block numbers.  Renumber the blocks
00856 /// and update the arrays that parallel this numbering.
00857 void MipsConstantIslands::updateForInsertedWaterBlock
00858   (MachineBasicBlock *NewBB) {
00859   // Renumber the MBB's to keep them consecutive.
00860   NewBB->getParent()->RenumberBlocks(NewBB);
00861 
00862   // Insert an entry into BBInfo to align it properly with the (newly
00863   // renumbered) block numbers.
00864   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
00865 
00866   // Next, update WaterList.  Specifically, we need to add NewMBB as having
00867   // available water after it.
00868   water_iterator IP =
00869     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
00870                      CompareMBBNumbers);
00871   WaterList.insert(IP, NewBB);
00872 }
00873 
00874 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
00875   return getOffsetOf(U.MI);
00876 }
00877 
00878 /// Split the basic block containing MI into two blocks, which are joined by
00879 /// an unconditional branch.  Update data structures and renumber blocks to
00880 /// account for this change and returns the newly created block.
00881 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
00882   (MachineInstr *MI) {
00883   MachineBasicBlock *OrigBB = MI->getParent();
00884 
00885   // Create a new MBB for the code after the OrigBB.
00886   MachineBasicBlock *NewBB =
00887     MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
00888   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
00889   MF->insert(MBBI, NewBB);
00890 
00891   // Splice the instructions starting with MI over to NewBB.
00892   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
00893 
00894   // Add an unconditional branch from OrigBB to NewBB.
00895   // Note the new unconditional branch is not being recorded.
00896   // There doesn't seem to be meaningful DebugInfo available; this doesn't
00897   // correspond to anything in the source.
00898   BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
00899   ++NumSplit;
00900 
00901   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
00902   NewBB->transferSuccessors(OrigBB);
00903 
00904   // OrigBB branches to NewBB.
00905   OrigBB->addSuccessor(NewBB);
00906 
00907   // Update internal data structures to account for the newly inserted MBB.
00908   // This is almost the same as updateForInsertedWaterBlock, except that
00909   // the Water goes after OrigBB, not NewBB.
00910   MF->RenumberBlocks(NewBB);
00911 
00912   // Insert an entry into BBInfo to align it properly with the (newly
00913   // renumbered) block numbers.
00914   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
00915 
00916   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
00917   // available water after it (but not if it's already there, which happens
00918   // when splitting before a conditional branch that is followed by an
00919   // unconditional branch - in that case we want to insert NewBB).
00920   water_iterator IP =
00921     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
00922                      CompareMBBNumbers);
00923   MachineBasicBlock* WaterBB = *IP;
00924   if (WaterBB == OrigBB)
00925     WaterList.insert(std::next(IP), NewBB);
00926   else
00927     WaterList.insert(IP, OrigBB);
00928   NewWaterList.insert(OrigBB);
00929 
00930   // Figure out how large the OrigBB is.  As the first half of the original
00931   // block, it cannot contain a tablejump.  The size includes
00932   // the new jump we added.  (It should be possible to do this without
00933   // recounting everything, but it's very confusing, and this is rarely
00934   // executed.)
00935   computeBlockSize(OrigBB);
00936 
00937   // Figure out how large the NewMBB is.  As the second half of the original
00938   // block, it may contain a tablejump.
00939   computeBlockSize(NewBB);
00940 
00941   // All BBOffsets following these blocks must be modified.
00942   adjustBBOffsetsAfter(OrigBB);
00943 
00944   return NewBB;
00945 }
00946 
00947 
00948 
00949 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
00950 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
00951 /// constant pool entry).
00952 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
00953                                          unsigned TrialOffset, unsigned MaxDisp,
00954                                          bool NegativeOK) {
00955   if (UserOffset <= TrialOffset) {
00956     // User before the Trial.
00957     if (TrialOffset - UserOffset <= MaxDisp)
00958       return true;
00959   } else if (NegativeOK) {
00960     if (UserOffset - TrialOffset <= MaxDisp)
00961       return true;
00962   }
00963   return false;
00964 }
00965 
00966 /// isWaterInRange - Returns true if a CPE placed after the specified
00967 /// Water (a basic block) will be in range for the specific MI.
00968 ///
00969 /// Compute how much the function will grow by inserting a CPE after Water.
00970 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
00971                                         MachineBasicBlock* Water, CPUser &U,
00972                                         unsigned &Growth) {
00973   unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
00974   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
00975   unsigned NextBlockOffset, NextBlockAlignment;
00976   MachineFunction::const_iterator NextBlock = Water;
00977   if (++NextBlock == MF->end()) {
00978     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
00979     NextBlockAlignment = 0;
00980   } else {
00981     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
00982     NextBlockAlignment = NextBlock->getAlignment();
00983   }
00984   unsigned Size = U.CPEMI->getOperand(2).getImm();
00985   unsigned CPEEnd = CPEOffset + Size;
00986 
00987   // The CPE may be able to hide in the alignment padding before the next
00988   // block. It may also cause more padding to be required if it is more aligned
00989   // that the next block.
00990   if (CPEEnd > NextBlockOffset) {
00991     Growth = CPEEnd - NextBlockOffset;
00992     // Compute the padding that would go at the end of the CPE to align the next
00993     // block.
00994     Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
00995 
00996     // If the CPE is to be inserted before the instruction, that will raise
00997     // the offset of the instruction. Also account for unknown alignment padding
00998     // in blocks between CPE and the user.
00999     if (CPEOffset < UserOffset)
01000       UserOffset += Growth;
01001   } else
01002     // CPE fits in existing padding.
01003     Growth = 0;
01004 
01005   return isOffsetInRange(UserOffset, CPEOffset, U);
01006 }
01007 
01008 /// isCPEntryInRange - Returns true if the distance between specific MI and
01009 /// specific ConstPool entry instruction can fit in MI's displacement field.
01010 bool MipsConstantIslands::isCPEntryInRange
01011   (MachineInstr *MI, unsigned UserOffset,
01012    MachineInstr *CPEMI, unsigned MaxDisp,
01013    bool NegOk, bool DoDump) {
01014   unsigned CPEOffset  = getOffsetOf(CPEMI);
01015 
01016   if (DoDump) {
01017     DEBUG({
01018       unsigned Block = MI->getParent()->getNumber();
01019       const BasicBlockInfo &BBI = BBInfo[Block];
01020       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
01021              << " max delta=" << MaxDisp
01022              << format(" insn address=%#x", UserOffset)
01023              << " in BB#" << Block << ": "
01024              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
01025              << format("CPE address=%#x offset=%+d: ", CPEOffset,
01026                        int(CPEOffset-UserOffset));
01027     });
01028   }
01029 
01030   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
01031 }
01032 
01033 #ifndef NDEBUG
01034 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
01035 /// unconditionally branches to its only successor.
01036 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
01037   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
01038     return false;
01039   MachineBasicBlock *Succ = *MBB->succ_begin();
01040   MachineBasicBlock *Pred = *MBB->pred_begin();
01041   MachineInstr *PredMI = &Pred->back();
01042   if (PredMI->getOpcode() == Mips::Bimm16)
01043     return PredMI->getOperand(0).getMBB() == Succ;
01044   return false;
01045 }
01046 #endif
01047 
01048 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
01049   unsigned BBNum = BB->getNumber();
01050   for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
01051     // Get the offset and known bits at the end of the layout predecessor.
01052     // Include the alignment of the current block.
01053     unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
01054     BBInfo[i].Offset = Offset;
01055   }
01056 }
01057 
01058 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
01059 /// and instruction CPEMI, and decrement its refcount.  If the refcount
01060 /// becomes 0 remove the entry and instruction.  Returns true if we removed
01061 /// the entry, false if we didn't.
01062 
01063 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
01064                                                     MachineInstr *CPEMI) {
01065   // Find the old entry. Eliminate it if it is no longer used.
01066   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
01067   assert(CPE && "Unexpected!");
01068   if (--CPE->RefCount == 0) {
01069     removeDeadCPEMI(CPEMI);
01070     CPE->CPEMI = nullptr;
01071     --NumCPEs;
01072     return true;
01073   }
01074   return false;
01075 }
01076 
01077 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
01078 /// if not, see if an in-range clone of the CPE is in range, and if so,
01079 /// change the data structures so the user references the clone.  Returns:
01080 /// 0 = no existing entry found
01081 /// 1 = entry found, and there were no code insertions or deletions
01082 /// 2 = entry found, and there were code insertions or deletions
01083 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
01084 {
01085   MachineInstr *UserMI = U.MI;
01086   MachineInstr *CPEMI  = U.CPEMI;
01087 
01088   // Check to see if the CPE is already in-range.
01089   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
01090                        true)) {
01091     DEBUG(dbgs() << "In range\n");
01092     return 1;
01093   }
01094 
01095   // No.  Look for previously created clones of the CPE that are in range.
01096   unsigned CPI = CPEMI->getOperand(1).getIndex();
01097   std::vector<CPEntry> &CPEs = CPEntries[CPI];
01098   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
01099     // We already tried this one
01100     if (CPEs[i].CPEMI == CPEMI)
01101       continue;
01102     // Removing CPEs can leave empty entries, skip
01103     if (CPEs[i].CPEMI == nullptr)
01104       continue;
01105     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
01106                      U.NegOk)) {
01107       DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
01108                    << CPEs[i].CPI << "\n");
01109       // Point the CPUser node to the replacement
01110       U.CPEMI = CPEs[i].CPEMI;
01111       // Change the CPI in the instruction operand to refer to the clone.
01112       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
01113         if (UserMI->getOperand(j).isCPI()) {
01114           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
01115           break;
01116         }
01117       // Adjust the refcount of the clone...
01118       CPEs[i].RefCount++;
01119       // ...and the original.  If we didn't remove the old entry, none of the
01120       // addresses changed, so we don't need another pass.
01121       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
01122     }
01123   }
01124   return 0;
01125 }
01126 
01127 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
01128 /// This version checks if the longer form of the instruction can be used to
01129 /// to satisfy things.
01130 /// if not, see if an in-range clone of the CPE is in range, and if so,
01131 /// change the data structures so the user references the clone.  Returns:
01132 /// 0 = no existing entry found
01133 /// 1 = entry found, and there were no code insertions or deletions
01134 /// 2 = entry found, and there were code insertions or deletions
01135 int MipsConstantIslands::findLongFormInRangeCPEntry
01136   (CPUser& U, unsigned UserOffset)
01137 {
01138   MachineInstr *UserMI = U.MI;
01139   MachineInstr *CPEMI  = U.CPEMI;
01140 
01141   // Check to see if the CPE is already in-range.
01142   if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
01143                        U.getLongFormMaxDisp(), U.NegOk,
01144                        true)) {
01145     DEBUG(dbgs() << "In range\n");
01146     UserMI->setDesc(TII->get(U.getLongFormOpcode()));
01147     U.setMaxDisp(U.getLongFormMaxDisp());
01148     return 2;  // instruction is longer length now
01149   }
01150 
01151   // No.  Look for previously created clones of the CPE that are in range.
01152   unsigned CPI = CPEMI->getOperand(1).getIndex();
01153   std::vector<CPEntry> &CPEs = CPEntries[CPI];
01154   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
01155     // We already tried this one
01156     if (CPEs[i].CPEMI == CPEMI)
01157       continue;
01158     // Removing CPEs can leave empty entries, skip
01159     if (CPEs[i].CPEMI == nullptr)
01160       continue;
01161     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
01162                          U.getLongFormMaxDisp(), U.NegOk)) {
01163       DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
01164                    << CPEs[i].CPI << "\n");
01165       // Point the CPUser node to the replacement
01166       U.CPEMI = CPEs[i].CPEMI;
01167       // Change the CPI in the instruction operand to refer to the clone.
01168       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
01169         if (UserMI->getOperand(j).isCPI()) {
01170           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
01171           break;
01172         }
01173       // Adjust the refcount of the clone...
01174       CPEs[i].RefCount++;
01175       // ...and the original.  If we didn't remove the old entry, none of the
01176       // addresses changed, so we don't need another pass.
01177       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
01178     }
01179   }
01180   return 0;
01181 }
01182 
01183 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
01184 /// the specific unconditional branch instruction.
01185 static inline unsigned getUnconditionalBrDisp(int Opc) {
01186   switch (Opc) {
01187   case Mips::Bimm16:
01188     return ((1<<10)-1)*2;
01189   case Mips::BimmX16:
01190     return ((1<<16)-1)*2;
01191   default:
01192     break;
01193   }
01194   return ((1<<16)-1)*2;
01195 }
01196 
01197 /// findAvailableWater - Look for an existing entry in the WaterList in which
01198 /// we can place the CPE referenced from U so it's within range of U's MI.
01199 /// Returns true if found, false if not.  If it returns true, WaterIter
01200 /// is set to the WaterList entry.  
01201 /// To ensure that this pass
01202 /// terminates, the CPE location for a particular CPUser is only allowed to
01203 /// move to a lower address, so search backward from the end of the list and
01204 /// prefer the first water that is in range.
01205 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
01206                                       water_iterator &WaterIter) {
01207   if (WaterList.empty())
01208     return false;
01209 
01210   unsigned BestGrowth = ~0u;
01211   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
01212        --IP) {
01213     MachineBasicBlock* WaterBB = *IP;
01214     // Check if water is in range and is either at a lower address than the
01215     // current "high water mark" or a new water block that was created since
01216     // the previous iteration by inserting an unconditional branch.  In the
01217     // latter case, we want to allow resetting the high water mark back to
01218     // this new water since we haven't seen it before.  Inserting branches
01219     // should be relatively uncommon and when it does happen, we want to be
01220     // sure to take advantage of it for all the CPEs near that block, so that
01221     // we don't insert more branches than necessary.
01222     unsigned Growth;
01223     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
01224         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
01225          NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
01226       // This is the least amount of required padding seen so far.
01227       BestGrowth = Growth;
01228       WaterIter = IP;
01229       DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
01230                    << " Growth=" << Growth << '\n');
01231 
01232       // Keep looking unless it is perfect.
01233       if (BestGrowth == 0)
01234         return true;
01235     }
01236     if (IP == B)
01237       break;
01238   }
01239   return BestGrowth != ~0u;
01240 }
01241 
01242 /// createNewWater - No existing WaterList entry will work for
01243 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
01244 /// block is used if in range, and the conditional branch munged so control
01245 /// flow is correct.  Otherwise the block is split to create a hole with an
01246 /// unconditional branch around it.  In either case NewMBB is set to a
01247 /// block following which the new island can be inserted (the WaterList
01248 /// is not adjusted).
01249 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
01250                                         unsigned UserOffset,
01251                                         MachineBasicBlock *&NewMBB) {
01252   CPUser &U = CPUsers[CPUserIndex];
01253   MachineInstr *UserMI = U.MI;
01254   MachineInstr *CPEMI  = U.CPEMI;
01255   unsigned CPELogAlign = getCPELogAlign(CPEMI);
01256   MachineBasicBlock *UserMBB = UserMI->getParent();
01257   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
01258 
01259   // If the block does not end in an unconditional branch already, and if the
01260   // end of the block is within range, make new water there.  
01261   if (BBHasFallthrough(UserMBB)) {
01262     // Size of branch to insert.
01263     unsigned Delta = 2;
01264     // Compute the offset where the CPE will begin.
01265     unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
01266 
01267     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
01268       DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
01269             << format(", expected CPE offset %#x\n", CPEOffset));
01270       NewMBB = std::next(MachineFunction::iterator(UserMBB));
01271       // Add an unconditional branch from UserMBB to fallthrough block.  Record
01272       // it for branch lengthening; this new branch will not get out of range,
01273       // but if the preceding conditional branch is out of range, the targets
01274       // will be exchanged, and the altered branch may be out of range, so the
01275       // machinery has to know about it.
01276       int UncondBr = Mips::Bimm16;
01277       BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
01278       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
01279       ImmBranches.push_back(ImmBranch(&UserMBB->back(),
01280                                       MaxDisp, false, UncondBr));
01281       BBInfo[UserMBB->getNumber()].Size += Delta;
01282       adjustBBOffsetsAfter(UserMBB);
01283       return;
01284     }
01285   }
01286 
01287   // What a big block.  Find a place within the block to split it.  
01288 
01289   // Try to split the block so it's fully aligned.  Compute the latest split
01290   // point where we can add a 4-byte branch instruction, and then align to
01291   // LogAlign which is the largest possible alignment in the function.
01292   unsigned LogAlign = MF->getAlignment();
01293   assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
01294   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
01295   DEBUG(dbgs() << format("Split in middle of big block before %#x",
01296                          BaseInsertOffset));
01297 
01298   // The 4 in the following is for the unconditional branch we'll be inserting
01299   // Alignment of the island is handled
01300   // inside isOffsetInRange.
01301   BaseInsertOffset -= 4;
01302 
01303   DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
01304                << " la=" << LogAlign << '\n');
01305 
01306   // This could point off the end of the block if we've already got constant
01307   // pool entries following this block; only the last one is in the water list.
01308   // Back past any possible branches (allow for a conditional and a maximally
01309   // long unconditional).
01310   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
01311     BaseInsertOffset = UserBBI.postOffset() - 8;
01312     DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
01313   }
01314   unsigned EndInsertOffset = BaseInsertOffset + 4 +
01315     CPEMI->getOperand(2).getImm();
01316   MachineBasicBlock::iterator MI = UserMI;
01317   ++MI;
01318   unsigned CPUIndex = CPUserIndex+1;
01319   unsigned NumCPUsers = CPUsers.size();
01320   //MachineInstr *LastIT = 0;
01321   for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
01322        Offset < BaseInsertOffset;
01323        Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
01324     assert(MI != UserMBB->end() && "Fell off end of block");
01325     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
01326       CPUser &U = CPUsers[CPUIndex];
01327       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
01328         // Shift intertion point by one unit of alignment so it is within reach.
01329         BaseInsertOffset -= 1u << LogAlign;
01330         EndInsertOffset  -= 1u << LogAlign;
01331       }
01332       // This is overly conservative, as we don't account for CPEMIs being
01333       // reused within the block, but it doesn't matter much.  Also assume CPEs
01334       // are added in order with alignment padding.  We may eventually be able
01335       // to pack the aligned CPEs better.
01336       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
01337       CPUIndex++;
01338     }
01339   }
01340 
01341   --MI;
01342   NewMBB = splitBlockBeforeInstr(MI);
01343 }
01344 
01345 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
01346 /// is out-of-range.  If so, pick up the constant pool value and move it some
01347 /// place in-range.  Return true if we changed any addresses (thus must run
01348 /// another pass of branch lengthening), false otherwise.
01349 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
01350   CPUser &U = CPUsers[CPUserIndex];
01351   MachineInstr *UserMI = U.MI;
01352   MachineInstr *CPEMI  = U.CPEMI;
01353   unsigned CPI = CPEMI->getOperand(1).getIndex();
01354   unsigned Size = CPEMI->getOperand(2).getImm();
01355   // Compute this only once, it's expensive.
01356   unsigned UserOffset = getUserOffset(U);
01357 
01358   // See if the current entry is within range, or there is a clone of it
01359   // in range.
01360   int result = findInRangeCPEntry(U, UserOffset);
01361   if (result==1) return false;
01362   else if (result==2) return true;
01363 
01364 
01365   // Look for water where we can place this CPE.
01366   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
01367   MachineBasicBlock *NewMBB;
01368   water_iterator IP;
01369   if (findAvailableWater(U, UserOffset, IP)) {
01370     DEBUG(dbgs() << "Found water in range\n");
01371     MachineBasicBlock *WaterBB = *IP;
01372 
01373     // If the original WaterList entry was "new water" on this iteration,
01374     // propagate that to the new island.  This is just keeping NewWaterList
01375     // updated to match the WaterList, which will be updated below.
01376     if (NewWaterList.erase(WaterBB))
01377       NewWaterList.insert(NewIsland);
01378 
01379     // The new CPE goes before the following block (NewMBB).
01380     NewMBB = std::next(MachineFunction::iterator(WaterBB));
01381 
01382   } else {
01383     // No water found.
01384     // we first see if a longer form of the instrucion could have reached
01385     // the constant. in that case we won't bother to split
01386     if (!NoLoadRelaxation) {
01387       result = findLongFormInRangeCPEntry(U, UserOffset);
01388       if (result != 0) return true;
01389     }
01390     DEBUG(dbgs() << "No water found\n");
01391     createNewWater(CPUserIndex, UserOffset, NewMBB);
01392 
01393     // splitBlockBeforeInstr adds to WaterList, which is important when it is
01394     // called while handling branches so that the water will be seen on the
01395     // next iteration for constant pools, but in this context, we don't want
01396     // it.  Check for this so it will be removed from the WaterList.
01397     // Also remove any entry from NewWaterList.
01398     MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
01399     IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
01400     if (IP != WaterList.end())
01401       NewWaterList.erase(WaterBB);
01402 
01403     // We are adding new water.  Update NewWaterList.
01404     NewWaterList.insert(NewIsland);
01405   }
01406 
01407   // Remove the original WaterList entry; we want subsequent insertions in
01408   // this vicinity to go after the one we're about to insert.  This
01409   // considerably reduces the number of times we have to move the same CPE
01410   // more than once and is also important to ensure the algorithm terminates.
01411   if (IP != WaterList.end())
01412     WaterList.erase(IP);
01413 
01414   // Okay, we know we can put an island before NewMBB now, do it!
01415   MF->insert(NewMBB, NewIsland);
01416 
01417   // Update internal data structures to account for the newly inserted MBB.
01418   updateForInsertedWaterBlock(NewIsland);
01419 
01420   // Decrement the old entry, and remove it if refcount becomes 0.
01421   decrementCPEReferenceCount(CPI, CPEMI);
01422 
01423   // No existing clone of this CPE is within range.
01424   // We will be generating a new clone.  Get a UID for it.
01425   unsigned ID = createPICLabelUId();
01426 
01427   // Now that we have an island to add the CPE to, clone the original CPE and
01428   // add it to the island.
01429   U.HighWaterMark = NewIsland;
01430   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
01431                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
01432   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
01433   ++NumCPEs;
01434 
01435   // Mark the basic block as aligned as required by the const-pool entry.
01436   NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
01437 
01438   // Increase the size of the island block to account for the new entry.
01439   BBInfo[NewIsland->getNumber()].Size += Size;
01440   adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
01441 
01442 
01443 
01444   // Finally, change the CPI in the instruction operand to be ID.
01445   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
01446     if (UserMI->getOperand(i).isCPI()) {
01447       UserMI->getOperand(i).setIndex(ID);
01448       break;
01449     }
01450 
01451   DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
01452         << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
01453 
01454   return true;
01455 }
01456 
01457 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
01458 /// sizes and offsets of impacted basic blocks.
01459 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
01460   MachineBasicBlock *CPEBB = CPEMI->getParent();
01461   unsigned Size = CPEMI->getOperand(2).getImm();
01462   CPEMI->eraseFromParent();
01463   BBInfo[CPEBB->getNumber()].Size -= Size;
01464   // All succeeding offsets have the current size value added in, fix this.
01465   if (CPEBB->empty()) {
01466     BBInfo[CPEBB->getNumber()].Size = 0;
01467 
01468     // This block no longer needs to be aligned.
01469     CPEBB->setAlignment(0);
01470   } else
01471     // Entries are sorted by descending alignment, so realign from the front.
01472     CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
01473 
01474   adjustBBOffsetsAfter(CPEBB);
01475   // An island has only one predecessor BB and one successor BB. Check if
01476   // this BB's predecessor jumps directly to this BB's successor. This
01477   // shouldn't happen currently.
01478   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
01479   // FIXME: remove the empty blocks after all the work is done?
01480 }
01481 
01482 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
01483 /// are zero.
01484 bool MipsConstantIslands::removeUnusedCPEntries() {
01485   unsigned MadeChange = false;
01486   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
01487       std::vector<CPEntry> &CPEs = CPEntries[i];
01488       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
01489         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
01490           removeDeadCPEMI(CPEs[j].CPEMI);
01491           CPEs[j].CPEMI = nullptr;
01492           MadeChange = true;
01493         }
01494       }
01495   }
01496   return MadeChange;
01497 }
01498 
01499 /// isBBInRange - Returns true if the distance between specific MI and
01500 /// specific BB can fit in MI's displacement field.
01501 bool MipsConstantIslands::isBBInRange
01502   (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
01503 
01504 unsigned PCAdj = 4;
01505 
01506   unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
01507   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
01508 
01509   DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
01510                << " from BB#" << MI->getParent()->getNumber()
01511                << " max delta=" << MaxDisp
01512                << " from " << getOffsetOf(MI) << " to " << DestOffset
01513                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
01514 
01515   if (BrOffset <= DestOffset) {
01516     // Branch before the Dest.
01517     if (DestOffset-BrOffset <= MaxDisp)
01518       return true;
01519   } else {
01520     if (BrOffset-DestOffset <= MaxDisp)
01521       return true;
01522   }
01523   return false;
01524 }
01525 
01526 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
01527 /// away to fit in its displacement field.
01528 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
01529   MachineInstr *MI = Br.MI;
01530   unsigned TargetOperand = branchTargetOperand(MI);
01531   MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
01532 
01533   // Check to see if the DestBB is already in-range.
01534   if (isBBInRange(MI, DestBB, Br.MaxDisp))
01535     return false;
01536 
01537   if (!Br.isCond)
01538     return fixupUnconditionalBr(Br);
01539   return fixupConditionalBr(Br);
01540 }
01541 
01542 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
01543 /// too far away to fit in its displacement field. If the LR register has been
01544 /// spilled in the epilogue, then we can use BL to implement a far jump.
01545 /// Otherwise, add an intermediate branch instruction to a branch.
01546 bool
01547 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
01548   MachineInstr *MI = Br.MI;
01549   MachineBasicBlock *MBB = MI->getParent();
01550   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
01551   // Use BL to implement far jump.
01552   unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
01553   if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
01554     Br.MaxDisp = BimmX16MaxDisp;
01555     MI->setDesc(TII->get(Mips::BimmX16));
01556   }
01557   else {
01558     // need to give the math a more careful look here
01559     // this is really a segment address and not
01560     // a PC relative address. FIXME. But I think that
01561     // just reducing the bits by 1 as I've done is correct.
01562     // The basic block we are branching too much be longword aligned.
01563     // we know that RA is saved because we always save it right now.
01564     // this requirement will be relaxed later but we also have an alternate
01565     // way to implement this that I will implement that does not need jal.
01566     // We should have a way to back out this alignment restriction if we "can" later.
01567     // but it is not harmful.
01568     //
01569     DestBB->setAlignment(2);
01570     Br.MaxDisp = ((1<<24)-1) * 2;
01571     MI->setDesc(TII->get(Mips::JalB16));
01572   }
01573   BBInfo[MBB->getNumber()].Size += 2;
01574   adjustBBOffsetsAfter(MBB);
01575   HasFarJump = true;
01576   ++NumUBrFixed;
01577 
01578   DEBUG(dbgs() << "  Changed B to long jump " << *MI);
01579 
01580   return true;
01581 }
01582 
01583 
01584 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
01585 /// far away to fit in its displacement field. It is converted to an inverse
01586 /// conditional branch + an unconditional branch to the destination.
01587 bool
01588 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
01589   MachineInstr *MI = Br.MI;
01590   unsigned TargetOperand = branchTargetOperand(MI);
01591   MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
01592   unsigned Opcode = MI->getOpcode();
01593   unsigned LongFormOpcode = longformBranchOpcode(Opcode);
01594   unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
01595 
01596   // Check to see if the DestBB is already in-range.
01597   if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
01598     Br.MaxDisp = LongFormMaxOff;
01599     MI->setDesc(TII->get(LongFormOpcode));
01600     return true;
01601   }
01602 
01603   // Add an unconditional branch to the destination and invert the branch
01604   // condition to jump over it:
01605   // bteqz L1
01606   // =>
01607   // bnez L2
01608   // b   L1
01609   // L2:
01610 
01611   // If the branch is at the end of its MBB and that has a fall-through block,
01612   // direct the updated conditional branch to the fall-through block. Otherwise,
01613   // split the MBB before the next instruction.
01614   MachineBasicBlock *MBB = MI->getParent();
01615   MachineInstr *BMI = &MBB->back();
01616   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
01617   unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
01618  
01619   ++NumCBrFixed;
01620   if (BMI != MI) {
01621     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
01622         isUnconditionalBranch(BMI->getOpcode())) {
01623       // Last MI in the BB is an unconditional branch. Can we simply invert the
01624       // condition and swap destinations:
01625       // beqz L1
01626       // b   L2
01627       // =>
01628       // bnez L2
01629       // b   L1
01630       unsigned BMITargetOperand = branchTargetOperand(BMI);
01631       MachineBasicBlock *NewDest = 
01632         BMI->getOperand(BMITargetOperand).getMBB();
01633       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
01634         DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
01635                      << *BMI);
01636         MI->setDesc(TII->get(OppositeBranchOpcode));
01637         BMI->getOperand(BMITargetOperand).setMBB(DestBB);
01638         MI->getOperand(TargetOperand).setMBB(NewDest);
01639         return true;
01640       }
01641     }
01642   }
01643 
01644 
01645   if (NeedSplit) {
01646     splitBlockBeforeInstr(MI);
01647     // No need for the branch to the next block. We're adding an unconditional
01648     // branch to the destination.
01649     int delta = TII->GetInstSizeInBytes(&MBB->back());
01650     BBInfo[MBB->getNumber()].Size -= delta;
01651     MBB->back().eraseFromParent();
01652     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
01653   }
01654   MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
01655 
01656   DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
01657                << " also invert condition and change dest. to BB#"
01658                << NextBB->getNumber() << "\n");
01659 
01660   // Insert a new conditional branch and a new unconditional branch.
01661   // Also update the ImmBranch as well as adding a new entry for the new branch.
01662   if (MI->getNumExplicitOperands() == 2) {
01663     BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
01664            .addReg(MI->getOperand(0).getReg())
01665            .addMBB(NextBB);
01666   } else {
01667     BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
01668            .addMBB(NextBB);
01669   }
01670   Br.MI = &MBB->back();
01671   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
01672   BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
01673   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
01674   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
01675   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
01676 
01677   // Remove the old conditional branch.  It may or may not still be in MBB.
01678   BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
01679   MI->eraseFromParent();
01680   adjustBBOffsetsAfter(MBB);
01681   return true;
01682 }
01683 
01684 
01685 void MipsConstantIslands::prescanForConstants() {
01686   unsigned J = 0;
01687   (void)J;
01688   for (MachineFunction::iterator B =
01689          MF->begin(), E = MF->end(); B != E; ++B) {
01690     for (MachineBasicBlock::instr_iterator I =
01691         B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
01692       switch(I->getDesc().getOpcode()) {
01693         case Mips::LwConstant32: {
01694           PrescannedForConstants = true;
01695           DEBUG(dbgs() << "constant island constant " << *I << "\n");
01696           J = I->getNumOperands();
01697           DEBUG(dbgs() << "num operands " << J  << "\n");
01698           MachineOperand& Literal = I->getOperand(1);
01699           if (Literal.isImm()) {
01700             int64_t V = Literal.getImm();
01701             DEBUG(dbgs() << "literal " << V  << "\n");
01702             Type *Int32Ty =
01703               Type::getInt32Ty(MF->getFunction()->getContext());
01704             const Constant *C = ConstantInt::get(Int32Ty, V);
01705             unsigned index = MCP->getConstantPoolIndex(C, 4);
01706             I->getOperand(2).ChangeToImmediate(index);
01707             DEBUG(dbgs() << "constant island constant " << *I << "\n");
01708             I->setDesc(TII->get(Mips::LwRxPcTcp16));
01709             I->RemoveOperand(1);
01710             I->RemoveOperand(1);
01711             I->addOperand(MachineOperand::CreateCPI(index, 0));
01712             I->addOperand(MachineOperand::CreateImm(4));
01713           }
01714           break;
01715         }
01716         default:
01717           break;
01718       }
01719     }
01720   }
01721 }
01722