OSDN Git Service

Move common expression into a method.
[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/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       /// Compute the offset immediately following this block.
89       unsigned postOffset() const { return Offset + Size; }
90     };
91
92     std::vector<BasicBlockInfo> BBInfo;
93
94     /// WaterList - A sorted list of basic blocks where islands could be placed
95     /// (i.e. blocks that don't fall through to the following block, due
96     /// to a return, unreachable, or unconditional branch).
97     std::vector<MachineBasicBlock*> WaterList;
98
99     /// NewWaterList - The subset of WaterList that was created since the
100     /// previous iteration by inserting unconditional branches.
101     SmallSet<MachineBasicBlock*, 4> NewWaterList;
102
103     typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
104
105     /// CPUser - One user of a constant pool, keeping the machine instruction
106     /// pointer, the constant pool being referenced, and the max displacement
107     /// allowed from the instruction to the CP.  The HighWaterMark records the
108     /// highest basic block where a new CPEntry can be placed.  To ensure this
109     /// pass terminates, the CP entries are initially placed at the end of the
110     /// function and then move monotonically to lower addresses.  The
111     /// exception to this rule is when the current CP entry for a particular
112     /// CPUser is out of range, but there is another CP entry for the same
113     /// constant value in range.  We want to use the existing in-range CP
114     /// entry, but if it later moves out of range, the search for new water
115     /// should resume where it left off.  The HighWaterMark is used to record
116     /// that point.
117     struct CPUser {
118       MachineInstr *MI;
119       MachineInstr *CPEMI;
120       MachineBasicBlock *HighWaterMark;
121       unsigned MaxDisp;
122       bool NegOk;
123       bool IsSoImm;
124       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
125              bool neg, bool soimm)
126         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
127         HighWaterMark = CPEMI->getParent();
128       }
129     };
130
131     /// CPUsers - Keep track of all of the machine instructions that use various
132     /// constant pools and their max displacement.
133     std::vector<CPUser> CPUsers;
134
135     /// CPEntry - One per constant pool entry, keeping the machine instruction
136     /// pointer, the constpool index, and the number of CPUser's which
137     /// reference this entry.
138     struct CPEntry {
139       MachineInstr *CPEMI;
140       unsigned CPI;
141       unsigned RefCount;
142       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
143         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
144     };
145
146     /// CPEntries - Keep track of all of the constant pool entry machine
147     /// instructions. For each original constpool index (i.e. those that
148     /// existed upon entry to this pass), it keeps a vector of entries.
149     /// Original elements are cloned as we go along; the clones are
150     /// put in the vector of the original element, but have distinct CPIs.
151     std::vector<std::vector<CPEntry> > CPEntries;
152
153     /// ImmBranch - One per immediate branch, keeping the machine instruction
154     /// pointer, conditional or unconditional, the max displacement,
155     /// and (if isCond is true) the corresponding unconditional branch
156     /// opcode.
157     struct ImmBranch {
158       MachineInstr *MI;
159       unsigned MaxDisp : 31;
160       bool isCond : 1;
161       int UncondBr;
162       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
163         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
164     };
165
166     /// ImmBranches - Keep track of all the immediate branch instructions.
167     ///
168     std::vector<ImmBranch> ImmBranches;
169
170     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
171     ///
172     SmallVector<MachineInstr*, 4> PushPopMIs;
173
174     /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
175     SmallVector<MachineInstr*, 4> T2JumpTables;
176
177     /// HasFarJump - True if any far jump instruction has been emitted during
178     /// the branch fix up pass.
179     bool HasFarJump;
180
181     /// HasInlineAsm - True if the function contains inline assembly.
182     bool HasInlineAsm;
183
184     const ARMInstrInfo *TII;
185     const ARMSubtarget *STI;
186     ARMFunctionInfo *AFI;
187     bool isThumb;
188     bool isThumb1;
189     bool isThumb2;
190   public:
191     static char ID;
192     ARMConstantIslands() : MachineFunctionPass(ID) {}
193
194     virtual bool runOnMachineFunction(MachineFunction &MF);
195
196     virtual const char *getPassName() const {
197       return "ARM constant island placement and branch shortening pass";
198     }
199
200   private:
201     void DoInitialPlacement(MachineFunction &MF,
202                             std::vector<MachineInstr*> &CPEMIs);
203     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
204     void JumpTableFunctionScan(MachineFunction &MF);
205     void InitialFunctionScan(MachineFunction &MF,
206                              const std::vector<MachineInstr*> &CPEMIs);
207     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
208     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
209     void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
210     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
211     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
212     bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
213     void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
214                         MachineBasicBlock *&NewMBB);
215     bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
216     void RemoveDeadCPEMI(MachineInstr *CPEMI);
217     bool RemoveUnusedCPEntries();
218     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
219                       MachineInstr *CPEMI, unsigned Disp, bool NegOk,
220                       bool DoDump = false);
221     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
222                         CPUser &U);
223     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
224                          unsigned Disp, bool NegativeOK, bool IsSoImm = false);
225     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
226     bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
227     bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
228     bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
229     bool UndoLRSpillRestore();
230     bool OptimizeThumb2Instructions(MachineFunction &MF);
231     bool OptimizeThumb2Branches(MachineFunction &MF);
232     bool ReorderThumb2JumpTables(MachineFunction &MF);
233     bool OptimizeThumb2JumpTables(MachineFunction &MF);
234     MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
235                                                   MachineBasicBlock *JTBB);
236
237     unsigned GetOffsetOf(MachineInstr *MI) const;
238     void dumpBBs();
239     void verify(MachineFunction &MF);
240   };
241   char ARMConstantIslands::ID = 0;
242 }
243
244 /// verify - check BBOffsets, BBSizes, alignment of islands
245 void ARMConstantIslands::verify(MachineFunction &MF) {
246   for (unsigned i = 1, e = BBInfo.size(); i != e; ++i)
247     assert(BBInfo[i-1].postOffset() == BBInfo[i].Offset);
248   if (!isThumb)
249     return;
250 #ifndef NDEBUG
251   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
252        MBBI != E; ++MBBI) {
253     MachineBasicBlock *MBB = MBBI;
254     if (!MBB->empty() &&
255         MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
256       unsigned MBBId = MBB->getNumber();
257       assert(HasInlineAsm ||
258              (BBInfo[MBBId].Offset%4 == 0 && BBInfo[MBBId].Size%4 == 0) ||
259              (BBInfo[MBBId].Offset%4 != 0 && BBInfo[MBBId].Size%4 != 0));
260     }
261   }
262   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
263     CPUser &U = CPUsers[i];
264     unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
265     unsigned CPEOffset  = GetOffsetOf(U.CPEMI);
266     unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
267       UserOffset - CPEOffset;
268     assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
269   }
270 #endif
271 }
272
273 /// print block size and offset information - debugging
274 void ARMConstantIslands::dumpBBs() {
275   for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
276     DEBUG(errs() << "block " << J << " offset " << BBInfo[J].Offset
277                  << " size " << BBInfo[J].Size << "\n");
278   }
279 }
280
281 /// createARMConstantIslandPass - returns an instance of the constpool
282 /// island pass.
283 FunctionPass *llvm::createARMConstantIslandPass() {
284   return new ARMConstantIslands();
285 }
286
287 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
288   MachineConstantPool &MCP = *MF.getConstantPool();
289
290   TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
291   AFI = MF.getInfo<ARMFunctionInfo>();
292   STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
293
294   isThumb = AFI->isThumbFunction();
295   isThumb1 = AFI->isThumb1OnlyFunction();
296   isThumb2 = AFI->isThumb2Function();
297
298   HasFarJump = false;
299   HasInlineAsm = false;
300
301   // Renumber all of the machine basic blocks in the function, guaranteeing that
302   // the numbers agree with the position of the block in the function.
303   MF.RenumberBlocks();
304
305   // Try to reorder and otherwise adjust the block layout to make good use
306   // of the TB[BH] instructions.
307   bool MadeChange = false;
308   if (isThumb2 && AdjustJumpTableBlocks) {
309     JumpTableFunctionScan(MF);
310     MadeChange |= ReorderThumb2JumpTables(MF);
311     // Data is out of date, so clear it. It'll be re-computed later.
312     T2JumpTables.clear();
313     // Blocks may have shifted around. Keep the numbering up to date.
314     MF.RenumberBlocks();
315   }
316
317   // Thumb1 functions containing constant pools get 4-byte alignment.
318   // This is so we can keep exact track of where the alignment padding goes.
319
320   // ARM and Thumb2 functions need to be 4-byte aligned.
321   if (!isThumb1)
322     MF.EnsureAlignment(2);  // 2 = log2(4)
323
324   // Perform the initial placement of the constant pool entries.  To start with,
325   // we put them all at the end of the function.
326   std::vector<MachineInstr*> CPEMIs;
327   if (!MCP.isEmpty()) {
328     DoInitialPlacement(MF, CPEMIs);
329     if (isThumb1)
330       MF.EnsureAlignment(2);  // 2 = log2(4)
331   }
332
333   /// The next UID to take is the first unused one.
334   AFI->initPICLabelUId(CPEMIs.size());
335
336   // Do the initial scan of the function, building up information about the
337   // sizes of each block, the location of all the water, and finding all of the
338   // constant pool users.
339   InitialFunctionScan(MF, CPEMIs);
340   CPEMIs.clear();
341   DEBUG(dumpBBs());
342
343
344   /// Remove dead constant pool entries.
345   MadeChange |= RemoveUnusedCPEntries();
346
347   // Iteratively place constant pool entries and fix up branches until there
348   // is no change.
349   unsigned NoCPIters = 0, NoBRIters = 0;
350   while (true) {
351     bool CPChange = false;
352     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
353       CPChange |= HandleConstantPoolUser(MF, i);
354     if (CPChange && ++NoCPIters > 30)
355       llvm_unreachable("Constant Island pass failed to converge!");
356     DEBUG(dumpBBs());
357
358     // Clear NewWaterList now.  If we split a block for branches, it should
359     // appear as "new water" for the next iteration of constant pool placement.
360     NewWaterList.clear();
361
362     bool BRChange = false;
363     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
364       BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
365     if (BRChange && ++NoBRIters > 30)
366       llvm_unreachable("Branch Fix Up pass failed to converge!");
367     DEBUG(dumpBBs());
368
369     if (!CPChange && !BRChange)
370       break;
371     MadeChange = true;
372   }
373
374   // Shrink 32-bit Thumb2 branch, load, and store instructions.
375   if (isThumb2 && !STI->prefers32BitThumb())
376     MadeChange |= OptimizeThumb2Instructions(MF);
377
378   // After a while, this might be made debug-only, but it is not expensive.
379   verify(MF);
380
381   // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
382   // undo the spill / restore of LR if possible.
383   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
384     MadeChange |= UndoLRSpillRestore();
385
386   // Save the mapping between original and cloned constpool entries.
387   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
388     for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
389       const CPEntry & CPE = CPEntries[i][j];
390       AFI->recordCPEClone(i, CPE.CPI);
391     }
392   }
393
394   DEBUG(errs() << '\n'; dumpBBs());
395
396   BBInfo.clear();
397   WaterList.clear();
398   CPUsers.clear();
399   CPEntries.clear();
400   ImmBranches.clear();
401   PushPopMIs.clear();
402   T2JumpTables.clear();
403
404   return MadeChange;
405 }
406
407 /// DoInitialPlacement - Perform the initial placement of the constant pool
408 /// entries.  To start with, we put them all at the end of the function.
409 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
410                                         std::vector<MachineInstr*> &CPEMIs) {
411   // Create the basic block to hold the CPE's.
412   MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
413   MF.push_back(BB);
414
415   // Mark the basic block as 4-byte aligned as required by the const-pool.
416   BB->setAlignment(2);
417
418   // Add all of the constants from the constant pool to the end block, use an
419   // identity mapping of CPI's to CPE's.
420   const std::vector<MachineConstantPoolEntry> &CPs =
421     MF.getConstantPool()->getConstants();
422
423   const TargetData &TD = *MF.getTarget().getTargetData();
424   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
425     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
426     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
427     // we would have to pad them out or something so that instructions stay
428     // aligned.
429     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
430     MachineInstr *CPEMI =
431       BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
432         .addImm(i).addConstantPoolIndex(i).addImm(Size);
433     CPEMIs.push_back(CPEMI);
434
435     // Add a new CPEntry, but no corresponding CPUser yet.
436     std::vector<CPEntry> CPEs;
437     CPEs.push_back(CPEntry(CPEMI, i));
438     CPEntries.push_back(CPEs);
439     ++NumCPEs;
440     DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
441                  << "\n");
442   }
443 }
444
445 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
446 /// into the block immediately after it.
447 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
448   // Get the next machine basic block in the function.
449   MachineFunction::iterator MBBI = MBB;
450   // Can't fall off end of function.
451   if (llvm::next(MBBI) == MBB->getParent()->end())
452     return false;
453
454   MachineBasicBlock *NextBB = llvm::next(MBBI);
455   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
456        E = MBB->succ_end(); I != E; ++I)
457     if (*I == NextBB)
458       return true;
459
460   return false;
461 }
462
463 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
464 /// look up the corresponding CPEntry.
465 ARMConstantIslands::CPEntry
466 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
467                                         const MachineInstr *CPEMI) {
468   std::vector<CPEntry> &CPEs = CPEntries[CPI];
469   // Number of entries per constpool index should be small, just do a
470   // linear search.
471   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
472     if (CPEs[i].CPEMI == CPEMI)
473       return &CPEs[i];
474   }
475   return NULL;
476 }
477
478 /// JumpTableFunctionScan - Do a scan of the function, building up
479 /// information about the sizes of each block and the locations of all
480 /// the jump tables.
481 void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
482   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
483        MBBI != E; ++MBBI) {
484     MachineBasicBlock &MBB = *MBBI;
485
486     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
487          I != E; ++I)
488       if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
489         T2JumpTables.push_back(I);
490   }
491 }
492
493 /// InitialFunctionScan - Do the initial scan of the function, building up
494 /// information about the sizes of each block, the location of all the water,
495 /// and finding all of the constant pool users.
496 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
497                                  const std::vector<MachineInstr*> &CPEMIs) {
498   // First thing, see if the function has any inline assembly in it. If so,
499   // we have to be conservative about alignment assumptions, as we don't
500   // know for sure the size of any instructions in the inline assembly.
501   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
502        MBBI != E; ++MBBI) {
503     MachineBasicBlock &MBB = *MBBI;
504     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
505          I != E; ++I)
506       if (I->getOpcode() == ARM::INLINEASM)
507         HasInlineAsm = true;
508   }
509
510   // Now go back through the instructions and build up our data structures.
511   unsigned Offset = 0;
512   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
513        MBBI != E; ++MBBI) {
514     MachineBasicBlock &MBB = *MBBI;
515
516     // If this block doesn't fall through into the next MBB, then this is
517     // 'water' that a constant pool island could be placed.
518     if (!BBHasFallthrough(&MBB))
519       WaterList.push_back(&MBB);
520
521     unsigned MBBSize = 0;
522     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
523          I != E; ++I) {
524       if (I->isDebugValue())
525         continue;
526       // Add instruction size to MBBSize.
527       MBBSize += TII->GetInstSizeInBytes(I);
528
529       int Opc = I->getOpcode();
530       if (I->getDesc().isBranch()) {
531         bool isCond = false;
532         unsigned Bits = 0;
533         unsigned Scale = 1;
534         int UOpc = Opc;
535         switch (Opc) {
536         default:
537           continue;  // Ignore other JT branches
538         case ARM::tBR_JTr:
539           // A Thumb1 table jump may involve padding; for the offsets to
540           // be right, functions containing these must be 4-byte aligned.
541           // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
542           // table entries. So this code checks whether offset of tBR_JTr + 2
543           // is aligned.  That is held in Offset+MBBSize, which already has
544           // 2 added in for the size of the mov pc instruction.
545           MF.EnsureAlignment(2U);
546           if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
547             // FIXME: Add a pseudo ALIGN instruction instead.
548             MBBSize += 2;           // padding
549           continue;   // Does not get an entry in ImmBranches
550         case ARM::t2BR_JT:
551           T2JumpTables.push_back(I);
552           continue;   // Does not get an entry in ImmBranches
553         case ARM::Bcc:
554           isCond = true;
555           UOpc = ARM::B;
556           // Fallthrough
557         case ARM::B:
558           Bits = 24;
559           Scale = 4;
560           break;
561         case ARM::tBcc:
562           isCond = true;
563           UOpc = ARM::tB;
564           Bits = 8;
565           Scale = 2;
566           break;
567         case ARM::tB:
568           Bits = 11;
569           Scale = 2;
570           break;
571         case ARM::t2Bcc:
572           isCond = true;
573           UOpc = ARM::t2B;
574           Bits = 20;
575           Scale = 2;
576           break;
577         case ARM::t2B:
578           Bits = 24;
579           Scale = 2;
580           break;
581         }
582
583         // Record this immediate branch.
584         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
585         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
586       }
587
588       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
589         PushPopMIs.push_back(I);
590
591       if (Opc == ARM::CONSTPOOL_ENTRY)
592         continue;
593
594       // Scan the instructions for constant pool operands.
595       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
596         if (I->getOperand(op).isCPI()) {
597           // We found one.  The addressing mode tells us the max displacement
598           // from the PC that this instruction permits.
599
600           // Basic size info comes from the TSFlags field.
601           unsigned Bits = 0;
602           unsigned Scale = 1;
603           bool NegOk = false;
604           bool IsSoImm = false;
605
606           switch (Opc) {
607           default:
608             llvm_unreachable("Unknown addressing mode for CP reference!");
609             break;
610
611           // Taking the address of a CP entry.
612           case ARM::LEApcrel:
613             // This takes a SoImm, which is 8 bit immediate rotated. We'll
614             // pretend the maximum offset is 255 * 4. Since each instruction
615             // 4 byte wide, this is always correct. We'll check for other
616             // displacements that fits in a SoImm as well.
617             Bits = 8;
618             Scale = 4;
619             NegOk = true;
620             IsSoImm = true;
621             break;
622           case ARM::t2LEApcrel:
623             Bits = 12;
624             NegOk = true;
625             break;
626           case ARM::tLEApcrel:
627             Bits = 8;
628             Scale = 4;
629             break;
630
631           case ARM::LDRi12:
632           case ARM::LDRcp:
633           case ARM::t2LDRpci:
634             Bits = 12;  // +-offset_12
635             NegOk = true;
636             break;
637
638           case ARM::tLDRpci:
639             Bits = 8;
640             Scale = 4;  // +(offset_8*4)
641             break;
642
643           case ARM::VLDRD:
644           case ARM::VLDRS:
645             Bits = 8;
646             Scale = 4;  // +-(offset_8*4)
647             NegOk = true;
648             break;
649           }
650
651           // Remember that this is a user of a CP entry.
652           unsigned CPI = I->getOperand(op).getIndex();
653           MachineInstr *CPEMI = CPEMIs[CPI];
654           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
655           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
656
657           // Increment corresponding CPEntry reference count.
658           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
659           assert(CPE && "Cannot find a corresponding CPEntry!");
660           CPE->RefCount++;
661
662           // Instructions can only use one CP entry, don't bother scanning the
663           // rest of the operands.
664           break;
665         }
666     }
667
668     // In thumb mode, if this block is a constpool island, we may need padding
669     // so it's aligned on 4 byte boundary.
670     if (isThumb &&
671         !MBB.empty() &&
672         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
673         ((Offset%4) != 0 || HasInlineAsm))
674       MBBSize += 2;
675
676     BBInfo.push_back(BasicBlockInfo(Offset, MBBSize));
677     Offset += MBBSize;
678   }
679 }
680
681 /// GetOffsetOf - Return the current offset of the specified machine instruction
682 /// from the start of the function.  This offset changes as stuff is moved
683 /// around inside the function.
684 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
685   MachineBasicBlock *MBB = MI->getParent();
686
687   // The offset is composed of two things: the sum of the sizes of all MBB's
688   // before this instruction's block, and the offset from the start of the block
689   // it is in.
690   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
691
692   // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
693   // alignment padding, and compensate if so.
694   if (isThumb &&
695       MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
696       (Offset%4 != 0 || HasInlineAsm))
697     Offset += 2;
698
699   // Sum instructions before MI in MBB.
700   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
701     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
702     if (&*I == MI) return Offset;
703     Offset += TII->GetInstSizeInBytes(I);
704   }
705 }
706
707 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
708 /// ID.
709 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
710                               const MachineBasicBlock *RHS) {
711   return LHS->getNumber() < RHS->getNumber();
712 }
713
714 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
715 /// machine function, it upsets all of the block numbers.  Renumber the blocks
716 /// and update the arrays that parallel this numbering.
717 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
718   // Renumber the MBB's to keep them consecutive.
719   NewBB->getParent()->RenumberBlocks(NewBB);
720
721   // Insert an entry into BBInfo to align it properly with the (newly
722   // renumbered) block numbers.
723   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
724
725   // Next, update WaterList.  Specifically, we need to add NewMBB as having
726   // available water after it.
727   water_iterator IP =
728     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
729                      CompareMBBNumbers);
730   WaterList.insert(IP, NewBB);
731 }
732
733
734 /// Split the basic block containing MI into two blocks, which are joined by
735 /// an unconditional branch.  Update data structures and renumber blocks to
736 /// account for this change and returns the newly created block.
737 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
738   MachineBasicBlock *OrigBB = MI->getParent();
739   MachineFunction &MF = *OrigBB->getParent();
740
741   // Create a new MBB for the code after the OrigBB.
742   MachineBasicBlock *NewBB =
743     MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
744   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
745   MF.insert(MBBI, NewBB);
746
747   // Splice the instructions starting with MI over to NewBB.
748   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
749
750   // Add an unconditional branch from OrigBB to NewBB.
751   // Note the new unconditional branch is not being recorded.
752   // There doesn't seem to be meaningful DebugInfo available; this doesn't
753   // correspond to anything in the source.
754   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
755   if (!isThumb)
756     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
757   else
758     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
759             .addImm(ARMCC::AL).addReg(0);
760   ++NumSplit;
761
762   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
763   NewBB->transferSuccessors(OrigBB);
764
765   // OrigBB branches to NewBB.
766   OrigBB->addSuccessor(NewBB);
767
768   // Update internal data structures to account for the newly inserted MBB.
769   // This is almost the same as UpdateForInsertedWaterBlock, except that
770   // the Water goes after OrigBB, not NewBB.
771   MF.RenumberBlocks(NewBB);
772
773   // Insert an entry into BBInfo to align it properly with the (newly
774   // renumbered) block numbers.
775   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
776
777   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
778   // available water after it (but not if it's already there, which happens
779   // when splitting before a conditional branch that is followed by an
780   // unconditional branch - in that case we want to insert NewBB).
781   water_iterator IP =
782     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
783                      CompareMBBNumbers);
784   MachineBasicBlock* WaterBB = *IP;
785   if (WaterBB == OrigBB)
786     WaterList.insert(llvm::next(IP), NewBB);
787   else
788     WaterList.insert(IP, OrigBB);
789   NewWaterList.insert(OrigBB);
790
791   unsigned OrigBBI = OrigBB->getNumber();
792   unsigned NewBBI = NewBB->getNumber();
793
794   int delta = isThumb1 ? 2 : 4;
795
796   // Figure out how large the OrigBB is.  As the first half of the original
797   // block, it cannot contain a tablejump.  The size includes
798   // the new jump we added.  (It should be possible to do this without
799   // recounting everything, but it's very confusing, and this is rarely
800   // executed.)
801   unsigned OrigBBSize = 0;
802   for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
803        I != E; ++I)
804     OrigBBSize += TII->GetInstSizeInBytes(I);
805   BBInfo[OrigBBI].Size = OrigBBSize;
806
807   // ...and adjust BBOffsets for NewBB accordingly.
808   BBInfo[NewBBI].Offset = BBInfo[OrigBBI].postOffset();
809
810   // Figure out how large the NewMBB is.  As the second half of the original
811   // block, it may contain a tablejump.
812   unsigned NewBBSize = 0;
813   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
814        I != E; ++I)
815     NewBBSize += TII->GetInstSizeInBytes(I);
816   // Set the size of NewBB in BBSizes.  It does not include any padding now.
817   BBInfo[NewBBI].Size = NewBBSize;
818
819   MachineInstr* ThumbJTMI = prior(NewBB->end());
820   if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
821     // We've added another 2-byte instruction before this tablejump, which
822     // means we will always need padding if we didn't before, and vice versa.
823
824     // The original offset of the jump instruction was:
825     unsigned OrigOffset = BBInfo[OrigBBI].postOffset() - delta;
826     if (OrigOffset%4 == 0) {
827       // We had padding before and now we don't.  No net change in code size.
828       delta = 0;
829     } else {
830       // We didn't have padding before and now we do.
831       BBInfo[NewBBI].Size += 2;
832       delta = 4;
833     }
834   }
835
836   // All BBOffsets following these blocks must be modified.
837   if (delta)
838     AdjustBBOffsetsAfter(NewBB, delta);
839
840   return NewBB;
841 }
842
843 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
844 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
845 /// constant pool entry).
846 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
847                                          unsigned TrialOffset, unsigned MaxDisp,
848                                          bool NegativeOK, bool IsSoImm) {
849   // On Thumb offsets==2 mod 4 are rounded down by the hardware for
850   // purposes of the displacement computation; compensate for that here.
851   // Effectively, the valid range of displacements is 2 bytes smaller for such
852   // references.
853   unsigned TotalAdj = 0;
854   if (isThumb && UserOffset%4 !=0) {
855     UserOffset -= 2;
856     TotalAdj = 2;
857   }
858   // CPEs will be rounded up to a multiple of 4.
859   if (isThumb && TrialOffset%4 != 0) {
860     TrialOffset += 2;
861     TotalAdj += 2;
862   }
863
864   // In Thumb2 mode, later branch adjustments can shift instructions up and
865   // cause alignment change. In the worst case scenario this can cause the
866   // user's effective address to be subtracted by 2 and the CPE's address to
867   // be plus 2.
868   if (isThumb2 && TotalAdj != 4)
869     MaxDisp -= (4 - TotalAdj);
870
871   if (UserOffset <= TrialOffset) {
872     // User before the Trial.
873     if (TrialOffset - UserOffset <= MaxDisp)
874       return true;
875     // FIXME: Make use full range of soimm values.
876   } else if (NegativeOK) {
877     if (UserOffset - TrialOffset <= MaxDisp)
878       return true;
879     // FIXME: Make use full range of soimm values.
880   }
881   return false;
882 }
883
884 /// WaterIsInRange - Returns true if a CPE placed after the specified
885 /// Water (a basic block) will be in range for the specific MI.
886
887 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
888                                         MachineBasicBlock* Water, CPUser &U) {
889   unsigned MaxDisp = U.MaxDisp;
890   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
891
892   // If the CPE is to be inserted before the instruction, that will raise
893   // the offset of the instruction.
894   if (CPEOffset < UserOffset)
895     UserOffset += U.CPEMI->getOperand(2).getImm();
896
897   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
898 }
899
900 /// CPEIsInRange - Returns true if the distance between specific MI and
901 /// specific ConstPool entry instruction can fit in MI's displacement field.
902 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
903                                       MachineInstr *CPEMI, unsigned MaxDisp,
904                                       bool NegOk, bool DoDump) {
905   unsigned CPEOffset  = GetOffsetOf(CPEMI);
906   assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
907
908   if (DoDump) {
909     DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
910                  << " max delta=" << MaxDisp
911                  << " insn address=" << UserOffset
912                  << " CPE address=" << CPEOffset
913                  << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
914   }
915
916   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
917 }
918
919 #ifndef NDEBUG
920 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
921 /// unconditionally branches to its only successor.
922 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
923   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
924     return false;
925
926   MachineBasicBlock *Succ = *MBB->succ_begin();
927   MachineBasicBlock *Pred = *MBB->pred_begin();
928   MachineInstr *PredMI = &Pred->back();
929   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
930       || PredMI->getOpcode() == ARM::t2B)
931     return PredMI->getOperand(0).getMBB() == Succ;
932   return false;
933 }
934 #endif // NDEBUG
935
936 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
937                                               int delta) {
938   MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
939   for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
940       i < e; ++i) {
941     BBInfo[i].Offset += delta;
942     // If some existing blocks have padding, adjust the padding as needed, a
943     // bit tricky.  delta can be negative so don't use % on that.
944     if (!isThumb)
945       continue;
946     MachineBasicBlock *MBB = MBBI;
947     if (!MBB->empty() && !HasInlineAsm) {
948       // Constant pool entries require padding.
949       if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
950         unsigned OldOffset = BBInfo[i].Offset - delta;
951         if ((OldOffset%4) == 0 && (BBInfo[i].Offset%4) != 0) {
952           // add new padding
953           BBInfo[i].Size += 2;
954           delta += 2;
955         } else if ((OldOffset%4) != 0 && (BBInfo[i].Offset%4) == 0) {
956           // remove existing padding
957           BBInfo[i].Size -= 2;
958           delta -= 2;
959         }
960       }
961       // Thumb1 jump tables require padding.  They should be at the end;
962       // following unconditional branches are removed by AnalyzeBranch.
963       // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
964       // table entries. So this code checks whether offset of tBR_JTr
965       // is aligned; if it is, the offset of the jump table following the
966       // instruction will not be aligned, and we need padding.
967       MachineInstr *ThumbJTMI = prior(MBB->end());
968       if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
969         unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
970         unsigned OldMIOffset = NewMIOffset - delta;
971         if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
972           // remove existing padding
973           BBInfo[i].Size -= 2;
974           delta -= 2;
975         } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
976           // add new padding
977           BBInfo[i].Size += 2;
978           delta += 2;
979         }
980       }
981       if (delta==0)
982         return;
983     }
984     MBBI = llvm::next(MBBI);
985   }
986 }
987
988 /// DecrementOldEntry - find the constant pool entry with index CPI
989 /// and instruction CPEMI, and decrement its refcount.  If the refcount
990 /// becomes 0 remove the entry and instruction.  Returns true if we removed
991 /// the entry, false if we didn't.
992
993 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
994   // Find the old entry. Eliminate it if it is no longer used.
995   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
996   assert(CPE && "Unexpected!");
997   if (--CPE->RefCount == 0) {
998     RemoveDeadCPEMI(CPEMI);
999     CPE->CPEMI = NULL;
1000     --NumCPEs;
1001     return true;
1002   }
1003   return false;
1004 }
1005
1006 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1007 /// if not, see if an in-range clone of the CPE is in range, and if so,
1008 /// change the data structures so the user references the clone.  Returns:
1009 /// 0 = no existing entry found
1010 /// 1 = entry found, and there were no code insertions or deletions
1011 /// 2 = entry found, and there were code insertions or deletions
1012 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1013 {
1014   MachineInstr *UserMI = U.MI;
1015   MachineInstr *CPEMI  = U.CPEMI;
1016
1017   // Check to see if the CPE is already in-range.
1018   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
1019     DEBUG(errs() << "In range\n");
1020     return 1;
1021   }
1022
1023   // No.  Look for previously created clones of the CPE that are in range.
1024   unsigned CPI = CPEMI->getOperand(1).getIndex();
1025   std::vector<CPEntry> &CPEs = CPEntries[CPI];
1026   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1027     // We already tried this one
1028     if (CPEs[i].CPEMI == CPEMI)
1029       continue;
1030     // Removing CPEs can leave empty entries, skip
1031     if (CPEs[i].CPEMI == NULL)
1032       continue;
1033     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1034       DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1035                    << CPEs[i].CPI << "\n");
1036       // Point the CPUser node to the replacement
1037       U.CPEMI = CPEs[i].CPEMI;
1038       // Change the CPI in the instruction operand to refer to the clone.
1039       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1040         if (UserMI->getOperand(j).isCPI()) {
1041           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1042           break;
1043         }
1044       // Adjust the refcount of the clone...
1045       CPEs[i].RefCount++;
1046       // ...and the original.  If we didn't remove the old entry, none of the
1047       // addresses changed, so we don't need another pass.
1048       return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1049     }
1050   }
1051   return 0;
1052 }
1053
1054 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1055 /// the specific unconditional branch instruction.
1056 static inline unsigned getUnconditionalBrDisp(int Opc) {
1057   switch (Opc) {
1058   case ARM::tB:
1059     return ((1<<10)-1)*2;
1060   case ARM::t2B:
1061     return ((1<<23)-1)*2;
1062   default:
1063     break;
1064   }
1065
1066   return ((1<<23)-1)*4;
1067 }
1068
1069 /// LookForWater - Look for an existing entry in the WaterList in which
1070 /// we can place the CPE referenced from U so it's within range of U's MI.
1071 /// Returns true if found, false if not.  If it returns true, WaterIter
1072 /// is set to the WaterList entry.  For Thumb, prefer water that will not
1073 /// introduce padding to water that will.  To ensure that this pass
1074 /// terminates, the CPE location for a particular CPUser is only allowed to
1075 /// move to a lower address, so search backward from the end of the list and
1076 /// prefer the first water that is in range.
1077 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1078                                       water_iterator &WaterIter) {
1079   if (WaterList.empty())
1080     return false;
1081
1082   bool FoundWaterThatWouldPad = false;
1083   water_iterator IPThatWouldPad;
1084   for (water_iterator IP = prior(WaterList.end()),
1085          B = WaterList.begin();; --IP) {
1086     MachineBasicBlock* WaterBB = *IP;
1087     // Check if water is in range and is either at a lower address than the
1088     // current "high water mark" or a new water block that was created since
1089     // the previous iteration by inserting an unconditional branch.  In the
1090     // latter case, we want to allow resetting the high water mark back to
1091     // this new water since we haven't seen it before.  Inserting branches
1092     // should be relatively uncommon and when it does happen, we want to be
1093     // sure to take advantage of it for all the CPEs near that block, so that
1094     // we don't insert more branches than necessary.
1095     if (WaterIsInRange(UserOffset, WaterBB, U) &&
1096         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1097          NewWaterList.count(WaterBB))) {
1098       unsigned WBBId = WaterBB->getNumber();
1099       if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
1100         // This is valid Water, but would introduce padding.  Remember
1101         // it in case we don't find any Water that doesn't do this.
1102         if (!FoundWaterThatWouldPad) {
1103           FoundWaterThatWouldPad = true;
1104           IPThatWouldPad = IP;
1105         }
1106       } else {
1107         WaterIter = IP;
1108         return true;
1109       }
1110     }
1111     if (IP == B)
1112       break;
1113   }
1114   if (FoundWaterThatWouldPad) {
1115     WaterIter = IPThatWouldPad;
1116     return true;
1117   }
1118   return false;
1119 }
1120
1121 /// CreateNewWater - No existing WaterList entry will work for
1122 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1123 /// block is used if in range, and the conditional branch munged so control
1124 /// flow is correct.  Otherwise the block is split to create a hole with an
1125 /// unconditional branch around it.  In either case NewMBB is set to a
1126 /// block following which the new island can be inserted (the WaterList
1127 /// is not adjusted).
1128 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1129                                         unsigned UserOffset,
1130                                         MachineBasicBlock *&NewMBB) {
1131   CPUser &U = CPUsers[CPUserIndex];
1132   MachineInstr *UserMI = U.MI;
1133   MachineInstr *CPEMI  = U.CPEMI;
1134   MachineBasicBlock *UserMBB = UserMI->getParent();
1135   unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
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 }