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