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