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