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