OSDN Git Service

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