blob: 9aced30f0136e2e038e62558585ed70a63500de4 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
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
Dale Johannesen8593e412007-04-29 19:19:30 +000054 /// by MBB Number. The two-byte pads required for Thumb alignment are
55 /// counted as part of the following block (i.e., the offset and size for
56 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000057 std::vector<unsigned> BBSizes;
Evan Chenga8e29892007-01-19 07:51:42 +000058
Dale Johannesen99c49a42007-02-25 00:47:03 +000059 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000060 /// The two-byte pads required for Thumb alignment are counted as part of
61 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000062 std::vector<unsigned> BBOffsets;
63
Evan Chenga8e29892007-01-19 07:51:42 +000064 /// WaterList - A sorted list of basic blocks where islands could be placed
65 /// (i.e. blocks that don't fall through to the following block, due
66 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000067 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000068
Evan Chenga8e29892007-01-19 07:51:42 +000069 /// CPUser - One user of a constant pool, keeping the machine instruction
70 /// pointer, the constant pool being referenced, and the max displacement
71 /// allowed from the instruction to the CP.
72 struct CPUser {
73 MachineInstr *MI;
74 MachineInstr *CPEMI;
75 unsigned MaxDisp;
76 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
77 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
78 };
79
80 /// CPUsers - Keep track of all of the machine instructions that use various
81 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000082 std::vector<CPUser> CPUsers;
Evan Chengc99ef082007-02-09 20:54:44 +000083
84 /// CPEntry - One per constant pool entry, keeping the machine instruction
85 /// pointer, the constpool index, and the number of CPUser's which
86 /// reference this entry.
87 struct CPEntry {
88 MachineInstr *CPEMI;
89 unsigned CPI;
90 unsigned RefCount;
91 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
92 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
93 };
94
95 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +000096 /// instructions. For each original constpool index (i.e. those that
97 /// existed upon entry to this pass), it keeps a vector of entries.
98 /// Original elements are cloned as we go along; the clones are
99 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000100 std::vector<std::vector<CPEntry> > CPEntries;
Evan Chenga8e29892007-01-19 07:51:42 +0000101
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000102 /// ImmBranch - One per immediate branch, keeping the machine instruction
103 /// pointer, conditional or unconditional, the max displacement,
104 /// and (if isCond is true) the corresponding unconditional branch
105 /// opcode.
106 struct ImmBranch {
107 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000108 unsigned MaxDisp : 31;
109 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000110 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000111 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
112 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000113 };
114
Evan Cheng2706f972007-05-16 05:14:06 +0000115 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000116 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000117 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000118
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000119 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
120 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000121 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000122
123 /// HasFarJump - True if any far jump instruction has been emitted during
124 /// the branch fix up pass.
125 bool HasFarJump;
126
Evan Chenga8e29892007-01-19 07:51:42 +0000127 const TargetInstrInfo *TII;
Dale Johannesen8593e412007-04-29 19:19:30 +0000128 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000129 bool isThumb;
Evan Chenga8e29892007-01-19 07:51:42 +0000130 public:
Devang Patel19974732007-05-03 01:11:54 +0000131 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +0000132 ARMConstantIslands() : MachineFunctionPass((intptr_t)&ID) {}
133
Evan Chenga8e29892007-01-19 07:51:42 +0000134 virtual bool runOnMachineFunction(MachineFunction &Fn);
135
136 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000137 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000138 }
139
140 private:
141 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000142 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000143 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000144 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000145 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000146 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000147 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000148 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000149 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000150 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000151 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000152 MachineBasicBlock** NewMBB);
Dale Johannesen8593e412007-04-29 19:19:30 +0000153 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
154 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000155 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
156 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000157 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000158 void RemoveDeadCPEMI(MachineInstr *CPEMI);
159 bool RemoveUnusedCPEntries();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000160 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
161 MachineInstr *CPEMI, unsigned Disp,
162 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000163 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000164 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000165 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
166 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000167 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000168 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
169 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
170 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
171 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000172
Evan Chenga8e29892007-01-19 07:51:42 +0000173 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000174 void dumpBBs();
175 void verify(MachineFunction &Fn);
Evan Chenga8e29892007-01-19 07:51:42 +0000176 };
Devang Patel19974732007-05-03 01:11:54 +0000177 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000178}
179
Dale Johannesen8593e412007-04-29 19:19:30 +0000180/// verify - check BBOffsets, BBSizes, alignment of islands
181void ARMConstantIslands::verify(MachineFunction &Fn) {
182 assert(BBOffsets.size() == BBSizes.size());
183 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
184 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
185 if (isThumb) {
186 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
187 MBBI != E; ++MBBI) {
188 MachineBasicBlock *MBB = MBBI;
189 if (!MBB->empty() &&
190 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
191 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
192 BBSizes[MBB->getNumber()]%4 == 0) ||
193 (BBOffsets[MBB->getNumber()]%4 != 0 &&
194 BBSizes[MBB->getNumber()]%4 != 0));
195 }
196 }
197}
198
199/// print block size and offset information - debugging
200void ARMConstantIslands::dumpBBs() {
201 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000202 DOUT << "block " << J << " offset " << BBOffsets[J] <<
203 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000204 }
205}
206
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000207/// createARMConstantIslandPass - returns an instance of the constpool
208/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000209FunctionPass *llvm::createARMConstantIslandPass() {
210 return new ARMConstantIslands();
211}
212
213bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000214 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000215
216 TII = Fn.getTarget().getInstrInfo();
Dale Johannesen8593e412007-04-29 19:19:30 +0000217 AFI = Fn.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000218 isThumb = AFI->isThumbFunction();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000219
220 HasFarJump = false;
221
Evan Chenga8e29892007-01-19 07:51:42 +0000222 // Renumber all of the machine basic blocks in the function, guaranteeing that
223 // the numbers agree with the position of the block in the function.
224 Fn.RenumberBlocks();
225
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000226 /// Thumb functions containing constant pools get 2-byte alignment. This is so
227 /// we can keep exact track of where the alignment padding goes. Set default.
228 AFI->setAlign(isThumb ? 1U : 2U);
229
Evan Chenga8e29892007-01-19 07:51:42 +0000230 // Perform the initial placement of the constant pool entries. To start with,
231 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000232 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000233 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000234 DoInitialPlacement(Fn, CPEMIs);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000235 if (isThumb)
236 AFI->setAlign(2U);
237 }
Evan Chenga8e29892007-01-19 07:51:42 +0000238
239 /// The next UID to take is the first unused one.
240 NextUID = CPEMIs.size();
241
242 // Do the initial scan of the function, building up information about the
243 // sizes of each block, the location of all the water, and finding all of the
244 // constant pool users.
245 InitialFunctionScan(Fn, CPEMIs);
246 CPEMIs.clear();
247
Evan Chenged884f32007-04-03 23:39:48 +0000248 /// Remove dead constant pool entries.
249 RemoveUnusedCPEntries();
250
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000251 // Iteratively place constant pool entries and fix up branches until there
252 // is no change.
253 bool MadeChange = false;
254 while (true) {
255 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000256 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000257 Change |= HandleConstantPoolUser(Fn, i);
Evan Cheng82020102007-07-10 22:00:16 +0000258 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000259 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000260 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000261 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000262 if (!Change)
263 break;
264 MadeChange = true;
265 }
Evan Chenged884f32007-04-03 23:39:48 +0000266
Dale Johannesen8593e412007-04-29 19:19:30 +0000267 // After a while, this might be made debug-only, but it is not expensive.
268 verify(Fn);
269
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000270 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
271 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000272 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000273 MadeChange |= UndoLRSpillRestore();
274
Evan Chenga8e29892007-01-19 07:51:42 +0000275 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000276 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000277 WaterList.clear();
278 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000279 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000280 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000281 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000282
283 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000284}
285
286/// DoInitialPlacement - Perform the initial placement of the constant pool
287/// entries. To start with, we put them all at the end of the function.
288void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000289 std::vector<MachineInstr*> &CPEMIs){
Evan Chenga8e29892007-01-19 07:51:42 +0000290 // Create the basic block to hold the CPE's.
291 MachineBasicBlock *BB = new MachineBasicBlock();
292 Fn.getBasicBlockList().push_back(BB);
293
294 // Add all of the constants from the constant pool to the end block, use an
295 // identity mapping of CPI's to CPE's.
296 const std::vector<MachineConstantPoolEntry> &CPs =
297 Fn.getConstantPool()->getConstants();
298
299 const TargetData &TD = *Fn.getTarget().getTargetData();
300 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000301 unsigned Size = TD.getABITypeSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000302 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
303 // we would have to pad them out or something so that instructions stay
304 // aligned.
305 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
306 MachineInstr *CPEMI =
307 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
308 .addImm(i).addConstantPoolIndex(i).addImm(Size);
309 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000310
311 // Add a new CPEntry, but no corresponding CPUser yet.
312 std::vector<CPEntry> CPEs;
313 CPEs.push_back(CPEntry(CPEMI, i));
314 CPEntries.push_back(CPEs);
315 NumCPEs++;
316 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000317 }
318}
319
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000320/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000321/// into the block immediately after it.
322static bool BBHasFallthrough(MachineBasicBlock *MBB) {
323 // Get the next machine basic block in the function.
324 MachineFunction::iterator MBBI = MBB;
325 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
326 return false;
327
328 MachineBasicBlock *NextBB = next(MBBI);
329 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
330 E = MBB->succ_end(); I != E; ++I)
331 if (*I == NextBB)
332 return true;
333
334 return false;
335}
336
Evan Chengc99ef082007-02-09 20:54:44 +0000337/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
338/// look up the corresponding CPEntry.
339ARMConstantIslands::CPEntry
340*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
341 const MachineInstr *CPEMI) {
342 std::vector<CPEntry> &CPEs = CPEntries[CPI];
343 // Number of entries per constpool index should be small, just do a
344 // linear search.
345 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
346 if (CPEs[i].CPEMI == CPEMI)
347 return &CPEs[i];
348 }
349 return NULL;
350}
351
Evan Chenga8e29892007-01-19 07:51:42 +0000352/// InitialFunctionScan - Do the initial scan of the function, building up
353/// information about the sizes of each block, the location of all the water,
354/// and finding all of the constant pool users.
355void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000356 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000357 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000358 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
359 MBBI != E; ++MBBI) {
360 MachineBasicBlock &MBB = *MBBI;
361
362 // If this block doesn't fall through into the next MBB, then this is
363 // 'water' that a constant pool island could be placed.
364 if (!BBHasFallthrough(&MBB))
365 WaterList.push_back(&MBB);
366
367 unsigned MBBSize = 0;
368 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
369 I != E; ++I) {
370 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000371 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000372
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000373 int Opc = I->getOpcode();
374 if (TII->isBranch(Opc)) {
375 bool isCond = false;
376 unsigned Bits = 0;
377 unsigned Scale = 1;
378 int UOpc = Opc;
379 switch (Opc) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000380 case ARM::tBR_JTr:
381 // A Thumb table jump may involve padding; for the offsets to
382 // be right, functions containing these must be 4-byte aligned.
383 AFI->setAlign(2U);
384 if ((Offset+MBBSize)%4 != 0)
385 MBBSize += 2; // padding
386 continue; // Does not get an entry in ImmBranches
Evan Cheng743fa032007-01-25 19:43:52 +0000387 default:
Dale Johannesen8593e412007-04-29 19:19:30 +0000388 continue; // Ignore other JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000389 case ARM::Bcc:
390 isCond = true;
391 UOpc = ARM::B;
392 // Fallthrough
393 case ARM::B:
394 Bits = 24;
395 Scale = 4;
396 break;
397 case ARM::tBcc:
398 isCond = true;
399 UOpc = ARM::tB;
400 Bits = 8;
401 Scale = 2;
402 break;
403 case ARM::tB:
404 Bits = 11;
405 Scale = 2;
406 break;
407 }
Evan Chengb43216e2007-02-01 10:16:15 +0000408
409 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000410 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000411 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000412 }
413
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000414 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
415 PushPopMIs.push_back(I);
416
Evan Chenga8e29892007-01-19 07:51:42 +0000417 // Scan the instructions for constant pool operands.
418 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
419 if (I->getOperand(op).isConstantPoolIndex()) {
420 // We found one. The addressing mode tells us the max displacement
421 // from the PC that this instruction permits.
Evan Chenga8e29892007-01-19 07:51:42 +0000422
423 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000424 unsigned Bits = 0;
425 unsigned Scale = 1;
Evan Chenga8e29892007-01-19 07:51:42 +0000426 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
427 switch (TSFlags & ARMII::AddrModeMask) {
428 default:
429 // Constant pool entries can reach anything.
430 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
431 continue;
Evan Cheng768c9f72007-04-27 08:14:15 +0000432 if (I->getOpcode() == ARM::tLEApcrel) {
433 Bits = 8; // Taking the address of a CP entry.
434 break;
435 }
Evan Chenga8e29892007-01-19 07:51:42 +0000436 assert(0 && "Unknown addressing mode for CP reference!");
437 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000438 Bits = 8;
439 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000440 break;
441 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000442 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000443 break;
444 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000445 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000446 break;
447 // addrmode4 has no immediate offset.
448 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000449 Bits = 8;
450 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000451 break;
452 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000453 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000454 break;
455 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000456 Bits = 5;
457 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000458 break;
459 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000460 Bits = 5;
461 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000462 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000463 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000464 Bits = 8;
465 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000466 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000467 }
Evan Chengb43216e2007-02-01 10:16:15 +0000468
Evan Chenga8e29892007-01-19 07:51:42 +0000469 // Remember that this is a user of a CP entry.
Evan Chengc99ef082007-02-09 20:54:44 +0000470 unsigned CPI = I->getOperand(op).getConstantPoolIndex();
471 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng556f33c2007-02-01 20:44:52 +0000472 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000473 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000474
475 // Increment corresponding CPEntry reference count.
476 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
477 assert(CPE && "Cannot find a corresponding CPEntry!");
478 CPE->RefCount++;
Evan Chenga8e29892007-01-19 07:51:42 +0000479
480 // Instructions can only use one CP entry, don't bother scanning the
481 // rest of the operands.
482 break;
483 }
484 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000485
Dale Johannesen8593e412007-04-29 19:19:30 +0000486 // In thumb mode, if this block is a constpool island, we may need padding
487 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000488 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000489 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000490 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
491 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000492 MBBSize += 2;
493
Evan Chenga8e29892007-01-19 07:51:42 +0000494 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000495 BBOffsets.push_back(Offset);
496 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000497 }
498}
499
Evan Chenga8e29892007-01-19 07:51:42 +0000500/// GetOffsetOf - Return the current offset of the specified machine instruction
501/// from the start of the function. This offset changes as stuff is moved
502/// around inside the function.
503unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
504 MachineBasicBlock *MBB = MI->getParent();
505
506 // The offset is composed of two things: the sum of the sizes of all MBB's
507 // before this instruction's block, and the offset from the start of the block
508 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000509 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000510
Dale Johannesen8593e412007-04-29 19:19:30 +0000511 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
512 // alignment padding, and compensate if so.
513 if (isThumb &&
514 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
515 Offset%4 != 0)
516 Offset += 2;
517
Evan Chenga8e29892007-01-19 07:51:42 +0000518 // Sum instructions before MI in MBB.
519 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
520 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
521 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000522 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000523 }
524}
525
526/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
527/// ID.
528static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
529 const MachineBasicBlock *RHS) {
530 return LHS->getNumber() < RHS->getNumber();
531}
532
533/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
534/// machine function, it upsets all of the block numbers. Renumber the blocks
535/// and update the arrays that parallel this numbering.
536void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
537 // Renumber the MBB's to keep them consequtive.
538 NewBB->getParent()->RenumberBlocks(NewBB);
539
540 // Insert a size into BBSizes to align it properly with the (newly
541 // renumbered) block numbers.
542 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000543
544 // Likewise for BBOffsets.
545 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Evan Chenga8e29892007-01-19 07:51:42 +0000546
547 // Next, update WaterList. Specifically, we need to add NewMBB as having
548 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000549 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000550 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
551 CompareMBBNumbers);
552 WaterList.insert(IP, NewBB);
553}
554
555
556/// Split the basic block containing MI into two blocks, which are joined by
557/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000558/// account for this change and returns the newly created block.
559MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000560 MachineBasicBlock *OrigBB = MI->getParent();
561
562 // Create a new MBB for the code after the OrigBB.
563 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
564 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
565 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
566
567 // Splice the instructions starting with MI over to NewBB.
568 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
569
570 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000571 // Note the new unconditional branch is not being recorded.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000572 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000573 NumSplit++;
574
575 // Update the CFG. All succs of OrigBB are now succs of NewBB.
576 while (!OrigBB->succ_empty()) {
577 MachineBasicBlock *Succ = *OrigBB->succ_begin();
578 OrigBB->removeSuccessor(Succ);
579 NewBB->addSuccessor(Succ);
580
581 // This pass should be run after register allocation, so there should be no
582 // PHI nodes to update.
583 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
584 && "PHI nodes should be eliminated by now!");
585 }
586
587 // OrigBB branches to NewBB.
588 OrigBB->addSuccessor(NewBB);
589
590 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000591 // This is almost the same as UpdateForInsertedWaterBlock, except that
592 // the Water goes after OrigBB, not NewBB.
593 NewBB->getParent()->RenumberBlocks(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000594
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000595 // Insert a size into BBSizes to align it properly with the (newly
596 // renumbered) block numbers.
597 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
598
Dale Johannesen99c49a42007-02-25 00:47:03 +0000599 // Likewise for BBOffsets.
600 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
601
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000602 // Next, update WaterList. Specifically, we need to add OrigMBB as having
603 // available water after it (but not if it's already there, which happens
604 // when splitting before a conditional branch that is followed by an
605 // unconditional branch - in that case we want to insert NewBB).
606 std::vector<MachineBasicBlock*>::iterator IP =
607 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
608 CompareMBBNumbers);
609 MachineBasicBlock* WaterBB = *IP;
610 if (WaterBB == OrigBB)
611 WaterList.insert(next(IP), NewBB);
612 else
613 WaterList.insert(IP, OrigBB);
614
Dale Johannesen8593e412007-04-29 19:19:30 +0000615 // Figure out how large the first NewMBB is. (It cannot
616 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000617 unsigned NewBBSize = 0;
618 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
619 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000620 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000621
Dale Johannesen99c49a42007-02-25 00:47:03 +0000622 unsigned OrigBBI = OrigBB->getNumber();
623 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000624 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000625 BBSizes[NewBBI] = NewBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000626
627 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000628 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000629 unsigned delta = isThumb ? 2 : 4;
630 BBSizes[OrigBBI] -= NewBBSize - delta;
631
632 // ...and adjust BBOffsets for NewBB accordingly.
633 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
634
635 // All BBOffsets following these blocks must be modified.
636 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000637
638 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000639}
640
Dale Johannesen8593e412007-04-29 19:19:30 +0000641/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
642/// reference) is within MaxDisp of TrialOffset (a proposed location of a
643/// constant pool entry).
Dale Johannesen99c49a42007-02-25 00:47:03 +0000644bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
645 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000646 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
647 // purposes of the displacement computation; compensate for that here.
648 // Effectively, the valid range of displacements is 2 bytes smaller for such
649 // references.
650 if (isThumb && UserOffset%4 !=0)
651 UserOffset -= 2;
652 // CPEs will be rounded up to a multiple of 4.
653 if (isThumb && TrialOffset%4 != 0)
654 TrialOffset += 2;
655
Dale Johannesen99c49a42007-02-25 00:47:03 +0000656 if (UserOffset <= TrialOffset) {
657 // User before the Trial.
658 if (TrialOffset-UserOffset <= MaxDisp)
659 return true;
660 } else if (NegativeOK) {
661 if (UserOffset-TrialOffset <= MaxDisp)
662 return true;
663 }
664 return false;
665}
666
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000667/// WaterIsInRange - Returns true if a CPE placed after the specified
668/// Water (a basic block) will be in range for the specific MI.
669
670bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000671 MachineBasicBlock* Water, CPUser &U)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000672{
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000673 unsigned MaxDisp = U.MaxDisp;
Dale Johannesen8593e412007-04-29 19:19:30 +0000674 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Dale Johannesen99c49a42007-02-25 00:47:03 +0000675 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000676 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000677
Dale Johannesend959aa42007-04-02 20:31:06 +0000678 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000679 // the offset of the instruction. (Currently applies only to ARM, so
680 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000681 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000682 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000683
Dale Johannesen99c49a42007-02-25 00:47:03 +0000684 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000685}
686
687/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000688/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000689bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
690 MachineInstr *CPEMI,
691 unsigned MaxDisp, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000692 unsigned CPEOffset = GetOffsetOf(CPEMI);
693 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000694
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000695 if (DoDump) {
696 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
697 << " max delta=" << MaxDisp
698 << " insn address=" << UserOffset
699 << " CPE address=" << CPEOffset
700 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
701 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000702
Dale Johannesen99c49a42007-02-25 00:47:03 +0000703 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000704}
705
Evan Chengc99ef082007-02-09 20:54:44 +0000706/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
707/// unconditionally branches to its only successor.
708static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
709 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
710 return false;
711
712 MachineBasicBlock *Succ = *MBB->succ_begin();
713 MachineBasicBlock *Pred = *MBB->pred_begin();
714 MachineInstr *PredMI = &Pred->back();
715 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
716 return PredMI->getOperand(0).getMBB() == Succ;
717 return false;
718}
719
Dale Johannesen8593e412007-04-29 19:19:30 +0000720void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
721 int delta) {
722 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
723 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000724 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000725 // If some existing blocks have padding, adjust the padding as needed, a
726 // bit tricky. delta can be negative so don't use % on that.
727 if (isThumb) {
728 MachineBasicBlock *MBB = MBBI;
729 if (!MBB->empty()) {
730 // Constant pool entries require padding.
731 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
732 unsigned oldOffset = BBOffsets[i] - delta;
733 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
734 // add new padding
735 BBSizes[i] += 2;
736 delta += 2;
737 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
738 // remove existing padding
739 BBSizes[i] -=2;
740 delta -= 2;
741 }
742 }
Dale Johannesen66a2a8f2007-07-12 16:45:35 +0000743 // Thumb jump tables require padding. They should be at the end;
744 // following unconditional branches are removed by AnalyzeBranch.
Dale Johannesen8593e412007-04-29 19:19:30 +0000745 MachineInstr *ThumbJTMI = NULL;
746 if (prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
747 ThumbJTMI = prior(MBB->end());
Dale Johannesen8593e412007-04-29 19:19:30 +0000748 if (ThumbJTMI) {
749 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
750 unsigned oldMIOffset = newMIOffset - delta;
751 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
752 // remove existing padding
753 BBSizes[i] -= 2;
754 delta -= 2;
755 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
756 // add new padding
757 BBSizes[i] += 2;
758 delta += 2;
759 }
760 }
761 if (delta==0)
762 return;
763 }
764 MBBI = next(MBBI);
765 }
766 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000767}
768
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000769/// DecrementOldEntry - find the constant pool entry with index CPI
770/// and instruction CPEMI, and decrement its refcount. If the refcount
771/// becomes 0 remove the entry and instruction. Returns true if we removed
772/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000773
Evan Chenged884f32007-04-03 23:39:48 +0000774bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000775 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000776 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
777 assert(CPE && "Unexpected!");
778 if (--CPE->RefCount == 0) {
779 RemoveDeadCPEMI(CPEMI);
780 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000781 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000782 return true;
783 }
784 return false;
785}
786
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000787/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
788/// if not, see if an in-range clone of the CPE is in range, and if so,
789/// change the data structures so the user references the clone. Returns:
790/// 0 = no existing entry found
791/// 1 = entry found, and there were no code insertions or deletions
792/// 2 = entry found, and there were code insertions or deletions
793int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
794{
795 MachineInstr *UserMI = U.MI;
796 MachineInstr *CPEMI = U.CPEMI;
797
798 // Check to see if the CPE is already in-range.
Evan Cheng82020102007-07-10 22:00:16 +0000799 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
800 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000801 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000802 }
803
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000804 // No. Look for previously created clones of the CPE that are in range.
805 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
806 std::vector<CPEntry> &CPEs = CPEntries[CPI];
807 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
808 // We already tried this one
809 if (CPEs[i].CPEMI == CPEMI)
810 continue;
811 // Removing CPEs can leave empty entries, skip
812 if (CPEs[i].CPEMI == NULL)
813 continue;
814 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
815 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
816 // Point the CPUser node to the replacement
817 U.CPEMI = CPEs[i].CPEMI;
818 // Change the CPI in the instruction operand to refer to the clone.
819 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
820 if (UserMI->getOperand(j).isConstantPoolIndex()) {
821 UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
822 break;
823 }
824 // Adjust the refcount of the clone...
825 CPEs[i].RefCount++;
826 // ...and the original. If we didn't remove the old entry, none of the
827 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000828 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000829 }
830 }
831 return 0;
832}
833
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000834/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
835/// the specific unconditional branch instruction.
836static inline unsigned getUnconditionalBrDisp(int Opc) {
837 return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
838}
839
Dale Johannesen8593e412007-04-29 19:19:30 +0000840/// AcceptWater - Small amount of common code factored out of the following.
841
842MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
843 std::vector<MachineBasicBlock*>::iterator IP) {
844 DOUT << "found water in range\n";
845 // Remove the original WaterList entry; we want subsequent
846 // insertions in this vicinity to go after the one we're
847 // about to insert. This considerably reduces the number
848 // of times we have to move the same CPE more than once.
849 WaterList.erase(IP);
850 // CPE goes before following block (NewMBB).
851 return next(MachineFunction::iterator(WaterBB));
852}
853
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000854/// LookForWater - look for an existing entry in the WaterList in which
855/// we can place the CPE referenced from U so it's within range of U's MI.
856/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000857/// is set to the WaterList entry.
858/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
859/// water that will not introduce padding to water that will; within each
860/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000861
862bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000863 MachineBasicBlock** NewMBB) {
864 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
865 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000866 if (!WaterList.empty()) {
867 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
868 B = WaterList.begin();; --IP) {
869 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000870 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000871 if (isThumb &&
872 (BBOffsets[WaterBB->getNumber()] +
873 BBSizes[WaterBB->getNumber()])%4 != 0) {
874 // This is valid Water, but would introduce padding. Remember
875 // it in case we don't find any Water that doesn't do this.
876 if (!WaterBBThatWouldPad) {
877 WaterBBThatWouldPad = WaterBB;
878 IPThatWouldPad = IP;
879 }
880 } else {
881 *NewMBB = AcceptWater(WaterBB, IP);
882 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000883 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000884 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000885 if (IP == B)
886 break;
887 }
888 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000889 if (isThumb && WaterBBThatWouldPad) {
890 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
891 return true;
892 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000893 return false;
894}
895
896/// CreateNewWater - No existing WaterList entry will work for
897/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
898/// block is used if in range, and the conditional branch munged so control
899/// flow is correct. Otherwise the block is split to create a hole with an
900/// unconditional branch around it. In either case *NewMBB is set to a
901/// block following which the new island can be inserted (the WaterList
902/// is not adjusted).
903
904void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
905 unsigned UserOffset, MachineBasicBlock** NewMBB) {
906 CPUser &U = CPUsers[CPUserIndex];
907 MachineInstr *UserMI = U.MI;
908 MachineInstr *CPEMI = U.CPEMI;
909 MachineBasicBlock *UserMBB = UserMI->getParent();
910 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
911 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000912 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000913
914 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000915 // is within range, make new water there. (The addition below is
916 // for the unconditional branch we will be adding: 4 bytes on ARM,
917 // 2 on Thumb. Possible Thumb alignment padding is allowed for
918 // inside OffsetIsInRange.
919 // If the block ends in an unconditional branch already, it is water,
920 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000921 if (&UserMBB->back() == UserMI ||
Dale Johannesen8593e412007-04-29 19:19:30 +0000922 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
923 U.MaxDisp, !isThumb)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000924 DOUT << "Split at end of block\n";
925 if (&UserMBB->back() == UserMI)
926 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
927 *NewMBB = next(MachineFunction::iterator(UserMBB));
928 // Add an unconditional branch from UserMBB to fallthrough block.
929 // Record it for branch lengthening; this new branch will not get out of
930 // range, but if the preceding conditional branch is out of range, the
931 // targets will be exchanged, and the altered branch may be out of
932 // range, so the machinery has to know about it.
933 int UncondBr = isThumb ? ARM::tB : ARM::B;
934 BuildMI(UserMBB, TII->get(UncondBr)).addMBB(*NewMBB);
935 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
936 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
937 MaxDisp, false, UncondBr));
938 int delta = isThumb ? 2 : 4;
939 BBSizes[UserMBB->getNumber()] += delta;
940 AdjustBBOffsetsAfter(UserMBB, delta);
941 } else {
942 // What a big block. Find a place within the block to split it.
943 // This is a little tricky on Thumb since instructions are 2 bytes
944 // and constant pool entries are 4 bytes: if instruction I references
945 // island CPE, and instruction I+1 references CPE', it will
946 // not work well to put CPE as far forward as possible, since then
947 // CPE' cannot immediately follow it (that location is 2 bytes
948 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +0000949 // a new island. So, we make a first guess, then walk through the
950 // instructions between the one currently being looked at and the
951 // possible insertion point, and make sure any other instructions
952 // that reference CPEs will be able to use the same island area;
953 // if not, we back up the insertion point.
954
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000955 // The 4 in the following is for the unconditional branch we'll be
Dale Johannesen8593e412007-04-29 19:19:30 +0000956 // inserting (allows for long branch on Thumb). Alignment of the
957 // island is handled inside OffsetIsInRange.
958 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000959 // This could point off the end of the block if we've already got
960 // constant pool entries following this block; only the last one is
961 // in the water list. Back past any possible branches (allow for a
962 // conditional and a maximally long unconditional).
963 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
964 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
965 (isThumb ? 6 : 8);
966 unsigned EndInsertOffset = BaseInsertOffset +
967 CPEMI->getOperand(2).getImm();
968 MachineBasicBlock::iterator MI = UserMI;
969 ++MI;
970 unsigned CPUIndex = CPUserIndex+1;
971 for (unsigned Offset = UserOffset+ARM::GetInstSize(UserMI);
972 Offset < BaseInsertOffset;
973 Offset += ARM::GetInstSize(MI),
974 MI = next(MI)) {
975 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
976 if (!OffsetIsInRange(Offset, EndInsertOffset,
977 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
978 BaseInsertOffset -= (isThumb ? 2 : 4);
979 EndInsertOffset -= (isThumb ? 2 : 4);
980 }
981 // This is overly conservative, as we don't account for CPEMIs
982 // being reused within the block, but it doesn't matter much.
983 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
984 CPUIndex++;
985 }
986 }
987 DOUT << "Split in middle of big block\n";
988 *NewMBB = SplitBlockBeforeInstr(prior(MI));
989 }
990}
991
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000992/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
993/// is out-of-range. If so, pick it up the constant pool value and move it some
994/// place in-range. Return true if we changed any addresses (thus must run
995/// another pass of branch lengthening), false otherwise.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000996bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
997 unsigned CPUserIndex){
998 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000999 MachineInstr *UserMI = U.MI;
1000 MachineInstr *CPEMI = U.CPEMI;
1001 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
1002 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001003 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001004 // Compute this only once, it's expensive. The 4 or 8 is the value the
1005 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001006 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001007
Evan Cheng185ea1e2007-04-27 18:27:13 +00001008 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1009 // second instruction.
1010 if (UserMI->getOpcode() == ARM::tLEApcrel)
Evan Cheng768c9f72007-04-27 08:14:15 +00001011 UserOffset += 2;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001012
1013 // See if the current entry is within range, or there is a clone of it
1014 // in range.
1015 int result = LookForExistingCPEntry(U, UserOffset);
1016 if (result==1) return false;
1017 else if (result==2) return true;
1018
1019 // No existing clone of this CPE is within range.
1020 // We will be generating a new clone. Get a UID for it.
1021 unsigned ID = NextUID++;
1022
1023 // Look for water where we can place this CPE. We look for the farthest one
1024 // away that will work. Forward references only for now (although later
1025 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001026
Dale Johannesen8593e412007-04-29 19:19:30 +00001027 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001028 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001029 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001030 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001031 }
1032
1033 // Okay, we know we can put an island before NewMBB now, do it!
1034 MachineBasicBlock *NewIsland = new MachineBasicBlock();
1035 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
1036
1037 // Update internal data structures to account for the newly inserted MBB.
1038 UpdateForInsertedWaterBlock(NewIsland);
1039
1040 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001041 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001042
1043 // Now that we have an island to add the CPE to, clone the original CPE and
1044 // add it to the island.
Evan Chenga8e29892007-01-19 07:51:42 +00001045 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
1046 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001047 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001048 NumCPEs++;
1049
Dale Johannesen8593e412007-04-29 19:19:30 +00001050 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001051 // Compensate for .align 2 in thumb mode.
Dale Johannesen8593e412007-04-29 19:19:30 +00001052 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1053 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001054 // Increase the size of the island block to account for the new entry.
1055 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001056 AdjustBBOffsetsAfter(NewIsland, Size);
Evan Chenga8e29892007-01-19 07:51:42 +00001057
1058 // Finally, change the CPI in the instruction operand to be ID.
1059 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1060 if (UserMI->getOperand(i).isConstantPoolIndex()) {
1061 UserMI->getOperand(i).setConstantPoolIndex(ID);
1062 break;
1063 }
1064
Evan Chengc99ef082007-02-09 20:54:44 +00001065 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Evan Chenga8e29892007-01-19 07:51:42 +00001066
1067 return true;
1068}
1069
Evan Chenged884f32007-04-03 23:39:48 +00001070/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1071/// sizes and offsets of impacted basic blocks.
1072void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1073 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001074 unsigned Size = CPEMI->getOperand(2).getImm();
1075 CPEMI->eraseFromParent();
1076 BBSizes[CPEBB->getNumber()] -= Size;
1077 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001078 if (CPEBB->empty()) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001079 // In thumb mode, the size of island may be padded by two to compensate for
1080 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001081 // empty, so fix this.
1082 // All succeeding offsets have the current size value added in, fix this.
1083 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001084 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001085 BBSizes[CPEBB->getNumber()] = 0;
1086 }
Evan Chenged884f32007-04-03 23:39:48 +00001087 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001088 AdjustBBOffsetsAfter(CPEBB, -Size);
1089 // An island has only one predecessor BB and one successor BB. Check if
1090 // this BB's predecessor jumps directly to this BB's successor. This
1091 // shouldn't happen currently.
1092 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1093 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001094}
1095
1096/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1097/// are zero.
1098bool ARMConstantIslands::RemoveUnusedCPEntries() {
1099 unsigned MadeChange = false;
1100 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1101 std::vector<CPEntry> &CPEs = CPEntries[i];
1102 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1103 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1104 RemoveDeadCPEMI(CPEs[j].CPEMI);
1105 CPEs[j].CPEMI = NULL;
1106 MadeChange = true;
1107 }
1108 }
1109 }
1110 return MadeChange;
1111}
1112
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001113/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001114/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001115bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1116 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001117 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001118 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001119 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001120
Evan Chengc99ef082007-02-09 20:54:44 +00001121 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1122 << " from BB#" << MI->getParent()->getNumber()
1123 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001124 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1125 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001126
Dale Johannesen8593e412007-04-29 19:19:30 +00001127 if (BrOffset <= DestOffset) {
1128 // Branch before the Dest.
1129 if (DestOffset-BrOffset <= MaxDisp)
1130 return true;
1131 } else {
1132 if (BrOffset-DestOffset <= MaxDisp)
1133 return true;
1134 }
1135 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001136}
1137
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001138/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1139/// away to fit in its displacement field.
1140bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001141 MachineInstr *MI = Br.MI;
1142 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
1143
Evan Chengc0dbec72007-01-31 19:57:44 +00001144 // Check to see if the DestBB is already in-range.
1145 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001146 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001147
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001148 if (!Br.isCond)
1149 return FixUpUnconditionalBr(Fn, Br);
1150 return FixUpConditionalBr(Fn, Br);
1151}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001152
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001153/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1154/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001155/// spilled in the epilogue, then we can use BL to implement a far jump.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001156/// Otherwise, add an intermediate branch instruction to to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001157bool
1158ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1159 MachineInstr *MI = Br.MI;
1160 MachineBasicBlock *MBB = MI->getParent();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001161 assert(isThumb && "Expected a Thumb function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001162
1163 // Use BL to implement far jump.
1164 Br.MaxDisp = (1 << 21) * 2;
1165 MI->setInstrDescriptor(TII->get(ARM::tBfar));
1166 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001167 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001168 HasFarJump = true;
1169 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001170
Evan Chengc99ef082007-02-09 20:54:44 +00001171 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001172
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001173 return true;
1174}
1175
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001176/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001177/// far away to fit in its displacement field. It is converted to an inverse
1178/// conditional branch + an unconditional branch to the destination.
1179bool
1180ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1181 MachineInstr *MI = Br.MI;
1182 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
1183
1184 // Add a unconditional branch to the destination and invert the branch
1185 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001186 // blt L1
1187 // =>
1188 // bge L2
1189 // b L1
1190 // L2:
1191 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
1192 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001193 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001194
1195 // If the branch is at the end of its MBB and that has a fall-through block,
1196 // direct the updated conditional branch to the fall-through block. Otherwise,
1197 // split the MBB before the next instruction.
1198 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001199 MachineInstr *BMI = &MBB->back();
1200 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001201
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001202 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001203 if (BMI != MI) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001204 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001205 BMI->getOpcode() == Br.UncondBr) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001206 // Last MI in the BB is a unconditional branch. Can we simply invert the
1207 // condition and swap destinations:
1208 // beq L1
1209 // b L2
1210 // =>
1211 // bne L2
1212 // b L1
Evan Chengbd5d3db2007-02-03 02:08:34 +00001213 MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
Evan Chengc0dbec72007-01-31 19:57:44 +00001214 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001215 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001216 BMI->getOperand(0).setMachineBasicBlock(DestBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001217 MI->getOperand(0).setMachineBasicBlock(NewDest);
1218 MI->getOperand(1).setImm(CC);
1219 return true;
1220 }
1221 }
1222 }
1223
1224 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001225 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +00001226 // No need for the branch to the next block. We're adding a unconditional
1227 // branch to the destination.
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001228 int delta = ARM::GetInstSize(&MBB->back());
1229 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001230 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1231 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001232 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001233 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001234 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001235 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Evan Chengbd5d3db2007-02-03 02:08:34 +00001236
Evan Chengc99ef082007-02-09 20:54:44 +00001237 DOUT << " Insert B to BB#" << DestBB->getNumber()
1238 << " also invert condition and change dest. to BB#"
1239 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001240
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001241 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001242 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Cheng0e1d3792007-07-05 07:18:20 +00001243 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB)
1244 .addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001245 Br.MI = &MBB->back();
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001246 BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001247 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001248 BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001249 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001250 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001251
1252 // Remove the old conditional branch. It may or may not still be in MBB.
1253 BBSizes[MI->getParent()->getNumber()] -= ARM::GetInstSize(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001254 MI->eraseFromParent();
1255
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001256 // The net size change is an addition of one unconditional branch.
Dale Johannesen99c49a42007-02-25 00:47:03 +00001257 int delta = ARM::GetInstSize(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001258 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001259 return true;
1260}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001261
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001262/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1263/// LR / restores LR to pc.
1264bool ARMConstantIslands::UndoLRSpillRestore() {
1265 bool MadeChange = false;
1266 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1267 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001268 if (MI->getOpcode() == ARM::tPOP_RET &&
1269 MI->getOperand(0).getReg() == ARM::PC &&
1270 MI->getNumExplicitOperands() == 1) {
1271 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
1272 MI->eraseFromParent();
1273 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001274 }
1275 }
1276 return MadeChange;
1277}