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