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