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