blob: ecf91c7404462ad04dd482a264aad6c09acc09bc [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;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000124 const ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000125 bool isThumb;
Evan Chenga8e29892007-01-19 07:51:42 +0000126 public:
127 virtual bool runOnMachineFunction(MachineFunction &Fn);
128
129 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000130 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000131 }
132
133 private:
134 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000135 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000136 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000137 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000138 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000139 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000140 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000141 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000142 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000143 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000144 bool LookForWater(CPUser&U, unsigned UserOffset, bool* PadNewWater,
145 MachineBasicBlock** NewMBB);
146 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
147 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000148 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000149 void RemoveDeadCPEMI(MachineInstr *CPEMI);
150 bool RemoveUnusedCPEntries();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000151 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
152 MachineInstr *CPEMI, unsigned Disp,
153 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000154 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000155 unsigned Disp);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000156 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
157 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000158 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000159 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
160 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
161 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
162 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000163
Evan Chenga8e29892007-01-19 07:51:42 +0000164 unsigned GetOffsetOf(MachineInstr *MI) const;
165 };
166}
167
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000168/// createARMConstantIslandPass - returns an instance of the constpool
169/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000170FunctionPass *llvm::createARMConstantIslandPass() {
171 return new ARMConstantIslands();
172}
173
174bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000175 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000176
177 TII = Fn.getTarget().getInstrInfo();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000178 AFI = Fn.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000179 isThumb = AFI->isThumbFunction();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000180
181 HasFarJump = false;
182
Evan Chenga8e29892007-01-19 07:51:42 +0000183 // Renumber all of the machine basic blocks in the function, guaranteeing that
184 // the numbers agree with the position of the block in the function.
185 Fn.RenumberBlocks();
186
187 // Perform the initial placement of the constant pool entries. To start with,
188 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000189 std::vector<MachineInstr*> CPEMIs;
Evan Cheng7755fac2007-01-26 01:04:44 +0000190 if (!MCP.isEmpty())
191 DoInitialPlacement(Fn, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000192
193 /// The next UID to take is the first unused one.
194 NextUID = CPEMIs.size();
195
196 // Do the initial scan of the function, building up information about the
197 // sizes of each block, the location of all the water, and finding all of the
198 // constant pool users.
199 InitialFunctionScan(Fn, CPEMIs);
200 CPEMIs.clear();
201
Evan Chenged884f32007-04-03 23:39:48 +0000202 /// Remove dead constant pool entries.
203 RemoveUnusedCPEntries();
204
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000205 // Iteratively place constant pool entries and fix up branches until there
206 // is no change.
207 bool MadeChange = false;
208 while (true) {
209 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000210 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000211 Change |= HandleConstantPoolUser(Fn, i);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000212 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000213 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
214 if (!Change)
215 break;
216 MadeChange = true;
217 }
Evan Chenged884f32007-04-03 23:39:48 +0000218
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000219 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
220 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000221 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000222 MadeChange |= UndoLRSpillRestore();
223
Evan Chenga8e29892007-01-19 07:51:42 +0000224 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000225 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000226 WaterList.clear();
227 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000228 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000229 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000230 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000231
232 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000233}
234
235/// DoInitialPlacement - Perform the initial placement of the constant pool
236/// entries. To start with, we put them all at the end of the function.
237void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000238 std::vector<MachineInstr*> &CPEMIs){
Evan Chenga8e29892007-01-19 07:51:42 +0000239 // Create the basic block to hold the CPE's.
240 MachineBasicBlock *BB = new MachineBasicBlock();
241 Fn.getBasicBlockList().push_back(BB);
242
243 // Add all of the constants from the constant pool to the end block, use an
244 // identity mapping of CPI's to CPE's.
245 const std::vector<MachineConstantPoolEntry> &CPs =
246 Fn.getConstantPool()->getConstants();
247
248 const TargetData &TD = *Fn.getTarget().getTargetData();
249 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
250 unsigned Size = TD.getTypeSize(CPs[i].getType());
251 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
252 // we would have to pad them out or something so that instructions stay
253 // aligned.
254 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
255 MachineInstr *CPEMI =
256 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
257 .addImm(i).addConstantPoolIndex(i).addImm(Size);
258 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000259
260 // Add a new CPEntry, but no corresponding CPUser yet.
261 std::vector<CPEntry> CPEs;
262 CPEs.push_back(CPEntry(CPEMI, i));
263 CPEntries.push_back(CPEs);
264 NumCPEs++;
265 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000266 }
267}
268
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000269/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000270/// into the block immediately after it.
271static bool BBHasFallthrough(MachineBasicBlock *MBB) {
272 // Get the next machine basic block in the function.
273 MachineFunction::iterator MBBI = MBB;
274 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
275 return false;
276
277 MachineBasicBlock *NextBB = next(MBBI);
278 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
279 E = MBB->succ_end(); I != E; ++I)
280 if (*I == NextBB)
281 return true;
282
283 return false;
284}
285
Evan Chengc99ef082007-02-09 20:54:44 +0000286/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
287/// look up the corresponding CPEntry.
288ARMConstantIslands::CPEntry
289*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
290 const MachineInstr *CPEMI) {
291 std::vector<CPEntry> &CPEs = CPEntries[CPI];
292 // Number of entries per constpool index should be small, just do a
293 // linear search.
294 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
295 if (CPEs[i].CPEMI == CPEMI)
296 return &CPEs[i];
297 }
298 return NULL;
299}
300
Evan Chenga8e29892007-01-19 07:51:42 +0000301/// InitialFunctionScan - Do the initial scan of the function, building up
302/// information about the sizes of each block, the location of all the water,
303/// and finding all of the constant pool users.
304void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000305 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000306 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000307 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
308 MBBI != E; ++MBBI) {
309 MachineBasicBlock &MBB = *MBBI;
310
311 // If this block doesn't fall through into the next MBB, then this is
312 // 'water' that a constant pool island could be placed.
313 if (!BBHasFallthrough(&MBB))
314 WaterList.push_back(&MBB);
315
316 unsigned MBBSize = 0;
317 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
318 I != E; ++I) {
319 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000320 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000321
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000322 int Opc = I->getOpcode();
323 if (TII->isBranch(Opc)) {
324 bool isCond = false;
325 unsigned Bits = 0;
326 unsigned Scale = 1;
327 int UOpc = Opc;
328 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000329 default:
330 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000331 case ARM::Bcc:
332 isCond = true;
333 UOpc = ARM::B;
334 // Fallthrough
335 case ARM::B:
336 Bits = 24;
337 Scale = 4;
338 break;
339 case ARM::tBcc:
340 isCond = true;
341 UOpc = ARM::tB;
342 Bits = 8;
343 Scale = 2;
344 break;
345 case ARM::tB:
346 Bits = 11;
347 Scale = 2;
348 break;
349 }
Evan Chengb43216e2007-02-01 10:16:15 +0000350
351 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000352 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000353 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000354 }
355
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000356 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
357 PushPopMIs.push_back(I);
358
Evan Chenga8e29892007-01-19 07:51:42 +0000359 // Scan the instructions for constant pool operands.
360 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
361 if (I->getOperand(op).isConstantPoolIndex()) {
362 // We found one. The addressing mode tells us the max displacement
363 // from the PC that this instruction permits.
Evan Chenga8e29892007-01-19 07:51:42 +0000364
365 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000366 unsigned Bits = 0;
367 unsigned Scale = 1;
Evan Chenga8e29892007-01-19 07:51:42 +0000368 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
369 switch (TSFlags & ARMII::AddrModeMask) {
370 default:
371 // Constant pool entries can reach anything.
372 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
373 continue;
374 assert(0 && "Unknown addressing mode for CP reference!");
375 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000376 Bits = 8;
377 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000378 break;
379 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000380 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000381 break;
382 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000383 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000384 break;
385 // addrmode4 has no immediate offset.
386 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000387 Bits = 8;
388 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000389 break;
390 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000391 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000392 break;
393 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000394 Bits = 5;
395 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000396 break;
397 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000398 Bits = 5;
399 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000400 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000401 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000402 Bits = 8;
403 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000404 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000405 }
Evan Chengb43216e2007-02-01 10:16:15 +0000406
Evan Chenga8e29892007-01-19 07:51:42 +0000407 // Remember that this is a user of a CP entry.
Evan Chengc99ef082007-02-09 20:54:44 +0000408 unsigned CPI = I->getOperand(op).getConstantPoolIndex();
409 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng556f33c2007-02-01 20:44:52 +0000410 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000411 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000412
413 // Increment corresponding CPEntry reference count.
414 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
415 assert(CPE && "Cannot find a corresponding CPEntry!");
416 CPE->RefCount++;
Evan Chenga8e29892007-01-19 07:51:42 +0000417
418 // Instructions can only use one CP entry, don't bother scanning the
419 // rest of the operands.
420 break;
421 }
422 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000423
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000424 // In thumb mode, if this block is a constpool island, pessimistically
425 // assume it needs to be padded by two byte so it's aligned on 4 byte
426 // boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000427 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000428 !MBB.empty() &&
Evan Cheng2021abe2007-02-01 01:09:47 +0000429 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
430 MBBSize += 2;
431
Evan Chenga8e29892007-01-19 07:51:42 +0000432 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000433 BBOffsets.push_back(Offset);
434 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000435 }
436}
437
Evan Chenga8e29892007-01-19 07:51:42 +0000438/// GetOffsetOf - Return the current offset of the specified machine instruction
439/// from the start of the function. This offset changes as stuff is moved
440/// around inside the function.
441unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
442 MachineBasicBlock *MBB = MI->getParent();
443
444 // The offset is composed of two things: the sum of the sizes of all MBB's
445 // before this instruction's block, and the offset from the start of the block
446 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000447 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000448
449 // Sum instructions before MI in MBB.
450 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
451 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
452 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000453 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000454 }
455}
456
457/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
458/// ID.
459static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
460 const MachineBasicBlock *RHS) {
461 return LHS->getNumber() < RHS->getNumber();
462}
463
464/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
465/// machine function, it upsets all of the block numbers. Renumber the blocks
466/// and update the arrays that parallel this numbering.
467void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
468 // Renumber the MBB's to keep them consequtive.
469 NewBB->getParent()->RenumberBlocks(NewBB);
470
471 // Insert a size into BBSizes to align it properly with the (newly
472 // renumbered) block numbers.
473 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000474
475 // Likewise for BBOffsets.
476 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Evan Chenga8e29892007-01-19 07:51:42 +0000477
478 // Next, update WaterList. Specifically, we need to add NewMBB as having
479 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000480 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000481 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
482 CompareMBBNumbers);
483 WaterList.insert(IP, NewBB);
484}
485
486
487/// Split the basic block containing MI into two blocks, which are joined by
488/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000489/// account for this change and returns the newly created block.
490MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000491 MachineBasicBlock *OrigBB = MI->getParent();
492
493 // Create a new MBB for the code after the OrigBB.
494 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
495 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
496 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
497
498 // Splice the instructions starting with MI over to NewBB.
499 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
500
501 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000502 // Note the new unconditional branch is not being recorded.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000503 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000504 NumSplit++;
505
506 // Update the CFG. All succs of OrigBB are now succs of NewBB.
507 while (!OrigBB->succ_empty()) {
508 MachineBasicBlock *Succ = *OrigBB->succ_begin();
509 OrigBB->removeSuccessor(Succ);
510 NewBB->addSuccessor(Succ);
511
512 // This pass should be run after register allocation, so there should be no
513 // PHI nodes to update.
514 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
515 && "PHI nodes should be eliminated by now!");
516 }
517
518 // OrigBB branches to NewBB.
519 OrigBB->addSuccessor(NewBB);
520
521 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000522 // This is almost the same as UpdateForInsertedWaterBlock, except that
523 // the Water goes after OrigBB, not NewBB.
524 NewBB->getParent()->RenumberBlocks(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000525
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000526 // Insert a size into BBSizes to align it properly with the (newly
527 // renumbered) block numbers.
528 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
529
Dale Johannesen99c49a42007-02-25 00:47:03 +0000530 // Likewise for BBOffsets.
531 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
532
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000533 // Next, update WaterList. Specifically, we need to add OrigMBB as having
534 // available water after it (but not if it's already there, which happens
535 // when splitting before a conditional branch that is followed by an
536 // unconditional branch - in that case we want to insert NewBB).
537 std::vector<MachineBasicBlock*>::iterator IP =
538 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
539 CompareMBBNumbers);
540 MachineBasicBlock* WaterBB = *IP;
541 if (WaterBB == OrigBB)
542 WaterList.insert(next(IP), NewBB);
543 else
544 WaterList.insert(IP, OrigBB);
545
Evan Chenga8e29892007-01-19 07:51:42 +0000546 // Figure out how large the first NewMBB is.
547 unsigned NewBBSize = 0;
548 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
549 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000550 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000551
Dale Johannesen99c49a42007-02-25 00:47:03 +0000552 unsigned OrigBBI = OrigBB->getNumber();
553 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000554 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000555 BBSizes[NewBBI] = NewBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000556
557 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000558 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000559 unsigned delta = isThumb ? 2 : 4;
560 BBSizes[OrigBBI] -= NewBBSize - delta;
561
562 // ...and adjust BBOffsets for NewBB accordingly.
563 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
564
565 // All BBOffsets following these blocks must be modified.
566 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000567
568 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000569}
570
Dale Johannesence74de42007-02-25 18:31:31 +0000571/// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
Dale Johannesen99c49a42007-02-25 00:47:03 +0000572/// TrialOffset.
573bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
574 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
575 if (UserOffset <= TrialOffset) {
576 // User before the Trial.
577 if (TrialOffset-UserOffset <= MaxDisp)
578 return true;
579 } else if (NegativeOK) {
580 if (UserOffset-TrialOffset <= MaxDisp)
581 return true;
582 }
583 return false;
584}
585
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000586/// WaterIsInRange - Returns true if a CPE placed after the specified
587/// Water (a basic block) will be in range for the specific MI.
588
589bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000590 MachineBasicBlock* Water, unsigned MaxDisp)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000591{
Dale Johannesen99c49a42007-02-25 00:47:03 +0000592 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000593 BBSizes[Water->getNumber()];
594 // If the Water is a constpool island, it has already been aligned.
595 // If not, align it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000596 if (isThumb &&
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000597 (Water->empty() ||
598 Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
599 CPEOffset += 2;
600
Dale Johannesend959aa42007-04-02 20:31:06 +0000601 // If the CPE is to be inserted before the instruction, that will raise
602 // the offset of the instruction.
603 if (CPEOffset < UserOffset)
604 UserOffset += isThumb ? 2 : 4;
605
Dale Johannesen99c49a42007-02-25 00:47:03 +0000606 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000607}
608
609/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000610/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000611bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
612 MachineInstr *CPEMI,
613 unsigned MaxDisp, bool DoDump) {
614 // In thumb mode, pessimistically assumes the .align 2 before the first CPE
Evan Cheng2021abe2007-02-01 01:09:47 +0000615 // in the island adds two byte padding.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000616 unsigned AlignAdj = isThumb ? 2 : 0;
Evan Cheng2021abe2007-02-01 01:09:47 +0000617 unsigned CPEOffset = GetOffsetOf(CPEMI) + AlignAdj;
618
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000619 if (DoDump) {
620 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
621 << " max delta=" << MaxDisp
622 << " insn address=" << UserOffset
623 << " CPE address=" << CPEOffset
624 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
625 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000626
Dale Johannesen99c49a42007-02-25 00:47:03 +0000627 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000628}
629
Evan Chengc99ef082007-02-09 20:54:44 +0000630/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
631/// unconditionally branches to its only successor.
632static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
633 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
634 return false;
635
636 MachineBasicBlock *Succ = *MBB->succ_begin();
637 MachineBasicBlock *Pred = *MBB->pred_begin();
638 MachineInstr *PredMI = &Pred->back();
639 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
640 return PredMI->getOperand(0).getMBB() == Succ;
641 return false;
642}
643
Dale Johannesen99c49a42007-02-25 00:47:03 +0000644void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
645{
646 MachineFunction::iterator MBBI = BB->getParent()->end();
Dale Johannesence74de42007-02-25 18:31:31 +0000647 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++)
Dale Johannesen99c49a42007-02-25 00:47:03 +0000648 BBOffsets[i] += delta;
649}
650
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000651/// DecrementOldEntry - find the constant pool entry with index CPI
652/// and instruction CPEMI, and decrement its refcount. If the refcount
653/// becomes 0 remove the entry and instruction. Returns true if we removed
654/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000655
Evan Chenged884f32007-04-03 23:39:48 +0000656bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000657 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000658 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
659 assert(CPE && "Unexpected!");
660 if (--CPE->RefCount == 0) {
661 RemoveDeadCPEMI(CPEMI);
662 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000663 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000664 return true;
665 }
666 return false;
667}
668
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000669/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
670/// if not, see if an in-range clone of the CPE is in range, and if so,
671/// change the data structures so the user references the clone. Returns:
672/// 0 = no existing entry found
673/// 1 = entry found, and there were no code insertions or deletions
674/// 2 = entry found, and there were code insertions or deletions
675int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
676{
677 MachineInstr *UserMI = U.MI;
678 MachineInstr *CPEMI = U.CPEMI;
679
680 // Check to see if the CPE is already in-range.
681 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
682 DOUT << "In range\n";
683 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000684 }
685
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000686 // No. Look for previously created clones of the CPE that are in range.
687 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
688 std::vector<CPEntry> &CPEs = CPEntries[CPI];
689 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
690 // We already tried this one
691 if (CPEs[i].CPEMI == CPEMI)
692 continue;
693 // Removing CPEs can leave empty entries, skip
694 if (CPEs[i].CPEMI == NULL)
695 continue;
696 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
697 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
698 // Point the CPUser node to the replacement
699 U.CPEMI = CPEs[i].CPEMI;
700 // Change the CPI in the instruction operand to refer to the clone.
701 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
702 if (UserMI->getOperand(j).isConstantPoolIndex()) {
703 UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
704 break;
705 }
706 // Adjust the refcount of the clone...
707 CPEs[i].RefCount++;
708 // ...and the original. If we didn't remove the old entry, none of the
709 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000710 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000711 }
712 }
713 return 0;
714}
715
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000716/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
717/// the specific unconditional branch instruction.
718static inline unsigned getUnconditionalBrDisp(int Opc) {
719 return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
720}
721
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000722/// LookForWater - look for an existing entry in the WaterList in which
723/// we can place the CPE referenced from U so it's within range of U's MI.
724/// Returns true if found, false if not. If it returns true, *NewMBB
725/// is set to the WaterList entry, and *PadNewWater is set to false if
726/// the WaterList entry is an island.
727
728bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
729 bool *PadNewWater, MachineBasicBlock** NewMBB) {
730 if (!WaterList.empty()) {
731 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
732 B = WaterList.begin();; --IP) {
733 MachineBasicBlock* WaterBB = *IP;
734 if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
735 DOUT << "found water in range\n";
736 // CPE goes before following block (NewMBB).
737 *NewMBB = next(MachineFunction::iterator(WaterBB));
738 // If WaterBB is an island, don't pad the new island.
739 // If WaterBB is empty, go backwards until we find something that
740 // isn't. WaterBB may become empty if it's an island whose
741 // contents were moved farther back.
742 if (isThumb) {
743 MachineBasicBlock* BB = WaterBB;
744 while (BB->empty())
745 BB = prior(MachineFunction::iterator(BB));
746 if (BB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
747 *PadNewWater = false;
748 }
749 // Remove the original WaterList entry; we want subsequent
750 // insertions in this vicinity to go after the one we're
751 // about to insert. This considerably reduces the number
752 // of times we have to move the same CPE more than once.
753 WaterList.erase(IP);
754 return true;
755 }
756 if (IP == B)
757 break;
758 }
759 }
760 return false;
761}
762
763/// CreateNewWater - No existing WaterList entry will work for
764/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
765/// block is used if in range, and the conditional branch munged so control
766/// flow is correct. Otherwise the block is split to create a hole with an
767/// unconditional branch around it. In either case *NewMBB is set to a
768/// block following which the new island can be inserted (the WaterList
769/// is not adjusted).
770
771void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
772 unsigned UserOffset, MachineBasicBlock** NewMBB) {
773 CPUser &U = CPUsers[CPUserIndex];
774 MachineInstr *UserMI = U.MI;
775 MachineInstr *CPEMI = U.CPEMI;
776 MachineBasicBlock *UserMBB = UserMI->getParent();
777 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
778 BBSizes[UserMBB->getNumber()];
779 assert(OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()+1]);
780
781 // If the use is at the end of the block, or the end of the block
782 // is within range, make new water there. (The +2 or 4 below is
783 // for the unconditional branch we will be adding. If the block ends in
784 // an unconditional branch already, it is water, and is known to
785 // be out of range, so we'll always be adding one.)
786 if (&UserMBB->back() == UserMI ||
787 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2 : 4),
788 U.MaxDisp, !isThumb)) {
789 DOUT << "Split at end of block\n";
790 if (&UserMBB->back() == UserMI)
791 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
792 *NewMBB = next(MachineFunction::iterator(UserMBB));
793 // Add an unconditional branch from UserMBB to fallthrough block.
794 // Record it for branch lengthening; this new branch will not get out of
795 // range, but if the preceding conditional branch is out of range, the
796 // targets will be exchanged, and the altered branch may be out of
797 // range, so the machinery has to know about it.
798 int UncondBr = isThumb ? ARM::tB : ARM::B;
799 BuildMI(UserMBB, TII->get(UncondBr)).addMBB(*NewMBB);
800 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
801 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
802 MaxDisp, false, UncondBr));
803 int delta = isThumb ? 2 : 4;
804 BBSizes[UserMBB->getNumber()] += delta;
805 AdjustBBOffsetsAfter(UserMBB, delta);
806 } else {
807 // What a big block. Find a place within the block to split it.
808 // This is a little tricky on Thumb since instructions are 2 bytes
809 // and constant pool entries are 4 bytes: if instruction I references
810 // island CPE, and instruction I+1 references CPE', it will
811 // not work well to put CPE as far forward as possible, since then
812 // CPE' cannot immediately follow it (that location is 2 bytes
813 // farther away from I+1 than CPE was from I) and we'd need to create
814 // a new island.
815 // The 4 in the following is for the unconditional branch we'll be
816 // inserting (allows for long branch on Thumb). The 2 or 0 is for
817 // alignment of the island.
818 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4 + (isThumb ? 2 : 0);
819 // This could point off the end of the block if we've already got
820 // constant pool entries following this block; only the last one is
821 // in the water list. Back past any possible branches (allow for a
822 // conditional and a maximally long unconditional).
823 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
824 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
825 (isThumb ? 6 : 8);
826 unsigned EndInsertOffset = BaseInsertOffset +
827 CPEMI->getOperand(2).getImm();
828 MachineBasicBlock::iterator MI = UserMI;
829 ++MI;
830 unsigned CPUIndex = CPUserIndex+1;
831 for (unsigned Offset = UserOffset+ARM::GetInstSize(UserMI);
832 Offset < BaseInsertOffset;
833 Offset += ARM::GetInstSize(MI),
834 MI = next(MI)) {
835 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
836 if (!OffsetIsInRange(Offset, EndInsertOffset,
837 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
838 BaseInsertOffset -= (isThumb ? 2 : 4);
839 EndInsertOffset -= (isThumb ? 2 : 4);
840 }
841 // This is overly conservative, as we don't account for CPEMIs
842 // being reused within the block, but it doesn't matter much.
843 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
844 CPUIndex++;
845 }
846 }
847 DOUT << "Split in middle of big block\n";
848 *NewMBB = SplitBlockBeforeInstr(prior(MI));
849 }
850}
851
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000852/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
853/// is out-of-range. If so, pick it up the constant pool value and move it some
854/// place in-range. Return true if we changed any addresses (thus must run
855/// another pass of branch lengthening), false otherwise.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000856bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
857 unsigned CPUserIndex){
858 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000859 MachineInstr *UserMI = U.MI;
860 MachineInstr *CPEMI = U.CPEMI;
861 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
862 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000863 MachineBasicBlock *NewMBB;
864 // Compute this only once, it's expensive
865 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
866
867 // See if the current entry is within range, or there is a clone of it
868 // in range.
869 int result = LookForExistingCPEntry(U, UserOffset);
870 if (result==1) return false;
871 else if (result==2) return true;
872
873 // No existing clone of this CPE is within range.
874 // We will be generating a new clone. Get a UID for it.
875 unsigned ID = NextUID++;
876
877 // Look for water where we can place this CPE. We look for the farthest one
878 // away that will work. Forward references only for now (although later
879 // we might find some that are backwards).
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000880 bool PadNewWater = true;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000881
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000882 if (!LookForWater(U, UserOffset, &PadNewWater, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000883 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000884 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000885 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000886 }
887
888 // Okay, we know we can put an island before NewMBB now, do it!
889 MachineBasicBlock *NewIsland = new MachineBasicBlock();
890 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
891
892 // Update internal data structures to account for the newly inserted MBB.
893 UpdateForInsertedWaterBlock(NewIsland);
894
895 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +0000896 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000897
898 // Now that we have an island to add the CPE to, clone the original CPE and
899 // add it to the island.
Evan Chenga8e29892007-01-19 07:51:42 +0000900 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
901 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000902 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +0000903 NumCPEs++;
904
Evan Chengb43216e2007-02-01 10:16:15 +0000905 // Compensate for .align 2 in thumb mode.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000906 if (isThumb && PadNewWater) Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +0000907 // Increase the size of the island block to account for the new entry.
908 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000909 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
910 AdjustBBOffsetsAfter(NewIsland, Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000911
912 // Finally, change the CPI in the instruction operand to be ID.
913 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
914 if (UserMI->getOperand(i).isConstantPoolIndex()) {
915 UserMI->getOperand(i).setConstantPoolIndex(ID);
916 break;
917 }
918
Evan Chengc99ef082007-02-09 20:54:44 +0000919 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Evan Chenga8e29892007-01-19 07:51:42 +0000920
921 return true;
922}
923
Evan Chenged884f32007-04-03 23:39:48 +0000924/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
925/// sizes and offsets of impacted basic blocks.
926void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
927 MachineBasicBlock *CPEBB = CPEMI->getParent();
928 if (CPEBB->empty()) {
929 // In thumb mode, the size of island is padded by two to compensate for
930 // the alignment requirement. Thus it will now be 2 when the block is
931 // empty, so fix this.
932 // All succeeding offsets have the current size value added in, fix this.
933 if (BBSizes[CPEBB->getNumber()] != 0) {
934 AdjustBBOffsetsAfter(CPEBB, -BBSizes[CPEBB->getNumber()]);
935 BBSizes[CPEBB->getNumber()] = 0;
936 }
937 // An island has only one predecessor BB and one successor BB. Check if
938 // this BB's predecessor jumps directly to this BB's successor. This
939 // shouldn't happen currently.
940 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
941 // FIXME: remove the empty blocks after all the work is done?
942 } else {
943 unsigned Size = CPEMI->getOperand(2).getImm();
944 BBSizes[CPEBB->getNumber()] -= Size;
945 // All succeeding offsets have the current size value added in, fix this.
946 AdjustBBOffsetsAfter(CPEBB, -Size);
947 }
948
949 CPEMI->eraseFromParent();
950}
951
952/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
953/// are zero.
954bool ARMConstantIslands::RemoveUnusedCPEntries() {
955 unsigned MadeChange = false;
956 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
957 std::vector<CPEntry> &CPEs = CPEntries[i];
958 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
959 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
960 RemoveDeadCPEMI(CPEs[j].CPEMI);
961 CPEs[j].CPEMI = NULL;
962 MadeChange = true;
963 }
964 }
965 }
966 return MadeChange;
967}
968
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000969/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +0000970/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +0000971bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
972 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000973 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +0000974 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000975 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +0000976
Evan Chengc99ef082007-02-09 20:54:44 +0000977 DOUT << "Branch of destination BB#" << DestBB->getNumber()
978 << " from BB#" << MI->getParent()->getNumber()
979 << " max delta=" << MaxDisp
980 << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +0000981
Dale Johannesen99c49a42007-02-25 00:47:03 +0000982 return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
Evan Cheng43aeab62007-01-26 20:38:26 +0000983}
984
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000985/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
986/// away to fit in its displacement field.
987bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000988 MachineInstr *MI = Br.MI;
989 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
990
Evan Chengc0dbec72007-01-31 19:57:44 +0000991 // Check to see if the DestBB is already in-range.
992 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +0000993 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000994
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000995 if (!Br.isCond)
996 return FixUpUnconditionalBr(Fn, Br);
997 return FixUpConditionalBr(Fn, Br);
998}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000999
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001000/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1001/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001002/// spilled in the epilogue, then we can use BL to implement a far jump.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001003/// Otherwise, add an intermediate branch instruction to to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001004bool
1005ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1006 MachineInstr *MI = Br.MI;
1007 MachineBasicBlock *MBB = MI->getParent();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001008 assert(isThumb && "Expected a Thumb function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001009
1010 // Use BL to implement far jump.
1011 Br.MaxDisp = (1 << 21) * 2;
1012 MI->setInstrDescriptor(TII->get(ARM::tBfar));
1013 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001014 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001015 HasFarJump = true;
1016 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001017
Evan Chengc99ef082007-02-09 20:54:44 +00001018 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001019
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001020 return true;
1021}
1022
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001023/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001024/// far away to fit in its displacement field. It is converted to an inverse
1025/// conditional branch + an unconditional branch to the destination.
1026bool
1027ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1028 MachineInstr *MI = Br.MI;
1029 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
1030
1031 // Add a unconditional branch to the destination and invert the branch
1032 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001033 // blt L1
1034 // =>
1035 // bge L2
1036 // b L1
1037 // L2:
1038 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
1039 CC = ARMCC::getOppositeCondition(CC);
1040
1041 // If the branch is at the end of its MBB and that has a fall-through block,
1042 // direct the updated conditional branch to the fall-through block. Otherwise,
1043 // split the MBB before the next instruction.
1044 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001045 MachineInstr *BMI = &MBB->back();
1046 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001047
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001048 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001049 if (BMI != MI) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001050 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001051 BMI->getOpcode() == Br.UncondBr) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001052 // Last MI in the BB is a unconditional branch. Can we simply invert the
1053 // condition and swap destinations:
1054 // beq L1
1055 // b L2
1056 // =>
1057 // bne L2
1058 // b L1
Evan Chengbd5d3db2007-02-03 02:08:34 +00001059 MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
Evan Chengc0dbec72007-01-31 19:57:44 +00001060 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001061 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001062 BMI->getOperand(0).setMachineBasicBlock(DestBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001063 MI->getOperand(0).setMachineBasicBlock(NewDest);
1064 MI->getOperand(1).setImm(CC);
1065 return true;
1066 }
1067 }
1068 }
1069
1070 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001071 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +00001072 // No need for the branch to the next block. We're adding a unconditional
1073 // branch to the destination.
1074 MBB->back().eraseFromParent();
1075 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001076 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Evan Chengbd5d3db2007-02-03 02:08:34 +00001077
Evan Chengc99ef082007-02-09 20:54:44 +00001078 DOUT << " Insert B to BB#" << DestBB->getNumber()
1079 << " also invert condition and change dest. to BB#"
1080 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001081
1082 // Insert a unconditional branch and replace the conditional branch.
1083 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +00001084 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001085 Br.MI = &MBB->back();
1086 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001087 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001088 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001089 MI->eraseFromParent();
1090
1091 // Increase the size of MBB to account for the new unconditional branch.
Dale Johannesen99c49a42007-02-25 00:47:03 +00001092 int delta = ARM::GetInstSize(&MBB->back());
1093 BBSizes[MBB->getNumber()] += delta;
1094 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001095 return true;
1096}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001097
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001098/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1099/// LR / restores LR to pc.
1100bool ARMConstantIslands::UndoLRSpillRestore() {
1101 bool MadeChange = false;
1102 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1103 MachineInstr *MI = PushPopMIs[i];
1104 if (MI->getNumOperands() == 1) {
1105 if (MI->getOpcode() == ARM::tPOP_RET &&
1106 MI->getOperand(0).getReg() == ARM::PC)
1107 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
1108 MI->eraseFromParent();
1109 MadeChange = true;
1110 }
1111 }
1112 return MadeChange;
1113}