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