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