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