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