Fix pre- and post-indexed load / store encoding bugs.
[oota-llvm.git] / lib / Target / ARM / ARMConstantIslandPass.cpp
1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
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 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function.  This is required due to the
12 // limited pc-relative displacements that ARM has.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "arm-cp-islands"
17 #include "ARM.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
30 using namespace llvm;
31
32 STATISTIC(NumCPEs,     "Number of constpool entries");
33 STATISTIC(NumSplit,    "Number of uncond branches inserted");
34 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
36
37 namespace {
38   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39   /// requires constant pool entries to be scattered among the instructions
40   /// inside a function.  To do this, it completely ignores the normal LLVM
41   /// constant pool; instead, it places constants wherever it feels like with
42   /// special instructions.
43   ///
44   /// The terminology used in this pass includes:
45   ///   Islands - Clumps of constants placed in the function.
46   ///   Water   - Potential places where an island could be formed.
47   ///   CPE     - A constant pool entry that has been placed somewhere, which
48   ///             tracks a list of users.
49   class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50     /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
51     /// by MBB Number.  The two-byte pads required for Thumb alignment are
52     /// counted as part of the following block (i.e., the offset and size for
53     /// a padded block will both be ==2 mod 4).
54     std::vector<unsigned> BBSizes;
55     
56     /// BBOffsets - the offset of each MBB in bytes, starting from 0.
57     /// The two-byte pads required for Thumb alignment are counted as part of
58     /// the following block.
59     std::vector<unsigned> BBOffsets;
60
61     /// WaterList - A sorted list of basic blocks where islands could be placed
62     /// (i.e. blocks that don't fall through to the following block, due
63     /// to a return, unreachable, or unconditional branch).
64     std::vector<MachineBasicBlock*> WaterList;
65
66     /// CPUser - One user of a constant pool, keeping the machine instruction
67     /// pointer, the constant pool being referenced, and the max displacement
68     /// allowed from the instruction to the CP.
69     struct CPUser {
70       MachineInstr *MI;
71       MachineInstr *CPEMI;
72       unsigned MaxDisp;
73       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
74         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
75     };
76     
77     /// CPUsers - Keep track of all of the machine instructions that use various
78     /// constant pools and their max displacement.
79     std::vector<CPUser> CPUsers;
80     
81     /// CPEntry - One per constant pool entry, keeping the machine instruction
82     /// pointer, the constpool index, and the number of CPUser's which
83     /// reference this entry.
84     struct CPEntry {
85       MachineInstr *CPEMI;
86       unsigned CPI;
87       unsigned RefCount;
88       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
89         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
90     };
91
92     /// CPEntries - Keep track of all of the constant pool entry machine
93     /// instructions. For each original constpool index (i.e. those that
94     /// existed upon entry to this pass), it keeps a vector of entries.
95     /// Original elements are cloned as we go along; the clones are
96     /// put in the vector of the original element, but have distinct CPIs.
97     std::vector<std::vector<CPEntry> > CPEntries;
98     
99     /// ImmBranch - One per immediate branch, keeping the machine instruction
100     /// pointer, conditional or unconditional, the max displacement,
101     /// and (if isCond is true) the corresponding unconditional branch
102     /// opcode.
103     struct ImmBranch {
104       MachineInstr *MI;
105       unsigned MaxDisp : 31;
106       bool isCond : 1;
107       int UncondBr;
108       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
109         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
110     };
111
112     /// ImmBranches - Keep track of all the immediate branch instructions.
113     ///
114     std::vector<ImmBranch> ImmBranches;
115
116     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
117     ///
118     SmallVector<MachineInstr*, 4> PushPopMIs;
119
120     /// HasFarJump - True if any far jump instruction has been emitted during
121     /// the branch fix up pass.
122     bool HasFarJump;
123
124     const TargetInstrInfo *TII;
125     ARMFunctionInfo *AFI;
126     bool isThumb;
127   public:
128     static char ID;
129     ARMConstantIslands() : MachineFunctionPass(&ID) {}
130
131     virtual bool runOnMachineFunction(MachineFunction &Fn);
132
133     virtual const char *getPassName() const {
134       return "ARM constant island placement and branch shortening pass";
135     }
136     
137   private:
138     void DoInitialPlacement(MachineFunction &Fn,
139                             std::vector<MachineInstr*> &CPEMIs);
140     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
141     void InitialFunctionScan(MachineFunction &Fn,
142                              const std::vector<MachineInstr*> &CPEMIs);
143     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
144     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
145     void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
146     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
147     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
148     bool LookForWater(CPUser&U, unsigned UserOffset, 
149                       MachineBasicBlock** NewMBB);
150     MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB, 
151                         std::vector<MachineBasicBlock*>::iterator IP);
152     void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
153                       MachineBasicBlock** NewMBB);
154     bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
155     void RemoveDeadCPEMI(MachineInstr *CPEMI);
156     bool RemoveUnusedCPEntries();
157     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset, 
158                       MachineInstr *CPEMI, unsigned Disp,
159                       bool DoDump);
160     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
161                         CPUser &U);
162     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
163                         unsigned Disp, bool NegativeOK);
164     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
165     bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
166     bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
167     bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
168     bool UndoLRSpillRestore();
169
170     unsigned GetOffsetOf(MachineInstr *MI) const;
171     void dumpBBs();
172     void verify(MachineFunction &Fn);
173   };
174   char ARMConstantIslands::ID = 0;
175 }
176
177 /// verify - check BBOffsets, BBSizes, alignment of islands
178 void ARMConstantIslands::verify(MachineFunction &Fn) {
179   assert(BBOffsets.size() == BBSizes.size());
180   for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
181     assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
182   if (isThumb) {
183     for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
184          MBBI != E; ++MBBI) {
185       MachineBasicBlock *MBB = MBBI;
186       if (!MBB->empty() &&
187           MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
188         assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
189                 BBSizes[MBB->getNumber()]%4 == 0) ||
190                (BBOffsets[MBB->getNumber()]%4 != 0 &&
191                 BBSizes[MBB->getNumber()]%4 != 0));
192     }
193   }
194 }
195
196 /// print block size and offset information - debugging
197 void ARMConstantIslands::dumpBBs() {
198   for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
199     DOUT << "block " << J << " offset " << BBOffsets[J] << 
200                             " size " << BBSizes[J] << "\n";
201   }
202 }
203
204 /// createARMConstantIslandPass - returns an instance of the constpool
205 /// island pass.
206 FunctionPass *llvm::createARMConstantIslandPass() {
207   return new ARMConstantIslands();
208 }
209
210 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
211   MachineConstantPool &MCP = *Fn.getConstantPool();
212   
213   TII = Fn.getTarget().getInstrInfo();
214   AFI = Fn.getInfo<ARMFunctionInfo>();
215   isThumb = AFI->isThumbFunction();
216
217   HasFarJump = false;
218
219   // Renumber all of the machine basic blocks in the function, guaranteeing that
220   // the numbers agree with the position of the block in the function.
221   Fn.RenumberBlocks();
222
223   /// Thumb functions containing constant pools get 2-byte alignment.  This is so
224   /// we can keep exact track of where the alignment padding goes.  Set default.
225   AFI->setAlign(isThumb ? 1U : 2U);
226
227   // Perform the initial placement of the constant pool entries.  To start with,
228   // we put them all at the end of the function.
229   std::vector<MachineInstr*> CPEMIs;
230   if (!MCP.isEmpty()) {
231     DoInitialPlacement(Fn, CPEMIs);
232     if (isThumb)
233       AFI->setAlign(2U);
234   }
235   
236   /// The next UID to take is the first unused one.
237   AFI->initConstPoolEntryUId(CPEMIs.size());
238   
239   // Do the initial scan of the function, building up information about the
240   // sizes of each block, the location of all the water, and finding all of the
241   // constant pool users.
242   InitialFunctionScan(Fn, CPEMIs);
243   CPEMIs.clear();
244   
245   /// Remove dead constant pool entries.
246   RemoveUnusedCPEntries();
247
248   // Iteratively place constant pool entries and fix up branches until there
249   // is no change.
250   bool MadeChange = false;
251   while (true) {
252     bool Change = false;
253     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
254       Change |= HandleConstantPoolUser(Fn, i);
255     DEBUG(dumpBBs());
256     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
257       Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
258     DEBUG(dumpBBs());
259     if (!Change)
260       break;
261     MadeChange = true;
262   }
263
264   // After a while, this might be made debug-only, but it is not expensive.
265   verify(Fn);
266
267   // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
268   // Undo the spill / restore of LR if possible.
269   if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
270     MadeChange |= UndoLRSpillRestore();
271
272   BBSizes.clear();
273   BBOffsets.clear();
274   WaterList.clear();
275   CPUsers.clear();
276   CPEntries.clear();
277   ImmBranches.clear();
278   PushPopMIs.clear();
279
280   return MadeChange;
281 }
282
283 /// DoInitialPlacement - Perform the initial placement of the constant pool
284 /// entries.  To start with, we put them all at the end of the function.
285 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
286                                         std::vector<MachineInstr*> &CPEMIs){
287   // Create the basic block to hold the CPE's.
288   MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
289   Fn.push_back(BB);
290   
291   // Add all of the constants from the constant pool to the end block, use an
292   // identity mapping of CPI's to CPE's.
293   const std::vector<MachineConstantPoolEntry> &CPs =
294     Fn.getConstantPool()->getConstants();
295   
296   const TargetData &TD = *Fn.getTarget().getTargetData();
297   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
298     unsigned Size = TD.getABITypeSize(CPs[i].getType());
299     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
300     // we would have to pad them out or something so that instructions stay
301     // aligned.
302     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
303     MachineInstr *CPEMI =
304       BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
305                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
306     CPEMIs.push_back(CPEMI);
307
308     // Add a new CPEntry, but no corresponding CPUser yet.
309     std::vector<CPEntry> CPEs;
310     CPEs.push_back(CPEntry(CPEMI, i));
311     CPEntries.push_back(CPEs);
312     NumCPEs++;
313     DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
314   }
315 }
316
317 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
318 /// into the block immediately after it.
319 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
320   // Get the next machine basic block in the function.
321   MachineFunction::iterator MBBI = MBB;
322   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
323     return false;
324   
325   MachineBasicBlock *NextBB = next(MBBI);
326   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
327        E = MBB->succ_end(); I != E; ++I)
328     if (*I == NextBB)
329       return true;
330   
331   return false;
332 }
333
334 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
335 /// look up the corresponding CPEntry.
336 ARMConstantIslands::CPEntry
337 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
338                                         const MachineInstr *CPEMI) {
339   std::vector<CPEntry> &CPEs = CPEntries[CPI];
340   // Number of entries per constpool index should be small, just do a
341   // linear search.
342   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
343     if (CPEs[i].CPEMI == CPEMI)
344       return &CPEs[i];
345   }
346   return NULL;
347 }
348
349 /// InitialFunctionScan - Do the initial scan of the function, building up
350 /// information about the sizes of each block, the location of all the water,
351 /// and finding all of the constant pool users.
352 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
353                                  const std::vector<MachineInstr*> &CPEMIs) {
354   unsigned Offset = 0;
355   for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
356        MBBI != E; ++MBBI) {
357     MachineBasicBlock &MBB = *MBBI;
358     
359     // If this block doesn't fall through into the next MBB, then this is
360     // 'water' that a constant pool island could be placed.
361     if (!BBHasFallthrough(&MBB))
362       WaterList.push_back(&MBB);
363     
364     unsigned MBBSize = 0;
365     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
366          I != E; ++I) {
367       // Add instruction size to MBBSize.
368       MBBSize += TII->GetInstSizeInBytes(I);
369
370       int Opc = I->getOpcode();
371       if (I->getDesc().isBranch()) {
372         bool isCond = false;
373         unsigned Bits = 0;
374         unsigned Scale = 1;
375         int UOpc = Opc;
376         switch (Opc) {
377         case ARM::tBR_JTr:
378           // A Thumb table jump may involve padding; for the offsets to
379           // be right, functions containing these must be 4-byte aligned.
380           AFI->setAlign(2U);
381           if ((Offset+MBBSize)%4 != 0)
382             MBBSize += 2;           // padding
383           continue;   // Does not get an entry in ImmBranches
384         default:
385           continue;  // Ignore other JT branches
386         case ARM::Bcc:
387           isCond = true;
388           UOpc = ARM::B;
389           // Fallthrough
390         case ARM::B:
391           Bits = 24;
392           Scale = 4;
393           break;
394         case ARM::tBcc:
395           isCond = true;
396           UOpc = ARM::tB;
397           Bits = 8;
398           Scale = 2;
399           break;
400         case ARM::tB:
401           Bits = 11;
402           Scale = 2;
403           break;
404         }
405
406         // Record this immediate branch.
407         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
408         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
409       }
410
411       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
412         PushPopMIs.push_back(I);
413
414       // Scan the instructions for constant pool operands.
415       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
416         if (I->getOperand(op).isCPI()) {
417           // We found one.  The addressing mode tells us the max displacement
418           // from the PC that this instruction permits.
419           
420           // Basic size info comes from the TSFlags field.
421           unsigned Bits = 0;
422           unsigned Scale = 1;
423           unsigned TSFlags = I->getDesc().TSFlags;
424           switch (TSFlags & ARMII::AddrModeMask) {
425           default: 
426             // Constant pool entries can reach anything.
427             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
428               continue;
429             if (I->getOpcode() == ARM::tLEApcrel) {
430               Bits = 8;  // Taking the address of a CP entry.
431               break;
432             }
433             assert(0 && "Unknown addressing mode for CP reference!");
434           case ARMII::AddrMode1: // AM1: 8 bits << 2
435             Bits = 8;
436             Scale = 4;  // Taking the address of a CP entry.
437             break;
438           case ARMII::AddrMode2:
439             Bits = 12;  // +-offset_12
440             break;
441           case ARMII::AddrMode3:
442             Bits = 8;   // +-offset_8
443             break;
444             // addrmode4 has no immediate offset.
445           case ARMII::AddrMode5:
446             Bits = 8;
447             Scale = 4;  // +-(offset_8*4)
448             break;
449           case ARMII::AddrModeT1:
450             Bits = 5;  // +offset_5
451             break;
452           case ARMII::AddrModeT2:
453             Bits = 5;
454             Scale = 2;  // +(offset_5*2)
455             break;
456           case ARMII::AddrModeT4:
457             Bits = 5;
458             Scale = 4;  // +(offset_5*4)
459             break;
460           case ARMII::AddrModeTs:
461             Bits = 8;
462             Scale = 4;  // +(offset_8*4)
463             break;
464           }
465
466           // Remember that this is a user of a CP entry.
467           unsigned CPI = I->getOperand(op).getIndex();
468           MachineInstr *CPEMI = CPEMIs[CPI];
469           unsigned MaxOffs = ((1 << Bits)-1) * Scale;          
470           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
471
472           // Increment corresponding CPEntry reference count.
473           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
474           assert(CPE && "Cannot find a corresponding CPEntry!");
475           CPE->RefCount++;
476           
477           // Instructions can only use one CP entry, don't bother scanning the
478           // rest of the operands.
479           break;
480         }
481     }
482
483     // In thumb mode, if this block is a constpool island, we may need padding
484     // so it's aligned on 4 byte boundary.
485     if (isThumb &&
486         !MBB.empty() &&
487         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
488         (Offset%4) != 0)
489       MBBSize += 2;
490
491     BBSizes.push_back(MBBSize);
492     BBOffsets.push_back(Offset);
493     Offset += MBBSize;
494   }
495 }
496
497 /// GetOffsetOf - Return the current offset of the specified machine instruction
498 /// from the start of the function.  This offset changes as stuff is moved
499 /// around inside the function.
500 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
501   MachineBasicBlock *MBB = MI->getParent();
502   
503   // The offset is composed of two things: the sum of the sizes of all MBB's
504   // before this instruction's block, and the offset from the start of the block
505   // it is in.
506   unsigned Offset = BBOffsets[MBB->getNumber()];
507
508   // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
509   // alignment padding, and compensate if so.
510   if (isThumb && 
511       MI->getOpcode() == ARM::CONSTPOOL_ENTRY && 
512       Offset%4 != 0)
513     Offset += 2;
514
515   // Sum instructions before MI in MBB.
516   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
517     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
518     if (&*I == MI) return Offset;
519     Offset += TII->GetInstSizeInBytes(I);
520   }
521 }
522
523 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
524 /// ID.
525 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
526                               const MachineBasicBlock *RHS) {
527   return LHS->getNumber() < RHS->getNumber();
528 }
529
530 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
531 /// machine function, it upsets all of the block numbers.  Renumber the blocks
532 /// and update the arrays that parallel this numbering.
533 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
534   // Renumber the MBB's to keep them consequtive.
535   NewBB->getParent()->RenumberBlocks(NewBB);
536   
537   // Insert a size into BBSizes to align it properly with the (newly
538   // renumbered) block numbers.
539   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
540
541   // Likewise for BBOffsets.
542   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
543   
544   // Next, update WaterList.  Specifically, we need to add NewMBB as having 
545   // available water after it.
546   std::vector<MachineBasicBlock*>::iterator IP =
547     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
548                      CompareMBBNumbers);
549   WaterList.insert(IP, NewBB);
550 }
551
552
553 /// Split the basic block containing MI into two blocks, which are joined by
554 /// an unconditional branch.  Update datastructures and renumber blocks to
555 /// account for this change and returns the newly created block.
556 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
557   MachineBasicBlock *OrigBB = MI->getParent();
558   MachineFunction &MF = *OrigBB->getParent();
559
560   // Create a new MBB for the code after the OrigBB.
561   MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
562   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
563   MF.insert(MBBI, NewBB);
564   
565   // Splice the instructions starting with MI over to NewBB.
566   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
567   
568   // Add an unconditional branch from OrigBB to NewBB.
569   // Note the new unconditional branch is not being recorded.
570   BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
571   NumSplit++;
572   
573   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
574   while (!OrigBB->succ_empty()) {
575     MachineBasicBlock *Succ = *OrigBB->succ_begin();
576     OrigBB->removeSuccessor(Succ);
577     NewBB->addSuccessor(Succ);
578     
579     // This pass should be run after register allocation, so there should be no
580     // PHI nodes to update.
581     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
582            && "PHI nodes should be eliminated by now!");
583   }
584   
585   // OrigBB branches to NewBB.
586   OrigBB->addSuccessor(NewBB);
587   
588   // Update internal data structures to account for the newly inserted MBB.
589   // This is almost the same as UpdateForInsertedWaterBlock, except that
590   // the Water goes after OrigBB, not NewBB.
591   MF.RenumberBlocks(NewBB);
592   
593   // Insert a size into BBSizes to align it properly with the (newly
594   // renumbered) block numbers.
595   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
596   
597   // Likewise for BBOffsets.
598   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
599
600   // Next, update WaterList.  Specifically, we need to add OrigMBB as having 
601   // available water after it (but not if it's already there, which happens
602   // when splitting before a conditional branch that is followed by an
603   // unconditional branch - in that case we want to insert NewBB).
604   std::vector<MachineBasicBlock*>::iterator IP =
605     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
606                      CompareMBBNumbers);
607   MachineBasicBlock* WaterBB = *IP;
608   if (WaterBB == OrigBB)
609     WaterList.insert(next(IP), NewBB);
610   else
611     WaterList.insert(IP, OrigBB);
612
613   // Figure out how large the first NewMBB is.  (It cannot
614   // contain a constpool_entry or tablejump.)
615   unsigned NewBBSize = 0;
616   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
617        I != E; ++I)
618     NewBBSize += TII->GetInstSizeInBytes(I);
619   
620   unsigned OrigBBI = OrigBB->getNumber();
621   unsigned NewBBI = NewBB->getNumber();
622   // Set the size of NewBB in BBSizes.
623   BBSizes[NewBBI] = NewBBSize;
624   
625   // We removed instructions from UserMBB, subtract that off from its size.
626   // Add 2 or 4 to the block to count the unconditional branch we added to it.
627   unsigned delta = isThumb ? 2 : 4;
628   BBSizes[OrigBBI] -= NewBBSize - delta;
629
630   // ...and adjust BBOffsets for NewBB accordingly.
631   BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
632
633   // All BBOffsets following these blocks must be modified.
634   AdjustBBOffsetsAfter(NewBB, delta);
635
636   return NewBB;
637 }
638
639 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
640 /// reference) is within MaxDisp of TrialOffset (a proposed location of a 
641 /// constant pool entry).
642 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset, 
643                       unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
644   // On Thumb offsets==2 mod 4 are rounded down by the hardware for 
645   // purposes of the displacement computation; compensate for that here.  
646   // Effectively, the valid range of displacements is 2 bytes smaller for such
647   // references.
648   if (isThumb && UserOffset%4 !=0)
649     UserOffset -= 2;
650   // CPEs will be rounded up to a multiple of 4.
651   if (isThumb && TrialOffset%4 != 0)
652     TrialOffset += 2;
653
654   if (UserOffset <= TrialOffset) {
655     // User before the Trial.
656     if (TrialOffset-UserOffset <= MaxDisp)
657       return true;
658   } else if (NegativeOK) {
659     if (UserOffset-TrialOffset <= MaxDisp)
660       return true;
661   }
662   return false;
663 }
664
665 /// WaterIsInRange - Returns true if a CPE placed after the specified
666 /// Water (a basic block) will be in range for the specific MI.
667
668 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
669                          MachineBasicBlock* Water, CPUser &U)
670 {
671   unsigned MaxDisp = U.MaxDisp;
672   MachineFunction::iterator I = next(MachineFunction::iterator(Water));
673   unsigned CPEOffset = BBOffsets[Water->getNumber()] + 
674                        BBSizes[Water->getNumber()];
675
676   // If the CPE is to be inserted before the instruction, that will raise
677   // the offset of the instruction.  (Currently applies only to ARM, so
678   // no alignment compensation attempted here.)
679   if (CPEOffset < UserOffset)
680     UserOffset += U.CPEMI->getOperand(2).getImm();
681
682   return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
683 }
684
685 /// CPEIsInRange - Returns true if the distance between specific MI and
686 /// specific ConstPool entry instruction can fit in MI's displacement field.
687 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
688                                       MachineInstr *CPEMI,
689                                       unsigned MaxDisp, bool DoDump) {
690   unsigned CPEOffset  = GetOffsetOf(CPEMI);
691   assert(CPEOffset%4 == 0 && "Misaligned CPE");
692
693   if (DoDump) {
694     DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
695          << " max delta=" << MaxDisp
696          << " insn address=" << UserOffset
697          << " CPE address=" << CPEOffset
698          << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
699   }
700
701   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
702 }
703
704 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
705 /// unconditionally branches to its only successor.
706 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
707   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
708     return false;
709
710   MachineBasicBlock *Succ = *MBB->succ_begin();
711   MachineBasicBlock *Pred = *MBB->pred_begin();
712   MachineInstr *PredMI = &Pred->back();
713   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
714     return PredMI->getOperand(0).getMBB() == Succ;
715   return false;
716 }
717
718 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, 
719                                               int delta) {
720   MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
721   for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
722     BBOffsets[i] += delta;
723     // If some existing blocks have padding, adjust the padding as needed, a
724     // bit tricky.  delta can be negative so don't use % on that.
725     if (isThumb) {
726       MachineBasicBlock *MBB = MBBI;
727       if (!MBB->empty()) {
728         // Constant pool entries require padding.
729         if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
730           unsigned oldOffset = BBOffsets[i] - delta;
731           if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
732             // add new padding
733             BBSizes[i] += 2;
734             delta += 2;
735           } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
736             // remove existing padding
737             BBSizes[i] -=2;
738             delta -= 2;
739           }
740         }
741         // Thumb jump tables require padding.  They should be at the end;
742         // following unconditional branches are removed by AnalyzeBranch.
743         MachineInstr *ThumbJTMI = NULL;
744         if (prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
745           ThumbJTMI = prior(MBB->end());
746         if (ThumbJTMI) {
747           unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
748           unsigned oldMIOffset = newMIOffset - delta;
749           if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
750             // remove existing padding
751             BBSizes[i] -= 2;
752             delta -= 2;
753           } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
754             // add new padding
755             BBSizes[i] += 2;
756             delta += 2;
757           }
758         }
759         if (delta==0)
760           return;
761       }
762       MBBI = next(MBBI);
763     }
764   }
765 }
766
767 /// DecrementOldEntry - find the constant pool entry with index CPI
768 /// and instruction CPEMI, and decrement its refcount.  If the refcount
769 /// becomes 0 remove the entry and instruction.  Returns true if we removed 
770 /// the entry, false if we didn't.
771
772 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
773   // Find the old entry. Eliminate it if it is no longer used.
774   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
775   assert(CPE && "Unexpected!");
776   if (--CPE->RefCount == 0) {
777     RemoveDeadCPEMI(CPEMI);
778     CPE->CPEMI = NULL;
779     NumCPEs--;
780     return true;
781   }
782   return false;
783 }
784
785 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
786 /// if not, see if an in-range clone of the CPE is in range, and if so,
787 /// change the data structures so the user references the clone.  Returns:
788 /// 0 = no existing entry found
789 /// 1 = entry found, and there were no code insertions or deletions
790 /// 2 = entry found, and there were code insertions or deletions
791 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
792 {
793   MachineInstr *UserMI = U.MI;
794   MachineInstr *CPEMI  = U.CPEMI;
795
796   // Check to see if the CPE is already in-range.
797   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
798     DOUT << "In range\n";
799     return 1;
800   }
801
802   // No.  Look for previously created clones of the CPE that are in range.
803   unsigned CPI = CPEMI->getOperand(1).getIndex();
804   std::vector<CPEntry> &CPEs = CPEntries[CPI];
805   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
806     // We already tried this one
807     if (CPEs[i].CPEMI == CPEMI)
808       continue;
809     // Removing CPEs can leave empty entries, skip
810     if (CPEs[i].CPEMI == NULL)
811       continue;
812     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
813       DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
814       // Point the CPUser node to the replacement
815       U.CPEMI = CPEs[i].CPEMI;
816       // Change the CPI in the instruction operand to refer to the clone.
817       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
818         if (UserMI->getOperand(j).isCPI()) {
819           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
820           break;
821         }
822       // Adjust the refcount of the clone...
823       CPEs[i].RefCount++;
824       // ...and the original.  If we didn't remove the old entry, none of the
825       // addresses changed, so we don't need another pass.
826       return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
827     }
828   }
829   return 0;
830 }
831
832 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
833 /// the specific unconditional branch instruction.
834 static inline unsigned getUnconditionalBrDisp(int Opc) {
835   return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
836 }
837
838 /// AcceptWater - Small amount of common code factored out of the following.
839
840 MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB, 
841                           std::vector<MachineBasicBlock*>::iterator IP) {
842   DOUT << "found water in range\n";
843   // Remove the original WaterList entry; we want subsequent
844   // insertions in this vicinity to go after the one we're
845   // about to insert.  This considerably reduces the number
846   // of times we have to move the same CPE more than once.
847   WaterList.erase(IP);
848   // CPE goes before following block (NewMBB).
849   return next(MachineFunction::iterator(WaterBB));
850 }
851
852 /// LookForWater - look for an existing entry in the WaterList in which
853 /// we can place the CPE referenced from U so it's within range of U's MI.
854 /// Returns true if found, false if not.  If it returns true, *NewMBB
855 /// is set to the WaterList entry.
856 /// For ARM, we prefer the water that's farthest away.  For Thumb, prefer
857 /// water that will not introduce padding to water that will; within each
858 /// group, prefer the water that's farthest away.
859
860 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
861                                       MachineBasicBlock** NewMBB) {
862   std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
863   MachineBasicBlock* WaterBBThatWouldPad = NULL;
864   if (!WaterList.empty()) {
865     for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
866         B = WaterList.begin();; --IP) {
867       MachineBasicBlock* WaterBB = *IP;
868       if (WaterIsInRange(UserOffset, WaterBB, U)) {
869         if (isThumb &&
870             (BBOffsets[WaterBB->getNumber()] + 
871              BBSizes[WaterBB->getNumber()])%4 != 0) {
872           // This is valid Water, but would introduce padding.  Remember
873           // it in case we don't find any Water that doesn't do this.
874           if (!WaterBBThatWouldPad) {
875             WaterBBThatWouldPad = WaterBB;
876             IPThatWouldPad = IP;
877           }
878         } else {
879           *NewMBB = AcceptWater(WaterBB, IP);
880           return true;
881         }
882     }
883       if (IP == B)
884         break;
885     }
886   }
887   if (isThumb && WaterBBThatWouldPad) {
888     *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
889     return true;
890   }
891   return false;
892 }
893
894 /// CreateNewWater - No existing WaterList entry will work for 
895 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
896 /// block is used if in range, and the conditional branch munged so control
897 /// flow is correct.  Otherwise the block is split to create a hole with an
898 /// unconditional branch around it.  In either case *NewMBB is set to a
899 /// block following which the new island can be inserted (the WaterList
900 /// is not adjusted).
901
902 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex, 
903                         unsigned UserOffset, MachineBasicBlock** NewMBB) {
904   CPUser &U = CPUsers[CPUserIndex];
905   MachineInstr *UserMI = U.MI;
906   MachineInstr *CPEMI  = U.CPEMI;
907   MachineBasicBlock *UserMBB = UserMI->getParent();
908   unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] + 
909                                BBSizes[UserMBB->getNumber()];
910   assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
911
912   // If the use is at the end of the block, or the end of the block
913   // is within range, make new water there.  (The addition below is
914   // for the unconditional branch we will be adding:  4 bytes on ARM,
915   // 2 on Thumb.  Possible Thumb alignment padding is allowed for
916   // inside OffsetIsInRange.
917   // If the block ends in an unconditional branch already, it is water, 
918   // and is known to be out of range, so we'll always be adding a branch.)
919   if (&UserMBB->back() == UserMI ||
920       OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
921            U.MaxDisp, !isThumb)) {
922     DOUT << "Split at end of block\n";
923     if (&UserMBB->back() == UserMI)
924       assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
925     *NewMBB = next(MachineFunction::iterator(UserMBB));
926     // Add an unconditional branch from UserMBB to fallthrough block.
927     // Record it for branch lengthening; this new branch will not get out of
928     // range, but if the preceding conditional branch is out of range, the
929     // targets will be exchanged, and the altered branch may be out of
930     // range, so the machinery has to know about it.
931     int UncondBr = isThumb ? ARM::tB : ARM::B;
932     BuildMI(UserMBB, TII->get(UncondBr)).addMBB(*NewMBB);
933     unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
934     ImmBranches.push_back(ImmBranch(&UserMBB->back(), 
935                           MaxDisp, false, UncondBr));
936     int delta = isThumb ? 2 : 4;
937     BBSizes[UserMBB->getNumber()] += delta;
938     AdjustBBOffsetsAfter(UserMBB, delta);
939   } else {
940     // What a big block.  Find a place within the block to split it.
941     // This is a little tricky on Thumb since instructions are 2 bytes
942     // and constant pool entries are 4 bytes: if instruction I references
943     // island CPE, and instruction I+1 references CPE', it will
944     // not work well to put CPE as far forward as possible, since then
945     // CPE' cannot immediately follow it (that location is 2 bytes
946     // farther away from I+1 than CPE was from I) and we'd need to create
947     // a new island.  So, we make a first guess, then walk through the
948     // instructions between the one currently being looked at and the
949     // possible insertion point, and make sure any other instructions
950     // that reference CPEs will be able to use the same island area;
951     // if not, we back up the insertion point.
952
953     // The 4 in the following is for the unconditional branch we'll be
954     // inserting (allows for long branch on Thumb).  Alignment of the
955     // island is handled inside OffsetIsInRange.
956     unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
957     // This could point off the end of the block if we've already got
958     // constant pool entries following this block; only the last one is
959     // in the water list.  Back past any possible branches (allow for a
960     // conditional and a maximally long unconditional).
961     if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
962       BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] - 
963                               (isThumb ? 6 : 8);
964     unsigned EndInsertOffset = BaseInsertOffset +
965            CPEMI->getOperand(2).getImm();
966     MachineBasicBlock::iterator MI = UserMI;
967     ++MI;
968     unsigned CPUIndex = CPUserIndex+1;
969     for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
970          Offset < BaseInsertOffset;
971          Offset += TII->GetInstSizeInBytes(MI),
972             MI = next(MI)) {
973       if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
974         if (!OffsetIsInRange(Offset, EndInsertOffset, 
975               CPUsers[CPUIndex].MaxDisp, !isThumb)) {
976           BaseInsertOffset -= (isThumb ? 2 : 4);
977           EndInsertOffset -= (isThumb ? 2 : 4);
978         }
979         // This is overly conservative, as we don't account for CPEMIs
980         // being reused within the block, but it doesn't matter much.
981         EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
982         CPUIndex++;
983       }
984     }
985     DOUT << "Split in middle of big block\n";
986     *NewMBB = SplitBlockBeforeInstr(prior(MI));
987   }
988 }
989
990 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
991 /// is out-of-range.  If so, pick it up the constant pool value and move it some
992 /// place in-range.  Return true if we changed any addresses (thus must run
993 /// another pass of branch lengthening), false otherwise.
994 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, 
995                                                 unsigned CPUserIndex){
996   CPUser &U = CPUsers[CPUserIndex];
997   MachineInstr *UserMI = U.MI;
998   MachineInstr *CPEMI  = U.CPEMI;
999   unsigned CPI = CPEMI->getOperand(1).getIndex();
1000   unsigned Size = CPEMI->getOperand(2).getImm();
1001   MachineBasicBlock *NewMBB;
1002   // Compute this only once, it's expensive.  The 4 or 8 is the value the
1003   //  hardware keeps in the PC (2 insns ahead of the reference).
1004   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1005
1006   // Special case: tLEApcrel are two instructions MI's. The actual user is the
1007   // second instruction.
1008   if (UserMI->getOpcode() == ARM::tLEApcrel)
1009     UserOffset += 2;
1010  
1011   // See if the current entry is within range, or there is a clone of it
1012   // in range.
1013   int result = LookForExistingCPEntry(U, UserOffset);
1014   if (result==1) return false;
1015   else if (result==2) return true;
1016
1017   // No existing clone of this CPE is within range.
1018   // We will be generating a new clone.  Get a UID for it.
1019   unsigned ID  = AFI->createConstPoolEntryUId();
1020
1021   // Look for water where we can place this CPE.  We look for the farthest one
1022   // away that will work.  Forward references only for now (although later
1023   // we might find some that are backwards).
1024
1025   if (!LookForWater(U, UserOffset, &NewMBB)) {
1026     // No water found.
1027     DOUT << "No water found\n";
1028     CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1029   }
1030
1031   // Okay, we know we can put an island before NewMBB now, do it!
1032   MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1033   Fn.insert(NewMBB, NewIsland);
1034
1035   // Update internal data structures to account for the newly inserted MBB.
1036   UpdateForInsertedWaterBlock(NewIsland);
1037
1038   // Decrement the old entry, and remove it if refcount becomes 0.
1039   DecrementOldEntry(CPI, CPEMI);
1040
1041   // Now that we have an island to add the CPE to, clone the original CPE and
1042   // add it to the island.
1043   U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
1044                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1045   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1046   NumCPEs++;
1047
1048   BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1049   // Compensate for .align 2 in thumb mode.
1050   if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0) 
1051     Size += 2;
1052   // Increase the size of the island block to account for the new entry.
1053   BBSizes[NewIsland->getNumber()] += Size;
1054   AdjustBBOffsetsAfter(NewIsland, Size);
1055   
1056   // Finally, change the CPI in the instruction operand to be ID.
1057   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1058     if (UserMI->getOperand(i).isCPI()) {
1059       UserMI->getOperand(i).setIndex(ID);
1060       break;
1061     }
1062       
1063   DOUT << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
1064       
1065   return true;
1066 }
1067
1068 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1069 /// sizes and offsets of impacted basic blocks.
1070 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1071   MachineBasicBlock *CPEBB = CPEMI->getParent();
1072   unsigned Size = CPEMI->getOperand(2).getImm();
1073   CPEMI->eraseFromParent();
1074   BBSizes[CPEBB->getNumber()] -= Size;
1075   // All succeeding offsets have the current size value added in, fix this.
1076   if (CPEBB->empty()) {
1077     // In thumb mode, the size of island may be  padded by two to compensate for
1078     // the alignment requirement.  Then it will now be 2 when the block is
1079     // empty, so fix this.
1080     // All succeeding offsets have the current size value added in, fix this.
1081     if (BBSizes[CPEBB->getNumber()] != 0) {
1082       Size += BBSizes[CPEBB->getNumber()];
1083       BBSizes[CPEBB->getNumber()] = 0;
1084     }
1085   }
1086   AdjustBBOffsetsAfter(CPEBB, -Size);
1087   // An island has only one predecessor BB and one successor BB. Check if
1088   // this BB's predecessor jumps directly to this BB's successor. This
1089   // shouldn't happen currently.
1090   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1091   // FIXME: remove the empty blocks after all the work is done?
1092 }
1093
1094 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1095 /// are zero.
1096 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1097   unsigned MadeChange = false;
1098   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1099       std::vector<CPEntry> &CPEs = CPEntries[i];
1100       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1101         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1102           RemoveDeadCPEMI(CPEs[j].CPEMI);
1103           CPEs[j].CPEMI = NULL;
1104           MadeChange = true;
1105         }
1106       }
1107   }  
1108   return MadeChange;
1109 }
1110
1111 /// BBIsInRange - Returns true if the distance between specific MI and
1112 /// specific BB can fit in MI's displacement field.
1113 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1114                                      unsigned MaxDisp) {
1115   unsigned PCAdj      = isThumb ? 4 : 8;
1116   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
1117   unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1118
1119   DOUT << "Branch of destination BB#" << DestBB->getNumber()
1120        << " from BB#" << MI->getParent()->getNumber()
1121        << " max delta=" << MaxDisp
1122        << " from " << GetOffsetOf(MI) << " to " << DestOffset
1123        << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1124
1125   if (BrOffset <= DestOffset) {
1126     // Branch before the Dest.
1127     if (DestOffset-BrOffset <= MaxDisp)
1128       return true;
1129   } else {
1130     if (BrOffset-DestOffset <= MaxDisp)
1131       return true;
1132   }
1133   return false;
1134 }
1135
1136 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1137 /// away to fit in its displacement field.
1138 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1139   MachineInstr *MI = Br.MI;
1140   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1141
1142   // Check to see if the DestBB is already in-range.
1143   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1144     return false;
1145
1146   if (!Br.isCond)
1147     return FixUpUnconditionalBr(Fn, Br);
1148   return FixUpConditionalBr(Fn, Br);
1149 }
1150
1151 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1152 /// too far away to fit in its displacement field. If the LR register has been
1153 /// spilled in the epilogue, then we can use BL to implement a far jump.
1154 /// Otherwise, add an intermediate branch instruction to to a branch.
1155 bool
1156 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1157   MachineInstr *MI = Br.MI;
1158   MachineBasicBlock *MBB = MI->getParent();
1159   assert(isThumb && "Expected a Thumb function!");
1160
1161   // Use BL to implement far jump.
1162   Br.MaxDisp = (1 << 21) * 2;
1163   MI->setDesc(TII->get(ARM::tBfar));
1164   BBSizes[MBB->getNumber()] += 2;
1165   AdjustBBOffsetsAfter(MBB, 2);
1166   HasFarJump = true;
1167   NumUBrFixed++;
1168
1169   DOUT << "  Changed B to long jump " << *MI;
1170
1171   return true;
1172 }
1173
1174 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1175 /// far away to fit in its displacement field. It is converted to an inverse
1176 /// conditional branch + an unconditional branch to the destination.
1177 bool
1178 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1179   MachineInstr *MI = Br.MI;
1180   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1181
1182   // Add a unconditional branch to the destination and invert the branch
1183   // condition to jump over it:
1184   // blt L1
1185   // =>
1186   // bge L2
1187   // b   L1
1188   // L2:
1189   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1190   CC = ARMCC::getOppositeCondition(CC);
1191   unsigned CCReg = MI->getOperand(2).getReg();
1192
1193   // If the branch is at the end of its MBB and that has a fall-through block,
1194   // direct the updated conditional branch to the fall-through block. Otherwise,
1195   // split the MBB before the next instruction.
1196   MachineBasicBlock *MBB = MI->getParent();
1197   MachineInstr *BMI = &MBB->back();
1198   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1199
1200   NumCBrFixed++;
1201   if (BMI != MI) {
1202     if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1203         BMI->getOpcode() == Br.UncondBr) {
1204       // Last MI in the BB is a unconditional branch. Can we simply invert the
1205       // condition and swap destinations:
1206       // beq L1
1207       // b   L2
1208       // =>
1209       // bne L2
1210       // b   L1
1211       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1212       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1213         DOUT << "  Invert Bcc condition and swap its destination with " << *BMI;
1214         BMI->getOperand(0).setMBB(DestBB);
1215         MI->getOperand(0).setMBB(NewDest);
1216         MI->getOperand(1).setImm(CC);
1217         return true;
1218       }
1219     }
1220   }
1221
1222   if (NeedSplit) {
1223     SplitBlockBeforeInstr(MI);
1224     // No need for the branch to the next block. We're adding a unconditional
1225     // branch to the destination.
1226     int delta = TII->GetInstSizeInBytes(&MBB->back());
1227     BBSizes[MBB->getNumber()] -= delta;
1228     MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1229     AdjustBBOffsetsAfter(SplitBB, -delta);
1230     MBB->back().eraseFromParent();
1231     // BBOffsets[SplitBB] is wrong temporarily, fixed below
1232   }
1233   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1234  
1235   DOUT << "  Insert B to BB#" << DestBB->getNumber()
1236        << " also invert condition and change dest. to BB#"
1237        << NextBB->getNumber() << "\n";
1238
1239   // Insert a new conditional branch and a new unconditional branch.
1240   // Also update the ImmBranch as well as adding a new entry for the new branch.
1241   BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB)
1242     .addImm(CC).addReg(CCReg);
1243   Br.MI = &MBB->back();
1244   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1245   BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
1246   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1247   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1248   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1249
1250   // Remove the old conditional branch.  It may or may not still be in MBB.
1251   BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1252   MI->eraseFromParent();
1253
1254   // The net size change is an addition of one unconditional branch.
1255   int delta = TII->GetInstSizeInBytes(&MBB->back());
1256   AdjustBBOffsetsAfter(MBB, delta);
1257   return true;
1258 }
1259
1260 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1261 /// LR / restores LR to pc.
1262 bool ARMConstantIslands::UndoLRSpillRestore() {
1263   bool MadeChange = false;
1264   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1265     MachineInstr *MI = PushPopMIs[i];
1266     if (MI->getOpcode() == ARM::tPOP_RET &&
1267         MI->getOperand(0).getReg() == ARM::PC &&
1268         MI->getNumExplicitOperands() == 1) {
1269       BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
1270       MI->eraseFromParent();
1271       MadeChange = true;
1272     }
1273   }
1274   return MadeChange;
1275 }