ARMConstantIslandPass.cpp revision 9a4d2e40a02b6e5fab5ccf1c768a52c76f3aec6a
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 "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  MadeChange |= 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::t2LDRi12:
609          case ARM::t2LDRHi12:
610          case ARM::t2LDRBi12:
611          case ARM::t2LDRSHi12:
612          case ARM::t2LDRSBi12:
613            Bits = 12;  // +-offset_12
614            NegOk = true;
615            break;
616
617          case ARM::tLDRpci:
618            Bits = 8;
619            Scale = 4;  // +(offset_8*4)
620            break;
621
622          case ARM::VLDRD:
623          case ARM::VLDRS:
624            Bits = 8;
625            Scale = 4;  // +-(offset_8*4)
626            NegOk = true;
627            break;
628          }
629
630          // Remember that this is a user of a CP entry.
631          unsigned CPI = I->getOperand(op).getIndex();
632          MachineInstr *CPEMI = CPEMIs[CPI];
633          unsigned MaxOffs = ((1 << Bits)-1) * Scale;
634          CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
635
636          // Increment corresponding CPEntry reference count.
637          CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
638          assert(CPE && "Cannot find a corresponding CPEntry!");
639          CPE->RefCount++;
640
641          // Instructions can only use one CP entry, don't bother scanning the
642          // rest of the operands.
643          break;
644        }
645    }
646
647    // In thumb mode, if this block is a constpool island, we may need padding
648    // so it's aligned on 4 byte boundary.
649    if (isThumb &&
650        !MBB.empty() &&
651        MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
652        ((Offset%4) != 0 || HasInlineAsm))
653      MBBSize += 2;
654
655    BBSizes.push_back(MBBSize);
656    BBOffsets.push_back(Offset);
657    Offset += MBBSize;
658  }
659}
660
661/// GetOffsetOf - Return the current offset of the specified machine instruction
662/// from the start of the function.  This offset changes as stuff is moved
663/// around inside the function.
664unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
665  MachineBasicBlock *MBB = MI->getParent();
666
667  // The offset is composed of two things: the sum of the sizes of all MBB's
668  // before this instruction's block, and the offset from the start of the block
669  // it is in.
670  unsigned Offset = BBOffsets[MBB->getNumber()];
671
672  // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
673  // alignment padding, and compensate if so.
674  if (isThumb &&
675      MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
676      (Offset%4 != 0 || HasInlineAsm))
677    Offset += 2;
678
679  // Sum instructions before MI in MBB.
680  for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
681    assert(I != MBB->end() && "Didn't find MI in its own basic block?");
682    if (&*I == MI) return Offset;
683    Offset += TII->GetInstSizeInBytes(I);
684  }
685}
686
687/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
688/// ID.
689static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
690                              const MachineBasicBlock *RHS) {
691  return LHS->getNumber() < RHS->getNumber();
692}
693
694/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
695/// machine function, it upsets all of the block numbers.  Renumber the blocks
696/// and update the arrays that parallel this numbering.
697void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
698  // Renumber the MBB's to keep them consequtive.
699  NewBB->getParent()->RenumberBlocks(NewBB);
700
701  // Insert a size into BBSizes to align it properly with the (newly
702  // renumbered) block numbers.
703  BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
704
705  // Likewise for BBOffsets.
706  BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
707
708  // Next, update WaterList.  Specifically, we need to add NewMBB as having
709  // available water after it.
710  water_iterator IP =
711    std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
712                     CompareMBBNumbers);
713  WaterList.insert(IP, NewBB);
714}
715
716
717/// Split the basic block containing MI into two blocks, which are joined by
718/// an unconditional branch.  Update data structures and renumber blocks to
719/// account for this change and returns the newly created block.
720MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
721  MachineBasicBlock *OrigBB = MI->getParent();
722  MachineFunction &MF = *OrigBB->getParent();
723
724  // Create a new MBB for the code after the OrigBB.
725  MachineBasicBlock *NewBB =
726    MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
727  MachineFunction::iterator MBBI = OrigBB; ++MBBI;
728  MF.insert(MBBI, NewBB);
729
730  // Splice the instructions starting with MI over to NewBB.
731  NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
732
733  // Add an unconditional branch from OrigBB to NewBB.
734  // Note the new unconditional branch is not being recorded.
735  // There doesn't seem to be meaningful DebugInfo available; this doesn't
736  // correspond to anything in the source.
737  unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
738  BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
739  ++NumSplit;
740
741  // Update the CFG.  All succs of OrigBB are now succs of NewBB.
742  while (!OrigBB->succ_empty()) {
743    MachineBasicBlock *Succ = *OrigBB->succ_begin();
744    OrigBB->removeSuccessor(Succ);
745    NewBB->addSuccessor(Succ);
746
747    // This pass should be run after register allocation, so there should be no
748    // PHI nodes to update.
749    assert((Succ->empty() || !Succ->begin()->isPHI())
750           && "PHI nodes should be eliminated by now!");
751  }
752
753  // OrigBB branches to NewBB.
754  OrigBB->addSuccessor(NewBB);
755
756  // Update internal data structures to account for the newly inserted MBB.
757  // This is almost the same as UpdateForInsertedWaterBlock, except that
758  // the Water goes after OrigBB, not NewBB.
759  MF.RenumberBlocks(NewBB);
760
761  // Insert a size into BBSizes to align it properly with the (newly
762  // renumbered) block numbers.
763  BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
764
765  // Likewise for BBOffsets.
766  BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
767
768  // Next, update WaterList.  Specifically, we need to add OrigMBB as having
769  // available water after it (but not if it's already there, which happens
770  // when splitting before a conditional branch that is followed by an
771  // unconditional branch - in that case we want to insert NewBB).
772  water_iterator IP =
773    std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
774                     CompareMBBNumbers);
775  MachineBasicBlock* WaterBB = *IP;
776  if (WaterBB == OrigBB)
777    WaterList.insert(llvm::next(IP), NewBB);
778  else
779    WaterList.insert(IP, OrigBB);
780  NewWaterList.insert(OrigBB);
781
782  unsigned OrigBBI = OrigBB->getNumber();
783  unsigned NewBBI = NewBB->getNumber();
784
785  int delta = isThumb1 ? 2 : 4;
786
787  // Figure out how large the OrigBB is.  As the first half of the original
788  // block, it cannot contain a tablejump.  The size includes
789  // the new jump we added.  (It should be possible to do this without
790  // recounting everything, but it's very confusing, and this is rarely
791  // executed.)
792  unsigned OrigBBSize = 0;
793  for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
794       I != E; ++I)
795    OrigBBSize += TII->GetInstSizeInBytes(I);
796  BBSizes[OrigBBI] = OrigBBSize;
797
798  // ...and adjust BBOffsets for NewBB accordingly.
799  BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
800
801  // Figure out how large the NewMBB is.  As the second half of the original
802  // block, it may contain a tablejump.
803  unsigned NewBBSize = 0;
804  for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
805       I != E; ++I)
806    NewBBSize += TII->GetInstSizeInBytes(I);
807  // Set the size of NewBB in BBSizes.  It does not include any padding now.
808  BBSizes[NewBBI] = NewBBSize;
809
810  MachineInstr* ThumbJTMI = prior(NewBB->end());
811  if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
812    // We've added another 2-byte instruction before this tablejump, which
813    // means we will always need padding if we didn't before, and vice versa.
814
815    // The original offset of the jump instruction was:
816    unsigned OrigOffset = BBOffsets[OrigBBI] + BBSizes[OrigBBI] - delta;
817    if (OrigOffset%4 == 0) {
818      // We had padding before and now we don't.  No net change in code size.
819      delta = 0;
820    } else {
821      // We didn't have padding before and now we do.
822      BBSizes[NewBBI] += 2;
823      delta = 4;
824    }
825  }
826
827  // All BBOffsets following these blocks must be modified.
828  if (delta)
829    AdjustBBOffsetsAfter(NewBB, delta);
830
831  return NewBB;
832}
833
834/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
835/// reference) is within MaxDisp of TrialOffset (a proposed location of a
836/// constant pool entry).
837bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
838                                         unsigned TrialOffset, unsigned MaxDisp,
839                                         bool NegativeOK, bool IsSoImm) {
840  // On Thumb offsets==2 mod 4 are rounded down by the hardware for
841  // purposes of the displacement computation; compensate for that here.
842  // Effectively, the valid range of displacements is 2 bytes smaller for such
843  // references.
844  unsigned TotalAdj = 0;
845  if (isThumb && UserOffset%4 !=0) {
846    UserOffset -= 2;
847    TotalAdj = 2;
848  }
849  // CPEs will be rounded up to a multiple of 4.
850  if (isThumb && TrialOffset%4 != 0) {
851    TrialOffset += 2;
852    TotalAdj += 2;
853  }
854
855  // In Thumb2 mode, later branch adjustments can shift instructions up and
856  // cause alignment change. In the worst case scenario this can cause the
857  // user's effective address to be subtracted by 2 and the CPE's address to
858  // be plus 2.
859  if (isThumb2 && TotalAdj != 4)
860    MaxDisp -= (4 - TotalAdj);
861
862  if (UserOffset <= TrialOffset) {
863    // User before the Trial.
864    if (TrialOffset - UserOffset <= MaxDisp)
865      return true;
866    // FIXME: Make use full range of soimm values.
867  } else if (NegativeOK) {
868    if (UserOffset - TrialOffset <= MaxDisp)
869      return true;
870    // FIXME: Make use full range of soimm values.
871  }
872  return false;
873}
874
875/// WaterIsInRange - Returns true if a CPE placed after the specified
876/// Water (a basic block) will be in range for the specific MI.
877
878bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
879                                        MachineBasicBlock* Water, CPUser &U) {
880  unsigned MaxDisp = U.MaxDisp;
881  unsigned CPEOffset = BBOffsets[Water->getNumber()] +
882                       BBSizes[Water->getNumber()];
883
884  // If the CPE is to be inserted before the instruction, that will raise
885  // the offset of the instruction.
886  if (CPEOffset < UserOffset)
887    UserOffset += U.CPEMI->getOperand(2).getImm();
888
889  return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
890}
891
892/// CPEIsInRange - Returns true if the distance between specific MI and
893/// specific ConstPool entry instruction can fit in MI's displacement field.
894bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
895                                      MachineInstr *CPEMI, unsigned MaxDisp,
896                                      bool NegOk, bool DoDump) {
897  unsigned CPEOffset  = GetOffsetOf(CPEMI);
898  assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
899
900  if (DoDump) {
901    DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
902                 << " max delta=" << MaxDisp
903                 << " insn address=" << UserOffset
904                 << " CPE address=" << CPEOffset
905                 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
906  }
907
908  return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
909}
910
911#ifndef NDEBUG
912/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
913/// unconditionally branches to its only successor.
914static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
915  if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
916    return false;
917
918  MachineBasicBlock *Succ = *MBB->succ_begin();
919  MachineBasicBlock *Pred = *MBB->pred_begin();
920  MachineInstr *PredMI = &Pred->back();
921  if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
922      || PredMI->getOpcode() == ARM::t2B)
923    return PredMI->getOperand(0).getMBB() == Succ;
924  return false;
925}
926#endif // NDEBUG
927
928void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
929                                              int delta) {
930  MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
931  for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
932      i < e; ++i) {
933    BBOffsets[i] += delta;
934    // If some existing blocks have padding, adjust the padding as needed, a
935    // bit tricky.  delta can be negative so don't use % on that.
936    if (!isThumb)
937      continue;
938    MachineBasicBlock *MBB = MBBI;
939    if (!MBB->empty() && !HasInlineAsm) {
940      // Constant pool entries require padding.
941      if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
942        unsigned OldOffset = BBOffsets[i] - delta;
943        if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
944          // add new padding
945          BBSizes[i] += 2;
946          delta += 2;
947        } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
948          // remove existing padding
949          BBSizes[i] -= 2;
950          delta -= 2;
951        }
952      }
953      // Thumb1 jump tables require padding.  They should be at the end;
954      // following unconditional branches are removed by AnalyzeBranch.
955      // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
956      // table entries. So this code checks whether offset of tBR_JTr
957      // is aligned; if it is, the offset of the jump table following the
958      // instruction will not be aligned, and we need padding.
959      MachineInstr *ThumbJTMI = prior(MBB->end());
960      if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
961        unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
962        unsigned OldMIOffset = NewMIOffset - delta;
963        if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
964          // remove existing padding
965          BBSizes[i] -= 2;
966          delta -= 2;
967        } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
968          // add new padding
969          BBSizes[i] += 2;
970          delta += 2;
971        }
972      }
973      if (delta==0)
974        return;
975    }
976    MBBI = llvm::next(MBBI);
977  }
978}
979
980/// DecrementOldEntry - find the constant pool entry with index CPI
981/// and instruction CPEMI, and decrement its refcount.  If the refcount
982/// becomes 0 remove the entry and instruction.  Returns true if we removed
983/// the entry, false if we didn't.
984
985bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
986  // Find the old entry. Eliminate it if it is no longer used.
987  CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
988  assert(CPE && "Unexpected!");
989  if (--CPE->RefCount == 0) {
990    RemoveDeadCPEMI(CPEMI);
991    CPE->CPEMI = NULL;
992    --NumCPEs;
993    return true;
994  }
995  return false;
996}
997
998/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
999/// if not, see if an in-range clone of the CPE is in range, and if so,
1000/// change the data structures so the user references the clone.  Returns:
1001/// 0 = no existing entry found
1002/// 1 = entry found, and there were no code insertions or deletions
1003/// 2 = entry found, and there were code insertions or deletions
1004int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1005{
1006  MachineInstr *UserMI = U.MI;
1007  MachineInstr *CPEMI  = U.CPEMI;
1008
1009  // Check to see if the CPE is already in-range.
1010  if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
1011    DEBUG(errs() << "In range\n");
1012    return 1;
1013  }
1014
1015  // No.  Look for previously created clones of the CPE that are in range.
1016  unsigned CPI = CPEMI->getOperand(1).getIndex();
1017  std::vector<CPEntry> &CPEs = CPEntries[CPI];
1018  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1019    // We already tried this one
1020    if (CPEs[i].CPEMI == CPEMI)
1021      continue;
1022    // Removing CPEs can leave empty entries, skip
1023    if (CPEs[i].CPEMI == NULL)
1024      continue;
1025    if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1026      DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1027                   << CPEs[i].CPI << "\n");
1028      // Point the CPUser node to the replacement
1029      U.CPEMI = CPEs[i].CPEMI;
1030      // Change the CPI in the instruction operand to refer to the clone.
1031      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1032        if (UserMI->getOperand(j).isCPI()) {
1033          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1034          break;
1035        }
1036      // Adjust the refcount of the clone...
1037      CPEs[i].RefCount++;
1038      // ...and the original.  If we didn't remove the old entry, none of the
1039      // addresses changed, so we don't need another pass.
1040      return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1041    }
1042  }
1043  return 0;
1044}
1045
1046/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1047/// the specific unconditional branch instruction.
1048static inline unsigned getUnconditionalBrDisp(int Opc) {
1049  switch (Opc) {
1050  case ARM::tB:
1051    return ((1<<10)-1)*2;
1052  case ARM::t2B:
1053    return ((1<<23)-1)*2;
1054  default:
1055    break;
1056  }
1057
1058  return ((1<<23)-1)*4;
1059}
1060
1061/// LookForWater - Look for an existing entry in the WaterList in which
1062/// we can place the CPE referenced from U so it's within range of U's MI.
1063/// Returns true if found, false if not.  If it returns true, WaterIter
1064/// is set to the WaterList entry.  For Thumb, prefer water that will not
1065/// introduce padding to water that will.  To ensure that this pass
1066/// terminates, the CPE location for a particular CPUser is only allowed to
1067/// move to a lower address, so search backward from the end of the list and
1068/// prefer the first water that is in range.
1069bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1070                                      water_iterator &WaterIter) {
1071  if (WaterList.empty())
1072    return false;
1073
1074  bool FoundWaterThatWouldPad = false;
1075  water_iterator IPThatWouldPad;
1076  for (water_iterator IP = prior(WaterList.end()),
1077         B = WaterList.begin();; --IP) {
1078    MachineBasicBlock* WaterBB = *IP;
1079    // Check if water is in range and is either at a lower address than the
1080    // current "high water mark" or a new water block that was created since
1081    // the previous iteration by inserting an unconditional branch.  In the
1082    // latter case, we want to allow resetting the high water mark back to
1083    // this new water since we haven't seen it before.  Inserting branches
1084    // should be relatively uncommon and when it does happen, we want to be
1085    // sure to take advantage of it for all the CPEs near that block, so that
1086    // we don't insert more branches than necessary.
1087    if (WaterIsInRange(UserOffset, WaterBB, U) &&
1088        (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1089         NewWaterList.count(WaterBB))) {
1090      unsigned WBBId = WaterBB->getNumber();
1091      if (isThumb &&
1092          (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1093        // This is valid Water, but would introduce padding.  Remember
1094        // it in case we don't find any Water that doesn't do this.
1095        if (!FoundWaterThatWouldPad) {
1096          FoundWaterThatWouldPad = true;
1097          IPThatWouldPad = IP;
1098        }
1099      } else {
1100        WaterIter = IP;
1101        return true;
1102      }
1103    }
1104    if (IP == B)
1105      break;
1106  }
1107  if (FoundWaterThatWouldPad) {
1108    WaterIter = IPThatWouldPad;
1109    return true;
1110  }
1111  return false;
1112}
1113
1114/// CreateNewWater - No existing WaterList entry will work for
1115/// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1116/// block is used if in range, and the conditional branch munged so control
1117/// flow is correct.  Otherwise the block is split to create a hole with an
1118/// unconditional branch around it.  In either case NewMBB is set to a
1119/// block following which the new island can be inserted (the WaterList
1120/// is not adjusted).
1121void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1122                                        unsigned UserOffset,
1123                                        MachineBasicBlock *&NewMBB) {
1124  CPUser &U = CPUsers[CPUserIndex];
1125  MachineInstr *UserMI = U.MI;
1126  MachineInstr *CPEMI  = U.CPEMI;
1127  MachineBasicBlock *UserMBB = UserMI->getParent();
1128  unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
1129                               BBSizes[UserMBB->getNumber()];
1130  assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1131
1132  // If the block does not end in an unconditional branch already, and if the
1133  // end of the block is within range, make new water there.  (The addition
1134  // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1135  // Thumb2, 2 on Thumb1.  Possible Thumb1 alignment padding is allowed for
1136  // inside OffsetIsInRange.
1137  if (BBHasFallthrough(UserMBB) &&
1138      OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1139                      U.MaxDisp, U.NegOk, U.IsSoImm)) {
1140    DEBUG(errs() << "Split at end of block\n");
1141    if (&UserMBB->back() == UserMI)
1142      assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1143    NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1144    // Add an unconditional branch from UserMBB to fallthrough block.
1145    // Record it for branch lengthening; this new branch will not get out of
1146    // range, but if the preceding conditional branch is out of range, the
1147    // targets will be exchanged, and the altered branch may be out of
1148    // range, so the machinery has to know about it.
1149    int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1150    BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1151    unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1152    ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1153                          MaxDisp, false, UncondBr));
1154    int delta = isThumb1 ? 2 : 4;
1155    BBSizes[UserMBB->getNumber()] += delta;
1156    AdjustBBOffsetsAfter(UserMBB, delta);
1157  } else {
1158    // What a big block.  Find a place within the block to split it.
1159    // This is a little tricky on Thumb1 since instructions are 2 bytes
1160    // and constant pool entries are 4 bytes: if instruction I references
1161    // island CPE, and instruction I+1 references CPE', it will
1162    // not work well to put CPE as far forward as possible, since then
1163    // CPE' cannot immediately follow it (that location is 2 bytes
1164    // farther away from I+1 than CPE was from I) and we'd need to create
1165    // a new island.  So, we make a first guess, then walk through the
1166    // instructions between the one currently being looked at and the
1167    // possible insertion point, and make sure any other instructions
1168    // that reference CPEs will be able to use the same island area;
1169    // if not, we back up the insertion point.
1170
1171    // The 4 in the following is for the unconditional branch we'll be
1172    // inserting (allows for long branch on Thumb1).  Alignment of the
1173    // island is handled inside OffsetIsInRange.
1174    unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1175    // This could point off the end of the block if we've already got
1176    // constant pool entries following this block; only the last one is
1177    // in the water list.  Back past any possible branches (allow for a
1178    // conditional and a maximally long unconditional).
1179    if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1180      BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1181                              (isThumb1 ? 6 : 8);
1182    unsigned EndInsertOffset = BaseInsertOffset +
1183           CPEMI->getOperand(2).getImm();
1184    MachineBasicBlock::iterator MI = UserMI;
1185    ++MI;
1186    unsigned CPUIndex = CPUserIndex+1;
1187    unsigned NumCPUsers = CPUsers.size();
1188    MachineInstr *LastIT = 0;
1189    for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1190         Offset < BaseInsertOffset;
1191         Offset += TII->GetInstSizeInBytes(MI),
1192           MI = llvm::next(MI)) {
1193      if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1194        CPUser &U = CPUsers[CPUIndex];
1195        if (!OffsetIsInRange(Offset, EndInsertOffset,
1196                             U.MaxDisp, U.NegOk, U.IsSoImm)) {
1197          BaseInsertOffset -= (isThumb1 ? 2 : 4);
1198          EndInsertOffset  -= (isThumb1 ? 2 : 4);
1199        }
1200        // This is overly conservative, as we don't account for CPEMIs
1201        // being reused within the block, but it doesn't matter much.
1202        EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1203        CPUIndex++;
1204      }
1205
1206      // Remember the last IT instruction.
1207      if (MI->getOpcode() == ARM::t2IT)
1208        LastIT = MI;
1209    }
1210
1211    DEBUG(errs() << "Split in middle of big block\n");
1212    --MI;
1213
1214    // Avoid splitting an IT block.
1215    if (LastIT) {
1216      unsigned PredReg = 0;
1217      ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1218      if (CC != ARMCC::AL)
1219        MI = LastIT;
1220    }
1221    NewMBB = SplitBlockBeforeInstr(MI);
1222  }
1223}
1224
1225/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1226/// is out-of-range.  If so, pick up the constant pool value and move it some
1227/// place in-range.  Return true if we changed any addresses (thus must run
1228/// another pass of branch lengthening), false otherwise.
1229bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1230                                                unsigned CPUserIndex) {
1231  CPUser &U = CPUsers[CPUserIndex];
1232  MachineInstr *UserMI = U.MI;
1233  MachineInstr *CPEMI  = U.CPEMI;
1234  unsigned CPI = CPEMI->getOperand(1).getIndex();
1235  unsigned Size = CPEMI->getOperand(2).getImm();
1236  // Compute this only once, it's expensive.  The 4 or 8 is the value the
1237  // hardware keeps in the PC.
1238  unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1239
1240  // See if the current entry is within range, or there is a clone of it
1241  // in range.
1242  int result = LookForExistingCPEntry(U, UserOffset);
1243  if (result==1) return false;
1244  else if (result==2) return true;
1245
1246  // No existing clone of this CPE is within range.
1247  // We will be generating a new clone.  Get a UID for it.
1248  unsigned ID = AFI->createConstPoolEntryUId();
1249
1250  // Look for water where we can place this CPE.
1251  MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1252  MachineBasicBlock *NewMBB;
1253  water_iterator IP;
1254  if (LookForWater(U, UserOffset, IP)) {
1255    DEBUG(errs() << "found water in range\n");
1256    MachineBasicBlock *WaterBB = *IP;
1257
1258    // If the original WaterList entry was "new water" on this iteration,
1259    // propagate that to the new island.  This is just keeping NewWaterList
1260    // updated to match the WaterList, which will be updated below.
1261    if (NewWaterList.count(WaterBB)) {
1262      NewWaterList.erase(WaterBB);
1263      NewWaterList.insert(NewIsland);
1264    }
1265    // The new CPE goes before the following block (NewMBB).
1266    NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1267
1268  } else {
1269    // No water found.
1270    DEBUG(errs() << "No water found\n");
1271    CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1272
1273    // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1274    // called while handling branches so that the water will be seen on the
1275    // next iteration for constant pools, but in this context, we don't want
1276    // it.  Check for this so it will be removed from the WaterList.
1277    // Also remove any entry from NewWaterList.
1278    MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1279    IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1280    if (IP != WaterList.end())
1281      NewWaterList.erase(WaterBB);
1282
1283    // We are adding new water.  Update NewWaterList.
1284    NewWaterList.insert(NewIsland);
1285  }
1286
1287  // Remove the original WaterList entry; we want subsequent insertions in
1288  // this vicinity to go after the one we're about to insert.  This
1289  // considerably reduces the number of times we have to move the same CPE
1290  // more than once and is also important to ensure the algorithm terminates.
1291  if (IP != WaterList.end())
1292    WaterList.erase(IP);
1293
1294  // Okay, we know we can put an island before NewMBB now, do it!
1295  MF.insert(NewMBB, NewIsland);
1296
1297  // Update internal data structures to account for the newly inserted MBB.
1298  UpdateForInsertedWaterBlock(NewIsland);
1299
1300  // Decrement the old entry, and remove it if refcount becomes 0.
1301  DecrementOldEntry(CPI, CPEMI);
1302
1303  // Now that we have an island to add the CPE to, clone the original CPE and
1304  // add it to the island.
1305  U.HighWaterMark = NewIsland;
1306  U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1307                .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1308  CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1309  ++NumCPEs;
1310
1311  BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1312  // Compensate for .align 2 in thumb mode.
1313  if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
1314    Size += 2;
1315  // Increase the size of the island block to account for the new entry.
1316  BBSizes[NewIsland->getNumber()] += Size;
1317  AdjustBBOffsetsAfter(NewIsland, Size);
1318
1319  // Finally, change the CPI in the instruction operand to be ID.
1320  for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1321    if (UserMI->getOperand(i).isCPI()) {
1322      UserMI->getOperand(i).setIndex(ID);
1323      break;
1324    }
1325
1326  DEBUG(errs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1327           << '\t' << *UserMI);
1328
1329  return true;
1330}
1331
1332/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1333/// sizes and offsets of impacted basic blocks.
1334void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1335  MachineBasicBlock *CPEBB = CPEMI->getParent();
1336  unsigned Size = CPEMI->getOperand(2).getImm();
1337  CPEMI->eraseFromParent();
1338  BBSizes[CPEBB->getNumber()] -= Size;
1339  // All succeeding offsets have the current size value added in, fix this.
1340  if (CPEBB->empty()) {
1341    // In thumb1 mode, the size of island may be padded by two to compensate for
1342    // the alignment requirement.  Then it will now be 2 when the block is
1343    // empty, so fix this.
1344    // All succeeding offsets have the current size value added in, fix this.
1345    if (BBSizes[CPEBB->getNumber()] != 0) {
1346      Size += BBSizes[CPEBB->getNumber()];
1347      BBSizes[CPEBB->getNumber()] = 0;
1348    }
1349  }
1350  AdjustBBOffsetsAfter(CPEBB, -Size);
1351  // An island has only one predecessor BB and one successor BB. Check if
1352  // this BB's predecessor jumps directly to this BB's successor. This
1353  // shouldn't happen currently.
1354  assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1355  // FIXME: remove the empty blocks after all the work is done?
1356}
1357
1358/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1359/// are zero.
1360bool ARMConstantIslands::RemoveUnusedCPEntries() {
1361  unsigned MadeChange = false;
1362  for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1363      std::vector<CPEntry> &CPEs = CPEntries[i];
1364      for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1365        if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1366          RemoveDeadCPEMI(CPEs[j].CPEMI);
1367          CPEs[j].CPEMI = NULL;
1368          MadeChange = true;
1369        }
1370      }
1371  }
1372  return MadeChange;
1373}
1374
1375/// BBIsInRange - Returns true if the distance between specific MI and
1376/// specific BB can fit in MI's displacement field.
1377bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1378                                     unsigned MaxDisp) {
1379  unsigned PCAdj      = isThumb ? 4 : 8;
1380  unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
1381  unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1382
1383  DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1384               << " from BB#" << MI->getParent()->getNumber()
1385               << " max delta=" << MaxDisp
1386               << " from " << GetOffsetOf(MI) << " to " << DestOffset
1387               << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1388
1389  if (BrOffset <= DestOffset) {
1390    // Branch before the Dest.
1391    if (DestOffset-BrOffset <= MaxDisp)
1392      return true;
1393  } else {
1394    if (BrOffset-DestOffset <= MaxDisp)
1395      return true;
1396  }
1397  return false;
1398}
1399
1400/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1401/// away to fit in its displacement field.
1402bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1403  MachineInstr *MI = Br.MI;
1404  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1405
1406  // Check to see if the DestBB is already in-range.
1407  if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1408    return false;
1409
1410  if (!Br.isCond)
1411    return FixUpUnconditionalBr(MF, Br);
1412  return FixUpConditionalBr(MF, Br);
1413}
1414
1415/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1416/// too far away to fit in its displacement field. If the LR register has been
1417/// spilled in the epilogue, then we can use BL to implement a far jump.
1418/// Otherwise, add an intermediate branch instruction to a branch.
1419bool
1420ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1421  MachineInstr *MI = Br.MI;
1422  MachineBasicBlock *MBB = MI->getParent();
1423  if (!isThumb1)
1424    llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1425
1426  // Use BL to implement far jump.
1427  Br.MaxDisp = (1 << 21) * 2;
1428  MI->setDesc(TII->get(ARM::tBfar));
1429  BBSizes[MBB->getNumber()] += 2;
1430  AdjustBBOffsetsAfter(MBB, 2);
1431  HasFarJump = true;
1432  ++NumUBrFixed;
1433
1434  DEBUG(errs() << "  Changed B to long jump " << *MI);
1435
1436  return true;
1437}
1438
1439/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1440/// far away to fit in its displacement field. It is converted to an inverse
1441/// conditional branch + an unconditional branch to the destination.
1442bool
1443ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1444  MachineInstr *MI = Br.MI;
1445  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1446
1447  // Add an unconditional branch to the destination and invert the branch
1448  // condition to jump over it:
1449  // blt L1
1450  // =>
1451  // bge L2
1452  // b   L1
1453  // L2:
1454  ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1455  CC = ARMCC::getOppositeCondition(CC);
1456  unsigned CCReg = MI->getOperand(2).getReg();
1457
1458  // If the branch is at the end of its MBB and that has a fall-through block,
1459  // direct the updated conditional branch to the fall-through block. Otherwise,
1460  // split the MBB before the next instruction.
1461  MachineBasicBlock *MBB = MI->getParent();
1462  MachineInstr *BMI = &MBB->back();
1463  bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1464
1465  ++NumCBrFixed;
1466  if (BMI != MI) {
1467    if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1468        BMI->getOpcode() == Br.UncondBr) {
1469      // Last MI in the BB is an unconditional branch. Can we simply invert the
1470      // condition and swap destinations:
1471      // beq L1
1472      // b   L2
1473      // =>
1474      // bne L2
1475      // b   L1
1476      MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1477      if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1478        DEBUG(errs() << "  Invert Bcc condition and swap its destination with "
1479                     << *BMI);
1480        BMI->getOperand(0).setMBB(DestBB);
1481        MI->getOperand(0).setMBB(NewDest);
1482        MI->getOperand(1).setImm(CC);
1483        return true;
1484      }
1485    }
1486  }
1487
1488  if (NeedSplit) {
1489    SplitBlockBeforeInstr(MI);
1490    // No need for the branch to the next block. We're adding an unconditional
1491    // branch to the destination.
1492    int delta = TII->GetInstSizeInBytes(&MBB->back());
1493    BBSizes[MBB->getNumber()] -= delta;
1494    MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
1495    AdjustBBOffsetsAfter(SplitBB, -delta);
1496    MBB->back().eraseFromParent();
1497    // BBOffsets[SplitBB] is wrong temporarily, fixed below
1498  }
1499  MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1500
1501  DEBUG(errs() << "  Insert B to BB#" << DestBB->getNumber()
1502               << " also invert condition and change dest. to BB#"
1503               << NextBB->getNumber() << "\n");
1504
1505  // Insert a new conditional branch and a new unconditional branch.
1506  // Also update the ImmBranch as well as adding a new entry for the new branch.
1507  BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1508    .addMBB(NextBB).addImm(CC).addReg(CCReg);
1509  Br.MI = &MBB->back();
1510  BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1511  BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1512  BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1513  unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1514  ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1515
1516  // Remove the old conditional branch.  It may or may not still be in MBB.
1517  BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1518  MI->eraseFromParent();
1519
1520  // The net size change is an addition of one unconditional branch.
1521  int delta = TII->GetInstSizeInBytes(&MBB->back());
1522  AdjustBBOffsetsAfter(MBB, delta);
1523  return true;
1524}
1525
1526/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1527/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1528/// to do this if tBfar is not used.
1529bool ARMConstantIslands::UndoLRSpillRestore() {
1530  bool MadeChange = false;
1531  for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1532    MachineInstr *MI = PushPopMIs[i];
1533    // First two operands are predicates.
1534    if (MI->getOpcode() == ARM::tPOP_RET &&
1535        MI->getOperand(2).getReg() == ARM::PC &&
1536        MI->getNumExplicitOperands() == 3) {
1537      BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1538      MI->eraseFromParent();
1539      MadeChange = true;
1540    }
1541  }
1542  return MadeChange;
1543}
1544
1545bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1546  bool MadeChange = false;
1547
1548  // Shrink ADR and LDR from constantpool.
1549  for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1550    CPUser &U = CPUsers[i];
1551    unsigned Opcode = U.MI->getOpcode();
1552    unsigned NewOpc = 0;
1553    unsigned Scale = 1;
1554    unsigned Bits = 0;
1555    switch (Opcode) {
1556    default: break;
1557    case ARM::t2LEApcrel:
1558      if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1559        NewOpc = ARM::tLEApcrel;
1560        Bits = 8;
1561        Scale = 4;
1562      }
1563      break;
1564    case ARM::t2LDRpci:
1565      if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1566        NewOpc = ARM::tLDRpci;
1567        Bits = 8;
1568        Scale = 4;
1569      }
1570      break;
1571    }
1572
1573    if (!NewOpc)
1574      continue;
1575
1576    unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1577    unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1578    // FIXME: Check if offset is multiple of scale if scale is not 4.
1579    if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1580      U.MI->setDesc(TII->get(NewOpc));
1581      MachineBasicBlock *MBB = U.MI->getParent();
1582      BBSizes[MBB->getNumber()] -= 2;
1583      AdjustBBOffsetsAfter(MBB, -2);
1584      ++NumT2CPShrunk;
1585      MadeChange = true;
1586    }
1587  }
1588
1589  MadeChange |= OptimizeThumb2Branches(MF);
1590  MadeChange |= OptimizeThumb2JumpTables(MF);
1591  return MadeChange;
1592}
1593
1594bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1595  bool MadeChange = false;
1596
1597  for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1598    ImmBranch &Br = ImmBranches[i];
1599    unsigned Opcode = Br.MI->getOpcode();
1600    unsigned NewOpc = 0;
1601    unsigned Scale = 1;
1602    unsigned Bits = 0;
1603    switch (Opcode) {
1604    default: break;
1605    case ARM::t2B:
1606      NewOpc = ARM::tB;
1607      Bits = 11;
1608      Scale = 2;
1609      break;
1610    case ARM::t2Bcc: {
1611      NewOpc = ARM::tBcc;
1612      Bits = 8;
1613      Scale = 2;
1614      break;
1615    }
1616    }
1617    if (NewOpc) {
1618      unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1619      MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1620      if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1621        Br.MI->setDesc(TII->get(NewOpc));
1622        MachineBasicBlock *MBB = Br.MI->getParent();
1623        BBSizes[MBB->getNumber()] -= 2;
1624        AdjustBBOffsetsAfter(MBB, -2);
1625        ++NumT2BrShrunk;
1626        MadeChange = true;
1627      }
1628    }
1629
1630    Opcode = Br.MI->getOpcode();
1631    if (Opcode != ARM::tBcc)
1632      continue;
1633
1634    NewOpc = 0;
1635    unsigned PredReg = 0;
1636    ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1637    if (Pred == ARMCC::EQ)
1638      NewOpc = ARM::tCBZ;
1639    else if (Pred == ARMCC::NE)
1640      NewOpc = ARM::tCBNZ;
1641    if (!NewOpc)
1642      continue;
1643    MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1644    // Check if the distance is within 126. Subtract starting offset by 2
1645    // because the cmp will be eliminated.
1646    unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1647    unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1648    if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1649      MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1650      if (CmpMI->getOpcode() == ARM::tCMPi8) {
1651        unsigned Reg = CmpMI->getOperand(0).getReg();
1652        Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1653        if (Pred == ARMCC::AL &&
1654            CmpMI->getOperand(1).getImm() == 0 &&
1655            isARMLowRegister(Reg)) {
1656          MachineBasicBlock *MBB = Br.MI->getParent();
1657          MachineInstr *NewBR =
1658            BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1659            .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1660          CmpMI->eraseFromParent();
1661          Br.MI->eraseFromParent();
1662          Br.MI = NewBR;
1663          BBSizes[MBB->getNumber()] -= 2;
1664          AdjustBBOffsetsAfter(MBB, -2);
1665          ++NumCBZ;
1666          MadeChange = true;
1667        }
1668      }
1669    }
1670  }
1671
1672  return MadeChange;
1673}
1674
1675/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1676/// jumptables when it's possible.
1677bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1678  bool MadeChange = false;
1679
1680  // FIXME: After the tables are shrunk, can we get rid some of the
1681  // constantpool tables?
1682  MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1683  if (MJTI == 0) return false;
1684
1685  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1686  for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1687    MachineInstr *MI = T2JumpTables[i];
1688    const TargetInstrDesc &TID = MI->getDesc();
1689    unsigned NumOps = TID.getNumOperands();
1690    unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1691    MachineOperand JTOP = MI->getOperand(JTOpIdx);
1692    unsigned JTI = JTOP.getIndex();
1693    assert(JTI < JT.size());
1694
1695    bool ByteOk = true;
1696    bool HalfWordOk = true;
1697    unsigned JTOffset = GetOffsetOf(MI) + 4;
1698    const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1699    for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1700      MachineBasicBlock *MBB = JTBBs[j];
1701      unsigned DstOffset = BBOffsets[MBB->getNumber()];
1702      // Negative offset is not ok. FIXME: We should change BB layout to make
1703      // sure all the branches are forward.
1704      if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1705        ByteOk = false;
1706      unsigned TBHLimit = ((1<<16)-1)*2;
1707      if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1708        HalfWordOk = false;
1709      if (!ByteOk && !HalfWordOk)
1710        break;
1711    }
1712
1713    if (ByteOk || HalfWordOk) {
1714      MachineBasicBlock *MBB = MI->getParent();
1715      unsigned BaseReg = MI->getOperand(0).getReg();
1716      bool BaseRegKill = MI->getOperand(0).isKill();
1717      if (!BaseRegKill)
1718        continue;
1719      unsigned IdxReg = MI->getOperand(1).getReg();
1720      bool IdxRegKill = MI->getOperand(1).isKill();
1721
1722      // Scan backwards to find the instruction that defines the base
1723      // register. Due to post-RA scheduling, we can't count on it
1724      // immediately preceding the branch instruction.
1725      MachineBasicBlock::iterator PrevI = MI;
1726      MachineBasicBlock::iterator B = MBB->begin();
1727      while (PrevI != B && !PrevI->definesRegister(BaseReg))
1728        --PrevI;
1729
1730      // If for some reason we didn't find it, we can't do anything, so
1731      // just skip this one.
1732      if (!PrevI->definesRegister(BaseReg))
1733        continue;
1734
1735      MachineInstr *AddrMI = PrevI;
1736      bool OptOk = true;
1737      // Examine the instruction that calculates the jumptable entry address.
1738      // Make sure it only defines the base register and kills any uses
1739      // other than the index register.
1740      for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1741        const MachineOperand &MO = AddrMI->getOperand(k);
1742        if (!MO.isReg() || !MO.getReg())
1743          continue;
1744        if (MO.isDef() && MO.getReg() != BaseReg) {
1745          OptOk = false;
1746          break;
1747        }
1748        if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1749          OptOk = false;
1750          break;
1751        }
1752      }
1753      if (!OptOk)
1754        continue;
1755
1756      // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1757      // that gave us the initial base register definition.
1758      for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1759        ;
1760
1761      // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1762      // to delete it as well.
1763      MachineInstr *LeaMI = PrevI;
1764      if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1765           LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1766          LeaMI->getOperand(0).getReg() != BaseReg)
1767        OptOk = false;
1768
1769      if (!OptOk)
1770        continue;
1771
1772      unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1773      MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1774        .addReg(IdxReg, getKillRegState(IdxRegKill))
1775        .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1776        .addImm(MI->getOperand(JTOpIdx+1).getImm());
1777      // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1778      // is 2-byte aligned. For now, asm printer will fix it up.
1779      unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1780      unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1781      OrigSize += TII->GetInstSizeInBytes(LeaMI);
1782      OrigSize += TII->GetInstSizeInBytes(MI);
1783
1784      AddrMI->eraseFromParent();
1785      LeaMI->eraseFromParent();
1786      MI->eraseFromParent();
1787
1788      int delta = OrigSize - NewSize;
1789      BBSizes[MBB->getNumber()] -= delta;
1790      AdjustBBOffsetsAfter(MBB, -delta);
1791
1792      ++NumTBs;
1793      MadeChange = true;
1794    }
1795  }
1796
1797  return MadeChange;
1798}
1799
1800/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1801/// jump tables always branch forwards, since that's what tbb and tbh need.
1802bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1803  bool MadeChange = false;
1804
1805  MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1806  if (MJTI == 0) return false;
1807
1808  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1809  for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1810    MachineInstr *MI = T2JumpTables[i];
1811    const TargetInstrDesc &TID = MI->getDesc();
1812    unsigned NumOps = TID.getNumOperands();
1813    unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1814    MachineOperand JTOP = MI->getOperand(JTOpIdx);
1815    unsigned JTI = JTOP.getIndex();
1816    assert(JTI < JT.size());
1817
1818    // We prefer if target blocks for the jump table come after the jump
1819    // instruction so we can use TB[BH]. Loop through the target blocks
1820    // and try to adjust them such that that's true.
1821    int JTNumber = MI->getParent()->getNumber();
1822    const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1823    for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1824      MachineBasicBlock *MBB = JTBBs[j];
1825      int DTNumber = MBB->getNumber();
1826
1827      if (DTNumber < JTNumber) {
1828        // The destination precedes the switch. Try to move the block forward
1829        // so we have a positive offset.
1830        MachineBasicBlock *NewBB =
1831          AdjustJTTargetBlockForward(MBB, MI->getParent());
1832        if (NewBB)
1833          MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1834        MadeChange = true;
1835      }
1836    }
1837  }
1838
1839  return MadeChange;
1840}
1841
1842MachineBasicBlock *ARMConstantIslands::
1843AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1844{
1845  MachineFunction &MF = *BB->getParent();
1846
1847  // If the destination block is terminated by an unconditional branch,
1848  // try to move it; otherwise, create a new block following the jump
1849  // table that branches back to the actual target. This is a very simple
1850  // heuristic. FIXME: We can definitely improve it.
1851  MachineBasicBlock *TBB = 0, *FBB = 0;
1852  SmallVector<MachineOperand, 4> Cond;
1853  SmallVector<MachineOperand, 4> CondPrior;
1854  MachineFunction::iterator BBi = BB;
1855  MachineFunction::iterator OldPrior = prior(BBi);
1856
1857  // If the block terminator isn't analyzable, don't try to move the block
1858  bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1859
1860  // If the block ends in an unconditional branch, move it. The prior block
1861  // has to have an analyzable terminator for us to move this one. Be paranoid
1862  // and make sure we're not trying to move the entry block of the function.
1863  if (!B && Cond.empty() && BB != MF.begin() &&
1864      !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1865    BB->moveAfter(JTBB);
1866    OldPrior->updateTerminator();
1867    BB->updateTerminator();
1868    // Update numbering to account for the block being moved.
1869    MF.RenumberBlocks();
1870    ++NumJTMoved;
1871    return NULL;
1872  }
1873
1874  // Create a new MBB for the code after the jump BB.
1875  MachineBasicBlock *NewBB =
1876    MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1877  MachineFunction::iterator MBBI = JTBB; ++MBBI;
1878  MF.insert(MBBI, NewBB);
1879
1880  // Add an unconditional branch from NewBB to BB.
1881  // There doesn't seem to be meaningful DebugInfo available; this doesn't
1882  // correspond directly to anything in the source.
1883  assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1884  BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB);
1885
1886  // Update internal data structures to account for the newly inserted MBB.
1887  MF.RenumberBlocks(NewBB);
1888
1889  // Update the CFG.
1890  NewBB->addSuccessor(BB);
1891  JTBB->removeSuccessor(BB);
1892  JTBB->addSuccessor(NewBB);
1893
1894  ++NumJTInserted;
1895  return NewBB;
1896}
1897