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