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