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