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