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