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