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