blob: ae6afcee44d1ef4dc23e758c99763a4834698b09 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source 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"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Chenga8e29892007-01-19 07:51:42 +000023#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Debug.h"
Evan Chengc99ef082007-02-09 20:54:44 +000027#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
Evan Chenga8e29892007-01-19 07:51:42 +000030using namespace llvm;
31
Evan Chengc99ef082007-02-09 20:54:44 +000032STATISTIC(NumCPEs, "Number of constpool entries");
Evan Chengd1b2c1e2007-01-30 01:18:38 +000033STATISTIC(NumSplit, "Number of uncond branches inserted");
34STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Evan Chenga8e29892007-01-19 07:51:42 +000036
37namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000038 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000039 /// requires constant pool entries to be scattered among the instructions
40 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000041 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000042 /// special instructions.
43 ///
44 /// The terminology used in this pass includes:
45 /// Islands - Clumps of constants placed in the function.
46 /// Water - Potential places where an island could be formed.
47 /// CPE - A constant pool entry that has been placed somewhere, which
48 /// tracks a list of users.
49 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50 /// NextUID - Assign unique ID's to CPE's.
51 unsigned NextUID;
Dale Johannesen99c49a42007-02-25 00:47:03 +000052
Evan Chenga8e29892007-01-19 07:51:42 +000053 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
54 /// by MBB Number.
Evan Chenge03cff62007-02-09 23:59:14 +000055 std::vector<unsigned> BBSizes;
Evan Chenga8e29892007-01-19 07:51:42 +000056
Dale Johannesen99c49a42007-02-25 00:47:03 +000057 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
58 std::vector<unsigned> BBOffsets;
59
Evan Chenga8e29892007-01-19 07:51:42 +000060 /// WaterList - A sorted list of basic blocks where islands could be placed
61 /// (i.e. blocks that don't fall through to the following block, due
62 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000063 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000064
Evan Chenga8e29892007-01-19 07:51:42 +000065 /// CPUser - One user of a constant pool, keeping the machine instruction
66 /// pointer, the constant pool being referenced, and the max displacement
67 /// allowed from the instruction to the CP.
68 struct CPUser {
69 MachineInstr *MI;
70 MachineInstr *CPEMI;
71 unsigned MaxDisp;
72 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
73 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
74 };
75
76 /// CPUsers - Keep track of all of the machine instructions that use various
77 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000078 std::vector<CPUser> CPUsers;
Evan Chengc99ef082007-02-09 20:54:44 +000079
80 /// CPEntry - One per constant pool entry, keeping the machine instruction
81 /// pointer, the constpool index, and the number of CPUser's which
82 /// reference this entry.
83 struct CPEntry {
84 MachineInstr *CPEMI;
85 unsigned CPI;
86 unsigned RefCount;
87 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
88 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
89 };
90
91 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +000092 /// instructions. For each original constpool index (i.e. those that
93 /// existed upon entry to this pass), it keeps a vector of entries.
94 /// Original elements are cloned as we go along; the clones are
95 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +000096 std::vector<std::vector<CPEntry> > CPEntries;
Evan Chenga8e29892007-01-19 07:51:42 +000097
Evan Chengaf5cbcb2007-01-25 03:12:46 +000098 /// ImmBranch - One per immediate branch, keeping the machine instruction
99 /// pointer, conditional or unconditional, the max displacement,
100 /// and (if isCond is true) the corresponding unconditional branch
101 /// opcode.
102 struct ImmBranch {
103 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000104 unsigned MaxDisp : 31;
105 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000106 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000107 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
108 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000109 };
110
Evan Chengc2854142007-01-25 23:18:59 +0000111 /// Branches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000112 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000113 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000114
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000115 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
116 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000117 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000118
119 /// HasFarJump - True if any far jump instruction has been emitted during
120 /// the branch fix up pass.
121 bool HasFarJump;
122
Evan Chenga8e29892007-01-19 07:51:42 +0000123 const TargetInstrInfo *TII;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000124 bool isThumb;
Evan Chenga8e29892007-01-19 07:51:42 +0000125 public:
126 virtual bool runOnMachineFunction(MachineFunction &Fn);
127
128 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000129 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000130 }
131
132 private:
133 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000134 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000135 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000136 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000137 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000138 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000139 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000140 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000141 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000142 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000143 bool LookForWater(CPUser&U, unsigned UserOffset, bool* PadNewWater,
144 MachineBasicBlock** NewMBB);
145 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
146 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000147 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000148 void RemoveDeadCPEMI(MachineInstr *CPEMI);
149 bool RemoveUnusedCPEntries();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000150 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
151 MachineInstr *CPEMI, unsigned Disp,
152 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000153 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000154 unsigned Disp);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000155 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
156 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000157 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000158 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
159 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
160 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
161 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000162
Evan Chenga8e29892007-01-19 07:51:42 +0000163 unsigned GetOffsetOf(MachineInstr *MI) const;
164 };
165}
166
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000167/// createARMConstantIslandPass - returns an instance of the constpool
168/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000169FunctionPass *llvm::createARMConstantIslandPass() {
170 return new ARMConstantIslands();
171}
172
173bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000174 MachineConstantPool &MCP = *Fn.getConstantPool();
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000175 ARMFunctionInfo *AFI = Fn.getInfo<ARMFunctionInfo>();
Evan Chenga8e29892007-01-19 07:51:42 +0000176
177 TII = Fn.getTarget().getInstrInfo();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000178 isThumb = AFI->isThumbFunction();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000179
180 HasFarJump = false;
181
Evan Chenga8e29892007-01-19 07:51:42 +0000182 // Renumber all of the machine basic blocks in the function, guaranteeing that
183 // the numbers agree with the position of the block in the function.
184 Fn.RenumberBlocks();
185
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000186 /// Thumb functions containing constant pools get 2-byte alignment. This is so
187 /// we can keep exact track of where the alignment padding goes. Set default.
188 AFI->setAlign(isThumb ? 1U : 2U);
189
Evan Chenga8e29892007-01-19 07:51:42 +0000190 // Perform the initial placement of the constant pool entries. To start with,
191 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000192 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000193 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000194 DoInitialPlacement(Fn, CPEMIs);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000195 if (isThumb)
196 AFI->setAlign(2U);
197 }
Evan Chenga8e29892007-01-19 07:51:42 +0000198
199 /// The next UID to take is the first unused one.
200 NextUID = CPEMIs.size();
201
202 // Do the initial scan of the function, building up information about the
203 // sizes of each block, the location of all the water, and finding all of the
204 // constant pool users.
205 InitialFunctionScan(Fn, CPEMIs);
206 CPEMIs.clear();
207
Evan Chenged884f32007-04-03 23:39:48 +0000208 /// Remove dead constant pool entries.
209 RemoveUnusedCPEntries();
210
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000211 // Iteratively place constant pool entries and fix up branches until there
212 // is no change.
213 bool MadeChange = false;
214 while (true) {
215 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000216 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000217 Change |= HandleConstantPoolUser(Fn, i);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000218 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000219 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
220 if (!Change)
221 break;
222 MadeChange = true;
223 }
Evan Chenged884f32007-04-03 23:39:48 +0000224
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000225 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
226 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000227 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000228 MadeChange |= UndoLRSpillRestore();
229
Evan Chenga8e29892007-01-19 07:51:42 +0000230 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000231 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000232 WaterList.clear();
233 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000234 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000235 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000236 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000237
238 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000239}
240
241/// DoInitialPlacement - Perform the initial placement of the constant pool
242/// entries. To start with, we put them all at the end of the function.
243void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000244 std::vector<MachineInstr*> &CPEMIs){
Evan Chenga8e29892007-01-19 07:51:42 +0000245 // Create the basic block to hold the CPE's.
246 MachineBasicBlock *BB = new MachineBasicBlock();
247 Fn.getBasicBlockList().push_back(BB);
248
249 // Add all of the constants from the constant pool to the end block, use an
250 // identity mapping of CPI's to CPE's.
251 const std::vector<MachineConstantPoolEntry> &CPs =
252 Fn.getConstantPool()->getConstants();
253
254 const TargetData &TD = *Fn.getTarget().getTargetData();
255 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
256 unsigned Size = TD.getTypeSize(CPs[i].getType());
257 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
258 // we would have to pad them out or something so that instructions stay
259 // aligned.
260 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
261 MachineInstr *CPEMI =
262 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
263 .addImm(i).addConstantPoolIndex(i).addImm(Size);
264 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000265
266 // Add a new CPEntry, but no corresponding CPUser yet.
267 std::vector<CPEntry> CPEs;
268 CPEs.push_back(CPEntry(CPEMI, i));
269 CPEntries.push_back(CPEs);
270 NumCPEs++;
271 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000272 }
273}
274
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000275/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000276/// into the block immediately after it.
277static bool BBHasFallthrough(MachineBasicBlock *MBB) {
278 // Get the next machine basic block in the function.
279 MachineFunction::iterator MBBI = MBB;
280 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
281 return false;
282
283 MachineBasicBlock *NextBB = next(MBBI);
284 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
285 E = MBB->succ_end(); I != E; ++I)
286 if (*I == NextBB)
287 return true;
288
289 return false;
290}
291
Evan Chengc99ef082007-02-09 20:54:44 +0000292/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
293/// look up the corresponding CPEntry.
294ARMConstantIslands::CPEntry
295*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
296 const MachineInstr *CPEMI) {
297 std::vector<CPEntry> &CPEs = CPEntries[CPI];
298 // Number of entries per constpool index should be small, just do a
299 // linear search.
300 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
301 if (CPEs[i].CPEMI == CPEMI)
302 return &CPEs[i];
303 }
304 return NULL;
305}
306
Evan Chenga8e29892007-01-19 07:51:42 +0000307/// InitialFunctionScan - Do the initial scan of the function, building up
308/// information about the sizes of each block, the location of all the water,
309/// and finding all of the constant pool users.
310void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000311 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000312 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000313 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
314 MBBI != E; ++MBBI) {
315 MachineBasicBlock &MBB = *MBBI;
316
317 // If this block doesn't fall through into the next MBB, then this is
318 // 'water' that a constant pool island could be placed.
319 if (!BBHasFallthrough(&MBB))
320 WaterList.push_back(&MBB);
321
322 unsigned MBBSize = 0;
323 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
324 I != E; ++I) {
325 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000326 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000327
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000328 int Opc = I->getOpcode();
329 if (TII->isBranch(Opc)) {
330 bool isCond = false;
331 unsigned Bits = 0;
332 unsigned Scale = 1;
333 int UOpc = Opc;
334 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000335 default:
336 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000337 case ARM::Bcc:
338 isCond = true;
339 UOpc = ARM::B;
340 // Fallthrough
341 case ARM::B:
342 Bits = 24;
343 Scale = 4;
344 break;
345 case ARM::tBcc:
346 isCond = true;
347 UOpc = ARM::tB;
348 Bits = 8;
349 Scale = 2;
350 break;
351 case ARM::tB:
352 Bits = 11;
353 Scale = 2;
354 break;
355 }
Evan Chengb43216e2007-02-01 10:16:15 +0000356
357 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000358 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000359 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000360 }
361
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000362 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
363 PushPopMIs.push_back(I);
364
Evan Chenga8e29892007-01-19 07:51:42 +0000365 // Scan the instructions for constant pool operands.
366 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
367 if (I->getOperand(op).isConstantPoolIndex()) {
368 // We found one. The addressing mode tells us the max displacement
369 // from the PC that this instruction permits.
Evan Chenga8e29892007-01-19 07:51:42 +0000370
371 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000372 unsigned Bits = 0;
373 unsigned Scale = 1;
Evan Chenga8e29892007-01-19 07:51:42 +0000374 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
375 switch (TSFlags & ARMII::AddrModeMask) {
376 default:
377 // Constant pool entries can reach anything.
378 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
379 continue;
380 assert(0 && "Unknown addressing mode for CP reference!");
381 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000382 Bits = 8;
383 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000384 break;
385 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000386 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000387 break;
388 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000389 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000390 break;
391 // addrmode4 has no immediate offset.
392 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000393 Bits = 8;
394 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000395 break;
396 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000397 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000398 break;
399 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000400 Bits = 5;
401 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000402 break;
403 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000404 Bits = 5;
405 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000406 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000407 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000408 Bits = 8;
409 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000410 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000411 }
Evan Chengb43216e2007-02-01 10:16:15 +0000412
Evan Chenga8e29892007-01-19 07:51:42 +0000413 // Remember that this is a user of a CP entry.
Evan Chengc99ef082007-02-09 20:54:44 +0000414 unsigned CPI = I->getOperand(op).getConstantPoolIndex();
415 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng556f33c2007-02-01 20:44:52 +0000416 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000417 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000418
419 // Increment corresponding CPEntry reference count.
420 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
421 assert(CPE && "Cannot find a corresponding CPEntry!");
422 CPE->RefCount++;
Evan Chenga8e29892007-01-19 07:51:42 +0000423
424 // Instructions can only use one CP entry, don't bother scanning the
425 // rest of the operands.
426 break;
427 }
428 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000429
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000430 // In thumb mode, if this block is a constpool island, pessimistically
431 // assume it needs to be padded by two byte so it's aligned on 4 byte
432 // boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000433 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000434 !MBB.empty() &&
Evan Cheng2021abe2007-02-01 01:09:47 +0000435 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
436 MBBSize += 2;
437
Evan Chenga8e29892007-01-19 07:51:42 +0000438 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000439 BBOffsets.push_back(Offset);
440 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000441 }
442}
443
Evan Chenga8e29892007-01-19 07:51:42 +0000444/// GetOffsetOf - Return the current offset of the specified machine instruction
445/// from the start of the function. This offset changes as stuff is moved
446/// around inside the function.
447unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
448 MachineBasicBlock *MBB = MI->getParent();
449
450 // The offset is composed of two things: the sum of the sizes of all MBB's
451 // before this instruction's block, and the offset from the start of the block
452 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000453 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000454
455 // Sum instructions before MI in MBB.
456 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
457 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
458 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000459 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000460 }
461}
462
463/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
464/// ID.
465static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
466 const MachineBasicBlock *RHS) {
467 return LHS->getNumber() < RHS->getNumber();
468}
469
470/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
471/// machine function, it upsets all of the block numbers. Renumber the blocks
472/// and update the arrays that parallel this numbering.
473void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
474 // Renumber the MBB's to keep them consequtive.
475 NewBB->getParent()->RenumberBlocks(NewBB);
476
477 // Insert a size into BBSizes to align it properly with the (newly
478 // renumbered) block numbers.
479 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000480
481 // Likewise for BBOffsets.
482 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Evan Chenga8e29892007-01-19 07:51:42 +0000483
484 // Next, update WaterList. Specifically, we need to add NewMBB as having
485 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000486 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000487 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
488 CompareMBBNumbers);
489 WaterList.insert(IP, NewBB);
490}
491
492
493/// Split the basic block containing MI into two blocks, which are joined by
494/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000495/// account for this change and returns the newly created block.
496MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000497 MachineBasicBlock *OrigBB = MI->getParent();
498
499 // Create a new MBB for the code after the OrigBB.
500 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
501 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
502 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
503
504 // Splice the instructions starting with MI over to NewBB.
505 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
506
507 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000508 // Note the new unconditional branch is not being recorded.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000509 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000510 NumSplit++;
511
512 // Update the CFG. All succs of OrigBB are now succs of NewBB.
513 while (!OrigBB->succ_empty()) {
514 MachineBasicBlock *Succ = *OrigBB->succ_begin();
515 OrigBB->removeSuccessor(Succ);
516 NewBB->addSuccessor(Succ);
517
518 // This pass should be run after register allocation, so there should be no
519 // PHI nodes to update.
520 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
521 && "PHI nodes should be eliminated by now!");
522 }
523
524 // OrigBB branches to NewBB.
525 OrigBB->addSuccessor(NewBB);
526
527 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000528 // This is almost the same as UpdateForInsertedWaterBlock, except that
529 // the Water goes after OrigBB, not NewBB.
530 NewBB->getParent()->RenumberBlocks(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000531
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000532 // Insert a size into BBSizes to align it properly with the (newly
533 // renumbered) block numbers.
534 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
535
Dale Johannesen99c49a42007-02-25 00:47:03 +0000536 // Likewise for BBOffsets.
537 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
538
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000539 // Next, update WaterList. Specifically, we need to add OrigMBB as having
540 // available water after it (but not if it's already there, which happens
541 // when splitting before a conditional branch that is followed by an
542 // unconditional branch - in that case we want to insert NewBB).
543 std::vector<MachineBasicBlock*>::iterator IP =
544 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
545 CompareMBBNumbers);
546 MachineBasicBlock* WaterBB = *IP;
547 if (WaterBB == OrigBB)
548 WaterList.insert(next(IP), NewBB);
549 else
550 WaterList.insert(IP, OrigBB);
551
Evan Chenga8e29892007-01-19 07:51:42 +0000552 // Figure out how large the first NewMBB is.
553 unsigned NewBBSize = 0;
554 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
555 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000556 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000557
Dale Johannesen99c49a42007-02-25 00:47:03 +0000558 unsigned OrigBBI = OrigBB->getNumber();
559 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000560 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000561 BBSizes[NewBBI] = NewBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000562
563 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000564 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000565 unsigned delta = isThumb ? 2 : 4;
566 BBSizes[OrigBBI] -= NewBBSize - delta;
567
568 // ...and adjust BBOffsets for NewBB accordingly.
569 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
570
571 // All BBOffsets following these blocks must be modified.
572 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000573
574 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000575}
576
Dale Johannesence74de42007-02-25 18:31:31 +0000577/// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
Dale Johannesen99c49a42007-02-25 00:47:03 +0000578/// TrialOffset.
579bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
580 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
581 if (UserOffset <= TrialOffset) {
582 // User before the Trial.
583 if (TrialOffset-UserOffset <= MaxDisp)
584 return true;
585 } else if (NegativeOK) {
586 if (UserOffset-TrialOffset <= MaxDisp)
587 return true;
588 }
589 return false;
590}
591
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000592/// WaterIsInRange - Returns true if a CPE placed after the specified
593/// Water (a basic block) will be in range for the specific MI.
594
595bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000596 MachineBasicBlock* Water, unsigned MaxDisp)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000597{
Dale Johannesen99c49a42007-02-25 00:47:03 +0000598 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000599 BBSizes[Water->getNumber()];
600 // If the Water is a constpool island, it has already been aligned.
601 // If not, align it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000602 if (isThumb &&
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000603 (Water->empty() ||
604 Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
605 CPEOffset += 2;
606
Dale Johannesend959aa42007-04-02 20:31:06 +0000607 // If the CPE is to be inserted before the instruction, that will raise
608 // the offset of the instruction.
609 if (CPEOffset < UserOffset)
610 UserOffset += isThumb ? 2 : 4;
611
Dale Johannesen99c49a42007-02-25 00:47:03 +0000612 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000613}
614
615/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000616/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000617bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
618 MachineInstr *CPEMI,
619 unsigned MaxDisp, bool DoDump) {
620 // In thumb mode, pessimistically assumes the .align 2 before the first CPE
Evan Cheng2021abe2007-02-01 01:09:47 +0000621 // in the island adds two byte padding.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000622 unsigned AlignAdj = isThumb ? 2 : 0;
Evan Cheng2021abe2007-02-01 01:09:47 +0000623 unsigned CPEOffset = GetOffsetOf(CPEMI) + AlignAdj;
624
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000625 if (DoDump) {
626 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
627 << " max delta=" << MaxDisp
628 << " insn address=" << UserOffset
629 << " CPE address=" << CPEOffset
630 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
631 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000632
Dale Johannesen99c49a42007-02-25 00:47:03 +0000633 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000634}
635
Evan Chengc99ef082007-02-09 20:54:44 +0000636/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
637/// unconditionally branches to its only successor.
638static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
639 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
640 return false;
641
642 MachineBasicBlock *Succ = *MBB->succ_begin();
643 MachineBasicBlock *Pred = *MBB->pred_begin();
644 MachineInstr *PredMI = &Pred->back();
645 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
646 return PredMI->getOperand(0).getMBB() == Succ;
647 return false;
648}
649
Dale Johannesen99c49a42007-02-25 00:47:03 +0000650void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
651{
652 MachineFunction::iterator MBBI = BB->getParent()->end();
Dale Johannesence74de42007-02-25 18:31:31 +0000653 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++)
Dale Johannesen99c49a42007-02-25 00:47:03 +0000654 BBOffsets[i] += delta;
655}
656
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000657/// DecrementOldEntry - find the constant pool entry with index CPI
658/// and instruction CPEMI, and decrement its refcount. If the refcount
659/// becomes 0 remove the entry and instruction. Returns true if we removed
660/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000661
Evan Chenged884f32007-04-03 23:39:48 +0000662bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000663 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000664 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
665 assert(CPE && "Unexpected!");
666 if (--CPE->RefCount == 0) {
667 RemoveDeadCPEMI(CPEMI);
668 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000669 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000670 return true;
671 }
672 return false;
673}
674
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000675/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
676/// if not, see if an in-range clone of the CPE is in range, and if so,
677/// change the data structures so the user references the clone. Returns:
678/// 0 = no existing entry found
679/// 1 = entry found, and there were no code insertions or deletions
680/// 2 = entry found, and there were code insertions or deletions
681int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
682{
683 MachineInstr *UserMI = U.MI;
684 MachineInstr *CPEMI = U.CPEMI;
685
686 // Check to see if the CPE is already in-range.
687 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
688 DOUT << "In range\n";
689 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000690 }
691
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000692 // No. Look for previously created clones of the CPE that are in range.
693 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
694 std::vector<CPEntry> &CPEs = CPEntries[CPI];
695 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
696 // We already tried this one
697 if (CPEs[i].CPEMI == CPEMI)
698 continue;
699 // Removing CPEs can leave empty entries, skip
700 if (CPEs[i].CPEMI == NULL)
701 continue;
702 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
703 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
704 // Point the CPUser node to the replacement
705 U.CPEMI = CPEs[i].CPEMI;
706 // Change the CPI in the instruction operand to refer to the clone.
707 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
708 if (UserMI->getOperand(j).isConstantPoolIndex()) {
709 UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
710 break;
711 }
712 // Adjust the refcount of the clone...
713 CPEs[i].RefCount++;
714 // ...and the original. If we didn't remove the old entry, none of the
715 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000716 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000717 }
718 }
719 return 0;
720}
721
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000722/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
723/// the specific unconditional branch instruction.
724static inline unsigned getUnconditionalBrDisp(int Opc) {
725 return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
726}
727
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000728/// LookForWater - look for an existing entry in the WaterList in which
729/// we can place the CPE referenced from U so it's within range of U's MI.
730/// Returns true if found, false if not. If it returns true, *NewMBB
731/// is set to the WaterList entry, and *PadNewWater is set to false if
732/// the WaterList entry is an island.
733
734bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
735 bool *PadNewWater, MachineBasicBlock** NewMBB) {
736 if (!WaterList.empty()) {
737 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
738 B = WaterList.begin();; --IP) {
739 MachineBasicBlock* WaterBB = *IP;
740 if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
741 DOUT << "found water in range\n";
742 // CPE goes before following block (NewMBB).
743 *NewMBB = next(MachineFunction::iterator(WaterBB));
744 // If WaterBB is an island, don't pad the new island.
745 // If WaterBB is empty, go backwards until we find something that
746 // isn't. WaterBB may become empty if it's an island whose
747 // contents were moved farther back.
748 if (isThumb) {
749 MachineBasicBlock* BB = WaterBB;
750 while (BB->empty())
751 BB = prior(MachineFunction::iterator(BB));
752 if (BB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
753 *PadNewWater = false;
754 }
755 // Remove the original WaterList entry; we want subsequent
756 // insertions in this vicinity to go after the one we're
757 // about to insert. This considerably reduces the number
758 // of times we have to move the same CPE more than once.
759 WaterList.erase(IP);
760 return true;
761 }
762 if (IP == B)
763 break;
764 }
765 }
766 return false;
767}
768
769/// CreateNewWater - No existing WaterList entry will work for
770/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
771/// block is used if in range, and the conditional branch munged so control
772/// flow is correct. Otherwise the block is split to create a hole with an
773/// unconditional branch around it. In either case *NewMBB is set to a
774/// block following which the new island can be inserted (the WaterList
775/// is not adjusted).
776
777void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
778 unsigned UserOffset, MachineBasicBlock** NewMBB) {
779 CPUser &U = CPUsers[CPUserIndex];
780 MachineInstr *UserMI = U.MI;
781 MachineInstr *CPEMI = U.CPEMI;
782 MachineBasicBlock *UserMBB = UserMI->getParent();
783 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
784 BBSizes[UserMBB->getNumber()];
785 assert(OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()+1]);
786
787 // If the use is at the end of the block, or the end of the block
788 // is within range, make new water there. (The +2 or 4 below is
789 // for the unconditional branch we will be adding. If the block ends in
790 // an unconditional branch already, it is water, and is known to
791 // be out of range, so we'll always be adding one.)
792 if (&UserMBB->back() == UserMI ||
793 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2 : 4),
794 U.MaxDisp, !isThumb)) {
795 DOUT << "Split at end of block\n";
796 if (&UserMBB->back() == UserMI)
797 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
798 *NewMBB = next(MachineFunction::iterator(UserMBB));
799 // Add an unconditional branch from UserMBB to fallthrough block.
800 // Record it for branch lengthening; this new branch will not get out of
801 // range, but if the preceding conditional branch is out of range, the
802 // targets will be exchanged, and the altered branch may be out of
803 // range, so the machinery has to know about it.
804 int UncondBr = isThumb ? ARM::tB : ARM::B;
805 BuildMI(UserMBB, TII->get(UncondBr)).addMBB(*NewMBB);
806 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
807 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
808 MaxDisp, false, UncondBr));
809 int delta = isThumb ? 2 : 4;
810 BBSizes[UserMBB->getNumber()] += delta;
811 AdjustBBOffsetsAfter(UserMBB, delta);
812 } else {
813 // What a big block. Find a place within the block to split it.
814 // This is a little tricky on Thumb since instructions are 2 bytes
815 // and constant pool entries are 4 bytes: if instruction I references
816 // island CPE, and instruction I+1 references CPE', it will
817 // not work well to put CPE as far forward as possible, since then
818 // CPE' cannot immediately follow it (that location is 2 bytes
819 // farther away from I+1 than CPE was from I) and we'd need to create
820 // a new island.
821 // The 4 in the following is for the unconditional branch we'll be
822 // inserting (allows for long branch on Thumb). The 2 or 0 is for
823 // alignment of the island.
824 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4 + (isThumb ? 2 : 0);
825 // This could point off the end of the block if we've already got
826 // constant pool entries following this block; only the last one is
827 // in the water list. Back past any possible branches (allow for a
828 // conditional and a maximally long unconditional).
829 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
830 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
831 (isThumb ? 6 : 8);
832 unsigned EndInsertOffset = BaseInsertOffset +
833 CPEMI->getOperand(2).getImm();
834 MachineBasicBlock::iterator MI = UserMI;
835 ++MI;
836 unsigned CPUIndex = CPUserIndex+1;
837 for (unsigned Offset = UserOffset+ARM::GetInstSize(UserMI);
838 Offset < BaseInsertOffset;
839 Offset += ARM::GetInstSize(MI),
840 MI = next(MI)) {
841 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
842 if (!OffsetIsInRange(Offset, EndInsertOffset,
843 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
844 BaseInsertOffset -= (isThumb ? 2 : 4);
845 EndInsertOffset -= (isThumb ? 2 : 4);
846 }
847 // This is overly conservative, as we don't account for CPEMIs
848 // being reused within the block, but it doesn't matter much.
849 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
850 CPUIndex++;
851 }
852 }
853 DOUT << "Split in middle of big block\n";
854 *NewMBB = SplitBlockBeforeInstr(prior(MI));
855 }
856}
857
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000858/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
859/// is out-of-range. If so, pick it up the constant pool value and move it some
860/// place in-range. Return true if we changed any addresses (thus must run
861/// another pass of branch lengthening), false otherwise.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000862bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
863 unsigned CPUserIndex){
864 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000865 MachineInstr *UserMI = U.MI;
866 MachineInstr *CPEMI = U.CPEMI;
867 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
868 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000869 MachineBasicBlock *NewMBB;
870 // Compute this only once, it's expensive
871 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
872
873 // See if the current entry is within range, or there is a clone of it
874 // in range.
875 int result = LookForExistingCPEntry(U, UserOffset);
876 if (result==1) return false;
877 else if (result==2) return true;
878
879 // No existing clone of this CPE is within range.
880 // We will be generating a new clone. Get a UID for it.
881 unsigned ID = NextUID++;
882
883 // Look for water where we can place this CPE. We look for the farthest one
884 // away that will work. Forward references only for now (although later
885 // we might find some that are backwards).
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000886 bool PadNewWater = true;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000887
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000888 if (!LookForWater(U, UserOffset, &PadNewWater, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000889 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000890 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000891 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000892 }
893
894 // Okay, we know we can put an island before NewMBB now, do it!
895 MachineBasicBlock *NewIsland = new MachineBasicBlock();
896 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
897
898 // Update internal data structures to account for the newly inserted MBB.
899 UpdateForInsertedWaterBlock(NewIsland);
900
901 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +0000902 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000903
904 // Now that we have an island to add the CPE to, clone the original CPE and
905 // add it to the island.
Evan Chenga8e29892007-01-19 07:51:42 +0000906 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
907 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000908 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +0000909 NumCPEs++;
910
Evan Chengb43216e2007-02-01 10:16:15 +0000911 // Compensate for .align 2 in thumb mode.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000912 if (isThumb && PadNewWater) Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +0000913 // Increase the size of the island block to account for the new entry.
914 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000915 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
916 AdjustBBOffsetsAfter(NewIsland, Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000917
918 // Finally, change the CPI in the instruction operand to be ID.
919 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
920 if (UserMI->getOperand(i).isConstantPoolIndex()) {
921 UserMI->getOperand(i).setConstantPoolIndex(ID);
922 break;
923 }
924
Evan Chengc99ef082007-02-09 20:54:44 +0000925 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Evan Chenga8e29892007-01-19 07:51:42 +0000926
927 return true;
928}
929
Evan Chenged884f32007-04-03 23:39:48 +0000930/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
931/// sizes and offsets of impacted basic blocks.
932void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
933 MachineBasicBlock *CPEBB = CPEMI->getParent();
934 if (CPEBB->empty()) {
935 // In thumb mode, the size of island is padded by two to compensate for
936 // the alignment requirement. Thus it will now be 2 when the block is
937 // empty, so fix this.
938 // All succeeding offsets have the current size value added in, fix this.
939 if (BBSizes[CPEBB->getNumber()] != 0) {
940 AdjustBBOffsetsAfter(CPEBB, -BBSizes[CPEBB->getNumber()]);
941 BBSizes[CPEBB->getNumber()] = 0;
942 }
943 // An island has only one predecessor BB and one successor BB. Check if
944 // this BB's predecessor jumps directly to this BB's successor. This
945 // shouldn't happen currently.
946 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
947 // FIXME: remove the empty blocks after all the work is done?
948 } else {
949 unsigned Size = CPEMI->getOperand(2).getImm();
950 BBSizes[CPEBB->getNumber()] -= Size;
951 // All succeeding offsets have the current size value added in, fix this.
952 AdjustBBOffsetsAfter(CPEBB, -Size);
953 }
954
955 CPEMI->eraseFromParent();
956}
957
958/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
959/// are zero.
960bool ARMConstantIslands::RemoveUnusedCPEntries() {
961 unsigned MadeChange = false;
962 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
963 std::vector<CPEntry> &CPEs = CPEntries[i];
964 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
965 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
966 RemoveDeadCPEMI(CPEs[j].CPEMI);
967 CPEs[j].CPEMI = NULL;
968 MadeChange = true;
969 }
970 }
971 }
972 return MadeChange;
973}
974
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000975/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +0000976/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +0000977bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
978 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000979 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +0000980 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000981 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +0000982
Evan Chengc99ef082007-02-09 20:54:44 +0000983 DOUT << "Branch of destination BB#" << DestBB->getNumber()
984 << " from BB#" << MI->getParent()->getNumber()
985 << " max delta=" << MaxDisp
986 << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +0000987
Dale Johannesen99c49a42007-02-25 00:47:03 +0000988 return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
Evan Cheng43aeab62007-01-26 20:38:26 +0000989}
990
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000991/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
992/// away to fit in its displacement field.
993bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000994 MachineInstr *MI = Br.MI;
995 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
996
Evan Chengc0dbec72007-01-31 19:57:44 +0000997 // Check to see if the DestBB is already in-range.
998 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +0000999 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001000
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001001 if (!Br.isCond)
1002 return FixUpUnconditionalBr(Fn, Br);
1003 return FixUpConditionalBr(Fn, Br);
1004}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001005
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001006/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1007/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001008/// spilled in the epilogue, then we can use BL to implement a far jump.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001009/// Otherwise, add an intermediate branch instruction to to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001010bool
1011ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1012 MachineInstr *MI = Br.MI;
1013 MachineBasicBlock *MBB = MI->getParent();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001014 assert(isThumb && "Expected a Thumb function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001015
1016 // Use BL to implement far jump.
1017 Br.MaxDisp = (1 << 21) * 2;
1018 MI->setInstrDescriptor(TII->get(ARM::tBfar));
1019 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001020 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001021 HasFarJump = true;
1022 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001023
Evan Chengc99ef082007-02-09 20:54:44 +00001024 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001025
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001026 return true;
1027}
1028
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001029/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001030/// far away to fit in its displacement field. It is converted to an inverse
1031/// conditional branch + an unconditional branch to the destination.
1032bool
1033ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1034 MachineInstr *MI = Br.MI;
1035 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
1036
1037 // Add a unconditional branch to the destination and invert the branch
1038 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001039 // blt L1
1040 // =>
1041 // bge L2
1042 // b L1
1043 // L2:
1044 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
1045 CC = ARMCC::getOppositeCondition(CC);
1046
1047 // If the branch is at the end of its MBB and that has a fall-through block,
1048 // direct the updated conditional branch to the fall-through block. Otherwise,
1049 // split the MBB before the next instruction.
1050 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001051 MachineInstr *BMI = &MBB->back();
1052 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001053
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001054 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001055 if (BMI != MI) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001056 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001057 BMI->getOpcode() == Br.UncondBr) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001058 // Last MI in the BB is a unconditional branch. Can we simply invert the
1059 // condition and swap destinations:
1060 // beq L1
1061 // b L2
1062 // =>
1063 // bne L2
1064 // b L1
Evan Chengbd5d3db2007-02-03 02:08:34 +00001065 MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
Evan Chengc0dbec72007-01-31 19:57:44 +00001066 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001067 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001068 BMI->getOperand(0).setMachineBasicBlock(DestBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001069 MI->getOperand(0).setMachineBasicBlock(NewDest);
1070 MI->getOperand(1).setImm(CC);
1071 return true;
1072 }
1073 }
1074 }
1075
1076 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001077 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +00001078 // No need for the branch to the next block. We're adding a unconditional
1079 // branch to the destination.
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001080 int delta = ARM::GetInstSize(&MBB->back());
1081 BBSizes[MBB->getNumber()] -= delta;
1082 AdjustBBOffsetsAfter(MBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001083 MBB->back().eraseFromParent();
1084 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001085 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Evan Chengbd5d3db2007-02-03 02:08:34 +00001086
Evan Chengc99ef082007-02-09 20:54:44 +00001087 DOUT << " Insert B to BB#" << DestBB->getNumber()
1088 << " also invert condition and change dest. to BB#"
1089 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001090
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001091 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001092 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +00001093 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001094 Br.MI = &MBB->back();
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001095 BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001096 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001097 BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001098 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001099 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001100
1101 // Remove the old conditional branch. It may or may not still be in MBB.
1102 BBSizes[MI->getParent()->getNumber()] -= ARM::GetInstSize(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001103 MI->eraseFromParent();
1104
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001105 // The net size change is an addition of one unconditional branch.
Dale Johannesen99c49a42007-02-25 00:47:03 +00001106 int delta = ARM::GetInstSize(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001107 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001108 return true;
1109}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001110
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001111/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1112/// LR / restores LR to pc.
1113bool ARMConstantIslands::UndoLRSpillRestore() {
1114 bool MadeChange = false;
1115 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1116 MachineInstr *MI = PushPopMIs[i];
1117 if (MI->getNumOperands() == 1) {
1118 if (MI->getOpcode() == ARM::tPOP_RET &&
1119 MI->getOperand(0).getReg() == ARM::PC)
1120 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
1121 MI->eraseFromParent();
1122 MadeChange = true;
1123 }
1124 }
1125 return MadeChange;
1126}