1//===-- MipsConstantIslandPass.cpp - Emit Pc Relative loads----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//
11// This pass is used to make Pc relative loads of constants.
12// For now, only Mips16 will use this.
13//
14// Loading constants inline is expensive on Mips16 and it's in general better
15// to place the constant nearby in code space and then it can be loaded with a
16// simple 16 bit load instruction.
17//
18// The constants can be not just numbers but addresses of functions and labels.
19// This can be particularly helpful in static relocation mode for embedded
20// non-linux targets.
21//
22//
23
24#include "Mips.h"
25#include "MCTargetDesc/MipsBaseInfo.h"
26#include "Mips16InstrInfo.h"
27#include "MipsMachineFunction.h"
28#include "MipsTargetMachine.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/CodeGen/MachineBasicBlock.h"
31#include "llvm/CodeGen/MachineConstantPool.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/InstIterator.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Format.h"
40#include "llvm/Support/MathExtras.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetRegisterInfo.h"
45#include <algorithm>
46
47using namespace llvm;
48
49#define DEBUG_TYPE "mips-constant-islands"
50
51STATISTIC(NumCPEs,       "Number of constpool entries");
52STATISTIC(NumSplit,      "Number of uncond branches inserted");
53STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
54STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
55
56// FIXME: This option should be removed once it has received sufficient testing.
57static cl::opt<bool>
58AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
59          cl::desc("Align constant islands in code"));
60
61
62// Rather than do make check tests with huge amounts of code, we force
63// the test to use this amount.
64//
65static cl::opt<int> ConstantIslandsSmallOffset(
66  "mips-constant-islands-small-offset",
67  cl::init(0),
68  cl::desc("Make small offsets be this amount for testing purposes"),
69  cl::Hidden);
70
71//
72// For testing purposes we tell it to not use relaxed load forms so that it
73// will split blocks.
74//
75static cl::opt<bool> NoLoadRelaxation(
76  "mips-constant-islands-no-load-relaxation",
77  cl::init(false),
78  cl::desc("Don't relax loads to long loads - for testing purposes"),
79  cl::Hidden);
80
81static unsigned int branchTargetOperand(MachineInstr *MI) {
82  switch (MI->getOpcode()) {
83  case Mips::Bimm16:
84  case Mips::BimmX16:
85  case Mips::Bteqz16:
86  case Mips::BteqzX16:
87  case Mips::Btnez16:
88  case Mips::BtnezX16:
89  case Mips::JalB16:
90    return 0;
91  case Mips::BeqzRxImm16:
92  case Mips::BeqzRxImmX16:
93  case Mips::BnezRxImm16:
94  case Mips::BnezRxImmX16:
95    return 1;
96  }
97  llvm_unreachable("Unknown branch type");
98}
99
100static bool isUnconditionalBranch(unsigned int Opcode) {
101  switch (Opcode) {
102  default: return false;
103  case Mips::Bimm16:
104  case Mips::BimmX16:
105  case Mips::JalB16:
106    return true;
107  }
108}
109
110static unsigned int longformBranchOpcode(unsigned int Opcode) {
111  switch (Opcode) {
112  case Mips::Bimm16:
113  case Mips::BimmX16:
114    return Mips::BimmX16;
115  case Mips::Bteqz16:
116  case Mips::BteqzX16:
117    return Mips::BteqzX16;
118  case Mips::Btnez16:
119  case Mips::BtnezX16:
120    return Mips::BtnezX16;
121  case Mips::JalB16:
122    return Mips::JalB16;
123  case Mips::BeqzRxImm16:
124  case Mips::BeqzRxImmX16:
125    return Mips::BeqzRxImmX16;
126  case Mips::BnezRxImm16:
127  case Mips::BnezRxImmX16:
128    return Mips::BnezRxImmX16;
129  }
130  llvm_unreachable("Unknown branch type");
131}
132
133//
134// FIXME: need to go through this whole constant islands port and check the math
135// for branch ranges and clean this up and make some functions to calculate things
136// that are done many times identically.
137// Need to refactor some of the code to call this routine.
138//
139static unsigned int branchMaxOffsets(unsigned int Opcode) {
140  unsigned Bits, Scale;
141  switch (Opcode) {
142    case Mips::Bimm16:
143      Bits = 11;
144      Scale = 2;
145      break;
146    case Mips::BimmX16:
147      Bits = 16;
148      Scale = 2;
149      break;
150    case Mips::BeqzRxImm16:
151      Bits = 8;
152      Scale = 2;
153      break;
154    case Mips::BeqzRxImmX16:
155      Bits = 16;
156      Scale = 2;
157      break;
158    case Mips::BnezRxImm16:
159      Bits = 8;
160      Scale = 2;
161      break;
162    case Mips::BnezRxImmX16:
163      Bits = 16;
164      Scale = 2;
165      break;
166    case Mips::Bteqz16:
167      Bits = 8;
168      Scale = 2;
169      break;
170    case Mips::BteqzX16:
171      Bits = 16;
172      Scale = 2;
173      break;
174    case Mips::Btnez16:
175      Bits = 8;
176      Scale = 2;
177      break;
178    case Mips::BtnezX16:
179      Bits = 16;
180      Scale = 2;
181      break;
182    default:
183      llvm_unreachable("Unknown branch type");
184  }
185  unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
186  return MaxOffs;
187}
188
189namespace {
190
191
192  typedef MachineBasicBlock::iterator Iter;
193  typedef MachineBasicBlock::reverse_iterator ReverseIter;
194
195  /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
196  /// requires constant pool entries to be scattered among the instructions
197  /// inside a function.  To do this, it completely ignores the normal LLVM
198  /// constant pool; instead, it places constants wherever it feels like with
199  /// special instructions.
200  ///
201  /// The terminology used in this pass includes:
202  ///   Islands - Clumps of constants placed in the function.
203  ///   Water   - Potential places where an island could be formed.
204  ///   CPE     - A constant pool entry that has been placed somewhere, which
205  ///             tracks a list of users.
206
207  class MipsConstantIslands : public MachineFunctionPass {
208
209    /// BasicBlockInfo - Information about the offset and size of a single
210    /// basic block.
211    struct BasicBlockInfo {
212      /// Offset - Distance from the beginning of the function to the beginning
213      /// of this basic block.
214      ///
215      /// Offsets are computed assuming worst case padding before an aligned
216      /// block. This means that subtracting basic block offsets always gives a
217      /// conservative estimate of the real distance which may be smaller.
218      ///
219      /// Because worst case padding is used, the computed offset of an aligned
220      /// block may not actually be aligned.
221      unsigned Offset;
222
223      /// Size - Size of the basic block in bytes.  If the block contains
224      /// inline assembly, this is a worst case estimate.
225      ///
226      /// The size does not include any alignment padding whether from the
227      /// beginning of the block, or from an aligned jump table at the end.
228      unsigned Size;
229
230      // FIXME: ignore LogAlign for this patch
231      //
232      unsigned postOffset(unsigned LogAlign = 0) const {
233        unsigned PO = Offset + Size;
234        return PO;
235      }
236
237      BasicBlockInfo() : Offset(0), Size(0) {}
238
239    };
240
241    std::vector<BasicBlockInfo> BBInfo;
242
243    /// WaterList - A sorted list of basic blocks where islands could be placed
244    /// (i.e. blocks that don't fall through to the following block, due
245    /// to a return, unreachable, or unconditional branch).
246    std::vector<MachineBasicBlock*> WaterList;
247
248    /// NewWaterList - The subset of WaterList that was created since the
249    /// previous iteration by inserting unconditional branches.
250    SmallSet<MachineBasicBlock*, 4> NewWaterList;
251
252    typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
253
254    /// CPUser - One user of a constant pool, keeping the machine instruction
255    /// pointer, the constant pool being referenced, and the max displacement
256    /// allowed from the instruction to the CP.  The HighWaterMark records the
257    /// highest basic block where a new CPEntry can be placed.  To ensure this
258    /// pass terminates, the CP entries are initially placed at the end of the
259    /// function and then move monotonically to lower addresses.  The
260    /// exception to this rule is when the current CP entry for a particular
261    /// CPUser is out of range, but there is another CP entry for the same
262    /// constant value in range.  We want to use the existing in-range CP
263    /// entry, but if it later moves out of range, the search for new water
264    /// should resume where it left off.  The HighWaterMark is used to record
265    /// that point.
266    struct CPUser {
267      MachineInstr *MI;
268      MachineInstr *CPEMI;
269      MachineBasicBlock *HighWaterMark;
270    private:
271      unsigned MaxDisp;
272      unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
273                                // with different displacements
274      unsigned LongFormOpcode;
275    public:
276      bool NegOk;
277      CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
278             bool neg,
279             unsigned longformmaxdisp, unsigned longformopcode)
280        : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
281          LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
282          NegOk(neg){
283        HighWaterMark = CPEMI->getParent();
284      }
285      /// getMaxDisp - Returns the maximum displacement supported by MI.
286      unsigned getMaxDisp() const {
287        unsigned xMaxDisp = ConstantIslandsSmallOffset?
288                            ConstantIslandsSmallOffset: MaxDisp;
289        return xMaxDisp;
290      }
291      void setMaxDisp(unsigned val) {
292        MaxDisp = val;
293      }
294      unsigned getLongFormMaxDisp() const {
295        return LongFormMaxDisp;
296      }
297      unsigned getLongFormOpcode() const {
298          return LongFormOpcode;
299      }
300    };
301
302    /// CPUsers - Keep track of all of the machine instructions that use various
303    /// constant pools and their max displacement.
304    std::vector<CPUser> CPUsers;
305
306  /// CPEntry - One per constant pool entry, keeping the machine instruction
307  /// pointer, the constpool index, and the number of CPUser's which
308  /// reference this entry.
309  struct CPEntry {
310    MachineInstr *CPEMI;
311    unsigned CPI;
312    unsigned RefCount;
313    CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
314      : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
315  };
316
317  /// CPEntries - Keep track of all of the constant pool entry machine
318  /// instructions. For each original constpool index (i.e. those that
319  /// existed upon entry to this pass), it keeps a vector of entries.
320  /// Original elements are cloned as we go along; the clones are
321  /// put in the vector of the original element, but have distinct CPIs.
322  std::vector<std::vector<CPEntry> > CPEntries;
323
324  /// ImmBranch - One per immediate branch, keeping the machine instruction
325  /// pointer, conditional or unconditional, the max displacement,
326  /// and (if isCond is true) the corresponding unconditional branch
327  /// opcode.
328  struct ImmBranch {
329    MachineInstr *MI;
330    unsigned MaxDisp : 31;
331    bool isCond : 1;
332    int UncondBr;
333    ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
334      : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
335  };
336
337  /// ImmBranches - Keep track of all the immediate branch instructions.
338  ///
339  std::vector<ImmBranch> ImmBranches;
340
341  /// HasFarJump - True if any far jump instruction has been emitted during
342  /// the branch fix up pass.
343  bool HasFarJump;
344
345  const TargetMachine &TM;
346  bool IsPIC;
347  const MipsSubtarget *STI;
348  const Mips16InstrInfo *TII;
349  MipsFunctionInfo *MFI;
350  MachineFunction *MF;
351  MachineConstantPool *MCP;
352
353  unsigned PICLabelUId;
354  bool PrescannedForConstants;
355
356  void initPICLabelUId(unsigned UId) {
357    PICLabelUId = UId;
358  }
359
360
361  unsigned createPICLabelUId() {
362    return PICLabelUId++;
363  }
364
365  public:
366    static char ID;
367    MipsConstantIslands(TargetMachine &tm)
368        : MachineFunctionPass(ID), TM(tm),
369          IsPIC(TM.getRelocationModel() == Reloc::PIC_), STI(nullptr),
370          MF(nullptr), MCP(nullptr), PrescannedForConstants(false) {}
371
372    const char *getPassName() const override {
373      return "Mips Constant Islands";
374    }
375
376    bool runOnMachineFunction(MachineFunction &F) override;
377
378    void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
379    CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
380    unsigned getCPELogAlign(const MachineInstr *CPEMI);
381    void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
382    unsigned getOffsetOf(MachineInstr *MI) const;
383    unsigned getUserOffset(CPUser&) const;
384    void dumpBBs();
385
386    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
387                         unsigned Disp, bool NegativeOK);
388    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
389                         const CPUser &U);
390
391    void computeBlockSize(MachineBasicBlock *MBB);
392    MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
393    void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
394    void adjustBBOffsetsAfter(MachineBasicBlock *BB);
395    bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
396    int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
397    int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
398    bool findAvailableWater(CPUser&U, unsigned UserOffset,
399                            water_iterator &WaterIter);
400    void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
401                        MachineBasicBlock *&NewMBB);
402    bool handleConstantPoolUser(unsigned CPUserIndex);
403    void removeDeadCPEMI(MachineInstr *CPEMI);
404    bool removeUnusedCPEntries();
405    bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
406                          MachineInstr *CPEMI, unsigned Disp, bool NegOk,
407                          bool DoDump = false);
408    bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
409                        CPUser &U, unsigned &Growth);
410    bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
411    bool fixupImmediateBr(ImmBranch &Br);
412    bool fixupConditionalBr(ImmBranch &Br);
413    bool fixupUnconditionalBr(ImmBranch &Br);
414
415    void prescanForConstants();
416
417  private:
418
419  };
420
421  char MipsConstantIslands::ID = 0;
422} // end of anonymous namespace
423
424bool MipsConstantIslands::isOffsetInRange
425  (unsigned UserOffset, unsigned TrialOffset,
426   const CPUser &U) {
427  return isOffsetInRange(UserOffset, TrialOffset,
428                         U.getMaxDisp(), U.NegOk);
429}
430/// print block size and offset information - debugging
431void MipsConstantIslands::dumpBBs() {
432  DEBUG({
433    for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
434      const BasicBlockInfo &BBI = BBInfo[J];
435      dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
436             << format(" size=%#x\n", BBInfo[J].Size);
437    }
438  });
439}
440/// createMipsLongBranchPass - Returns a pass that converts branches to long
441/// branches.
442FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
443  return new MipsConstantIslands(tm);
444}
445
446bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
447  // The intention is for this to be a mips16 only pass for now
448  // FIXME:
449  MF = &mf;
450  MCP = mf.getConstantPool();
451  STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
452  DEBUG(dbgs() << "constant island machine function " << "\n");
453  if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
454    return false;
455  }
456  TII = (const Mips16InstrInfo *)STI->getInstrInfo();
457  MFI = MF->getInfo<MipsFunctionInfo>();
458  DEBUG(dbgs() << "constant island processing " << "\n");
459  //
460  // will need to make predermination if there is any constants we need to
461  // put in constant islands. TBD.
462  //
463  if (!PrescannedForConstants) prescanForConstants();
464
465  HasFarJump = false;
466  // This pass invalidates liveness information when it splits basic blocks.
467  MF->getRegInfo().invalidateLiveness();
468
469  // Renumber all of the machine basic blocks in the function, guaranteeing that
470  // the numbers agree with the position of the block in the function.
471  MF->RenumberBlocks();
472
473  bool MadeChange = false;
474
475  // Perform the initial placement of the constant pool entries.  To start with,
476  // we put them all at the end of the function.
477  std::vector<MachineInstr*> CPEMIs;
478  if (!MCP->isEmpty())
479    doInitialPlacement(CPEMIs);
480
481  /// The next UID to take is the first unused one.
482  initPICLabelUId(CPEMIs.size());
483
484  // Do the initial scan of the function, building up information about the
485  // sizes of each block, the location of all the water, and finding all of the
486  // constant pool users.
487  initializeFunctionInfo(CPEMIs);
488  CPEMIs.clear();
489  DEBUG(dumpBBs());
490
491  /// Remove dead constant pool entries.
492  MadeChange |= removeUnusedCPEntries();
493
494  // Iteratively place constant pool entries and fix up branches until there
495  // is no change.
496  unsigned NoCPIters = 0, NoBRIters = 0;
497  (void)NoBRIters;
498  while (true) {
499    DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
500    bool CPChange = false;
501    for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
502      CPChange |= handleConstantPoolUser(i);
503    if (CPChange && ++NoCPIters > 30)
504      report_fatal_error("Constant Island pass failed to converge!");
505    DEBUG(dumpBBs());
506
507    // Clear NewWaterList now.  If we split a block for branches, it should
508    // appear as "new water" for the next iteration of constant pool placement.
509    NewWaterList.clear();
510
511    DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
512    bool BRChange = false;
513    for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
514      BRChange |= fixupImmediateBr(ImmBranches[i]);
515    if (BRChange && ++NoBRIters > 30)
516      report_fatal_error("Branch Fix Up pass failed to converge!");
517    DEBUG(dumpBBs());
518    if (!CPChange && !BRChange)
519      break;
520    MadeChange = true;
521  }
522
523  DEBUG(dbgs() << '\n'; dumpBBs());
524
525  BBInfo.clear();
526  WaterList.clear();
527  CPUsers.clear();
528  CPEntries.clear();
529  ImmBranches.clear();
530  return MadeChange;
531}
532
533/// doInitialPlacement - Perform the initial placement of the constant pool
534/// entries.  To start with, we put them all at the end of the function.
535void
536MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
537  // Create the basic block to hold the CPE's.
538  MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
539  MF->push_back(BB);
540
541
542  // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
543  unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
544
545  // Mark the basic block as required by the const-pool.
546  // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
547  BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
548
549  // The function needs to be as aligned as the basic blocks. The linker may
550  // move functions around based on their alignment.
551  MF->ensureAlignment(BB->getAlignment());
552
553  // Order the entries in BB by descending alignment.  That ensures correct
554  // alignment of all entries as long as BB is sufficiently aligned.  Keep
555  // track of the insertion point for each alignment.  We are going to bucket
556  // sort the entries as they are created.
557  SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
558
559  // Add all of the constants from the constant pool to the end block, use an
560  // identity mapping of CPI's to CPE's.
561  const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
562
563  const DataLayout &TD = *MF->getTarget().getDataLayout();
564  for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
565    unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
566    assert(Size >= 4 && "Too small constant pool entry");
567    unsigned Align = CPs[i].getAlignment();
568    assert(isPowerOf2_32(Align) && "Invalid alignment");
569    // Verify that all constant pool entries are a multiple of their alignment.
570    // If not, we would have to pad them out so that instructions stay aligned.
571    assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
572
573    // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
574    unsigned LogAlign = Log2_32(Align);
575    MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
576
577    MachineInstr *CPEMI =
578      BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
579        .addImm(i).addConstantPoolIndex(i).addImm(Size);
580
581    CPEMIs.push_back(CPEMI);
582
583    // Ensure that future entries with higher alignment get inserted before
584    // CPEMI. This is bucket sort with iterators.
585    for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
586      if (InsPoint[a] == InsAt)
587        InsPoint[a] = CPEMI;
588    // Add a new CPEntry, but no corresponding CPUser yet.
589    CPEntries.emplace_back(1, CPEntry(CPEMI, i));
590    ++NumCPEs;
591    DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
592                 << Size << ", align = " << Align <<'\n');
593  }
594  DEBUG(BB->dump());
595}
596
597/// BBHasFallthrough - Return true if the specified basic block can fallthrough
598/// into the block immediately after it.
599static bool BBHasFallthrough(MachineBasicBlock *MBB) {
600  // Get the next machine basic block in the function.
601  MachineFunction::iterator MBBI = MBB;
602  // Can't fall off end of function.
603  if (std::next(MBBI) == MBB->getParent()->end())
604    return false;
605
606  MachineBasicBlock *NextBB = std::next(MBBI);
607  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
608       E = MBB->succ_end(); I != E; ++I)
609    if (*I == NextBB)
610      return true;
611
612  return false;
613}
614
615/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
616/// look up the corresponding CPEntry.
617MipsConstantIslands::CPEntry
618*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
619                                        const MachineInstr *CPEMI) {
620  std::vector<CPEntry> &CPEs = CPEntries[CPI];
621  // Number of entries per constpool index should be small, just do a
622  // linear search.
623  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
624    if (CPEs[i].CPEMI == CPEMI)
625      return &CPEs[i];
626  }
627  return nullptr;
628}
629
630/// getCPELogAlign - Returns the required alignment of the constant pool entry
631/// represented by CPEMI.  Alignment is measured in log2(bytes) units.
632unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
633  assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
634
635  // Everything is 4-byte aligned unless AlignConstantIslands is set.
636  if (!AlignConstantIslands)
637    return 2;
638
639  unsigned CPI = CPEMI->getOperand(1).getIndex();
640  assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
641  unsigned Align = MCP->getConstants()[CPI].getAlignment();
642  assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
643  return Log2_32(Align);
644}
645
646/// initializeFunctionInfo - Do the initial scan of the function, building up
647/// information about the sizes of each block, the location of all the water,
648/// and finding all of the constant pool users.
649void MipsConstantIslands::
650initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
651  BBInfo.clear();
652  BBInfo.resize(MF->getNumBlockIDs());
653
654  // First thing, compute the size of all basic blocks, and see if the function
655  // has any inline assembly in it. If so, we have to be conservative about
656  // alignment assumptions, as we don't know for sure the size of any
657  // instructions in the inline assembly.
658  for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
659    computeBlockSize(I);
660
661
662  // Compute block offsets.
663  adjustBBOffsetsAfter(MF->begin());
664
665  // Now go back through the instructions and build up our data structures.
666  for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
667       MBBI != E; ++MBBI) {
668    MachineBasicBlock &MBB = *MBBI;
669
670    // If this block doesn't fall through into the next MBB, then this is
671    // 'water' that a constant pool island could be placed.
672    if (!BBHasFallthrough(&MBB))
673      WaterList.push_back(&MBB);
674    for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
675         I != E; ++I) {
676      if (I->isDebugValue())
677        continue;
678
679      int Opc = I->getOpcode();
680      if (I->isBranch()) {
681        bool isCond = false;
682        unsigned Bits = 0;
683        unsigned Scale = 1;
684        int UOpc = Opc;
685        switch (Opc) {
686        default:
687          continue;  // Ignore other branches for now
688        case Mips::Bimm16:
689          Bits = 11;
690          Scale = 2;
691          isCond = false;
692          break;
693        case Mips::BimmX16:
694          Bits = 16;
695          Scale = 2;
696          isCond = false;
697          break;
698        case Mips::BeqzRxImm16:
699          UOpc=Mips::Bimm16;
700          Bits = 8;
701          Scale = 2;
702          isCond = true;
703          break;
704        case Mips::BeqzRxImmX16:
705          UOpc=Mips::Bimm16;
706          Bits = 16;
707          Scale = 2;
708          isCond = true;
709          break;
710        case Mips::BnezRxImm16:
711          UOpc=Mips::Bimm16;
712          Bits = 8;
713          Scale = 2;
714          isCond = true;
715          break;
716        case Mips::BnezRxImmX16:
717          UOpc=Mips::Bimm16;
718          Bits = 16;
719          Scale = 2;
720          isCond = true;
721          break;
722        case Mips::Bteqz16:
723          UOpc=Mips::Bimm16;
724          Bits = 8;
725          Scale = 2;
726          isCond = true;
727          break;
728        case Mips::BteqzX16:
729          UOpc=Mips::Bimm16;
730          Bits = 16;
731          Scale = 2;
732          isCond = true;
733          break;
734        case Mips::Btnez16:
735          UOpc=Mips::Bimm16;
736          Bits = 8;
737          Scale = 2;
738          isCond = true;
739          break;
740        case Mips::BtnezX16:
741          UOpc=Mips::Bimm16;
742          Bits = 16;
743          Scale = 2;
744          isCond = true;
745          break;
746        }
747        // Record this immediate branch.
748        unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
749        ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
750      }
751
752      if (Opc == Mips::CONSTPOOL_ENTRY)
753        continue;
754
755
756      // Scan the instructions for constant pool operands.
757      for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
758        if (I->getOperand(op).isCPI()) {
759
760          // We found one.  The addressing mode tells us the max displacement
761          // from the PC that this instruction permits.
762
763          // Basic size info comes from the TSFlags field.
764          unsigned Bits = 0;
765          unsigned Scale = 1;
766          bool NegOk = false;
767          unsigned LongFormBits = 0;
768          unsigned LongFormScale = 0;
769          unsigned LongFormOpcode = 0;
770          switch (Opc) {
771          default:
772            llvm_unreachable("Unknown addressing mode for CP reference!");
773          case Mips::LwRxPcTcp16:
774            Bits = 8;
775            Scale = 4;
776            LongFormOpcode = Mips::LwRxPcTcpX16;
777            LongFormBits = 14;
778            LongFormScale = 1;
779            break;
780          case Mips::LwRxPcTcpX16:
781            Bits = 14;
782            Scale = 1;
783            NegOk = true;
784            break;
785          }
786          // Remember that this is a user of a CP entry.
787          unsigned CPI = I->getOperand(op).getIndex();
788          MachineInstr *CPEMI = CPEMIs[CPI];
789          unsigned MaxOffs = ((1 << Bits)-1) * Scale;
790          unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
791          CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
792                                   LongFormMaxOffs, LongFormOpcode));
793
794          // Increment corresponding CPEntry reference count.
795          CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
796          assert(CPE && "Cannot find a corresponding CPEntry!");
797          CPE->RefCount++;
798
799          // Instructions can only use one CP entry, don't bother scanning the
800          // rest of the operands.
801          break;
802
803        }
804
805    }
806  }
807
808}
809
810/// computeBlockSize - Compute the size and some alignment information for MBB.
811/// This function updates BBInfo directly.
812void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
813  BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
814  BBI.Size = 0;
815
816  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
817       ++I)
818    BBI.Size += TII->GetInstSizeInBytes(I);
819
820}
821
822/// getOffsetOf - Return the current offset of the specified machine instruction
823/// from the start of the function.  This offset changes as stuff is moved
824/// around inside the function.
825unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
826  MachineBasicBlock *MBB = MI->getParent();
827
828  // The offset is composed of two things: the sum of the sizes of all MBB's
829  // before this instruction's block, and the offset from the start of the block
830  // it is in.
831  unsigned Offset = BBInfo[MBB->getNumber()].Offset;
832
833  // Sum instructions before MI in MBB.
834  for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
835    assert(I != MBB->end() && "Didn't find MI in its own basic block?");
836    Offset += TII->GetInstSizeInBytes(I);
837  }
838  return Offset;
839}
840
841/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
842/// ID.
843static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
844                              const MachineBasicBlock *RHS) {
845  return LHS->getNumber() < RHS->getNumber();
846}
847
848/// updateForInsertedWaterBlock - When a block is newly inserted into the
849/// machine function, it upsets all of the block numbers.  Renumber the blocks
850/// and update the arrays that parallel this numbering.
851void MipsConstantIslands::updateForInsertedWaterBlock
852  (MachineBasicBlock *NewBB) {
853  // Renumber the MBB's to keep them consecutive.
854  NewBB->getParent()->RenumberBlocks(NewBB);
855
856  // Insert an entry into BBInfo to align it properly with the (newly
857  // renumbered) block numbers.
858  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
859
860  // Next, update WaterList.  Specifically, we need to add NewMBB as having
861  // available water after it.
862  water_iterator IP =
863    std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
864                     CompareMBBNumbers);
865  WaterList.insert(IP, NewBB);
866}
867
868unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
869  return getOffsetOf(U.MI);
870}
871
872/// Split the basic block containing MI into two blocks, which are joined by
873/// an unconditional branch.  Update data structures and renumber blocks to
874/// account for this change and returns the newly created block.
875MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
876  (MachineInstr *MI) {
877  MachineBasicBlock *OrigBB = MI->getParent();
878
879  // Create a new MBB for the code after the OrigBB.
880  MachineBasicBlock *NewBB =
881    MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
882  MachineFunction::iterator MBBI = OrigBB; ++MBBI;
883  MF->insert(MBBI, NewBB);
884
885  // Splice the instructions starting with MI over to NewBB.
886  NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
887
888  // Add an unconditional branch from OrigBB to NewBB.
889  // Note the new unconditional branch is not being recorded.
890  // There doesn't seem to be meaningful DebugInfo available; this doesn't
891  // correspond to anything in the source.
892  BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
893  ++NumSplit;
894
895  // Update the CFG.  All succs of OrigBB are now succs of NewBB.
896  NewBB->transferSuccessors(OrigBB);
897
898  // OrigBB branches to NewBB.
899  OrigBB->addSuccessor(NewBB);
900
901  // Update internal data structures to account for the newly inserted MBB.
902  // This is almost the same as updateForInsertedWaterBlock, except that
903  // the Water goes after OrigBB, not NewBB.
904  MF->RenumberBlocks(NewBB);
905
906  // Insert an entry into BBInfo to align it properly with the (newly
907  // renumbered) block numbers.
908  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
909
910  // Next, update WaterList.  Specifically, we need to add OrigMBB as having
911  // available water after it (but not if it's already there, which happens
912  // when splitting before a conditional branch that is followed by an
913  // unconditional branch - in that case we want to insert NewBB).
914  water_iterator IP =
915    std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
916                     CompareMBBNumbers);
917  MachineBasicBlock* WaterBB = *IP;
918  if (WaterBB == OrigBB)
919    WaterList.insert(std::next(IP), NewBB);
920  else
921    WaterList.insert(IP, OrigBB);
922  NewWaterList.insert(OrigBB);
923
924  // Figure out how large the OrigBB is.  As the first half of the original
925  // block, it cannot contain a tablejump.  The size includes
926  // the new jump we added.  (It should be possible to do this without
927  // recounting everything, but it's very confusing, and this is rarely
928  // executed.)
929  computeBlockSize(OrigBB);
930
931  // Figure out how large the NewMBB is.  As the second half of the original
932  // block, it may contain a tablejump.
933  computeBlockSize(NewBB);
934
935  // All BBOffsets following these blocks must be modified.
936  adjustBBOffsetsAfter(OrigBB);
937
938  return NewBB;
939}
940
941
942
943/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
944/// reference) is within MaxDisp of TrialOffset (a proposed location of a
945/// constant pool entry).
946bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
947                                         unsigned TrialOffset, unsigned MaxDisp,
948                                         bool NegativeOK) {
949  if (UserOffset <= TrialOffset) {
950    // User before the Trial.
951    if (TrialOffset - UserOffset <= MaxDisp)
952      return true;
953  } else if (NegativeOK) {
954    if (UserOffset - TrialOffset <= MaxDisp)
955      return true;
956  }
957  return false;
958}
959
960/// isWaterInRange - Returns true if a CPE placed after the specified
961/// Water (a basic block) will be in range for the specific MI.
962///
963/// Compute how much the function will grow by inserting a CPE after Water.
964bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
965                                        MachineBasicBlock* Water, CPUser &U,
966                                        unsigned &Growth) {
967  unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
968  unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
969  unsigned NextBlockOffset, NextBlockAlignment;
970  MachineFunction::const_iterator NextBlock = Water;
971  if (++NextBlock == MF->end()) {
972    NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
973    NextBlockAlignment = 0;
974  } else {
975    NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
976    NextBlockAlignment = NextBlock->getAlignment();
977  }
978  unsigned Size = U.CPEMI->getOperand(2).getImm();
979  unsigned CPEEnd = CPEOffset + Size;
980
981  // The CPE may be able to hide in the alignment padding before the next
982  // block. It may also cause more padding to be required if it is more aligned
983  // that the next block.
984  if (CPEEnd > NextBlockOffset) {
985    Growth = CPEEnd - NextBlockOffset;
986    // Compute the padding that would go at the end of the CPE to align the next
987    // block.
988    Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
989
990    // If the CPE is to be inserted before the instruction, that will raise
991    // the offset of the instruction. Also account for unknown alignment padding
992    // in blocks between CPE and the user.
993    if (CPEOffset < UserOffset)
994      UserOffset += Growth;
995  } else
996    // CPE fits in existing padding.
997    Growth = 0;
998
999  return isOffsetInRange(UserOffset, CPEOffset, U);
1000}
1001
1002/// isCPEntryInRange - Returns true if the distance between specific MI and
1003/// specific ConstPool entry instruction can fit in MI's displacement field.
1004bool MipsConstantIslands::isCPEntryInRange
1005  (MachineInstr *MI, unsigned UserOffset,
1006   MachineInstr *CPEMI, unsigned MaxDisp,
1007   bool NegOk, bool DoDump) {
1008  unsigned CPEOffset  = getOffsetOf(CPEMI);
1009
1010  if (DoDump) {
1011    DEBUG({
1012      unsigned Block = MI->getParent()->getNumber();
1013      const BasicBlockInfo &BBI = BBInfo[Block];
1014      dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1015             << " max delta=" << MaxDisp
1016             << format(" insn address=%#x", UserOffset)
1017             << " in BB#" << Block << ": "
1018             << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1019             << format("CPE address=%#x offset=%+d: ", CPEOffset,
1020                       int(CPEOffset-UserOffset));
1021    });
1022  }
1023
1024  return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1025}
1026
1027#ifndef NDEBUG
1028/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1029/// unconditionally branches to its only successor.
1030static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1031  if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1032    return false;
1033  MachineBasicBlock *Succ = *MBB->succ_begin();
1034  MachineBasicBlock *Pred = *MBB->pred_begin();
1035  MachineInstr *PredMI = &Pred->back();
1036  if (PredMI->getOpcode() == Mips::Bimm16)
1037    return PredMI->getOperand(0).getMBB() == Succ;
1038  return false;
1039}
1040#endif
1041
1042void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1043  unsigned BBNum = BB->getNumber();
1044  for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1045    // Get the offset and known bits at the end of the layout predecessor.
1046    // Include the alignment of the current block.
1047    unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
1048    BBInfo[i].Offset = Offset;
1049  }
1050}
1051
1052/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1053/// and instruction CPEMI, and decrement its refcount.  If the refcount
1054/// becomes 0 remove the entry and instruction.  Returns true if we removed
1055/// the entry, false if we didn't.
1056
1057bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1058                                                    MachineInstr *CPEMI) {
1059  // Find the old entry. Eliminate it if it is no longer used.
1060  CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1061  assert(CPE && "Unexpected!");
1062  if (--CPE->RefCount == 0) {
1063    removeDeadCPEMI(CPEMI);
1064    CPE->CPEMI = nullptr;
1065    --NumCPEs;
1066    return true;
1067  }
1068  return false;
1069}
1070
1071/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1072/// if not, see if an in-range clone of the CPE is in range, and if so,
1073/// change the data structures so the user references the clone.  Returns:
1074/// 0 = no existing entry found
1075/// 1 = entry found, and there were no code insertions or deletions
1076/// 2 = entry found, and there were code insertions or deletions
1077int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1078{
1079  MachineInstr *UserMI = U.MI;
1080  MachineInstr *CPEMI  = U.CPEMI;
1081
1082  // Check to see if the CPE is already in-range.
1083  if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1084                       true)) {
1085    DEBUG(dbgs() << "In range\n");
1086    return 1;
1087  }
1088
1089  // No.  Look for previously created clones of the CPE that are in range.
1090  unsigned CPI = CPEMI->getOperand(1).getIndex();
1091  std::vector<CPEntry> &CPEs = CPEntries[CPI];
1092  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1093    // We already tried this one
1094    if (CPEs[i].CPEMI == CPEMI)
1095      continue;
1096    // Removing CPEs can leave empty entries, skip
1097    if (CPEs[i].CPEMI == nullptr)
1098      continue;
1099    if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1100                     U.NegOk)) {
1101      DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1102                   << CPEs[i].CPI << "\n");
1103      // Point the CPUser node to the replacement
1104      U.CPEMI = CPEs[i].CPEMI;
1105      // Change the CPI in the instruction operand to refer to the clone.
1106      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1107        if (UserMI->getOperand(j).isCPI()) {
1108          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1109          break;
1110        }
1111      // Adjust the refcount of the clone...
1112      CPEs[i].RefCount++;
1113      // ...and the original.  If we didn't remove the old entry, none of the
1114      // addresses changed, so we don't need another pass.
1115      return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1116    }
1117  }
1118  return 0;
1119}
1120
1121/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1122/// This version checks if the longer form of the instruction can be used to
1123/// to satisfy things.
1124/// if not, see if an in-range clone of the CPE is in range, and if so,
1125/// change the data structures so the user references the clone.  Returns:
1126/// 0 = no existing entry found
1127/// 1 = entry found, and there were no code insertions or deletions
1128/// 2 = entry found, and there were code insertions or deletions
1129int MipsConstantIslands::findLongFormInRangeCPEntry
1130  (CPUser& U, unsigned UserOffset)
1131{
1132  MachineInstr *UserMI = U.MI;
1133  MachineInstr *CPEMI  = U.CPEMI;
1134
1135  // Check to see if the CPE is already in-range.
1136  if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1137                       U.getLongFormMaxDisp(), U.NegOk,
1138                       true)) {
1139    DEBUG(dbgs() << "In range\n");
1140    UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1141    U.setMaxDisp(U.getLongFormMaxDisp());
1142    return 2;  // instruction is longer length now
1143  }
1144
1145  // No.  Look for previously created clones of the CPE that are in range.
1146  unsigned CPI = CPEMI->getOperand(1).getIndex();
1147  std::vector<CPEntry> &CPEs = CPEntries[CPI];
1148  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1149    // We already tried this one
1150    if (CPEs[i].CPEMI == CPEMI)
1151      continue;
1152    // Removing CPEs can leave empty entries, skip
1153    if (CPEs[i].CPEMI == nullptr)
1154      continue;
1155    if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1156                         U.getLongFormMaxDisp(), U.NegOk)) {
1157      DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1158                   << CPEs[i].CPI << "\n");
1159      // Point the CPUser node to the replacement
1160      U.CPEMI = CPEs[i].CPEMI;
1161      // Change the CPI in the instruction operand to refer to the clone.
1162      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1163        if (UserMI->getOperand(j).isCPI()) {
1164          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1165          break;
1166        }
1167      // Adjust the refcount of the clone...
1168      CPEs[i].RefCount++;
1169      // ...and the original.  If we didn't remove the old entry, none of the
1170      // addresses changed, so we don't need another pass.
1171      return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1172    }
1173  }
1174  return 0;
1175}
1176
1177/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1178/// the specific unconditional branch instruction.
1179static inline unsigned getUnconditionalBrDisp(int Opc) {
1180  switch (Opc) {
1181  case Mips::Bimm16:
1182    return ((1<<10)-1)*2;
1183  case Mips::BimmX16:
1184    return ((1<<16)-1)*2;
1185  default:
1186    break;
1187  }
1188  return ((1<<16)-1)*2;
1189}
1190
1191/// findAvailableWater - Look for an existing entry in the WaterList in which
1192/// we can place the CPE referenced from U so it's within range of U's MI.
1193/// Returns true if found, false if not.  If it returns true, WaterIter
1194/// is set to the WaterList entry.
1195/// To ensure that this pass
1196/// terminates, the CPE location for a particular CPUser is only allowed to
1197/// move to a lower address, so search backward from the end of the list and
1198/// prefer the first water that is in range.
1199bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1200                                      water_iterator &WaterIter) {
1201  if (WaterList.empty())
1202    return false;
1203
1204  unsigned BestGrowth = ~0u;
1205  for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1206       --IP) {
1207    MachineBasicBlock* WaterBB = *IP;
1208    // Check if water is in range and is either at a lower address than the
1209    // current "high water mark" or a new water block that was created since
1210    // the previous iteration by inserting an unconditional branch.  In the
1211    // latter case, we want to allow resetting the high water mark back to
1212    // this new water since we haven't seen it before.  Inserting branches
1213    // should be relatively uncommon and when it does happen, we want to be
1214    // sure to take advantage of it for all the CPEs near that block, so that
1215    // we don't insert more branches than necessary.
1216    unsigned Growth;
1217    if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1218        (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1219         NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1220      // This is the least amount of required padding seen so far.
1221      BestGrowth = Growth;
1222      WaterIter = IP;
1223      DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1224                   << " Growth=" << Growth << '\n');
1225
1226      // Keep looking unless it is perfect.
1227      if (BestGrowth == 0)
1228        return true;
1229    }
1230    if (IP == B)
1231      break;
1232  }
1233  return BestGrowth != ~0u;
1234}
1235
1236/// createNewWater - No existing WaterList entry will work for
1237/// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1238/// block is used if in range, and the conditional branch munged so control
1239/// flow is correct.  Otherwise the block is split to create a hole with an
1240/// unconditional branch around it.  In either case NewMBB is set to a
1241/// block following which the new island can be inserted (the WaterList
1242/// is not adjusted).
1243void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1244                                        unsigned UserOffset,
1245                                        MachineBasicBlock *&NewMBB) {
1246  CPUser &U = CPUsers[CPUserIndex];
1247  MachineInstr *UserMI = U.MI;
1248  MachineInstr *CPEMI  = U.CPEMI;
1249  unsigned CPELogAlign = getCPELogAlign(CPEMI);
1250  MachineBasicBlock *UserMBB = UserMI->getParent();
1251  const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1252
1253  // If the block does not end in an unconditional branch already, and if the
1254  // end of the block is within range, make new water there.
1255  if (BBHasFallthrough(UserMBB)) {
1256    // Size of branch to insert.
1257    unsigned Delta = 2;
1258    // Compute the offset where the CPE will begin.
1259    unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1260
1261    if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1262      DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1263            << format(", expected CPE offset %#x\n", CPEOffset));
1264      NewMBB = std::next(MachineFunction::iterator(UserMBB));
1265      // Add an unconditional branch from UserMBB to fallthrough block.  Record
1266      // it for branch lengthening; this new branch will not get out of range,
1267      // but if the preceding conditional branch is out of range, the targets
1268      // will be exchanged, and the altered branch may be out of range, so the
1269      // machinery has to know about it.
1270      int UncondBr = Mips::Bimm16;
1271      BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1272      unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1273      ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1274                                      MaxDisp, false, UncondBr));
1275      BBInfo[UserMBB->getNumber()].Size += Delta;
1276      adjustBBOffsetsAfter(UserMBB);
1277      return;
1278    }
1279  }
1280
1281  // What a big block.  Find a place within the block to split it.
1282
1283  // Try to split the block so it's fully aligned.  Compute the latest split
1284  // point where we can add a 4-byte branch instruction, and then align to
1285  // LogAlign which is the largest possible alignment in the function.
1286  unsigned LogAlign = MF->getAlignment();
1287  assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1288  unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1289  DEBUG(dbgs() << format("Split in middle of big block before %#x",
1290                         BaseInsertOffset));
1291
1292  // The 4 in the following is for the unconditional branch we'll be inserting
1293  // Alignment of the island is handled
1294  // inside isOffsetInRange.
1295  BaseInsertOffset -= 4;
1296
1297  DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1298               << " la=" << LogAlign << '\n');
1299
1300  // This could point off the end of the block if we've already got constant
1301  // pool entries following this block; only the last one is in the water list.
1302  // Back past any possible branches (allow for a conditional and a maximally
1303  // long unconditional).
1304  if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1305    BaseInsertOffset = UserBBI.postOffset() - 8;
1306    DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1307  }
1308  unsigned EndInsertOffset = BaseInsertOffset + 4 +
1309    CPEMI->getOperand(2).getImm();
1310  MachineBasicBlock::iterator MI = UserMI;
1311  ++MI;
1312  unsigned CPUIndex = CPUserIndex+1;
1313  unsigned NumCPUsers = CPUsers.size();
1314  //MachineInstr *LastIT = 0;
1315  for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1316       Offset < BaseInsertOffset;
1317       Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
1318    assert(MI != UserMBB->end() && "Fell off end of block");
1319    if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1320      CPUser &U = CPUsers[CPUIndex];
1321      if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1322        // Shift intertion point by one unit of alignment so it is within reach.
1323        BaseInsertOffset -= 1u << LogAlign;
1324        EndInsertOffset  -= 1u << LogAlign;
1325      }
1326      // This is overly conservative, as we don't account for CPEMIs being
1327      // reused within the block, but it doesn't matter much.  Also assume CPEs
1328      // are added in order with alignment padding.  We may eventually be able
1329      // to pack the aligned CPEs better.
1330      EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1331      CPUIndex++;
1332    }
1333  }
1334
1335  --MI;
1336  NewMBB = splitBlockBeforeInstr(MI);
1337}
1338
1339/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1340/// is out-of-range.  If so, pick up the constant pool value and move it some
1341/// place in-range.  Return true if we changed any addresses (thus must run
1342/// another pass of branch lengthening), false otherwise.
1343bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1344  CPUser &U = CPUsers[CPUserIndex];
1345  MachineInstr *UserMI = U.MI;
1346  MachineInstr *CPEMI  = U.CPEMI;
1347  unsigned CPI = CPEMI->getOperand(1).getIndex();
1348  unsigned Size = CPEMI->getOperand(2).getImm();
1349  // Compute this only once, it's expensive.
1350  unsigned UserOffset = getUserOffset(U);
1351
1352  // See if the current entry is within range, or there is a clone of it
1353  // in range.
1354  int result = findInRangeCPEntry(U, UserOffset);
1355  if (result==1) return false;
1356  else if (result==2) return true;
1357
1358
1359  // Look for water where we can place this CPE.
1360  MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1361  MachineBasicBlock *NewMBB;
1362  water_iterator IP;
1363  if (findAvailableWater(U, UserOffset, IP)) {
1364    DEBUG(dbgs() << "Found water in range\n");
1365    MachineBasicBlock *WaterBB = *IP;
1366
1367    // If the original WaterList entry was "new water" on this iteration,
1368    // propagate that to the new island.  This is just keeping NewWaterList
1369    // updated to match the WaterList, which will be updated below.
1370    if (NewWaterList.erase(WaterBB))
1371      NewWaterList.insert(NewIsland);
1372
1373    // The new CPE goes before the following block (NewMBB).
1374    NewMBB = std::next(MachineFunction::iterator(WaterBB));
1375
1376  } else {
1377    // No water found.
1378    // we first see if a longer form of the instrucion could have reached
1379    // the constant. in that case we won't bother to split
1380    if (!NoLoadRelaxation) {
1381      result = findLongFormInRangeCPEntry(U, UserOffset);
1382      if (result != 0) return true;
1383    }
1384    DEBUG(dbgs() << "No water found\n");
1385    createNewWater(CPUserIndex, UserOffset, NewMBB);
1386
1387    // splitBlockBeforeInstr adds to WaterList, which is important when it is
1388    // called while handling branches so that the water will be seen on the
1389    // next iteration for constant pools, but in this context, we don't want
1390    // it.  Check for this so it will be removed from the WaterList.
1391    // Also remove any entry from NewWaterList.
1392    MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
1393    IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1394    if (IP != WaterList.end())
1395      NewWaterList.erase(WaterBB);
1396
1397    // We are adding new water.  Update NewWaterList.
1398    NewWaterList.insert(NewIsland);
1399  }
1400
1401  // Remove the original WaterList entry; we want subsequent insertions in
1402  // this vicinity to go after the one we're about to insert.  This
1403  // considerably reduces the number of times we have to move the same CPE
1404  // more than once and is also important to ensure the algorithm terminates.
1405  if (IP != WaterList.end())
1406    WaterList.erase(IP);
1407
1408  // Okay, we know we can put an island before NewMBB now, do it!
1409  MF->insert(NewMBB, NewIsland);
1410
1411  // Update internal data structures to account for the newly inserted MBB.
1412  updateForInsertedWaterBlock(NewIsland);
1413
1414  // Decrement the old entry, and remove it if refcount becomes 0.
1415  decrementCPEReferenceCount(CPI, CPEMI);
1416
1417  // No existing clone of this CPE is within range.
1418  // We will be generating a new clone.  Get a UID for it.
1419  unsigned ID = createPICLabelUId();
1420
1421  // Now that we have an island to add the CPE to, clone the original CPE and
1422  // add it to the island.
1423  U.HighWaterMark = NewIsland;
1424  U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1425                .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1426  CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1427  ++NumCPEs;
1428
1429  // Mark the basic block as aligned as required by the const-pool entry.
1430  NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1431
1432  // Increase the size of the island block to account for the new entry.
1433  BBInfo[NewIsland->getNumber()].Size += Size;
1434  adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
1435
1436
1437
1438  // Finally, change the CPI in the instruction operand to be ID.
1439  for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1440    if (UserMI->getOperand(i).isCPI()) {
1441      UserMI->getOperand(i).setIndex(ID);
1442      break;
1443    }
1444
1445  DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1446        << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1447
1448  return true;
1449}
1450
1451/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1452/// sizes and offsets of impacted basic blocks.
1453void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1454  MachineBasicBlock *CPEBB = CPEMI->getParent();
1455  unsigned Size = CPEMI->getOperand(2).getImm();
1456  CPEMI->eraseFromParent();
1457  BBInfo[CPEBB->getNumber()].Size -= Size;
1458  // All succeeding offsets have the current size value added in, fix this.
1459  if (CPEBB->empty()) {
1460    BBInfo[CPEBB->getNumber()].Size = 0;
1461
1462    // This block no longer needs to be aligned.
1463    CPEBB->setAlignment(0);
1464  } else
1465    // Entries are sorted by descending alignment, so realign from the front.
1466    CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1467
1468  adjustBBOffsetsAfter(CPEBB);
1469  // An island has only one predecessor BB and one successor BB. Check if
1470  // this BB's predecessor jumps directly to this BB's successor. This
1471  // shouldn't happen currently.
1472  assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1473  // FIXME: remove the empty blocks after all the work is done?
1474}
1475
1476/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1477/// are zero.
1478bool MipsConstantIslands::removeUnusedCPEntries() {
1479  unsigned MadeChange = false;
1480  for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1481      std::vector<CPEntry> &CPEs = CPEntries[i];
1482      for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1483        if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1484          removeDeadCPEMI(CPEs[j].CPEMI);
1485          CPEs[j].CPEMI = nullptr;
1486          MadeChange = true;
1487        }
1488      }
1489  }
1490  return MadeChange;
1491}
1492
1493/// isBBInRange - Returns true if the distance between specific MI and
1494/// specific BB can fit in MI's displacement field.
1495bool MipsConstantIslands::isBBInRange
1496  (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1497
1498unsigned PCAdj = 4;
1499
1500  unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
1501  unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1502
1503  DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1504               << " from BB#" << MI->getParent()->getNumber()
1505               << " max delta=" << MaxDisp
1506               << " from " << getOffsetOf(MI) << " to " << DestOffset
1507               << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1508
1509  if (BrOffset <= DestOffset) {
1510    // Branch before the Dest.
1511    if (DestOffset-BrOffset <= MaxDisp)
1512      return true;
1513  } else {
1514    if (BrOffset-DestOffset <= MaxDisp)
1515      return true;
1516  }
1517  return false;
1518}
1519
1520/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1521/// away to fit in its displacement field.
1522bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1523  MachineInstr *MI = Br.MI;
1524  unsigned TargetOperand = branchTargetOperand(MI);
1525  MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1526
1527  // Check to see if the DestBB is already in-range.
1528  if (isBBInRange(MI, DestBB, Br.MaxDisp))
1529    return false;
1530
1531  if (!Br.isCond)
1532    return fixupUnconditionalBr(Br);
1533  return fixupConditionalBr(Br);
1534}
1535
1536/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1537/// too far away to fit in its displacement field. If the LR register has been
1538/// spilled in the epilogue, then we can use BL to implement a far jump.
1539/// Otherwise, add an intermediate branch instruction to a branch.
1540bool
1541MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1542  MachineInstr *MI = Br.MI;
1543  MachineBasicBlock *MBB = MI->getParent();
1544  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1545  // Use BL to implement far jump.
1546  unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1547  if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1548    Br.MaxDisp = BimmX16MaxDisp;
1549    MI->setDesc(TII->get(Mips::BimmX16));
1550  }
1551  else {
1552    // need to give the math a more careful look here
1553    // this is really a segment address and not
1554    // a PC relative address. FIXME. But I think that
1555    // just reducing the bits by 1 as I've done is correct.
1556    // The basic block we are branching too much be longword aligned.
1557    // we know that RA is saved because we always save it right now.
1558    // this requirement will be relaxed later but we also have an alternate
1559    // way to implement this that I will implement that does not need jal.
1560    // We should have a way to back out this alignment restriction if we "can" later.
1561    // but it is not harmful.
1562    //
1563    DestBB->setAlignment(2);
1564    Br.MaxDisp = ((1<<24)-1) * 2;
1565    MI->setDesc(TII->get(Mips::JalB16));
1566  }
1567  BBInfo[MBB->getNumber()].Size += 2;
1568  adjustBBOffsetsAfter(MBB);
1569  HasFarJump = true;
1570  ++NumUBrFixed;
1571
1572  DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1573
1574  return true;
1575}
1576
1577
1578/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1579/// far away to fit in its displacement field. It is converted to an inverse
1580/// conditional branch + an unconditional branch to the destination.
1581bool
1582MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1583  MachineInstr *MI = Br.MI;
1584  unsigned TargetOperand = branchTargetOperand(MI);
1585  MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1586  unsigned Opcode = MI->getOpcode();
1587  unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1588  unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1589
1590  // Check to see if the DestBB is already in-range.
1591  if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1592    Br.MaxDisp = LongFormMaxOff;
1593    MI->setDesc(TII->get(LongFormOpcode));
1594    return true;
1595  }
1596
1597  // Add an unconditional branch to the destination and invert the branch
1598  // condition to jump over it:
1599  // bteqz L1
1600  // =>
1601  // bnez L2
1602  // b   L1
1603  // L2:
1604
1605  // If the branch is at the end of its MBB and that has a fall-through block,
1606  // direct the updated conditional branch to the fall-through block. Otherwise,
1607  // split the MBB before the next instruction.
1608  MachineBasicBlock *MBB = MI->getParent();
1609  MachineInstr *BMI = &MBB->back();
1610  bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1611  unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
1612
1613  ++NumCBrFixed;
1614  if (BMI != MI) {
1615    if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1616        isUnconditionalBranch(BMI->getOpcode())) {
1617      // Last MI in the BB is an unconditional branch. Can we simply invert the
1618      // condition and swap destinations:
1619      // beqz L1
1620      // b   L2
1621      // =>
1622      // bnez L2
1623      // b   L1
1624      unsigned BMITargetOperand = branchTargetOperand(BMI);
1625      MachineBasicBlock *NewDest =
1626        BMI->getOperand(BMITargetOperand).getMBB();
1627      if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1628        DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
1629                     << *BMI);
1630        MI->setDesc(TII->get(OppositeBranchOpcode));
1631        BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1632        MI->getOperand(TargetOperand).setMBB(NewDest);
1633        return true;
1634      }
1635    }
1636  }
1637
1638
1639  if (NeedSplit) {
1640    splitBlockBeforeInstr(MI);
1641    // No need for the branch to the next block. We're adding an unconditional
1642    // branch to the destination.
1643    int delta = TII->GetInstSizeInBytes(&MBB->back());
1644    BBInfo[MBB->getNumber()].Size -= delta;
1645    MBB->back().eraseFromParent();
1646    // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1647  }
1648  MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
1649
1650  DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
1651               << " also invert condition and change dest. to BB#"
1652               << NextBB->getNumber() << "\n");
1653
1654  // Insert a new conditional branch and a new unconditional branch.
1655  // Also update the ImmBranch as well as adding a new entry for the new branch.
1656  if (MI->getNumExplicitOperands() == 2) {
1657    BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1658           .addReg(MI->getOperand(0).getReg())
1659           .addMBB(NextBB);
1660  } else {
1661    BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1662           .addMBB(NextBB);
1663  }
1664  Br.MI = &MBB->back();
1665  BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1666  BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1667  BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1668  unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1669  ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1670
1671  // Remove the old conditional branch.  It may or may not still be in MBB.
1672  BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1673  MI->eraseFromParent();
1674  adjustBBOffsetsAfter(MBB);
1675  return true;
1676}
1677
1678
1679void MipsConstantIslands::prescanForConstants() {
1680  unsigned J = 0;
1681  (void)J;
1682  for (MachineFunction::iterator B =
1683         MF->begin(), E = MF->end(); B != E; ++B) {
1684    for (MachineBasicBlock::instr_iterator I =
1685        B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1686      switch(I->getDesc().getOpcode()) {
1687        case Mips::LwConstant32: {
1688          PrescannedForConstants = true;
1689          DEBUG(dbgs() << "constant island constant " << *I << "\n");
1690          J = I->getNumOperands();
1691          DEBUG(dbgs() << "num operands " << J  << "\n");
1692          MachineOperand& Literal = I->getOperand(1);
1693          if (Literal.isImm()) {
1694            int64_t V = Literal.getImm();
1695            DEBUG(dbgs() << "literal " << V  << "\n");
1696            Type *Int32Ty =
1697              Type::getInt32Ty(MF->getFunction()->getContext());
1698            const Constant *C = ConstantInt::get(Int32Ty, V);
1699            unsigned index = MCP->getConstantPoolIndex(C, 4);
1700            I->getOperand(2).ChangeToImmediate(index);
1701            DEBUG(dbgs() << "constant island constant " << *I << "\n");
1702            I->setDesc(TII->get(Mips::LwRxPcTcp16));
1703            I->RemoveOperand(1);
1704            I->RemoveOperand(1);
1705            I->addOperand(MachineOperand::CreateCPI(index, 0));
1706            I->addOperand(MachineOperand::CreateImm(4));
1707          }
1708          break;
1709        }
1710        default:
1711          break;
1712      }
1713    }
1714  }
1715}
1716
1717