blob: 1a547c61cf94479160abf9dc9c316e9b6c6a35b2 [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"
Torok Edwinc25e7582009-07-11 20:10:48 +000027#include "llvm/Support/ErrorHandling.h"
Evan Chengc99ef082007-02-09 20:54:44 +000028#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000029#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Statistic.h"
Evan Chenga8e29892007-01-19 07:51:42 +000031using namespace llvm;
32
Evan Chengc99ef082007-02-09 20:54:44 +000033STATISTIC(NumCPEs, "Number of constpool entries");
Evan Chengd1b2c1e2007-01-30 01:18:38 +000034STATISTIC(NumSplit, "Number of uncond branches inserted");
35STATISTIC(NumCBrFixed, "Number of cond branches fixed");
36STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Evan Chenga8e29892007-01-19 07:51:42 +000037
38namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000039 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000040 /// requires constant pool entries to be scattered among the instructions
41 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000042 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000043 /// special instructions.
44 ///
45 /// The terminology used in this pass includes:
46 /// Islands - Clumps of constants placed in the function.
47 /// Water - Potential places where an island could be formed.
48 /// CPE - A constant pool entry that has been placed somewhere, which
49 /// tracks a list of users.
50 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000051 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000052 /// by MBB Number. The two-byte pads required for Thumb alignment are
53 /// counted as part of the following block (i.e., the offset and size for
54 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000055 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000056
Dale Johannesen99c49a42007-02-25 00:47:03 +000057 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000058 /// The two-byte pads required for Thumb alignment are counted as part of
59 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000060 std::vector<unsigned> BBOffsets;
61
Evan Chenga8e29892007-01-19 07:51:42 +000062 /// WaterList - A sorted list of basic blocks where islands could be placed
63 /// (i.e. blocks that don't fall through to the following block, due
64 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000065 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000066
Evan Chenga8e29892007-01-19 07:51:42 +000067 /// CPUser - One user of a constant pool, keeping the machine instruction
68 /// pointer, the constant pool being referenced, and the max displacement
69 /// allowed from the instruction to the CP.
70 struct CPUser {
71 MachineInstr *MI;
72 MachineInstr *CPEMI;
73 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000074 bool NegOk;
75 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp, bool neg)
76 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg) {}
Evan Chenga8e29892007-01-19 07:51:42 +000077 };
Bob Wilson84945262009-05-12 17:09:30 +000078
Evan Chenga8e29892007-01-19 07:51:42 +000079 /// CPUsers - Keep track of all of the machine instructions that use various
80 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000081 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +000082
Evan Chengc99ef082007-02-09 20:54:44 +000083 /// CPEntry - One per constant pool entry, keeping the machine instruction
84 /// pointer, the constpool index, and the number of CPUser's which
85 /// reference this entry.
86 struct CPEntry {
87 MachineInstr *CPEMI;
88 unsigned CPI;
89 unsigned RefCount;
90 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
91 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
92 };
93
94 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +000095 /// instructions. For each original constpool index (i.e. those that
96 /// existed upon entry to this pass), it keeps a vector of entries.
97 /// Original elements are cloned as we go along; the clones are
98 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +000099 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000100
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000101 /// ImmBranch - One per immediate branch, keeping the machine instruction
102 /// pointer, conditional or unconditional, the max displacement,
103 /// and (if isCond is true) the corresponding unconditional branch
104 /// opcode.
105 struct ImmBranch {
106 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000107 unsigned MaxDisp : 31;
108 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000109 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000110 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
111 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000112 };
113
Evan Cheng2706f972007-05-16 05:14:06 +0000114 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000115 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000116 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000117
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000118 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
119 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000120 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000121
122 /// HasFarJump - True if any far jump instruction has been emitted during
123 /// the branch fix up pass.
124 bool HasFarJump;
125
Evan Chenga8e29892007-01-19 07:51:42 +0000126 const TargetInstrInfo *TII;
Dale Johannesen8593e412007-04-29 19:19:30 +0000127 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000128 bool isThumb;
David Goodwinf1daf7d2009-07-08 23:10:31 +0000129 bool isThumb1Only;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000130 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000131 public:
Devang Patel19974732007-05-03 01:11:54 +0000132 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000133 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000134
Evan Chenga8e29892007-01-19 07:51:42 +0000135 virtual bool runOnMachineFunction(MachineFunction &Fn);
136
137 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000138 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000139 }
Bob Wilson84945262009-05-12 17:09:30 +0000140
Evan Chenga8e29892007-01-19 07:51:42 +0000141 private:
142 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000143 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000144 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000145 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000146 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000147 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000148 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000149 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000150 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000151 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000152 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000153 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000154 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000155 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000156 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
157 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000158 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000159 void RemoveDeadCPEMI(MachineInstr *CPEMI);
160 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000161 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000162 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
163 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000164 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000165 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000166 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
167 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000168 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000169 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
170 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
171 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
172 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000173
Evan Chenga8e29892007-01-19 07:51:42 +0000174 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000175 void dumpBBs();
176 void verify(MachineFunction &Fn);
Evan Chenga8e29892007-01-19 07:51:42 +0000177 };
Devang Patel19974732007-05-03 01:11:54 +0000178 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000179}
180
Dale Johannesen8593e412007-04-29 19:19:30 +0000181/// verify - check BBOffsets, BBSizes, alignment of islands
182void ARMConstantIslands::verify(MachineFunction &Fn) {
183 assert(BBOffsets.size() == BBSizes.size());
184 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
185 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
186 if (isThumb) {
187 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
188 MBBI != E; ++MBBI) {
189 MachineBasicBlock *MBB = MBBI;
190 if (!MBB->empty() &&
191 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
192 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
193 BBSizes[MBB->getNumber()]%4 == 0) ||
194 (BBOffsets[MBB->getNumber()]%4 != 0 &&
195 BBSizes[MBB->getNumber()]%4 != 0));
196 }
197 }
198}
199
200/// print block size and offset information - debugging
201void ARMConstantIslands::dumpBBs() {
202 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000203 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000204 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000205 }
206}
207
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000208/// createARMConstantIslandPass - returns an instance of the constpool
209/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000210FunctionPass *llvm::createARMConstantIslandPass() {
211 return new ARMConstantIslands();
212}
213
214bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000215 MachineConstantPool &MCP = *Fn.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000216
Evan Chenga8e29892007-01-19 07:51:42 +0000217 TII = Fn.getTarget().getInstrInfo();
Dale Johannesen8593e412007-04-29 19:19:30 +0000218 AFI = Fn.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000219 isThumb = AFI->isThumbFunction();
David Goodwinf1daf7d2009-07-08 23:10:31 +0000220 isThumb1Only = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000221 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000222
223 HasFarJump = false;
224
Evan Chenga8e29892007-01-19 07:51:42 +0000225 // Renumber all of the machine basic blocks in the function, guaranteeing that
226 // the numbers agree with the position of the block in the function.
227 Fn.RenumberBlocks();
228
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000229 /// Thumb1 functions containing constant pools get 2-byte alignment.
Bob Wilson84945262009-05-12 17:09:30 +0000230 /// This is so we can keep exact track of where the alignment padding goes.
231 /// Set default.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000232 AFI->setAlign(isThumb1Only ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000233
Evan Chenga8e29892007-01-19 07:51:42 +0000234 // Perform the initial placement of the constant pool entries. To start with,
235 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000236 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000237 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000238 DoInitialPlacement(Fn, CPEMIs);
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000239 if (isThumb1Only)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000240 AFI->setAlign(2U);
241 }
Bob Wilson84945262009-05-12 17:09:30 +0000242
Evan Chenga8e29892007-01-19 07:51:42 +0000243 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000244 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000245
Evan Chenga8e29892007-01-19 07:51:42 +0000246 // Do the initial scan of the function, building up information about the
247 // sizes of each block, the location of all the water, and finding all of the
248 // constant pool users.
249 InitialFunctionScan(Fn, CPEMIs);
250 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000251
Evan Chenged884f32007-04-03 23:39:48 +0000252 /// Remove dead constant pool entries.
253 RemoveUnusedCPEntries();
254
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000255 // Iteratively place constant pool entries and fix up branches until there
256 // is no change.
257 bool MadeChange = false;
258 while (true) {
259 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000260 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000261 Change |= HandleConstantPoolUser(Fn, i);
Evan Cheng82020102007-07-10 22:00:16 +0000262 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000263 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000264 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000265 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000266 if (!Change)
267 break;
268 MadeChange = true;
269 }
Evan Chenged884f32007-04-03 23:39:48 +0000270
Dale Johannesen8593e412007-04-29 19:19:30 +0000271 // After a while, this might be made debug-only, but it is not expensive.
272 verify(Fn);
273
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000274 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
275 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000276 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000277 MadeChange |= UndoLRSpillRestore();
278
Evan Chenga8e29892007-01-19 07:51:42 +0000279 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000280 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000281 WaterList.clear();
282 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000283 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000284 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000285 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000286
287 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000288}
289
290/// DoInitialPlacement - Perform the initial placement of the constant pool
291/// entries. To start with, we put them all at the end of the function.
292void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Bob Wilson84945262009-05-12 17:09:30 +0000293 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000294 // Create the basic block to hold the CPE's.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000295 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
296 Fn.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000297
Evan Chenga8e29892007-01-19 07:51:42 +0000298 // Add all of the constants from the constant pool to the end block, use an
299 // identity mapping of CPI's to CPE's.
300 const std::vector<MachineConstantPoolEntry> &CPs =
301 Fn.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000302
Evan Chenga8e29892007-01-19 07:51:42 +0000303 const TargetData &TD = *Fn.getTarget().getTargetData();
304 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000305 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000306 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
307 // we would have to pad them out or something so that instructions stay
308 // aligned.
309 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
310 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000311 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000312 .addImm(i).addConstantPoolIndex(i).addImm(Size);
313 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000314
315 // Add a new CPEntry, but no corresponding CPUser yet.
316 std::vector<CPEntry> CPEs;
317 CPEs.push_back(CPEntry(CPEMI, i));
318 CPEntries.push_back(CPEs);
319 NumCPEs++;
320 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000321 }
322}
323
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000324/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000325/// into the block immediately after it.
326static bool BBHasFallthrough(MachineBasicBlock *MBB) {
327 // Get the next machine basic block in the function.
328 MachineFunction::iterator MBBI = MBB;
329 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
330 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000331
Evan Chenga8e29892007-01-19 07:51:42 +0000332 MachineBasicBlock *NextBB = next(MBBI);
333 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
334 E = MBB->succ_end(); I != E; ++I)
335 if (*I == NextBB)
336 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000337
Evan Chenga8e29892007-01-19 07:51:42 +0000338 return false;
339}
340
Evan Chengc99ef082007-02-09 20:54:44 +0000341/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
342/// look up the corresponding CPEntry.
343ARMConstantIslands::CPEntry
344*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
345 const MachineInstr *CPEMI) {
346 std::vector<CPEntry> &CPEs = CPEntries[CPI];
347 // Number of entries per constpool index should be small, just do a
348 // linear search.
349 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
350 if (CPEs[i].CPEMI == CPEMI)
351 return &CPEs[i];
352 }
353 return NULL;
354}
355
Evan Chenga8e29892007-01-19 07:51:42 +0000356/// InitialFunctionScan - Do the initial scan of the function, building up
357/// information about the sizes of each block, the location of all the water,
358/// and finding all of the constant pool users.
359void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000360 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000361 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000362 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
363 MBBI != E; ++MBBI) {
364 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000365
Evan Chenga8e29892007-01-19 07:51:42 +0000366 // If this block doesn't fall through into the next MBB, then this is
367 // 'water' that a constant pool island could be placed.
368 if (!BBHasFallthrough(&MBB))
369 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000370
Evan Chenga8e29892007-01-19 07:51:42 +0000371 unsigned MBBSize = 0;
372 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
373 I != E; ++I) {
374 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000375 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000376
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000377 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000378 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000379 bool isCond = false;
380 unsigned Bits = 0;
381 unsigned Scale = 1;
382 int UOpc = Opc;
383 switch (Opc) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000384 case ARM::tBR_JTr:
David Goodwin5e47a9a2009-06-30 18:04:13 +0000385 case ARM::t2BR_JTr:
David Goodwinc9a59b52009-06-30 19:50:22 +0000386 case ARM::t2BR_JTm:
387 case ARM::t2BR_JTadd:
Dale Johannesen8593e412007-04-29 19:19:30 +0000388 // A Thumb table jump may involve padding; for the offsets to
389 // be right, functions containing these must be 4-byte aligned.
390 AFI->setAlign(2U);
391 if ((Offset+MBBSize)%4 != 0)
392 MBBSize += 2; // padding
393 continue; // Does not get an entry in ImmBranches
Evan Cheng743fa032007-01-25 19:43:52 +0000394 default:
Dale Johannesen8593e412007-04-29 19:19:30 +0000395 continue; // Ignore other JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000396 case ARM::Bcc:
397 isCond = true;
398 UOpc = ARM::B;
399 // Fallthrough
400 case ARM::B:
401 Bits = 24;
402 Scale = 4;
403 break;
404 case ARM::tBcc:
405 isCond = true;
406 UOpc = ARM::tB;
407 Bits = 8;
408 Scale = 2;
409 break;
410 case ARM::tB:
411 Bits = 11;
412 Scale = 2;
413 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000414 case ARM::t2Bcc:
415 isCond = true;
416 UOpc = ARM::t2B;
417 Bits = 20;
418 Scale = 2;
419 break;
420 case ARM::t2B:
421 Bits = 24;
422 Scale = 2;
423 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000424 }
Evan Chengb43216e2007-02-01 10:16:15 +0000425
426 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000427 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000428 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000429 }
430
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000431 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
432 PushPopMIs.push_back(I);
433
Evan Chenga8e29892007-01-19 07:51:42 +0000434 // Scan the instructions for constant pool operands.
435 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000436 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000437 // We found one. The addressing mode tells us the max displacement
438 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000439
Evan Chenga8e29892007-01-19 07:51:42 +0000440 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000441 unsigned Bits = 0;
442 unsigned Scale = 1;
Chris Lattner749c6f62008-01-07 07:27:27 +0000443 unsigned TSFlags = I->getDesc().TSFlags;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000444 bool NegOk = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000445 switch (TSFlags & ARMII::AddrModeMask) {
Bob Wilson84945262009-05-12 17:09:30 +0000446 default:
Evan Chenga8e29892007-01-19 07:51:42 +0000447 // Constant pool entries can reach anything.
448 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
449 continue;
Evan Cheng768c9f72007-04-27 08:14:15 +0000450 if (I->getOpcode() == ARM::tLEApcrel) {
451 Bits = 8; // Taking the address of a CP entry.
452 break;
453 }
Torok Edwinc23197a2009-07-14 16:55:14 +0000454 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000455 case ARMII::AddrMode1: // AM1: 8 bits << 2 - FIXME: this is wrong?
Evan Chengb43216e2007-02-01 10:16:15 +0000456 Bits = 8;
457 Scale = 4; // Taking the address of a CP entry.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000458 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000459 break;
460 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000461 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000462 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000463 break;
464 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000465 Bits = 8; // +-offset_8
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000466 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000467 break;
468 // addrmode4 has no immediate offset.
469 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000470 Bits = 8;
471 Scale = 4; // +-(offset_8*4)
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000472 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000473 break;
Bob Wilson8b024a52009-07-01 23:16:05 +0000474 // addrmode6 has no immediate offset.
Evan Cheng055b0312009-06-29 07:51:04 +0000475 case ARMII::AddrModeT1_1:
Evan Chengb43216e2007-02-01 10:16:15 +0000476 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000477 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000478 case ARMII::AddrModeT1_2:
Evan Chengb43216e2007-02-01 10:16:15 +0000479 Bits = 5;
480 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000481 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000482 case ARMII::AddrModeT1_4:
Evan Chengb43216e2007-02-01 10:16:15 +0000483 Bits = 5;
484 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000485 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000486 case ARMII::AddrModeT1_s:
Evan Chengb43216e2007-02-01 10:16:15 +0000487 Bits = 8;
488 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000489 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000490 case ARMII::AddrModeT2_pc:
491 Bits = 12; // +-offset_12
492 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000493 }
Evan Chengb43216e2007-02-01 10:16:15 +0000494
Evan Chenga8e29892007-01-19 07:51:42 +0000495 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000496 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000497 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilson84945262009-05-12 17:09:30 +0000498 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000499 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk));
Evan Chengc99ef082007-02-09 20:54:44 +0000500
501 // Increment corresponding CPEntry reference count.
502 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
503 assert(CPE && "Cannot find a corresponding CPEntry!");
504 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000505
Evan Chenga8e29892007-01-19 07:51:42 +0000506 // Instructions can only use one CP entry, don't bother scanning the
507 // rest of the operands.
508 break;
509 }
510 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000511
Dale Johannesen8593e412007-04-29 19:19:30 +0000512 // In thumb mode, if this block is a constpool island, we may need padding
513 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000514 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000515 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000516 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
517 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000518 MBBSize += 2;
519
Evan Chenga8e29892007-01-19 07:51:42 +0000520 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000521 BBOffsets.push_back(Offset);
522 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000523 }
524}
525
Evan Chenga8e29892007-01-19 07:51:42 +0000526/// GetOffsetOf - Return the current offset of the specified machine instruction
527/// from the start of the function. This offset changes as stuff is moved
528/// around inside the function.
529unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
530 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000531
Evan Chenga8e29892007-01-19 07:51:42 +0000532 // The offset is composed of two things: the sum of the sizes of all MBB's
533 // before this instruction's block, and the offset from the start of the block
534 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000535 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000536
Dale Johannesen8593e412007-04-29 19:19:30 +0000537 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
538 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000539 if (isThumb &&
540 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000541 Offset%4 != 0)
542 Offset += 2;
543
Evan Chenga8e29892007-01-19 07:51:42 +0000544 // Sum instructions before MI in MBB.
545 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
546 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
547 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000548 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000549 }
550}
551
552/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
553/// ID.
554static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
555 const MachineBasicBlock *RHS) {
556 return LHS->getNumber() < RHS->getNumber();
557}
558
559/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
560/// machine function, it upsets all of the block numbers. Renumber the blocks
561/// and update the arrays that parallel this numbering.
562void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
563 // Renumber the MBB's to keep them consequtive.
564 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000565
Evan Chenga8e29892007-01-19 07:51:42 +0000566 // Insert a size into BBSizes to align it properly with the (newly
567 // renumbered) block numbers.
568 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000569
570 // Likewise for BBOffsets.
571 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000572
573 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000574 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000575 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000576 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
577 CompareMBBNumbers);
578 WaterList.insert(IP, NewBB);
579}
580
581
582/// Split the basic block containing MI into two blocks, which are joined by
583/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000584/// account for this change and returns the newly created block.
585MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000586 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000587 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000588
589 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000590 MachineBasicBlock *NewBB =
591 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000592 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000593 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000594
Evan Chenga8e29892007-01-19 07:51:42 +0000595 // Splice the instructions starting with MI over to NewBB.
596 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000597
Evan Chenga8e29892007-01-19 07:51:42 +0000598 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000599 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000600 // There doesn't seem to be meaningful DebugInfo available; this doesn't
601 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000602 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
603 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000604 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000605
Evan Chenga8e29892007-01-19 07:51:42 +0000606 // Update the CFG. All succs of OrigBB are now succs of NewBB.
607 while (!OrigBB->succ_empty()) {
608 MachineBasicBlock *Succ = *OrigBB->succ_begin();
609 OrigBB->removeSuccessor(Succ);
610 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000611
Evan Chenga8e29892007-01-19 07:51:42 +0000612 // This pass should be run after register allocation, so there should be no
613 // PHI nodes to update.
614 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
615 && "PHI nodes should be eliminated by now!");
616 }
Bob Wilson84945262009-05-12 17:09:30 +0000617
Evan Chenga8e29892007-01-19 07:51:42 +0000618 // OrigBB branches to NewBB.
619 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000620
Evan Chenga8e29892007-01-19 07:51:42 +0000621 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000622 // This is almost the same as UpdateForInsertedWaterBlock, except that
623 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000624 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000625
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000626 // Insert a size into BBSizes to align it properly with the (newly
627 // renumbered) block numbers.
628 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000629
Dale Johannesen99c49a42007-02-25 00:47:03 +0000630 // Likewise for BBOffsets.
631 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
632
Bob Wilson84945262009-05-12 17:09:30 +0000633 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000634 // available water after it (but not if it's already there, which happens
635 // when splitting before a conditional branch that is followed by an
636 // unconditional branch - in that case we want to insert NewBB).
637 std::vector<MachineBasicBlock*>::iterator IP =
638 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
639 CompareMBBNumbers);
640 MachineBasicBlock* WaterBB = *IP;
641 if (WaterBB == OrigBB)
642 WaterList.insert(next(IP), NewBB);
643 else
644 WaterList.insert(IP, OrigBB);
645
Dale Johannesen8593e412007-04-29 19:19:30 +0000646 // Figure out how large the first NewMBB is. (It cannot
647 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000648 unsigned NewBBSize = 0;
649 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
650 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000651 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000652
Dale Johannesen99c49a42007-02-25 00:47:03 +0000653 unsigned OrigBBI = OrigBB->getNumber();
654 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000655 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000656 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000657
Evan Chenga8e29892007-01-19 07:51:42 +0000658 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000659 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000660 unsigned delta = isThumb1Only ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000661 BBSizes[OrigBBI] -= NewBBSize - delta;
662
663 // ...and adjust BBOffsets for NewBB accordingly.
664 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
665
666 // All BBOffsets following these blocks must be modified.
667 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000668
669 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000670}
671
Dale Johannesen8593e412007-04-29 19:19:30 +0000672/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000673/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000674/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000675bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000676 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Bob Wilson84945262009-05-12 17:09:30 +0000677 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
678 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000679 // Effectively, the valid range of displacements is 2 bytes smaller for such
680 // references.
681 if (isThumb && UserOffset%4 !=0)
682 UserOffset -= 2;
683 // CPEs will be rounded up to a multiple of 4.
684 if (isThumb && TrialOffset%4 != 0)
685 TrialOffset += 2;
686
Dale Johannesen99c49a42007-02-25 00:47:03 +0000687 if (UserOffset <= TrialOffset) {
688 // User before the Trial.
689 if (TrialOffset-UserOffset <= MaxDisp)
690 return true;
691 } else if (NegativeOK) {
692 if (UserOffset-TrialOffset <= MaxDisp)
693 return true;
694 }
695 return false;
696}
697
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000698/// WaterIsInRange - Returns true if a CPE placed after the specified
699/// Water (a basic block) will be in range for the specific MI.
700
701bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000702 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000703 unsigned MaxDisp = U.MaxDisp;
Dale Johannesen8593e412007-04-29 19:19:30 +0000704 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Bob Wilson84945262009-05-12 17:09:30 +0000705 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000706 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000707
Dale Johannesend959aa42007-04-02 20:31:06 +0000708 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000709 // the offset of the instruction. (Currently applies only to ARM, so
710 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000711 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000712 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000713
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000714 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000715}
716
717/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000718/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000719bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000720 MachineInstr *CPEMI, unsigned MaxDisp,
721 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000722 unsigned CPEOffset = GetOffsetOf(CPEMI);
723 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000724
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000725 if (DoDump) {
726 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
727 << " max delta=" << MaxDisp
728 << " insn address=" << UserOffset
729 << " CPE address=" << CPEOffset
730 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
731 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000732
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000733 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000734}
735
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000736#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000737/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
738/// unconditionally branches to its only successor.
739static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
740 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
741 return false;
742
743 MachineBasicBlock *Succ = *MBB->succ_begin();
744 MachineBasicBlock *Pred = *MBB->pred_begin();
745 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000746 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
747 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000748 return PredMI->getOperand(0).getMBB() == Succ;
749 return false;
750}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000751#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000752
Bob Wilson84945262009-05-12 17:09:30 +0000753void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000754 int delta) {
755 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
756 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000757 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000758 // If some existing blocks have padding, adjust the padding as needed, a
759 // bit tricky. delta can be negative so don't use % on that.
760 if (isThumb) {
761 MachineBasicBlock *MBB = MBBI;
762 if (!MBB->empty()) {
763 // Constant pool entries require padding.
764 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
765 unsigned oldOffset = BBOffsets[i] - delta;
766 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
767 // add new padding
768 BBSizes[i] += 2;
769 delta += 2;
770 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
771 // remove existing padding
772 BBSizes[i] -=2;
773 delta -= 2;
774 }
775 }
Dale Johannesen66a2a8f2007-07-12 16:45:35 +0000776 // Thumb jump tables require padding. They should be at the end;
777 // following unconditional branches are removed by AnalyzeBranch.
Dale Johannesen8593e412007-04-29 19:19:30 +0000778 MachineInstr *ThumbJTMI = NULL;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000779 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
David Goodwinc9a59b52009-06-30 19:50:22 +0000780 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
781 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
782 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
Dale Johannesen8593e412007-04-29 19:19:30 +0000783 ThumbJTMI = prior(MBB->end());
Dale Johannesen8593e412007-04-29 19:19:30 +0000784 if (ThumbJTMI) {
785 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
786 unsigned oldMIOffset = newMIOffset - delta;
787 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
788 // remove existing padding
789 BBSizes[i] -= 2;
790 delta -= 2;
791 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
792 // add new padding
793 BBSizes[i] += 2;
794 delta += 2;
795 }
796 }
797 if (delta==0)
798 return;
799 }
800 MBBI = next(MBBI);
801 }
802 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000803}
804
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000805/// DecrementOldEntry - find the constant pool entry with index CPI
806/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000807/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000808/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000809
Evan Chenged884f32007-04-03 23:39:48 +0000810bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000811 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000812 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
813 assert(CPE && "Unexpected!");
814 if (--CPE->RefCount == 0) {
815 RemoveDeadCPEMI(CPEMI);
816 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000817 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000818 return true;
819 }
820 return false;
821}
822
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000823/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
824/// if not, see if an in-range clone of the CPE is in range, and if so,
825/// change the data structures so the user references the clone. Returns:
826/// 0 = no existing entry found
827/// 1 = entry found, and there were no code insertions or deletions
828/// 2 = entry found, and there were code insertions or deletions
829int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
830{
831 MachineInstr *UserMI = U.MI;
832 MachineInstr *CPEMI = U.CPEMI;
833
834 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000835 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Evan Cheng82020102007-07-10 22:00:16 +0000836 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000837 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000838 }
839
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000840 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000841 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000842 std::vector<CPEntry> &CPEs = CPEntries[CPI];
843 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
844 // We already tried this one
845 if (CPEs[i].CPEMI == CPEMI)
846 continue;
847 // Removing CPEs can leave empty entries, skip
848 if (CPEs[i].CPEMI == NULL)
849 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000850 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000851 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
852 // Point the CPUser node to the replacement
853 U.CPEMI = CPEs[i].CPEMI;
854 // Change the CPI in the instruction operand to refer to the clone.
855 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000856 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000857 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000858 break;
859 }
860 // Adjust the refcount of the clone...
861 CPEs[i].RefCount++;
862 // ...and the original. If we didn't remove the old entry, none of the
863 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000864 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000865 }
866 }
867 return 0;
868}
869
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000870/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
871/// the specific unconditional branch instruction.
872static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000873 switch (Opc) {
874 case ARM::tB:
875 return ((1<<10)-1)*2;
876 case ARM::t2B:
877 return ((1<<23)-1)*2;
878 default:
879 break;
880 }
881
882 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000883}
884
Dale Johannesen8593e412007-04-29 19:19:30 +0000885/// AcceptWater - Small amount of common code factored out of the following.
886
Bob Wilson84945262009-05-12 17:09:30 +0000887MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000888 std::vector<MachineBasicBlock*>::iterator IP) {
889 DOUT << "found water in range\n";
890 // Remove the original WaterList entry; we want subsequent
891 // insertions in this vicinity to go after the one we're
892 // about to insert. This considerably reduces the number
893 // of times we have to move the same CPE more than once.
894 WaterList.erase(IP);
895 // CPE goes before following block (NewMBB).
896 return next(MachineFunction::iterator(WaterBB));
897}
898
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000899/// LookForWater - look for an existing entry in the WaterList in which
900/// we can place the CPE referenced from U so it's within range of U's MI.
901/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000902/// is set to the WaterList entry.
903/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
904/// water that will not introduce padding to water that will; within each
905/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000906
907bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000908 MachineBasicBlock** NewMBB) {
909 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
910 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000911 if (!WaterList.empty()) {
912 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
913 B = WaterList.begin();; --IP) {
914 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000915 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000916 if (isThumb &&
Bob Wilson84945262009-05-12 17:09:30 +0000917 (BBOffsets[WaterBB->getNumber()] +
Dale Johannesen8593e412007-04-29 19:19:30 +0000918 BBSizes[WaterBB->getNumber()])%4 != 0) {
919 // This is valid Water, but would introduce padding. Remember
920 // it in case we don't find any Water that doesn't do this.
921 if (!WaterBBThatWouldPad) {
922 WaterBBThatWouldPad = WaterBB;
923 IPThatWouldPad = IP;
924 }
925 } else {
926 *NewMBB = AcceptWater(WaterBB, IP);
927 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000928 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000929 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000930 if (IP == B)
931 break;
932 }
933 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000934 if (isThumb && WaterBBThatWouldPad) {
935 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
936 return true;
937 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000938 return false;
939}
940
Bob Wilson84945262009-05-12 17:09:30 +0000941/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000942/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
943/// block is used if in range, and the conditional branch munged so control
944/// flow is correct. Otherwise the block is split to create a hole with an
945/// unconditional branch around it. In either case *NewMBB is set to a
946/// block following which the new island can be inserted (the WaterList
947/// is not adjusted).
948
Bob Wilson84945262009-05-12 17:09:30 +0000949void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000950 unsigned UserOffset, MachineBasicBlock** NewMBB) {
951 CPUser &U = CPUsers[CPUserIndex];
952 MachineInstr *UserMI = U.MI;
953 MachineInstr *CPEMI = U.CPEMI;
954 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000955 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000956 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000957 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000958
959 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000960 // is within range, make new water there. (The addition below is
961 // for the unconditional branch we will be adding: 4 bytes on ARM,
962 // 2 on Thumb. Possible Thumb alignment padding is allowed for
963 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000964 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000965 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000966 if (&UserMBB->back() == UserMI ||
Dale Johannesen8593e412007-04-29 19:19:30 +0000967 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
968 U.MaxDisp, !isThumb)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000969 DOUT << "Split at end of block\n";
970 if (&UserMBB->back() == UserMI)
971 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
972 *NewMBB = next(MachineFunction::iterator(UserMBB));
973 // Add an unconditional branch from UserMBB to fallthrough block.
974 // Record it for branch lengthening; this new branch will not get out of
975 // range, but if the preceding conditional branch is out of range, the
976 // targets will be exchanged, and the altered branch may be out of
977 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +0000978 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +0000979 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
980 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000981 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +0000982 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000983 MaxDisp, false, UncondBr));
984 int delta = isThumb ? 2 : 4;
985 BBSizes[UserMBB->getNumber()] += delta;
986 AdjustBBOffsetsAfter(UserMBB, delta);
987 } else {
988 // What a big block. Find a place within the block to split it.
989 // This is a little tricky on Thumb since instructions are 2 bytes
990 // and constant pool entries are 4 bytes: if instruction I references
991 // island CPE, and instruction I+1 references CPE', it will
992 // not work well to put CPE as far forward as possible, since then
993 // CPE' cannot immediately follow it (that location is 2 bytes
994 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +0000995 // a new island. So, we make a first guess, then walk through the
996 // instructions between the one currently being looked at and the
997 // possible insertion point, and make sure any other instructions
998 // that reference CPEs will be able to use the same island area;
999 // if not, we back up the insertion point.
1000
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001001 // The 4 in the following is for the unconditional branch we'll be
Dale Johannesen8593e412007-04-29 19:19:30 +00001002 // inserting (allows for long branch on Thumb). Alignment of the
1003 // island is handled inside OffsetIsInRange.
1004 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001005 // This could point off the end of the block if we've already got
1006 // constant pool entries following this block; only the last one is
1007 // in the water list. Back past any possible branches (allow for a
1008 // conditional and a maximally long unconditional).
1009 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001010 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001011 (isThumb ? 6 : 8);
1012 unsigned EndInsertOffset = BaseInsertOffset +
1013 CPEMI->getOperand(2).getImm();
1014 MachineBasicBlock::iterator MI = UserMI;
1015 ++MI;
1016 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001017 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001018 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001019 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001020 MI = next(MI)) {
1021 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Bob Wilson84945262009-05-12 17:09:30 +00001022 if (!OffsetIsInRange(Offset, EndInsertOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001023 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1024 BaseInsertOffset -= (isThumb ? 2 : 4);
1025 EndInsertOffset -= (isThumb ? 2 : 4);
1026 }
1027 // This is overly conservative, as we don't account for CPEMIs
1028 // being reused within the block, but it doesn't matter much.
1029 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1030 CPUIndex++;
1031 }
1032 }
1033 DOUT << "Split in middle of big block\n";
1034 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1035 }
1036}
1037
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001038/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001039/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001040/// place in-range. Return true if we changed any addresses (thus must run
1041/// another pass of branch lengthening), false otherwise.
Bob Wilson84945262009-05-12 17:09:30 +00001042bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1043 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001044 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001045 MachineInstr *UserMI = U.MI;
1046 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001047 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001048 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001049 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001050 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilson39bf0512009-05-12 17:35:29 +00001051 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001052 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001053
Evan Cheng185ea1e2007-04-27 18:27:13 +00001054 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1055 // second instruction.
1056 if (UserMI->getOpcode() == ARM::tLEApcrel)
Evan Cheng768c9f72007-04-27 08:14:15 +00001057 UserOffset += 2;
Bob Wilson84945262009-05-12 17:09:30 +00001058
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001059 // See if the current entry is within range, or there is a clone of it
1060 // in range.
1061 int result = LookForExistingCPEntry(U, UserOffset);
1062 if (result==1) return false;
1063 else if (result==2) return true;
1064
1065 // No existing clone of this CPE is within range.
1066 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001067 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001068
1069 // Look for water where we can place this CPE. We look for the farthest one
1070 // away that will work. Forward references only for now (although later
1071 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001072
Dale Johannesen8593e412007-04-29 19:19:30 +00001073 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001074 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001075 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001076 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001077 }
1078
1079 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001080 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1081 Fn.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001082
1083 // Update internal data structures to account for the newly inserted MBB.
1084 UpdateForInsertedWaterBlock(NewIsland);
1085
1086 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001087 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001088
1089 // Now that we have an island to add the CPE to, clone the original CPE and
1090 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001091 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1092 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001093 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001094 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001095 NumCPEs++;
1096
Dale Johannesen8593e412007-04-29 19:19:30 +00001097 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001098 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001099 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001100 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001101 // Increase the size of the island block to account for the new entry.
1102 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001103 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001104
Evan Chenga8e29892007-01-19 07:51:42 +00001105 // Finally, change the CPI in the instruction operand to be ID.
1106 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001107 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001108 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001109 break;
1110 }
Bob Wilson84945262009-05-12 17:09:30 +00001111
Evan Chengc99ef082007-02-09 20:54:44 +00001112 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001113
Evan Chenga8e29892007-01-19 07:51:42 +00001114 return true;
1115}
1116
Evan Chenged884f32007-04-03 23:39:48 +00001117/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1118/// sizes and offsets of impacted basic blocks.
1119void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1120 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001121 unsigned Size = CPEMI->getOperand(2).getImm();
1122 CPEMI->eraseFromParent();
1123 BBSizes[CPEBB->getNumber()] -= Size;
1124 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001125 if (CPEBB->empty()) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001126 // In thumb mode, the size of island may be padded by two to compensate for
1127 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001128 // empty, so fix this.
1129 // All succeeding offsets have the current size value added in, fix this.
1130 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001131 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001132 BBSizes[CPEBB->getNumber()] = 0;
1133 }
Evan Chenged884f32007-04-03 23:39:48 +00001134 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001135 AdjustBBOffsetsAfter(CPEBB, -Size);
1136 // An island has only one predecessor BB and one successor BB. Check if
1137 // this BB's predecessor jumps directly to this BB's successor. This
1138 // shouldn't happen currently.
1139 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1140 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001141}
1142
1143/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1144/// are zero.
1145bool ARMConstantIslands::RemoveUnusedCPEntries() {
1146 unsigned MadeChange = false;
1147 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1148 std::vector<CPEntry> &CPEs = CPEntries[i];
1149 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1150 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1151 RemoveDeadCPEMI(CPEs[j].CPEMI);
1152 CPEs[j].CPEMI = NULL;
1153 MadeChange = true;
1154 }
1155 }
Bob Wilson84945262009-05-12 17:09:30 +00001156 }
Evan Chenged884f32007-04-03 23:39:48 +00001157 return MadeChange;
1158}
1159
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001160/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001161/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001162bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1163 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001164 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001165 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001166 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001167
Evan Chengc99ef082007-02-09 20:54:44 +00001168 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1169 << " from BB#" << MI->getParent()->getNumber()
1170 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001171 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1172 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001173
Dale Johannesen8593e412007-04-29 19:19:30 +00001174 if (BrOffset <= DestOffset) {
1175 // Branch before the Dest.
1176 if (DestOffset-BrOffset <= MaxDisp)
1177 return true;
1178 } else {
1179 if (BrOffset-DestOffset <= MaxDisp)
1180 return true;
1181 }
1182 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001183}
1184
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001185/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1186/// away to fit in its displacement field.
1187bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001188 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001189 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001190
Evan Chengc0dbec72007-01-31 19:57:44 +00001191 // Check to see if the DestBB is already in-range.
1192 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001193 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001194
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001195 if (!Br.isCond)
1196 return FixUpUnconditionalBr(Fn, Br);
1197 return FixUpConditionalBr(Fn, Br);
1198}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001199
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001200/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1201/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001202/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001203/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001204bool
1205ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1206 MachineInstr *MI = Br.MI;
1207 MachineBasicBlock *MBB = MI->getParent();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001208 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001209
1210 // Use BL to implement far jump.
1211 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001212 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001213 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001214 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001215 HasFarJump = true;
1216 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001217
Evan Chengc99ef082007-02-09 20:54:44 +00001218 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001219
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001220 return true;
1221}
1222
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001223/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001224/// far away to fit in its displacement field. It is converted to an inverse
1225/// conditional branch + an unconditional branch to the destination.
1226bool
1227ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1228 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001229 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001230
Bob Wilson39bf0512009-05-12 17:35:29 +00001231 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001232 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001233 // blt L1
1234 // =>
1235 // bge L2
1236 // b L1
1237 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001238 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001239 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001240 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001241
1242 // If the branch is at the end of its MBB and that has a fall-through block,
1243 // direct the updated conditional branch to the fall-through block. Otherwise,
1244 // split the MBB before the next instruction.
1245 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001246 MachineInstr *BMI = &MBB->back();
1247 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001248
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001249 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001250 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001251 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001252 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001253 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001254 // condition and swap destinations:
1255 // beq L1
1256 // b L2
1257 // =>
1258 // bne L2
1259 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001260 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001261 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001262 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001263 BMI->getOperand(0).setMBB(DestBB);
1264 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001265 MI->getOperand(1).setImm(CC);
1266 return true;
1267 }
1268 }
1269 }
1270
1271 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001272 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001273 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001274 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001275 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001276 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001277 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1278 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001279 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001280 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001281 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001282 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001283
Evan Chengc99ef082007-02-09 20:54:44 +00001284 DOUT << " Insert B to BB#" << DestBB->getNumber()
1285 << " also invert condition and change dest. to BB#"
1286 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001287
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001288 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001289 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001290 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1291 TII->get(MI->getOpcode()))
1292 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001293 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001294 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001295 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001296 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001297 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001298 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001299
1300 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001301 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001302 MI->eraseFromParent();
1303
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001304 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001305 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001306 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001307 return true;
1308}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001309
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001310/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1311/// LR / restores LR to pc.
1312bool ARMConstantIslands::UndoLRSpillRestore() {
1313 bool MadeChange = false;
1314 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1315 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001316 if (MI->getOpcode() == ARM::tPOP_RET &&
1317 MI->getOperand(0).getReg() == ARM::PC &&
1318 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001319 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001320 MI->eraseFromParent();
1321 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001322 }
1323 }
1324 return MadeChange;
1325}