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